ADAPT-Chase commited on
Commit
0e4b687
·
verified ·
1 Parent(s): 551221d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +11 -0
  2. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/INSTALLER +1 -0
  3. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/LICENSE.txt +13 -0
  4. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/METADATA +243 -0
  5. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/RECORD +120 -0
  6. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/REQUESTED +0 -0
  7. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/WHEEL +6 -0
  8. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/top_level.txt +1 -0
  9. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__init__.py +240 -0
  10. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_cparser.pxd +158 -0
  11. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_find_header.pxd +2 -0
  12. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_headers.pxi +83 -0
  13. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.cpython-312-x86_64-linux-gnu.so +3 -0
  14. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.pyi +6 -0
  15. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.pyx +35 -0
  16. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so +3 -0
  17. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_parser.pyx +836 -0
  18. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so +3 -0
  19. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_writer.pyx +163 -0
  20. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_websocket.cpython-312-x86_64-linux-gnu.so +3 -0
  21. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_websocket.pyx +56 -0
  22. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/abc.py +209 -0
  23. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/base_protocol.py +90 -0
  24. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client.py +1356 -0
  25. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_exceptions.py +346 -0
  26. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_proto.py +264 -0
  27. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_reqrep.py +1196 -0
  28. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_ws.py +315 -0
  29. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/compression_utils.py +157 -0
  30. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/connector.py +1489 -0
  31. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/cookiejar.py +419 -0
  32. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/formdata.py +172 -0
  33. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/hdrs.py +108 -0
  34. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/helpers.py +999 -0
  35. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http.py +72 -0
  36. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_exceptions.py +106 -0
  37. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_parser.py +1009 -0
  38. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_websocket.py +740 -0
  39. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_writer.py +198 -0
  40. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/locks.py +41 -0
  41. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/log.py +8 -0
  42. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/multipart.py +969 -0
  43. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/payload.py +463 -0
  44. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/payload_streamer.py +75 -0
  45. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/py.typed +1 -0
  46. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/pytest_plugin.py +381 -0
  47. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/resolver.py +160 -0
  48. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/streams.py +666 -0
  49. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/tcp_helpers.py +37 -0
  50. platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/test_utils.py +675 -0
.gitattributes CHANGED
@@ -3287,3 +3287,14 @@ platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/parsing.cpytho
3287
  platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cluster.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3288
  platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/util.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3289
  platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/protocol.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
3287
  platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/cluster.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3288
  platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/util.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3289
  platform/dataops/dto/.venv/lib/python3.12/site-packages/cassandra/protocol.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3290
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3291
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3292
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_websocket.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3293
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3294
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/distlib/t64-arm.exe filter=lfs diff=lfs merge=lfs -text
3295
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/distlib/t64.exe filter=lfs diff=lfs merge=lfs -text
3296
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text
3297
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text
3298
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/idna/__pycache__/uts46data.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
3299
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
3300
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright aio-libs contributors.
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.
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/METADATA ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: aiohttp
3
+ Version: 3.9.1
4
+ Summary: Async http client/server framework (asyncio)
5
+ Home-page: https://github.com/aio-libs/aiohttp
6
+ Maintainer: aiohttp team <team@aiohttp.org>
7
+ Maintainer-email: team@aiohttp.org
8
+ License: Apache 2
9
+ Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org
10
+ Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org
11
+ Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
12
+ Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp
13
+ Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html
14
+ Project-URL: Docs: RTD, https://docs.aiohttp.org
15
+ Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues
16
+ Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp
17
+ Classifier: Development Status :: 5 - Production/Stable
18
+ Classifier: Framework :: AsyncIO
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: License :: OSI Approved :: Apache Software License
21
+ Classifier: Operating System :: POSIX
22
+ Classifier: Operating System :: MacOS :: MacOS X
23
+ Classifier: Operating System :: Microsoft :: Windows
24
+ Classifier: Programming Language :: Python
25
+ Classifier: Programming Language :: Python :: 3
26
+ Classifier: Programming Language :: Python :: 3.8
27
+ Classifier: Programming Language :: Python :: 3.9
28
+ Classifier: Programming Language :: Python :: 3.10
29
+ Classifier: Topic :: Internet :: WWW/HTTP
30
+ Requires-Python: >=3.8
31
+ Description-Content-Type: text/x-rst
32
+ License-File: LICENSE.txt
33
+ Requires-Dist: attrs >=17.3.0
34
+ Requires-Dist: multidict <7.0,>=4.5
35
+ Requires-Dist: yarl <2.0,>=1.0
36
+ Requires-Dist: frozenlist >=1.1.1
37
+ Requires-Dist: aiosignal >=1.1.2
38
+ Requires-Dist: async-timeout <5.0,>=4.0 ; python_version < "3.11"
39
+ Provides-Extra: speedups
40
+ Requires-Dist: brotlicffi ; (platform_python_implementation != "CPython") and extra == 'speedups'
41
+ Requires-Dist: Brotli ; (platform_python_implementation == "CPython") and extra == 'speedups'
42
+ Requires-Dist: aiodns ; (sys_platform == "linux" or sys_platform == "darwin") and extra == 'speedups'
43
+
44
+ ==================================
45
+ Async http client/server framework
46
+ ==================================
47
+
48
+ .. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg
49
+ :height: 64px
50
+ :width: 64px
51
+ :alt: aiohttp logo
52
+
53
+ |
54
+
55
+ .. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg
56
+ :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
57
+ :alt: GitHub Actions status for master branch
58
+
59
+ .. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg
60
+ :target: https://codecov.io/gh/aio-libs/aiohttp
61
+ :alt: codecov.io status for master branch
62
+
63
+ .. image:: https://badge.fury.io/py/aiohttp.svg
64
+ :target: https://pypi.org/project/aiohttp
65
+ :alt: Latest PyPI package version
66
+
67
+ .. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest
68
+ :target: https://docs.aiohttp.org/
69
+ :alt: Latest Read The Docs
70
+
71
+ .. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
72
+ :target: https://matrix.to/#/%23aio-libs:matrix.org
73
+ :alt: Matrix Room — #aio-libs:matrix.org
74
+
75
+ .. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
76
+ :target: https://matrix.to/#/%23aio-libs-space:matrix.org
77
+ :alt: Matrix Space — #aio-libs-space:matrix.org
78
+
79
+
80
+ Key Features
81
+ ============
82
+
83
+ - Supports both client and server side of HTTP protocol.
84
+ - Supports both client and server Web-Sockets out-of-the-box and avoids
85
+ Callback Hell.
86
+ - Provides Web-server with middleware and pluggable routing.
87
+
88
+
89
+ Getting started
90
+ ===============
91
+
92
+ Client
93
+ ------
94
+
95
+ To get something from the web:
96
+
97
+ .. code-block:: python
98
+
99
+ import aiohttp
100
+ import asyncio
101
+
102
+ async def main():
103
+
104
+ async with aiohttp.ClientSession() as session:
105
+ async with session.get('http://python.org') as response:
106
+
107
+ print("Status:", response.status)
108
+ print("Content-type:", response.headers['content-type'])
109
+
110
+ html = await response.text()
111
+ print("Body:", html[:15], "...")
112
+
113
+ asyncio.run(main())
114
+
115
+ This prints:
116
+
117
+ .. code-block::
118
+
119
+ Status: 200
120
+ Content-type: text/html; charset=utf-8
121
+ Body: <!doctype html> ...
122
+
123
+ Coming from `requests <https://requests.readthedocs.io/>`_ ? Read `why we need so many lines <https://aiohttp.readthedocs.io/en/latest/http_request_lifecycle.html>`_.
124
+
125
+ Server
126
+ ------
127
+
128
+ An example using a simple server:
129
+
130
+ .. code-block:: python
131
+
132
+ # examples/server_simple.py
133
+ from aiohttp import web
134
+
135
+ async def handle(request):
136
+ name = request.match_info.get('name', "Anonymous")
137
+ text = "Hello, " + name
138
+ return web.Response(text=text)
139
+
140
+ async def wshandle(request):
141
+ ws = web.WebSocketResponse()
142
+ await ws.prepare(request)
143
+
144
+ async for msg in ws:
145
+ if msg.type == web.WSMsgType.text:
146
+ await ws.send_str("Hello, {}".format(msg.data))
147
+ elif msg.type == web.WSMsgType.binary:
148
+ await ws.send_bytes(msg.data)
149
+ elif msg.type == web.WSMsgType.close:
150
+ break
151
+
152
+ return ws
153
+
154
+
155
+ app = web.Application()
156
+ app.add_routes([web.get('/', handle),
157
+ web.get('/echo', wshandle),
158
+ web.get('/{name}', handle)])
159
+
160
+ if __name__ == '__main__':
161
+ web.run_app(app)
162
+
163
+
164
+ Documentation
165
+ =============
166
+
167
+ https://aiohttp.readthedocs.io/
168
+
169
+
170
+ Demos
171
+ =====
172
+
173
+ https://github.com/aio-libs/aiohttp-demos
174
+
175
+
176
+ External links
177
+ ==============
178
+
179
+ * `Third party libraries
180
+ <http://aiohttp.readthedocs.io/en/latest/third_party.html>`_
181
+ * `Built with aiohttp
182
+ <http://aiohttp.readthedocs.io/en/latest/built_with.html>`_
183
+ * `Powered by aiohttp
184
+ <http://aiohttp.readthedocs.io/en/latest/powered_by.html>`_
185
+
186
+ Feel free to make a Pull Request for adding your link to these pages!
187
+
188
+
189
+ Communication channels
190
+ ======================
191
+
192
+ *aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions
193
+
194
+ *gitter chat* https://gitter.im/aio-libs/Lobby
195
+
196
+ We support `Stack Overflow
197
+ <https://stackoverflow.com/questions/tagged/aiohttp>`_.
198
+ Please add *aiohttp* tag to your question there.
199
+
200
+ Requirements
201
+ ============
202
+
203
+ - async-timeout_
204
+ - attrs_
205
+ - multidict_
206
+ - yarl_
207
+ - frozenlist_
208
+
209
+ Optionally you may install the aiodns_ library (highly recommended for sake of speed).
210
+
211
+ .. _aiodns: https://pypi.python.org/pypi/aiodns
212
+ .. _attrs: https://github.com/python-attrs/attrs
213
+ .. _multidict: https://pypi.python.org/pypi/multidict
214
+ .. _frozenlist: https://pypi.org/project/frozenlist/
215
+ .. _yarl: https://pypi.python.org/pypi/yarl
216
+ .. _async-timeout: https://pypi.python.org/pypi/async_timeout
217
+
218
+ License
219
+ =======
220
+
221
+ ``aiohttp`` is offered under the Apache 2 license.
222
+
223
+
224
+ Keepsafe
225
+ ========
226
+
227
+ The aiohttp community would like to thank Keepsafe
228
+ (https://www.getkeepsafe.com) for its support in the early days of
229
+ the project.
230
+
231
+
232
+ Source code
233
+ ===========
234
+
235
+ The latest developer version is available in a GitHub repository:
236
+ https://github.com/aio-libs/aiohttp
237
+
238
+ Benchmarks
239
+ ==========
240
+
241
+ If you are interested in efficiency, the AsyncIO community maintains a
242
+ list of benchmarks on the official wiki:
243
+ https://github.com/python/asyncio/wiki/Benchmarks
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/RECORD ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohttp-3.9.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ aiohttp-3.9.1.dist-info/LICENSE.txt,sha256=n4DQ2311WpQdtFchcsJw7L2PCCuiFd3QlZhZQu2Uqes,588
3
+ aiohttp-3.9.1.dist-info/METADATA,sha256=62Q_RgoSLj5AlXdi63xBFYgkT11mgnluERhDIRpWHjY,7357
4
+ aiohttp-3.9.1.dist-info/RECORD,,
5
+ aiohttp-3.9.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ aiohttp-3.9.1.dist-info/WHEEL,sha256=vJMp7mUkE-fMIYyE5xJ9Q2cYPnWVgHf20clVdwMSXAg,152
7
+ aiohttp-3.9.1.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8
8
+ aiohttp/.hash/_cparser.pxd.hash,sha256=hYa9Vje-oMs2eh_7MfCPOh2QW_1x1yCjcZuc7AmwLd0,121
9
+ aiohttp/.hash/_find_header.pxd.hash,sha256=_mbpD6vM-CVCKq3ulUvsOAz5Wdo88wrDzfpOsMQaMNA,125
10
+ aiohttp/.hash/_helpers.pyi.hash,sha256=Ew4BZDc2LqFwszgZZUHHrJvw5P8HBhJ700n1Ntg52hE,121
11
+ aiohttp/.hash/_helpers.pyx.hash,sha256=5JQ6BlMBE4HnRaCGdkK9_wpL3ZSWpU1gyLYva0Wwx2c,121
12
+ aiohttp/.hash/_http_parser.pyx.hash,sha256=IRBIywLdT4-0kqWhb0g0WPjh6Gu10TreFmLI8JQF-L8,125
13
+ aiohttp/.hash/_http_writer.pyx.hash,sha256=3Qg3T3D-Ud73elzPHBufK0yEu9tP5jsu6g-aPKQY9gE,125
14
+ aiohttp/.hash/_websocket.pyx.hash,sha256=M97f-Yti-4vnE4GNTD1s_DzKs-fG_ww3jle6EUvixnE,123
15
+ aiohttp/.hash/hdrs.py.hash,sha256=2oEszMWjYFTHoF2w4OcFCoM7osv4vY9KLLJCu9HP0xI,116
16
+ aiohttp/__init__.py,sha256=EnBN-3iIseCzm7llWOVNSbPpNTarRN1dF2SSgRKtB-g,7782
17
+ aiohttp/__pycache__/__init__.cpython-312.pyc,,
18
+ aiohttp/__pycache__/abc.cpython-312.pyc,,
19
+ aiohttp/__pycache__/base_protocol.cpython-312.pyc,,
20
+ aiohttp/__pycache__/client.cpython-312.pyc,,
21
+ aiohttp/__pycache__/client_exceptions.cpython-312.pyc,,
22
+ aiohttp/__pycache__/client_proto.cpython-312.pyc,,
23
+ aiohttp/__pycache__/client_reqrep.cpython-312.pyc,,
24
+ aiohttp/__pycache__/client_ws.cpython-312.pyc,,
25
+ aiohttp/__pycache__/compression_utils.cpython-312.pyc,,
26
+ aiohttp/__pycache__/connector.cpython-312.pyc,,
27
+ aiohttp/__pycache__/cookiejar.cpython-312.pyc,,
28
+ aiohttp/__pycache__/formdata.cpython-312.pyc,,
29
+ aiohttp/__pycache__/hdrs.cpython-312.pyc,,
30
+ aiohttp/__pycache__/helpers.cpython-312.pyc,,
31
+ aiohttp/__pycache__/http.cpython-312.pyc,,
32
+ aiohttp/__pycache__/http_exceptions.cpython-312.pyc,,
33
+ aiohttp/__pycache__/http_parser.cpython-312.pyc,,
34
+ aiohttp/__pycache__/http_websocket.cpython-312.pyc,,
35
+ aiohttp/__pycache__/http_writer.cpython-312.pyc,,
36
+ aiohttp/__pycache__/locks.cpython-312.pyc,,
37
+ aiohttp/__pycache__/log.cpython-312.pyc,,
38
+ aiohttp/__pycache__/multipart.cpython-312.pyc,,
39
+ aiohttp/__pycache__/payload.cpython-312.pyc,,
40
+ aiohttp/__pycache__/payload_streamer.cpython-312.pyc,,
41
+ aiohttp/__pycache__/pytest_plugin.cpython-312.pyc,,
42
+ aiohttp/__pycache__/resolver.cpython-312.pyc,,
43
+ aiohttp/__pycache__/streams.cpython-312.pyc,,
44
+ aiohttp/__pycache__/tcp_helpers.cpython-312.pyc,,
45
+ aiohttp/__pycache__/test_utils.cpython-312.pyc,,
46
+ aiohttp/__pycache__/tracing.cpython-312.pyc,,
47
+ aiohttp/__pycache__/typedefs.cpython-312.pyc,,
48
+ aiohttp/__pycache__/web.cpython-312.pyc,,
49
+ aiohttp/__pycache__/web_app.cpython-312.pyc,,
50
+ aiohttp/__pycache__/web_exceptions.cpython-312.pyc,,
51
+ aiohttp/__pycache__/web_fileresponse.cpython-312.pyc,,
52
+ aiohttp/__pycache__/web_log.cpython-312.pyc,,
53
+ aiohttp/__pycache__/web_middlewares.cpython-312.pyc,,
54
+ aiohttp/__pycache__/web_protocol.cpython-312.pyc,,
55
+ aiohttp/__pycache__/web_request.cpython-312.pyc,,
56
+ aiohttp/__pycache__/web_response.cpython-312.pyc,,
57
+ aiohttp/__pycache__/web_routedef.cpython-312.pyc,,
58
+ aiohttp/__pycache__/web_runner.cpython-312.pyc,,
59
+ aiohttp/__pycache__/web_server.cpython-312.pyc,,
60
+ aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc,,
61
+ aiohttp/__pycache__/web_ws.cpython-312.pyc,,
62
+ aiohttp/__pycache__/worker.cpython-312.pyc,,
63
+ aiohttp/_cparser.pxd,sha256=8jGIg-VJ9p3llwCakUYDsPGxA4HiZe9dmK9Jmtlz-5g,4318
64
+ aiohttp/_find_header.pxd,sha256=0GfwFCPN2zxEKTO1_MA5sYq2UfzsG8kcV3aTqvwlz3g,68
65
+ aiohttp/_headers.pxi,sha256=n701k28dVPjwRnx5j6LpJhLTfj7dqu2vJt7f0O60Oyg,2007
66
+ aiohttp/_helpers.cpython-312-x86_64-linux-gnu.so,sha256=xQukDyoc-AzBs0yYHDXWrw8ICGrg8fQVexTfVBsICt0,613288
67
+ aiohttp/_helpers.pyi,sha256=ZoKiJSS51PxELhI2cmIr5737YjjZcJt7FbIRO3ym1Ss,202
68
+ aiohttp/_helpers.pyx,sha256=XeLbNft5X_4ifi8QB8i6TyrRuayijMSO3IDHeSA89uM,1049
69
+ aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so,sha256=ZvlhyVbDbz3UHTWTPeqmGsn1-cW0syQ4rgr3vD3ftrI,2788720
70
+ aiohttp/_http_parser.pyx,sha256=fzKwwVlcGnGVeiGOzo05d-2Rccqtl9-PzYKqgK3fxdI,28058
71
+ aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so,sha256=NgI7lQoig5xSvNGFFdHI3ZJpS2emu9zj78yOe1LgYKE,503128
72
+ aiohttp/_http_writer.pyx,sha256=aIHAp8g4ZV5kbGRdmZce-vXjELw2M6fGKyJuOdgYQqw,4575
73
+ aiohttp/_websocket.cpython-312-x86_64-linux-gnu.so,sha256=c3irDrlStRTO9xfB94T2KQkO_17dMYNZ-9-JkufCH6Q,278168
74
+ aiohttp/_websocket.pyx,sha256=1XuOSNDCbyDrzF5uMA2isqausSs8l2jWTLDlNDLM9Io,1561
75
+ aiohttp/abc.py,sha256=nAyCo7BadpvvExxO1khNYqDpYt40Qp1zFmepDfZqq28,5540
76
+ aiohttp/base_protocol.py,sha256=5JUyuIGwKf7sFhf0YLAnk36_hkSIxBnP4hN09RdMGGk,2741
77
+ aiohttp/client.py,sha256=6s0n3HM4CRk4Gl7f-umGBTGp2MiVA7yjMnGLhSkxZXs,46918
78
+ aiohttp/client_exceptions.py,sha256=4NmjMG2-P__buR9xfuz8_w0pvbXzr2oyuo62eQxsea8,9445
79
+ aiohttp/client_proto.py,sha256=eHQjoiZVvm1m31Vcj1H2huV-zwHZwEl71km5l-p22aE,8624
80
+ aiohttp/client_reqrep.py,sha256=xfJsqTzkfmRfAzChxp1za6NcfU2GDo1XXkEhTnJDik4,39756
81
+ aiohttp/client_ws.py,sha256=nNrwu1wA0U3B0cNsVr61QfV2S60bbKfaZXHfW7klFl4,11010
82
+ aiohttp/compression_utils.py,sha256=GCkBNJqrybMhiTQGwqqhORnaTLpRFZD_-UvRtnZ5lEQ,5015
83
+ aiohttp/connector.py,sha256=YnUCuZQSgseKsUbo2jJH7mi0nhZD_8A6UQ5Ll3GS37k,52834
84
+ aiohttp/cookiejar.py,sha256=PdvsOiDasDYYUOPaaAfuuFJzR4CJyHHjut02YiZ_N8M,14015
85
+ aiohttp/formdata.py,sha256=q2gpeiM9NFsl_eSFVxHZ7Qez6RbM8_BujERMkooQkx0,6106
86
+ aiohttp/hdrs.py,sha256=uzn5agn_jXid2h-ky6Y0ZAQ8BrPeTGLDGr-weiMctso,4613
87
+ aiohttp/helpers.py,sha256=hYm60xCxbJCdtdtLhTt7uspQ_9HPT27gTBx2q9Fu1Zk,30255
88
+ aiohttp/http.py,sha256=8o8j8xH70OWjnfTWA9V44NR785QPxEPrUtzMXiAVpwc,1842
89
+ aiohttp/http_exceptions.py,sha256=7LOFFUwq04fZsnZA-NP5nukd6c2i8daM8-ejj3ndbSQ,2716
90
+ aiohttp/http_parser.py,sha256=99kVO47hO22HQV0B4Y-1XhtOK4LTISOOs2d8c9yOGqQ,35166
91
+ aiohttp/http_websocket.py,sha256=5qBvfvbt6f24AptTHud-T99LEnpwbGQNLMB8wGcfs9c,26704
92
+ aiohttp/http_writer.py,sha256=fxpyRj_S3WcBl9fxxF05t8YYAUA-0jW5b_PjVSluT3Y,5933
93
+ aiohttp/locks.py,sha256=wRYFo1U82LwBBdqwU24JEPaoTAlKaaJd2FtfDKhkTb4,1136
94
+ aiohttp/log.py,sha256=BbNKx9e3VMIm0xYjZI0IcBBoS7wjdeIeSaiJE7-qK2g,325
95
+ aiohttp/multipart.py,sha256=rDZYg-I-530nIEq3-U4DF2Q-fl0E7mk5YEmejzT1bak,32492
96
+ aiohttp/payload.py,sha256=IV5HwxYqgUVY_SiyPjzUQ_YUIYvQaGkrmLmZlvSzDeM,13582
97
+ aiohttp/payload_streamer.py,sha256=eAS8S-UWfLkEMavRjP2Uu9amC3PnbV79wHTNDoRmYn8,2087
98
+ aiohttp/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
99
+ aiohttp/pytest_plugin.py,sha256=3IwpuxtFiUVFGS_ZitWuqvECSGgXQWvCW312B2TaVLY,11605
100
+ aiohttp/resolver.py,sha256=8peXjB482v0hg1ESn87op6f-UeLXk_fAMxQo_23Ek6M,5070
101
+ aiohttp/streams.py,sha256=vNCy0k5R7XlnSfsyTEQAkBD4Q9tNZgNm76Gqlw8Tjok,20836
102
+ aiohttp/tcp_helpers.py,sha256=BSadqVWaBpMFDRWnhaaR941N9MiDZ7bdTrxgCb0CW-M,961
103
+ aiohttp/test_utils.py,sha256=t5ibahuV6klkUMLdWuJhlSvzwtIRprWZqnkdHt5XJYU,20205
104
+ aiohttp/tracing.py,sha256=Kz9u3YGTegGebYM2EMhG9RKT6-ABcsHtM7J-Qvwyus8,15152
105
+ aiohttp/typedefs.py,sha256=8pDFTXt-5sYdzE4JsRH6UjAQyURnfZ0ueeEtgQccQZU,1491
106
+ aiohttp/web.py,sha256=HFTQaoYVK5pM3YmxNJtZl9fGrRIdFs_Nhloxe7_lJj0,19263
107
+ aiohttp/web_app.py,sha256=sUqIpip4BUL_pwc-Qs7IWDrFpeBNpaD8ocKFGfs9B0U,18351
108
+ aiohttp/web_exceptions.py,sha256=7nIuiwhZ39vJJ9KrWqArA5QcWbUdqkz2CLwEpJapeN8,10360
109
+ aiohttp/web_fileresponse.py,sha256=VRmCEr-qz7hzBy1TPa1wzid2DkgtQdIDjA18amkmRO4,10705
110
+ aiohttp/web_log.py,sha256=DOfOxGyh2U7K5K_w6O7ILdfGcs4qOdzHxOwj2-k3c6c,7801
111
+ aiohttp/web_middlewares.py,sha256=imxf1cfCKvfkv_jQLfTNNs_hA95oLnapRcPl-2aDsdA,4052
112
+ aiohttp/web_protocol.py,sha256=REP-s4onglMYW2XZ5nqPCWkK0vt_2f8FiP4MFQXdd3A,23064
113
+ aiohttp/web_request.py,sha256=TGTsWNNpGSL49Q-uV101ecX9hLZMm5PFs4mLxGkbkHc,28776
114
+ aiohttp/web_response.py,sha256=t8mNgT5nddHLpsgZhUkqbq0NDsipmdGzfZUB5pCP_Yo,27749
115
+ aiohttp/web_routedef.py,sha256=EFk3v1dcFnLimTT5z0JSBO3PShF0w9sIzfK9iJd-LNs,6152
116
+ aiohttp/web_runner.py,sha256=AM3klOcr72AZVGG9-LjYo8vJdHBWgNzDLsmi_aoKfAU,11736
117
+ aiohttp/web_server.py,sha256=5P-9uPCoPEDkK9ILbvEXmkkJWPhnTxBzdwAXwveyyDk,2587
118
+ aiohttp/web_urldispatcher.py,sha256=sblBVycAhKVFPRbtfbZGsrPivLL0sskeE3LRPK2Deec,39557
119
+ aiohttp/web_ws.py,sha256=eGjrE3_lUbv9kpYZluZFvdCfvahi5O4-fF7hWgyEHQk,18039
120
+ aiohttp/worker.py,sha256=bkozEd2rAzQS0qs4knnnplOmaZ4TNdYtqWXSXx9djEc,7965
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/REQUESTED ADDED
File without changes
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.42.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-manylinux_2_17_x86_64
5
+ Tag: cp312-cp312-manylinux2014_x86_64
6
+
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp-3.9.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ aiohttp
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__init__.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __version__ = "3.9.1"
2
+
3
+ from typing import TYPE_CHECKING, Tuple
4
+
5
+ from . import hdrs as hdrs
6
+ from .client import (
7
+ BaseConnector as BaseConnector,
8
+ ClientConnectionError as ClientConnectionError,
9
+ ClientConnectorCertificateError as ClientConnectorCertificateError,
10
+ ClientConnectorError as ClientConnectorError,
11
+ ClientConnectorSSLError as ClientConnectorSSLError,
12
+ ClientError as ClientError,
13
+ ClientHttpProxyError as ClientHttpProxyError,
14
+ ClientOSError as ClientOSError,
15
+ ClientPayloadError as ClientPayloadError,
16
+ ClientProxyConnectionError as ClientProxyConnectionError,
17
+ ClientRequest as ClientRequest,
18
+ ClientResponse as ClientResponse,
19
+ ClientResponseError as ClientResponseError,
20
+ ClientSession as ClientSession,
21
+ ClientSSLError as ClientSSLError,
22
+ ClientTimeout as ClientTimeout,
23
+ ClientWebSocketResponse as ClientWebSocketResponse,
24
+ ContentTypeError as ContentTypeError,
25
+ Fingerprint as Fingerprint,
26
+ InvalidURL as InvalidURL,
27
+ NamedPipeConnector as NamedPipeConnector,
28
+ RequestInfo as RequestInfo,
29
+ ServerConnectionError as ServerConnectionError,
30
+ ServerDisconnectedError as ServerDisconnectedError,
31
+ ServerFingerprintMismatch as ServerFingerprintMismatch,
32
+ ServerTimeoutError as ServerTimeoutError,
33
+ TCPConnector as TCPConnector,
34
+ TooManyRedirects as TooManyRedirects,
35
+ UnixConnector as UnixConnector,
36
+ WSServerHandshakeError as WSServerHandshakeError,
37
+ request as request,
38
+ )
39
+ from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar
40
+ from .formdata import FormData as FormData
41
+ from .helpers import BasicAuth, ChainMapProxy, ETag
42
+ from .http import (
43
+ HttpVersion as HttpVersion,
44
+ HttpVersion10 as HttpVersion10,
45
+ HttpVersion11 as HttpVersion11,
46
+ WebSocketError as WebSocketError,
47
+ WSCloseCode as WSCloseCode,
48
+ WSMessage as WSMessage,
49
+ WSMsgType as WSMsgType,
50
+ )
51
+ from .multipart import (
52
+ BadContentDispositionHeader as BadContentDispositionHeader,
53
+ BadContentDispositionParam as BadContentDispositionParam,
54
+ BodyPartReader as BodyPartReader,
55
+ MultipartReader as MultipartReader,
56
+ MultipartWriter as MultipartWriter,
57
+ content_disposition_filename as content_disposition_filename,
58
+ parse_content_disposition as parse_content_disposition,
59
+ )
60
+ from .payload import (
61
+ PAYLOAD_REGISTRY as PAYLOAD_REGISTRY,
62
+ AsyncIterablePayload as AsyncIterablePayload,
63
+ BufferedReaderPayload as BufferedReaderPayload,
64
+ BytesIOPayload as BytesIOPayload,
65
+ BytesPayload as BytesPayload,
66
+ IOBasePayload as IOBasePayload,
67
+ JsonPayload as JsonPayload,
68
+ Payload as Payload,
69
+ StringIOPayload as StringIOPayload,
70
+ StringPayload as StringPayload,
71
+ TextIOPayload as TextIOPayload,
72
+ get_payload as get_payload,
73
+ payload_type as payload_type,
74
+ )
75
+ from .payload_streamer import streamer as streamer
76
+ from .resolver import (
77
+ AsyncResolver as AsyncResolver,
78
+ DefaultResolver as DefaultResolver,
79
+ ThreadedResolver as ThreadedResolver,
80
+ )
81
+ from .streams import (
82
+ EMPTY_PAYLOAD as EMPTY_PAYLOAD,
83
+ DataQueue as DataQueue,
84
+ EofStream as EofStream,
85
+ FlowControlDataQueue as FlowControlDataQueue,
86
+ StreamReader as StreamReader,
87
+ )
88
+ from .tracing import (
89
+ TraceConfig as TraceConfig,
90
+ TraceConnectionCreateEndParams as TraceConnectionCreateEndParams,
91
+ TraceConnectionCreateStartParams as TraceConnectionCreateStartParams,
92
+ TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams,
93
+ TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams,
94
+ TraceConnectionReuseconnParams as TraceConnectionReuseconnParams,
95
+ TraceDnsCacheHitParams as TraceDnsCacheHitParams,
96
+ TraceDnsCacheMissParams as TraceDnsCacheMissParams,
97
+ TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams,
98
+ TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams,
99
+ TraceRequestChunkSentParams as TraceRequestChunkSentParams,
100
+ TraceRequestEndParams as TraceRequestEndParams,
101
+ TraceRequestExceptionParams as TraceRequestExceptionParams,
102
+ TraceRequestRedirectParams as TraceRequestRedirectParams,
103
+ TraceRequestStartParams as TraceRequestStartParams,
104
+ TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams,
105
+ )
106
+
107
+ if TYPE_CHECKING: # pragma: no cover
108
+ # At runtime these are lazy-loaded at the bottom of the file.
109
+ from .worker import (
110
+ GunicornUVLoopWebWorker as GunicornUVLoopWebWorker,
111
+ GunicornWebWorker as GunicornWebWorker,
112
+ )
113
+
114
+ __all__: Tuple[str, ...] = (
115
+ "hdrs",
116
+ # client
117
+ "BaseConnector",
118
+ "ClientConnectionError",
119
+ "ClientConnectorCertificateError",
120
+ "ClientConnectorError",
121
+ "ClientConnectorSSLError",
122
+ "ClientError",
123
+ "ClientHttpProxyError",
124
+ "ClientOSError",
125
+ "ClientPayloadError",
126
+ "ClientProxyConnectionError",
127
+ "ClientResponse",
128
+ "ClientRequest",
129
+ "ClientResponseError",
130
+ "ClientSSLError",
131
+ "ClientSession",
132
+ "ClientTimeout",
133
+ "ClientWebSocketResponse",
134
+ "ContentTypeError",
135
+ "Fingerprint",
136
+ "InvalidURL",
137
+ "RequestInfo",
138
+ "ServerConnectionError",
139
+ "ServerDisconnectedError",
140
+ "ServerFingerprintMismatch",
141
+ "ServerTimeoutError",
142
+ "TCPConnector",
143
+ "TooManyRedirects",
144
+ "UnixConnector",
145
+ "NamedPipeConnector",
146
+ "WSServerHandshakeError",
147
+ "request",
148
+ # cookiejar
149
+ "CookieJar",
150
+ "DummyCookieJar",
151
+ # formdata
152
+ "FormData",
153
+ # helpers
154
+ "BasicAuth",
155
+ "ChainMapProxy",
156
+ "ETag",
157
+ # http
158
+ "HttpVersion",
159
+ "HttpVersion10",
160
+ "HttpVersion11",
161
+ "WSMsgType",
162
+ "WSCloseCode",
163
+ "WSMessage",
164
+ "WebSocketError",
165
+ # multipart
166
+ "BadContentDispositionHeader",
167
+ "BadContentDispositionParam",
168
+ "BodyPartReader",
169
+ "MultipartReader",
170
+ "MultipartWriter",
171
+ "content_disposition_filename",
172
+ "parse_content_disposition",
173
+ # payload
174
+ "AsyncIterablePayload",
175
+ "BufferedReaderPayload",
176
+ "BytesIOPayload",
177
+ "BytesPayload",
178
+ "IOBasePayload",
179
+ "JsonPayload",
180
+ "PAYLOAD_REGISTRY",
181
+ "Payload",
182
+ "StringIOPayload",
183
+ "StringPayload",
184
+ "TextIOPayload",
185
+ "get_payload",
186
+ "payload_type",
187
+ # payload_streamer
188
+ "streamer",
189
+ # resolver
190
+ "AsyncResolver",
191
+ "DefaultResolver",
192
+ "ThreadedResolver",
193
+ # streams
194
+ "DataQueue",
195
+ "EMPTY_PAYLOAD",
196
+ "EofStream",
197
+ "FlowControlDataQueue",
198
+ "StreamReader",
199
+ # tracing
200
+ "TraceConfig",
201
+ "TraceConnectionCreateEndParams",
202
+ "TraceConnectionCreateStartParams",
203
+ "TraceConnectionQueuedEndParams",
204
+ "TraceConnectionQueuedStartParams",
205
+ "TraceConnectionReuseconnParams",
206
+ "TraceDnsCacheHitParams",
207
+ "TraceDnsCacheMissParams",
208
+ "TraceDnsResolveHostEndParams",
209
+ "TraceDnsResolveHostStartParams",
210
+ "TraceRequestChunkSentParams",
211
+ "TraceRequestEndParams",
212
+ "TraceRequestExceptionParams",
213
+ "TraceRequestRedirectParams",
214
+ "TraceRequestStartParams",
215
+ "TraceResponseChunkReceivedParams",
216
+ # workers (imported lazily with __getattr__)
217
+ "GunicornUVLoopWebWorker",
218
+ "GunicornWebWorker",
219
+ )
220
+
221
+
222
+ def __dir__() -> Tuple[str, ...]:
223
+ return __all__ + ("__author__", "__doc__")
224
+
225
+
226
+ def __getattr__(name: str) -> object:
227
+ global GunicornUVLoopWebWorker, GunicornWebWorker
228
+
229
+ # Importing gunicorn takes a long time (>100ms), so only import if actually needed.
230
+ if name in ("GunicornUVLoopWebWorker", "GunicornWebWorker"):
231
+ try:
232
+ from .worker import GunicornUVLoopWebWorker as guv, GunicornWebWorker as gw
233
+ except ImportError:
234
+ return None
235
+
236
+ GunicornUVLoopWebWorker = guv # type: ignore[misc]
237
+ GunicornWebWorker = gw # type: ignore[misc]
238
+ return guv if name == "GunicornUVLoopWebWorker" else gw
239
+
240
+ raise AttributeError(f"module {__name__} has no attribute {name}")
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_cparser.pxd ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc.stdint cimport int32_t, uint8_t, uint16_t, uint64_t
2
+
3
+
4
+ cdef extern from "../vendor/llhttp/build/llhttp.h":
5
+
6
+ struct llhttp__internal_s:
7
+ int32_t _index
8
+ void* _span_pos0
9
+ void* _span_cb0
10
+ int32_t error
11
+ const char* reason
12
+ const char* error_pos
13
+ void* data
14
+ void* _current
15
+ uint64_t content_length
16
+ uint8_t type
17
+ uint8_t method
18
+ uint8_t http_major
19
+ uint8_t http_minor
20
+ uint8_t header_state
21
+ uint8_t lenient_flags
22
+ uint8_t upgrade
23
+ uint8_t finish
24
+ uint16_t flags
25
+ uint16_t status_code
26
+ void* settings
27
+
28
+ ctypedef llhttp__internal_s llhttp__internal_t
29
+ ctypedef llhttp__internal_t llhttp_t
30
+
31
+ ctypedef int (*llhttp_data_cb)(llhttp_t*, const char *at, size_t length) except -1
32
+ ctypedef int (*llhttp_cb)(llhttp_t*) except -1
33
+
34
+ struct llhttp_settings_s:
35
+ llhttp_cb on_message_begin
36
+ llhttp_data_cb on_url
37
+ llhttp_data_cb on_status
38
+ llhttp_data_cb on_header_field
39
+ llhttp_data_cb on_header_value
40
+ llhttp_cb on_headers_complete
41
+ llhttp_data_cb on_body
42
+ llhttp_cb on_message_complete
43
+ llhttp_cb on_chunk_header
44
+ llhttp_cb on_chunk_complete
45
+
46
+ llhttp_cb on_url_complete
47
+ llhttp_cb on_status_complete
48
+ llhttp_cb on_header_field_complete
49
+ llhttp_cb on_header_value_complete
50
+
51
+ ctypedef llhttp_settings_s llhttp_settings_t
52
+
53
+ enum llhttp_errno:
54
+ HPE_OK,
55
+ HPE_INTERNAL,
56
+ HPE_STRICT,
57
+ HPE_LF_EXPECTED,
58
+ HPE_UNEXPECTED_CONTENT_LENGTH,
59
+ HPE_CLOSED_CONNECTION,
60
+ HPE_INVALID_METHOD,
61
+ HPE_INVALID_URL,
62
+ HPE_INVALID_CONSTANT,
63
+ HPE_INVALID_VERSION,
64
+ HPE_INVALID_HEADER_TOKEN,
65
+ HPE_INVALID_CONTENT_LENGTH,
66
+ HPE_INVALID_CHUNK_SIZE,
67
+ HPE_INVALID_STATUS,
68
+ HPE_INVALID_EOF_STATE,
69
+ HPE_INVALID_TRANSFER_ENCODING,
70
+ HPE_CB_MESSAGE_BEGIN,
71
+ HPE_CB_HEADERS_COMPLETE,
72
+ HPE_CB_MESSAGE_COMPLETE,
73
+ HPE_CB_CHUNK_HEADER,
74
+ HPE_CB_CHUNK_COMPLETE,
75
+ HPE_PAUSED,
76
+ HPE_PAUSED_UPGRADE,
77
+ HPE_USER
78
+
79
+ ctypedef llhttp_errno llhttp_errno_t
80
+
81
+ enum llhttp_flags:
82
+ F_CHUNKED,
83
+ F_CONTENT_LENGTH
84
+
85
+ enum llhttp_type:
86
+ HTTP_REQUEST,
87
+ HTTP_RESPONSE,
88
+ HTTP_BOTH
89
+
90
+ enum llhttp_method:
91
+ HTTP_DELETE,
92
+ HTTP_GET,
93
+ HTTP_HEAD,
94
+ HTTP_POST,
95
+ HTTP_PUT,
96
+ HTTP_CONNECT,
97
+ HTTP_OPTIONS,
98
+ HTTP_TRACE,
99
+ HTTP_COPY,
100
+ HTTP_LOCK,
101
+ HTTP_MKCOL,
102
+ HTTP_MOVE,
103
+ HTTP_PROPFIND,
104
+ HTTP_PROPPATCH,
105
+ HTTP_SEARCH,
106
+ HTTP_UNLOCK,
107
+ HTTP_BIND,
108
+ HTTP_REBIND,
109
+ HTTP_UNBIND,
110
+ HTTP_ACL,
111
+ HTTP_REPORT,
112
+ HTTP_MKACTIVITY,
113
+ HTTP_CHECKOUT,
114
+ HTTP_MERGE,
115
+ HTTP_MSEARCH,
116
+ HTTP_NOTIFY,
117
+ HTTP_SUBSCRIBE,
118
+ HTTP_UNSUBSCRIBE,
119
+ HTTP_PATCH,
120
+ HTTP_PURGE,
121
+ HTTP_MKCALENDAR,
122
+ HTTP_LINK,
123
+ HTTP_UNLINK,
124
+ HTTP_SOURCE,
125
+ HTTP_PRI,
126
+ HTTP_DESCRIBE,
127
+ HTTP_ANNOUNCE,
128
+ HTTP_SETUP,
129
+ HTTP_PLAY,
130
+ HTTP_PAUSE,
131
+ HTTP_TEARDOWN,
132
+ HTTP_GET_PARAMETER,
133
+ HTTP_SET_PARAMETER,
134
+ HTTP_REDIRECT,
135
+ HTTP_RECORD,
136
+ HTTP_FLUSH
137
+
138
+ ctypedef llhttp_method llhttp_method_t;
139
+
140
+ void llhttp_settings_init(llhttp_settings_t* settings)
141
+ void llhttp_init(llhttp_t* parser, llhttp_type type,
142
+ const llhttp_settings_t* settings)
143
+
144
+ llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len)
145
+
146
+ int llhttp_should_keep_alive(const llhttp_t* parser)
147
+
148
+ void llhttp_resume_after_upgrade(llhttp_t* parser)
149
+
150
+ llhttp_errno_t llhttp_get_errno(const llhttp_t* parser)
151
+ const char* llhttp_get_error_reason(const llhttp_t* parser)
152
+ const char* llhttp_get_error_pos(const llhttp_t* parser)
153
+
154
+ const char* llhttp_method_name(llhttp_method_t method)
155
+
156
+ void llhttp_set_lenient_headers(llhttp_t* parser, int enabled)
157
+ void llhttp_set_lenient_optional_cr_before_lf(llhttp_t* parser, int enabled)
158
+ void llhttp_set_lenient_spaces_after_chunk_size(llhttp_t* parser, int enabled)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_find_header.pxd ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ cdef extern from "_find_header.h":
2
+ int find_header(char *, int)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_headers.pxi ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The file is autogenerated from aiohttp/hdrs.py
2
+ # Run ./tools/gen.py to update it after the origin changing.
3
+
4
+ from . import hdrs
5
+ cdef tuple headers = (
6
+ hdrs.ACCEPT,
7
+ hdrs.ACCEPT_CHARSET,
8
+ hdrs.ACCEPT_ENCODING,
9
+ hdrs.ACCEPT_LANGUAGE,
10
+ hdrs.ACCEPT_RANGES,
11
+ hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
12
+ hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
13
+ hdrs.ACCESS_CONTROL_ALLOW_METHODS,
14
+ hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
15
+ hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
16
+ hdrs.ACCESS_CONTROL_MAX_AGE,
17
+ hdrs.ACCESS_CONTROL_REQUEST_HEADERS,
18
+ hdrs.ACCESS_CONTROL_REQUEST_METHOD,
19
+ hdrs.AGE,
20
+ hdrs.ALLOW,
21
+ hdrs.AUTHORIZATION,
22
+ hdrs.CACHE_CONTROL,
23
+ hdrs.CONNECTION,
24
+ hdrs.CONTENT_DISPOSITION,
25
+ hdrs.CONTENT_ENCODING,
26
+ hdrs.CONTENT_LANGUAGE,
27
+ hdrs.CONTENT_LENGTH,
28
+ hdrs.CONTENT_LOCATION,
29
+ hdrs.CONTENT_MD5,
30
+ hdrs.CONTENT_RANGE,
31
+ hdrs.CONTENT_TRANSFER_ENCODING,
32
+ hdrs.CONTENT_TYPE,
33
+ hdrs.COOKIE,
34
+ hdrs.DATE,
35
+ hdrs.DESTINATION,
36
+ hdrs.DIGEST,
37
+ hdrs.ETAG,
38
+ hdrs.EXPECT,
39
+ hdrs.EXPIRES,
40
+ hdrs.FORWARDED,
41
+ hdrs.FROM,
42
+ hdrs.HOST,
43
+ hdrs.IF_MATCH,
44
+ hdrs.IF_MODIFIED_SINCE,
45
+ hdrs.IF_NONE_MATCH,
46
+ hdrs.IF_RANGE,
47
+ hdrs.IF_UNMODIFIED_SINCE,
48
+ hdrs.KEEP_ALIVE,
49
+ hdrs.LAST_EVENT_ID,
50
+ hdrs.LAST_MODIFIED,
51
+ hdrs.LINK,
52
+ hdrs.LOCATION,
53
+ hdrs.MAX_FORWARDS,
54
+ hdrs.ORIGIN,
55
+ hdrs.PRAGMA,
56
+ hdrs.PROXY_AUTHENTICATE,
57
+ hdrs.PROXY_AUTHORIZATION,
58
+ hdrs.RANGE,
59
+ hdrs.REFERER,
60
+ hdrs.RETRY_AFTER,
61
+ hdrs.SEC_WEBSOCKET_ACCEPT,
62
+ hdrs.SEC_WEBSOCKET_EXTENSIONS,
63
+ hdrs.SEC_WEBSOCKET_KEY,
64
+ hdrs.SEC_WEBSOCKET_KEY1,
65
+ hdrs.SEC_WEBSOCKET_PROTOCOL,
66
+ hdrs.SEC_WEBSOCKET_VERSION,
67
+ hdrs.SERVER,
68
+ hdrs.SET_COOKIE,
69
+ hdrs.TE,
70
+ hdrs.TRAILER,
71
+ hdrs.TRANSFER_ENCODING,
72
+ hdrs.URI,
73
+ hdrs.UPGRADE,
74
+ hdrs.USER_AGENT,
75
+ hdrs.VARY,
76
+ hdrs.VIA,
77
+ hdrs.WWW_AUTHENTICATE,
78
+ hdrs.WANT_DIGEST,
79
+ hdrs.WARNING,
80
+ hdrs.X_FORWARDED_FOR,
81
+ hdrs.X_FORWARDED_HOST,
82
+ hdrs.X_FORWARDED_PROTO,
83
+ )
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c50ba40f2a1cf80cc1b34c981c35d6af0f08086ae0f1f4157b14df541b080add
3
+ size 613288
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.pyi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ class reify:
4
+ def __init__(self, wrapped: Any) -> None: ...
5
+ def __get__(self, inst: Any, owner: Any) -> Any: ...
6
+ def __set__(self, inst: Any, value: Any) -> None: ...
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_helpers.pyx ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cdef class reify:
2
+ """Use as a class method decorator. It operates almost exactly like
3
+ the Python `@property` decorator, but it puts the result of the
4
+ method it decorates into the instance dict after the first call,
5
+ effectively replacing the function it decorates with an instance
6
+ variable. It is, in Python parlance, a data descriptor.
7
+
8
+ """
9
+
10
+ cdef object wrapped
11
+ cdef object name
12
+
13
+ def __init__(self, wrapped):
14
+ self.wrapped = wrapped
15
+ self.name = wrapped.__name__
16
+
17
+ @property
18
+ def __doc__(self):
19
+ return self.wrapped.__doc__
20
+
21
+ def __get__(self, inst, owner):
22
+ try:
23
+ try:
24
+ return inst._cache[self.name]
25
+ except KeyError:
26
+ val = self.wrapped(inst)
27
+ inst._cache[self.name] = val
28
+ return val
29
+ except AttributeError:
30
+ if inst is None:
31
+ return self
32
+ raise
33
+
34
+ def __set__(self, inst, value):
35
+ raise AttributeError("reified property is read-only")
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66f961c956c36f3dd41d35933deaa61ac9f5f9c5b4b32438ae0af7bc3ddfb6b2
3
+ size 2788720
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_parser.pyx ADDED
@@ -0,0 +1,836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #cython: language_level=3
2
+ #
3
+ # Based on https://github.com/MagicStack/httptools
4
+ #
5
+
6
+ from cpython cimport (
7
+ Py_buffer,
8
+ PyBUF_SIMPLE,
9
+ PyBuffer_Release,
10
+ PyBytes_AsString,
11
+ PyBytes_AsStringAndSize,
12
+ PyObject_GetBuffer,
13
+ )
14
+ from cpython.mem cimport PyMem_Free, PyMem_Malloc
15
+ from libc.limits cimport ULLONG_MAX
16
+ from libc.string cimport memcpy
17
+
18
+ from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy
19
+ from yarl import URL as _URL
20
+
21
+ from aiohttp import hdrs
22
+ from aiohttp.helpers import DEBUG
23
+
24
+ from .http_exceptions import (
25
+ BadHttpMessage,
26
+ BadStatusLine,
27
+ ContentLengthError,
28
+ InvalidHeader,
29
+ InvalidURLError,
30
+ LineTooLong,
31
+ PayloadEncodingError,
32
+ TransferEncodingError,
33
+ )
34
+ from .http_parser import DeflateBuffer as _DeflateBuffer
35
+ from .http_writer import (
36
+ HttpVersion as _HttpVersion,
37
+ HttpVersion10 as _HttpVersion10,
38
+ HttpVersion11 as _HttpVersion11,
39
+ )
40
+ from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader
41
+
42
+ cimport cython
43
+
44
+ from aiohttp cimport _cparser as cparser
45
+
46
+ include "_headers.pxi"
47
+
48
+ from aiohttp cimport _find_header
49
+
50
+ DEF DEFAULT_FREELIST_SIZE = 250
51
+
52
+ cdef extern from "Python.h":
53
+ int PyByteArray_Resize(object, Py_ssize_t) except -1
54
+ Py_ssize_t PyByteArray_Size(object) except -1
55
+ char* PyByteArray_AsString(object)
56
+
57
+ __all__ = ('HttpRequestParser', 'HttpResponseParser',
58
+ 'RawRequestMessage', 'RawResponseMessage')
59
+
60
+ cdef object URL = _URL
61
+ cdef object URL_build = URL.build
62
+ cdef object CIMultiDict = _CIMultiDict
63
+ cdef object CIMultiDictProxy = _CIMultiDictProxy
64
+ cdef object HttpVersion = _HttpVersion
65
+ cdef object HttpVersion10 = _HttpVersion10
66
+ cdef object HttpVersion11 = _HttpVersion11
67
+ cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1
68
+ cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING
69
+ cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD
70
+ cdef object StreamReader = _StreamReader
71
+ cdef object DeflateBuffer = _DeflateBuffer
72
+
73
+
74
+ cdef inline object extend(object buf, const char* at, size_t length):
75
+ cdef Py_ssize_t s
76
+ cdef char* ptr
77
+ s = PyByteArray_Size(buf)
78
+ PyByteArray_Resize(buf, s + length)
79
+ ptr = PyByteArray_AsString(buf)
80
+ memcpy(ptr + s, at, length)
81
+
82
+
83
+ DEF METHODS_COUNT = 46;
84
+
85
+ cdef list _http_method = []
86
+
87
+ for i in range(METHODS_COUNT):
88
+ _http_method.append(
89
+ cparser.llhttp_method_name(<cparser.llhttp_method_t> i).decode('ascii'))
90
+
91
+
92
+ cdef inline str http_method_str(int i):
93
+ if i < METHODS_COUNT:
94
+ return <str>_http_method[i]
95
+ else:
96
+ return "<unknown>"
97
+
98
+ cdef inline object find_header(bytes raw_header):
99
+ cdef Py_ssize_t size
100
+ cdef char *buf
101
+ cdef int idx
102
+ PyBytes_AsStringAndSize(raw_header, &buf, &size)
103
+ idx = _find_header.find_header(buf, size)
104
+ if idx == -1:
105
+ return raw_header.decode('utf-8', 'surrogateescape')
106
+ return headers[idx]
107
+
108
+
109
+ @cython.freelist(DEFAULT_FREELIST_SIZE)
110
+ cdef class RawRequestMessage:
111
+ cdef readonly str method
112
+ cdef readonly str path
113
+ cdef readonly object version # HttpVersion
114
+ cdef readonly object headers # CIMultiDict
115
+ cdef readonly object raw_headers # tuple
116
+ cdef readonly object should_close
117
+ cdef readonly object compression
118
+ cdef readonly object upgrade
119
+ cdef readonly object chunked
120
+ cdef readonly object url # yarl.URL
121
+
122
+ def __init__(self, method, path, version, headers, raw_headers,
123
+ should_close, compression, upgrade, chunked, url):
124
+ self.method = method
125
+ self.path = path
126
+ self.version = version
127
+ self.headers = headers
128
+ self.raw_headers = raw_headers
129
+ self.should_close = should_close
130
+ self.compression = compression
131
+ self.upgrade = upgrade
132
+ self.chunked = chunked
133
+ self.url = url
134
+
135
+ def __repr__(self):
136
+ info = []
137
+ info.append(("method", self.method))
138
+ info.append(("path", self.path))
139
+ info.append(("version", self.version))
140
+ info.append(("headers", self.headers))
141
+ info.append(("raw_headers", self.raw_headers))
142
+ info.append(("should_close", self.should_close))
143
+ info.append(("compression", self.compression))
144
+ info.append(("upgrade", self.upgrade))
145
+ info.append(("chunked", self.chunked))
146
+ info.append(("url", self.url))
147
+ sinfo = ', '.join(name + '=' + repr(val) for name, val in info)
148
+ return '<RawRequestMessage(' + sinfo + ')>'
149
+
150
+ def _replace(self, **dct):
151
+ cdef RawRequestMessage ret
152
+ ret = _new_request_message(self.method,
153
+ self.path,
154
+ self.version,
155
+ self.headers,
156
+ self.raw_headers,
157
+ self.should_close,
158
+ self.compression,
159
+ self.upgrade,
160
+ self.chunked,
161
+ self.url)
162
+ if "method" in dct:
163
+ ret.method = dct["method"]
164
+ if "path" in dct:
165
+ ret.path = dct["path"]
166
+ if "version" in dct:
167
+ ret.version = dct["version"]
168
+ if "headers" in dct:
169
+ ret.headers = dct["headers"]
170
+ if "raw_headers" in dct:
171
+ ret.raw_headers = dct["raw_headers"]
172
+ if "should_close" in dct:
173
+ ret.should_close = dct["should_close"]
174
+ if "compression" in dct:
175
+ ret.compression = dct["compression"]
176
+ if "upgrade" in dct:
177
+ ret.upgrade = dct["upgrade"]
178
+ if "chunked" in dct:
179
+ ret.chunked = dct["chunked"]
180
+ if "url" in dct:
181
+ ret.url = dct["url"]
182
+ return ret
183
+
184
+ cdef _new_request_message(str method,
185
+ str path,
186
+ object version,
187
+ object headers,
188
+ object raw_headers,
189
+ bint should_close,
190
+ object compression,
191
+ bint upgrade,
192
+ bint chunked,
193
+ object url):
194
+ cdef RawRequestMessage ret
195
+ ret = RawRequestMessage.__new__(RawRequestMessage)
196
+ ret.method = method
197
+ ret.path = path
198
+ ret.version = version
199
+ ret.headers = headers
200
+ ret.raw_headers = raw_headers
201
+ ret.should_close = should_close
202
+ ret.compression = compression
203
+ ret.upgrade = upgrade
204
+ ret.chunked = chunked
205
+ ret.url = url
206
+ return ret
207
+
208
+
209
+ @cython.freelist(DEFAULT_FREELIST_SIZE)
210
+ cdef class RawResponseMessage:
211
+ cdef readonly object version # HttpVersion
212
+ cdef readonly int code
213
+ cdef readonly str reason
214
+ cdef readonly object headers # CIMultiDict
215
+ cdef readonly object raw_headers # tuple
216
+ cdef readonly object should_close
217
+ cdef readonly object compression
218
+ cdef readonly object upgrade
219
+ cdef readonly object chunked
220
+
221
+ def __init__(self, version, code, reason, headers, raw_headers,
222
+ should_close, compression, upgrade, chunked):
223
+ self.version = version
224
+ self.code = code
225
+ self.reason = reason
226
+ self.headers = headers
227
+ self.raw_headers = raw_headers
228
+ self.should_close = should_close
229
+ self.compression = compression
230
+ self.upgrade = upgrade
231
+ self.chunked = chunked
232
+
233
+ def __repr__(self):
234
+ info = []
235
+ info.append(("version", self.version))
236
+ info.append(("code", self.code))
237
+ info.append(("reason", self.reason))
238
+ info.append(("headers", self.headers))
239
+ info.append(("raw_headers", self.raw_headers))
240
+ info.append(("should_close", self.should_close))
241
+ info.append(("compression", self.compression))
242
+ info.append(("upgrade", self.upgrade))
243
+ info.append(("chunked", self.chunked))
244
+ sinfo = ', '.join(name + '=' + repr(val) for name, val in info)
245
+ return '<RawResponseMessage(' + sinfo + ')>'
246
+
247
+
248
+ cdef _new_response_message(object version,
249
+ int code,
250
+ str reason,
251
+ object headers,
252
+ object raw_headers,
253
+ bint should_close,
254
+ object compression,
255
+ bint upgrade,
256
+ bint chunked):
257
+ cdef RawResponseMessage ret
258
+ ret = RawResponseMessage.__new__(RawResponseMessage)
259
+ ret.version = version
260
+ ret.code = code
261
+ ret.reason = reason
262
+ ret.headers = headers
263
+ ret.raw_headers = raw_headers
264
+ ret.should_close = should_close
265
+ ret.compression = compression
266
+ ret.upgrade = upgrade
267
+ ret.chunked = chunked
268
+ return ret
269
+
270
+
271
+ @cython.internal
272
+ cdef class HttpParser:
273
+
274
+ cdef:
275
+ cparser.llhttp_t* _cparser
276
+ cparser.llhttp_settings_t* _csettings
277
+
278
+ bytearray _raw_name
279
+ bytearray _raw_value
280
+ bint _has_value
281
+
282
+ object _protocol
283
+ object _loop
284
+ object _timer
285
+
286
+ size_t _max_line_size
287
+ size_t _max_field_size
288
+ size_t _max_headers
289
+ bint _response_with_body
290
+ bint _read_until_eof
291
+
292
+ bint _started
293
+ object _url
294
+ bytearray _buf
295
+ str _path
296
+ str _reason
297
+ object _headers
298
+ list _raw_headers
299
+ bint _upgraded
300
+ list _messages
301
+ object _payload
302
+ bint _payload_error
303
+ object _payload_exception
304
+ object _last_error
305
+ bint _auto_decompress
306
+ int _limit
307
+
308
+ str _content_encoding
309
+
310
+ Py_buffer py_buf
311
+
312
+ def __cinit__(self):
313
+ self._cparser = <cparser.llhttp_t*> \
314
+ PyMem_Malloc(sizeof(cparser.llhttp_t))
315
+ if self._cparser is NULL:
316
+ raise MemoryError()
317
+
318
+ self._csettings = <cparser.llhttp_settings_t*> \
319
+ PyMem_Malloc(sizeof(cparser.llhttp_settings_t))
320
+ if self._csettings is NULL:
321
+ raise MemoryError()
322
+
323
+ def __dealloc__(self):
324
+ PyMem_Free(self._cparser)
325
+ PyMem_Free(self._csettings)
326
+
327
+ cdef _init(
328
+ self, cparser.llhttp_type mode,
329
+ object protocol, object loop, int limit,
330
+ object timer=None,
331
+ size_t max_line_size=8190, size_t max_headers=32768,
332
+ size_t max_field_size=8190, payload_exception=None,
333
+ bint response_with_body=True, bint read_until_eof=False,
334
+ bint auto_decompress=True,
335
+ ):
336
+ cparser.llhttp_settings_init(self._csettings)
337
+ cparser.llhttp_init(self._cparser, mode, self._csettings)
338
+ self._cparser.data = <void*>self
339
+ self._cparser.content_length = 0
340
+
341
+ self._protocol = protocol
342
+ self._loop = loop
343
+ self._timer = timer
344
+
345
+ self._buf = bytearray()
346
+ self._payload = None
347
+ self._payload_error = 0
348
+ self._payload_exception = payload_exception
349
+ self._messages = []
350
+
351
+ self._raw_name = bytearray()
352
+ self._raw_value = bytearray()
353
+ self._has_value = False
354
+
355
+ self._max_line_size = max_line_size
356
+ self._max_headers = max_headers
357
+ self._max_field_size = max_field_size
358
+ self._response_with_body = response_with_body
359
+ self._read_until_eof = read_until_eof
360
+ self._upgraded = False
361
+ self._auto_decompress = auto_decompress
362
+ self._content_encoding = None
363
+
364
+ self._csettings.on_url = cb_on_url
365
+ self._csettings.on_status = cb_on_status
366
+ self._csettings.on_header_field = cb_on_header_field
367
+ self._csettings.on_header_value = cb_on_header_value
368
+ self._csettings.on_headers_complete = cb_on_headers_complete
369
+ self._csettings.on_body = cb_on_body
370
+ self._csettings.on_message_begin = cb_on_message_begin
371
+ self._csettings.on_message_complete = cb_on_message_complete
372
+ self._csettings.on_chunk_header = cb_on_chunk_header
373
+ self._csettings.on_chunk_complete = cb_on_chunk_complete
374
+
375
+ self._last_error = None
376
+ self._limit = limit
377
+
378
+ cdef _process_header(self):
379
+ if self._raw_name:
380
+ raw_name = bytes(self._raw_name)
381
+ raw_value = bytes(self._raw_value)
382
+
383
+ name = find_header(raw_name)
384
+ value = raw_value.decode('utf-8', 'surrogateescape')
385
+
386
+ self._headers.add(name, value)
387
+
388
+ if name is CONTENT_ENCODING:
389
+ self._content_encoding = value
390
+
391
+ PyByteArray_Resize(self._raw_name, 0)
392
+ PyByteArray_Resize(self._raw_value, 0)
393
+ self._has_value = False
394
+ self._raw_headers.append((raw_name, raw_value))
395
+
396
+ cdef _on_header_field(self, char* at, size_t length):
397
+ cdef Py_ssize_t size
398
+ cdef char *buf
399
+ if self._has_value:
400
+ self._process_header()
401
+
402
+ size = PyByteArray_Size(self._raw_name)
403
+ PyByteArray_Resize(self._raw_name, size + length)
404
+ buf = PyByteArray_AsString(self._raw_name)
405
+ memcpy(buf + size, at, length)
406
+
407
+ cdef _on_header_value(self, char* at, size_t length):
408
+ cdef Py_ssize_t size
409
+ cdef char *buf
410
+
411
+ size = PyByteArray_Size(self._raw_value)
412
+ PyByteArray_Resize(self._raw_value, size + length)
413
+ buf = PyByteArray_AsString(self._raw_value)
414
+ memcpy(buf + size, at, length)
415
+ self._has_value = True
416
+
417
+ cdef _on_headers_complete(self):
418
+ self._process_header()
419
+
420
+ method = http_method_str(self._cparser.method)
421
+ should_close = not cparser.llhttp_should_keep_alive(self._cparser)
422
+ upgrade = self._cparser.upgrade
423
+ chunked = self._cparser.flags & cparser.F_CHUNKED
424
+
425
+ raw_headers = tuple(self._raw_headers)
426
+ headers = CIMultiDictProxy(self._headers)
427
+
428
+ if upgrade or self._cparser.method == cparser.HTTP_CONNECT:
429
+ self._upgraded = True
430
+
431
+ # do not support old websocket spec
432
+ if SEC_WEBSOCKET_KEY1 in headers:
433
+ raise InvalidHeader(SEC_WEBSOCKET_KEY1)
434
+
435
+ encoding = None
436
+ enc = self._content_encoding
437
+ if enc is not None:
438
+ self._content_encoding = None
439
+ enc = enc.lower()
440
+ if enc in ('gzip', 'deflate', 'br'):
441
+ encoding = enc
442
+
443
+ if self._cparser.type == cparser.HTTP_REQUEST:
444
+ msg = _new_request_message(
445
+ method, self._path,
446
+ self.http_version(), headers, raw_headers,
447
+ should_close, encoding, upgrade, chunked, self._url)
448
+ else:
449
+ msg = _new_response_message(
450
+ self.http_version(), self._cparser.status_code, self._reason,
451
+ headers, raw_headers, should_close, encoding,
452
+ upgrade, chunked)
453
+
454
+ if (
455
+ ULLONG_MAX > self._cparser.content_length > 0 or chunked or
456
+ self._cparser.method == cparser.HTTP_CONNECT or
457
+ (self._cparser.status_code >= 199 and
458
+ self._cparser.content_length == 0 and
459
+ self._read_until_eof)
460
+ ):
461
+ payload = StreamReader(
462
+ self._protocol, timer=self._timer, loop=self._loop,
463
+ limit=self._limit)
464
+ else:
465
+ payload = EMPTY_PAYLOAD
466
+
467
+ self._payload = payload
468
+ if encoding is not None and self._auto_decompress:
469
+ self._payload = DeflateBuffer(payload, encoding)
470
+
471
+ if not self._response_with_body:
472
+ payload = EMPTY_PAYLOAD
473
+
474
+ self._messages.append((msg, payload))
475
+
476
+ cdef _on_message_complete(self):
477
+ self._payload.feed_eof()
478
+ self._payload = None
479
+
480
+ cdef _on_chunk_header(self):
481
+ self._payload.begin_http_chunk_receiving()
482
+
483
+ cdef _on_chunk_complete(self):
484
+ self._payload.end_http_chunk_receiving()
485
+
486
+ cdef object _on_status_complete(self):
487
+ pass
488
+
489
+ cdef inline http_version(self):
490
+ cdef cparser.llhttp_t* parser = self._cparser
491
+
492
+ if parser.http_major == 1:
493
+ if parser.http_minor == 0:
494
+ return HttpVersion10
495
+ elif parser.http_minor == 1:
496
+ return HttpVersion11
497
+
498
+ return HttpVersion(parser.http_major, parser.http_minor)
499
+
500
+ ### Public API ###
501
+
502
+ def feed_eof(self):
503
+ cdef bytes desc
504
+
505
+ if self._payload is not None:
506
+ if self._cparser.flags & cparser.F_CHUNKED:
507
+ raise TransferEncodingError(
508
+ "Not enough data for satisfy transfer length header.")
509
+ elif self._cparser.flags & cparser.F_CONTENT_LENGTH:
510
+ raise ContentLengthError(
511
+ "Not enough data for satisfy content length header.")
512
+ elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK:
513
+ desc = cparser.llhttp_get_error_reason(self._cparser)
514
+ raise PayloadEncodingError(desc.decode('latin-1'))
515
+ else:
516
+ self._payload.feed_eof()
517
+ elif self._started:
518
+ self._on_headers_complete()
519
+ if self._messages:
520
+ return self._messages[-1][0]
521
+
522
+ def feed_data(self, data):
523
+ cdef:
524
+ size_t data_len
525
+ size_t nb
526
+ cdef cparser.llhttp_errno_t errno
527
+
528
+ PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE)
529
+ data_len = <size_t>self.py_buf.len
530
+
531
+ errno = cparser.llhttp_execute(
532
+ self._cparser,
533
+ <char*>self.py_buf.buf,
534
+ data_len)
535
+
536
+ if errno is cparser.HPE_PAUSED_UPGRADE:
537
+ cparser.llhttp_resume_after_upgrade(self._cparser)
538
+
539
+ nb = cparser.llhttp_get_error_pos(self._cparser) - <char*>self.py_buf.buf
540
+
541
+ PyBuffer_Release(&self.py_buf)
542
+
543
+ if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE):
544
+ if self._payload_error == 0:
545
+ if self._last_error is not None:
546
+ ex = self._last_error
547
+ self._last_error = None
548
+ else:
549
+ after = cparser.llhttp_get_error_pos(self._cparser)
550
+ before = data[:after - <char*>self.py_buf.buf]
551
+ after_b = after.split(b"\r\n", 1)[0]
552
+ before = before.rsplit(b"\r\n", 1)[-1]
553
+ data = before + after_b
554
+ pointer = " " * (len(repr(before))-1) + "^"
555
+ ex = parser_error_from_errno(self._cparser, data, pointer)
556
+ self._payload = None
557
+ raise ex
558
+
559
+ if self._messages:
560
+ messages = self._messages
561
+ self._messages = []
562
+ else:
563
+ messages = ()
564
+
565
+ if self._upgraded:
566
+ return messages, True, data[nb:]
567
+ else:
568
+ return messages, False, b''
569
+
570
+ def set_upgraded(self, val):
571
+ self._upgraded = val
572
+
573
+
574
+ cdef class HttpRequestParser(HttpParser):
575
+
576
+ def __init__(
577
+ self, protocol, loop, int limit, timer=None,
578
+ size_t max_line_size=8190, size_t max_headers=32768,
579
+ size_t max_field_size=8190, payload_exception=None,
580
+ bint response_with_body=True, bint read_until_eof=False,
581
+ bint auto_decompress=True,
582
+ ):
583
+ self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer,
584
+ max_line_size, max_headers, max_field_size,
585
+ payload_exception, response_with_body, read_until_eof,
586
+ auto_decompress)
587
+
588
+ cdef object _on_status_complete(self):
589
+ cdef int idx1, idx2
590
+ if not self._buf:
591
+ return
592
+ self._path = self._buf.decode('utf-8', 'surrogateescape')
593
+ try:
594
+ idx3 = len(self._path)
595
+ if self._cparser.method == cparser.HTTP_CONNECT:
596
+ # authority-form,
597
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
598
+ self._url = URL.build(authority=self._path, encoded=True)
599
+ elif idx3 > 1 and self._path[0] == '/':
600
+ # origin-form,
601
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
602
+ idx1 = self._path.find("?")
603
+ if idx1 == -1:
604
+ query = ""
605
+ idx2 = self._path.find("#")
606
+ if idx2 == -1:
607
+ path = self._path
608
+ fragment = ""
609
+ else:
610
+ path = self._path[0: idx2]
611
+ fragment = self._path[idx2+1:]
612
+
613
+ else:
614
+ path = self._path[0:idx1]
615
+ idx1 += 1
616
+ idx2 = self._path.find("#", idx1+1)
617
+ if idx2 == -1:
618
+ query = self._path[idx1:]
619
+ fragment = ""
620
+ else:
621
+ query = self._path[idx1: idx2]
622
+ fragment = self._path[idx2+1:]
623
+
624
+ self._url = URL.build(
625
+ path=path,
626
+ query_string=query,
627
+ fragment=fragment,
628
+ encoded=True,
629
+ )
630
+ else:
631
+ # absolute-form for proxy maybe,
632
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
633
+ self._url = URL(self._path, encoded=True)
634
+ finally:
635
+ PyByteArray_Resize(self._buf, 0)
636
+
637
+
638
+ cdef class HttpResponseParser(HttpParser):
639
+
640
+ def __init__(
641
+ self, protocol, loop, int limit, timer=None,
642
+ size_t max_line_size=8190, size_t max_headers=32768,
643
+ size_t max_field_size=8190, payload_exception=None,
644
+ bint response_with_body=True, bint read_until_eof=False,
645
+ bint auto_decompress=True
646
+ ):
647
+ self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer,
648
+ max_line_size, max_headers, max_field_size,
649
+ payload_exception, response_with_body, read_until_eof,
650
+ auto_decompress)
651
+ # Use strict parsing on dev mode, so users are warned about broken servers.
652
+ if not DEBUG:
653
+ cparser.llhttp_set_lenient_headers(self._cparser, 1)
654
+ cparser.llhttp_set_lenient_optional_cr_before_lf(self._cparser, 1)
655
+ cparser.llhttp_set_lenient_spaces_after_chunk_size(self._cparser, 1)
656
+
657
+ cdef object _on_status_complete(self):
658
+ if self._buf:
659
+ self._reason = self._buf.decode('utf-8', 'surrogateescape')
660
+ PyByteArray_Resize(self._buf, 0)
661
+ else:
662
+ self._reason = self._reason or ''
663
+
664
+ cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1:
665
+ cdef HttpParser pyparser = <HttpParser>parser.data
666
+
667
+ pyparser._started = True
668
+ pyparser._headers = CIMultiDict()
669
+ pyparser._raw_headers = []
670
+ PyByteArray_Resize(pyparser._buf, 0)
671
+ pyparser._path = None
672
+ pyparser._reason = None
673
+ return 0
674
+
675
+
676
+ cdef int cb_on_url(cparser.llhttp_t* parser,
677
+ const char *at, size_t length) except -1:
678
+ cdef HttpParser pyparser = <HttpParser>parser.data
679
+ try:
680
+ if length > pyparser._max_line_size:
681
+ raise LineTooLong(
682
+ 'Status line is too long', pyparser._max_line_size, length)
683
+ extend(pyparser._buf, at, length)
684
+ except BaseException as ex:
685
+ pyparser._last_error = ex
686
+ return -1
687
+ else:
688
+ return 0
689
+
690
+
691
+ cdef int cb_on_status(cparser.llhttp_t* parser,
692
+ const char *at, size_t length) except -1:
693
+ cdef HttpParser pyparser = <HttpParser>parser.data
694
+ cdef str reason
695
+ try:
696
+ if length > pyparser._max_line_size:
697
+ raise LineTooLong(
698
+ 'Status line is too long', pyparser._max_line_size, length)
699
+ extend(pyparser._buf, at, length)
700
+ except BaseException as ex:
701
+ pyparser._last_error = ex
702
+ return -1
703
+ else:
704
+ return 0
705
+
706
+
707
+ cdef int cb_on_header_field(cparser.llhttp_t* parser,
708
+ const char *at, size_t length) except -1:
709
+ cdef HttpParser pyparser = <HttpParser>parser.data
710
+ cdef Py_ssize_t size
711
+ try:
712
+ pyparser._on_status_complete()
713
+ size = len(pyparser._raw_name) + length
714
+ if size > pyparser._max_field_size:
715
+ raise LineTooLong(
716
+ 'Header name is too long', pyparser._max_field_size, size)
717
+ pyparser._on_header_field(at, length)
718
+ except BaseException as ex:
719
+ pyparser._last_error = ex
720
+ return -1
721
+ else:
722
+ return 0
723
+
724
+
725
+ cdef int cb_on_header_value(cparser.llhttp_t* parser,
726
+ const char *at, size_t length) except -1:
727
+ cdef HttpParser pyparser = <HttpParser>parser.data
728
+ cdef Py_ssize_t size
729
+ try:
730
+ size = len(pyparser._raw_value) + length
731
+ if size > pyparser._max_field_size:
732
+ raise LineTooLong(
733
+ 'Header value is too long', pyparser._max_field_size, size)
734
+ pyparser._on_header_value(at, length)
735
+ except BaseException as ex:
736
+ pyparser._last_error = ex
737
+ return -1
738
+ else:
739
+ return 0
740
+
741
+
742
+ cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1:
743
+ cdef HttpParser pyparser = <HttpParser>parser.data
744
+ try:
745
+ pyparser._on_status_complete()
746
+ pyparser._on_headers_complete()
747
+ except BaseException as exc:
748
+ pyparser._last_error = exc
749
+ return -1
750
+ else:
751
+ if (
752
+ pyparser._cparser.upgrade or
753
+ pyparser._cparser.method == cparser.HTTP_CONNECT
754
+ ):
755
+ return 2
756
+ else:
757
+ return 0
758
+
759
+
760
+ cdef int cb_on_body(cparser.llhttp_t* parser,
761
+ const char *at, size_t length) except -1:
762
+ cdef HttpParser pyparser = <HttpParser>parser.data
763
+ cdef bytes body = at[:length]
764
+ try:
765
+ pyparser._payload.feed_data(body, length)
766
+ except BaseException as exc:
767
+ if pyparser._payload_exception is not None:
768
+ pyparser._payload.set_exception(pyparser._payload_exception(str(exc)))
769
+ else:
770
+ pyparser._payload.set_exception(exc)
771
+ pyparser._payload_error = 1
772
+ return -1
773
+ else:
774
+ return 0
775
+
776
+
777
+ cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1:
778
+ cdef HttpParser pyparser = <HttpParser>parser.data
779
+ try:
780
+ pyparser._started = False
781
+ pyparser._on_message_complete()
782
+ except BaseException as exc:
783
+ pyparser._last_error = exc
784
+ return -1
785
+ else:
786
+ return 0
787
+
788
+
789
+ cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1:
790
+ cdef HttpParser pyparser = <HttpParser>parser.data
791
+ try:
792
+ pyparser._on_chunk_header()
793
+ except BaseException as exc:
794
+ pyparser._last_error = exc
795
+ return -1
796
+ else:
797
+ return 0
798
+
799
+
800
+ cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1:
801
+ cdef HttpParser pyparser = <HttpParser>parser.data
802
+ try:
803
+ pyparser._on_chunk_complete()
804
+ except BaseException as exc:
805
+ pyparser._last_error = exc
806
+ return -1
807
+ else:
808
+ return 0
809
+
810
+
811
+ cdef parser_error_from_errno(cparser.llhttp_t* parser, data, pointer):
812
+ cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser)
813
+ cdef bytes desc = cparser.llhttp_get_error_reason(parser)
814
+
815
+ err_msg = "{}:\n\n {!r}\n {}".format(desc.decode("latin-1"), data, pointer)
816
+
817
+ if errno in {cparser.HPE_CB_MESSAGE_BEGIN,
818
+ cparser.HPE_CB_HEADERS_COMPLETE,
819
+ cparser.HPE_CB_MESSAGE_COMPLETE,
820
+ cparser.HPE_CB_CHUNK_HEADER,
821
+ cparser.HPE_CB_CHUNK_COMPLETE,
822
+ cparser.HPE_INVALID_CONSTANT,
823
+ cparser.HPE_INVALID_HEADER_TOKEN,
824
+ cparser.HPE_INVALID_CONTENT_LENGTH,
825
+ cparser.HPE_INVALID_CHUNK_SIZE,
826
+ cparser.HPE_INVALID_EOF_STATE,
827
+ cparser.HPE_INVALID_TRANSFER_ENCODING}:
828
+ return BadHttpMessage(err_msg)
829
+ elif errno in {cparser.HPE_INVALID_STATUS,
830
+ cparser.HPE_INVALID_METHOD,
831
+ cparser.HPE_INVALID_VERSION}:
832
+ return BadStatusLine(error=err_msg)
833
+ elif errno == cparser.HPE_INVALID_URL:
834
+ return InvalidURLError(err_msg)
835
+
836
+ return BadHttpMessage(err_msg)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36023b950a22839c52bcd18515d1c8dd92694b67a6bbdce3efcc8e7b52e060a1
3
+ size 503128
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_http_writer.pyx ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cpython.bytes cimport PyBytes_FromStringAndSize
2
+ from cpython.exc cimport PyErr_NoMemory
3
+ from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc
4
+ from cpython.object cimport PyObject_Str
5
+ from libc.stdint cimport uint8_t, uint64_t
6
+ from libc.string cimport memcpy
7
+
8
+ from multidict import istr
9
+
10
+ DEF BUF_SIZE = 16 * 1024 # 16KiB
11
+ cdef char BUFFER[BUF_SIZE]
12
+
13
+ cdef object _istr = istr
14
+
15
+
16
+ # ----------------- writer ---------------------------
17
+
18
+ cdef struct Writer:
19
+ char *buf
20
+ Py_ssize_t size
21
+ Py_ssize_t pos
22
+
23
+
24
+ cdef inline void _init_writer(Writer* writer):
25
+ writer.buf = &BUFFER[0]
26
+ writer.size = BUF_SIZE
27
+ writer.pos = 0
28
+
29
+
30
+ cdef inline void _release_writer(Writer* writer):
31
+ if writer.buf != BUFFER:
32
+ PyMem_Free(writer.buf)
33
+
34
+
35
+ cdef inline int _write_byte(Writer* writer, uint8_t ch):
36
+ cdef char * buf
37
+ cdef Py_ssize_t size
38
+
39
+ if writer.pos == writer.size:
40
+ # reallocate
41
+ size = writer.size + BUF_SIZE
42
+ if writer.buf == BUFFER:
43
+ buf = <char*>PyMem_Malloc(size)
44
+ if buf == NULL:
45
+ PyErr_NoMemory()
46
+ return -1
47
+ memcpy(buf, writer.buf, writer.size)
48
+ else:
49
+ buf = <char*>PyMem_Realloc(writer.buf, size)
50
+ if buf == NULL:
51
+ PyErr_NoMemory()
52
+ return -1
53
+ writer.buf = buf
54
+ writer.size = size
55
+ writer.buf[writer.pos] = <char>ch
56
+ writer.pos += 1
57
+ return 0
58
+
59
+
60
+ cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol):
61
+ cdef uint64_t utf = <uint64_t> symbol
62
+
63
+ if utf < 0x80:
64
+ return _write_byte(writer, <uint8_t>utf)
65
+ elif utf < 0x800:
66
+ if _write_byte(writer, <uint8_t>(0xc0 | (utf >> 6))) < 0:
67
+ return -1
68
+ return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
69
+ elif 0xD800 <= utf <= 0xDFFF:
70
+ # surogate pair, ignored
71
+ return 0
72
+ elif utf < 0x10000:
73
+ if _write_byte(writer, <uint8_t>(0xe0 | (utf >> 12))) < 0:
74
+ return -1
75
+ if _write_byte(writer, <uint8_t>(0x80 | ((utf >> 6) & 0x3f))) < 0:
76
+ return -1
77
+ return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
78
+ elif utf > 0x10FFFF:
79
+ # symbol is too large
80
+ return 0
81
+ else:
82
+ if _write_byte(writer, <uint8_t>(0xf0 | (utf >> 18))) < 0:
83
+ return -1
84
+ if _write_byte(writer,
85
+ <uint8_t>(0x80 | ((utf >> 12) & 0x3f))) < 0:
86
+ return -1
87
+ if _write_byte(writer,
88
+ <uint8_t>(0x80 | ((utf >> 6) & 0x3f))) < 0:
89
+ return -1
90
+ return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
91
+
92
+
93
+ cdef inline int _write_str(Writer* writer, str s):
94
+ cdef Py_UCS4 ch
95
+ for ch in s:
96
+ if _write_utf8(writer, ch) < 0:
97
+ return -1
98
+
99
+
100
+ # --------------- _serialize_headers ----------------------
101
+
102
+ cdef str to_str(object s):
103
+ typ = type(s)
104
+ if typ is str:
105
+ return <str>s
106
+ elif typ is _istr:
107
+ return PyObject_Str(s)
108
+ elif not isinstance(s, str):
109
+ raise TypeError("Cannot serialize non-str key {!r}".format(s))
110
+ else:
111
+ return str(s)
112
+
113
+
114
+ cdef void _safe_header(str string) except *:
115
+ if "\r" in string or "\n" in string:
116
+ raise ValueError(
117
+ "Newline or carriage return character detected in HTTP status message or "
118
+ "header. This is a potential security issue."
119
+ )
120
+
121
+
122
+ def _serialize_headers(str status_line, headers):
123
+ cdef Writer writer
124
+ cdef object key
125
+ cdef object val
126
+ cdef bytes ret
127
+
128
+ _init_writer(&writer)
129
+
130
+ for key, val in headers.items():
131
+ _safe_header(to_str(key))
132
+ _safe_header(to_str(val))
133
+
134
+ try:
135
+ if _write_str(&writer, status_line) < 0:
136
+ raise
137
+ if _write_byte(&writer, b'\r') < 0:
138
+ raise
139
+ if _write_byte(&writer, b'\n') < 0:
140
+ raise
141
+
142
+ for key, val in headers.items():
143
+ if _write_str(&writer, to_str(key)) < 0:
144
+ raise
145
+ if _write_byte(&writer, b':') < 0:
146
+ raise
147
+ if _write_byte(&writer, b' ') < 0:
148
+ raise
149
+ if _write_str(&writer, to_str(val)) < 0:
150
+ raise
151
+ if _write_byte(&writer, b'\r') < 0:
152
+ raise
153
+ if _write_byte(&writer, b'\n') < 0:
154
+ raise
155
+
156
+ if _write_byte(&writer, b'\r') < 0:
157
+ raise
158
+ if _write_byte(&writer, b'\n') < 0:
159
+ raise
160
+
161
+ return PyBytes_FromStringAndSize(writer.buf, writer.pos)
162
+ finally:
163
+ _release_writer(&writer)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_websocket.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7378ab0eb952b514cef717c1f784f629090eff5edd318359fbdf8992e7c21fa4
3
+ size 278168
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/_websocket.pyx ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cpython cimport PyBytes_AsString
2
+
3
+
4
+ #from cpython cimport PyByteArray_AsString # cython still not exports that
5
+ cdef extern from "Python.h":
6
+ char* PyByteArray_AsString(bytearray ba) except NULL
7
+
8
+ from libc.stdint cimport uint32_t, uint64_t, uintmax_t
9
+
10
+
11
+ def _websocket_mask_cython(object mask, object data):
12
+ """Note, this function mutates its `data` argument
13
+ """
14
+ cdef:
15
+ Py_ssize_t data_len, i
16
+ # bit operations on signed integers are implementation-specific
17
+ unsigned char * in_buf
18
+ const unsigned char * mask_buf
19
+ uint32_t uint32_msk
20
+ uint64_t uint64_msk
21
+
22
+ assert len(mask) == 4
23
+
24
+ if not isinstance(mask, bytes):
25
+ mask = bytes(mask)
26
+
27
+ if isinstance(data, bytearray):
28
+ data = <bytearray>data
29
+ else:
30
+ data = bytearray(data)
31
+
32
+ data_len = len(data)
33
+ in_buf = <unsigned char*>PyByteArray_AsString(data)
34
+ mask_buf = <const unsigned char*>PyBytes_AsString(mask)
35
+ uint32_msk = (<uint32_t*>mask_buf)[0]
36
+
37
+ # TODO: align in_data ptr to achieve even faster speeds
38
+ # does it need in python ?! malloc() always aligns to sizeof(long) bytes
39
+
40
+ if sizeof(size_t) >= 8:
41
+ uint64_msk = uint32_msk
42
+ uint64_msk = (uint64_msk << 32) | uint32_msk
43
+
44
+ while data_len >= 8:
45
+ (<uint64_t*>in_buf)[0] ^= uint64_msk
46
+ in_buf += 8
47
+ data_len -= 8
48
+
49
+
50
+ while data_len >= 4:
51
+ (<uint32_t*>in_buf)[0] ^= uint32_msk
52
+ in_buf += 4
53
+ data_len -= 4
54
+
55
+ for i in range(0, data_len):
56
+ in_buf[i] ^= mask_buf[i]
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/abc.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Sized
5
+ from http.cookies import BaseCookie, Morsel
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ Awaitable,
10
+ Callable,
11
+ Dict,
12
+ Generator,
13
+ Iterable,
14
+ List,
15
+ Optional,
16
+ Tuple,
17
+ )
18
+
19
+ from multidict import CIMultiDict
20
+ from yarl import URL
21
+
22
+ from .helpers import get_running_loop
23
+ from .typedefs import LooseCookies
24
+
25
+ if TYPE_CHECKING: # pragma: no cover
26
+ from .web_app import Application
27
+ from .web_exceptions import HTTPException
28
+ from .web_request import BaseRequest, Request
29
+ from .web_response import StreamResponse
30
+ else:
31
+ BaseRequest = Request = Application = StreamResponse = None
32
+ HTTPException = None
33
+
34
+
35
+ class AbstractRouter(ABC):
36
+ def __init__(self) -> None:
37
+ self._frozen = False
38
+
39
+ def post_init(self, app: Application) -> None:
40
+ """Post init stage.
41
+
42
+ Not an abstract method for sake of backward compatibility,
43
+ but if the router wants to be aware of the application
44
+ it can override this.
45
+ """
46
+
47
+ @property
48
+ def frozen(self) -> bool:
49
+ return self._frozen
50
+
51
+ def freeze(self) -> None:
52
+ """Freeze router."""
53
+ self._frozen = True
54
+
55
+ @abstractmethod
56
+ async def resolve(self, request: Request) -> "AbstractMatchInfo":
57
+ """Return MATCH_INFO for given request"""
58
+
59
+
60
+ class AbstractMatchInfo(ABC):
61
+ @property # pragma: no branch
62
+ @abstractmethod
63
+ def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]:
64
+ """Execute matched request handler"""
65
+
66
+ @property
67
+ @abstractmethod
68
+ def expect_handler(
69
+ self,
70
+ ) -> Callable[[Request], Awaitable[Optional[StreamResponse]]]:
71
+ """Expect handler for 100-continue processing"""
72
+
73
+ @property # pragma: no branch
74
+ @abstractmethod
75
+ def http_exception(self) -> Optional[HTTPException]:
76
+ """HTTPException instance raised on router's resolving, or None"""
77
+
78
+ @abstractmethod # pragma: no branch
79
+ def get_info(self) -> Dict[str, Any]:
80
+ """Return a dict with additional info useful for introspection"""
81
+
82
+ @property # pragma: no branch
83
+ @abstractmethod
84
+ def apps(self) -> Tuple[Application, ...]:
85
+ """Stack of nested applications.
86
+
87
+ Top level application is left-most element.
88
+
89
+ """
90
+
91
+ @abstractmethod
92
+ def add_app(self, app: Application) -> None:
93
+ """Add application to the nested apps stack."""
94
+
95
+ @abstractmethod
96
+ def freeze(self) -> None:
97
+ """Freeze the match info.
98
+
99
+ The method is called after route resolution.
100
+
101
+ After the call .add_app() is forbidden.
102
+
103
+ """
104
+
105
+
106
+ class AbstractView(ABC):
107
+ """Abstract class based view."""
108
+
109
+ def __init__(self, request: Request) -> None:
110
+ self._request = request
111
+
112
+ @property
113
+ def request(self) -> Request:
114
+ """Request instance."""
115
+ return self._request
116
+
117
+ @abstractmethod
118
+ def __await__(self) -> Generator[Any, None, StreamResponse]:
119
+ """Execute the view handler."""
120
+
121
+
122
+ class AbstractResolver(ABC):
123
+ """Abstract DNS resolver."""
124
+
125
+ @abstractmethod
126
+ async def resolve(self, host: str, port: int, family: int) -> List[Dict[str, Any]]:
127
+ """Return IP address for given hostname"""
128
+
129
+ @abstractmethod
130
+ async def close(self) -> None:
131
+ """Release resolver"""
132
+
133
+
134
+ if TYPE_CHECKING: # pragma: no cover
135
+ IterableBase = Iterable[Morsel[str]]
136
+ else:
137
+ IterableBase = Iterable
138
+
139
+
140
+ ClearCookiePredicate = Callable[["Morsel[str]"], bool]
141
+
142
+
143
+ class AbstractCookieJar(Sized, IterableBase):
144
+ """Abstract Cookie Jar."""
145
+
146
+ def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
147
+ self._loop = get_running_loop(loop)
148
+
149
+ @abstractmethod
150
+ def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
151
+ """Clear all cookies if no predicate is passed."""
152
+
153
+ @abstractmethod
154
+ def clear_domain(self, domain: str) -> None:
155
+ """Clear all cookies for domain and all subdomains."""
156
+
157
+ @abstractmethod
158
+ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
159
+ """Update cookies."""
160
+
161
+ @abstractmethod
162
+ def filter_cookies(self, request_url: URL) -> "BaseCookie[str]":
163
+ """Return the jar's cookies filtered by their attributes."""
164
+
165
+
166
+ class AbstractStreamWriter(ABC):
167
+ """Abstract stream writer."""
168
+
169
+ buffer_size = 0
170
+ output_size = 0
171
+ length: Optional[int] = 0
172
+
173
+ @abstractmethod
174
+ async def write(self, chunk: bytes) -> None:
175
+ """Write chunk into stream."""
176
+
177
+ @abstractmethod
178
+ async def write_eof(self, chunk: bytes = b"") -> None:
179
+ """Write last chunk."""
180
+
181
+ @abstractmethod
182
+ async def drain(self) -> None:
183
+ """Flush the write buffer."""
184
+
185
+ @abstractmethod
186
+ def enable_compression(self, encoding: str = "deflate") -> None:
187
+ """Enable HTTP body compression"""
188
+
189
+ @abstractmethod
190
+ def enable_chunking(self) -> None:
191
+ """Enable HTTP chunked mode"""
192
+
193
+ @abstractmethod
194
+ async def write_headers(
195
+ self, status_line: str, headers: "CIMultiDict[str]"
196
+ ) -> None:
197
+ """Write HTTP headers"""
198
+
199
+
200
+ class AbstractAccessLogger(ABC):
201
+ """Abstract writer to access log."""
202
+
203
+ def __init__(self, logger: logging.Logger, log_format: str) -> None:
204
+ self.logger = logger
205
+ self.log_format = log_format
206
+
207
+ @abstractmethod
208
+ def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None:
209
+ """Emit log to logger."""
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/base_protocol.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import Optional, cast
3
+
4
+ from .tcp_helpers import tcp_nodelay
5
+
6
+
7
+ class BaseProtocol(asyncio.Protocol):
8
+ __slots__ = (
9
+ "_loop",
10
+ "_paused",
11
+ "_drain_waiter",
12
+ "_connection_lost",
13
+ "_reading_paused",
14
+ "transport",
15
+ )
16
+
17
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
18
+ self._loop: asyncio.AbstractEventLoop = loop
19
+ self._paused = False
20
+ self._drain_waiter: Optional[asyncio.Future[None]] = None
21
+ self._reading_paused = False
22
+
23
+ self.transport: Optional[asyncio.Transport] = None
24
+
25
+ @property
26
+ def connected(self) -> bool:
27
+ """Return True if the connection is open."""
28
+ return self.transport is not None
29
+
30
+ def pause_writing(self) -> None:
31
+ assert not self._paused
32
+ self._paused = True
33
+
34
+ def resume_writing(self) -> None:
35
+ assert self._paused
36
+ self._paused = False
37
+
38
+ waiter = self._drain_waiter
39
+ if waiter is not None:
40
+ self._drain_waiter = None
41
+ if not waiter.done():
42
+ waiter.set_result(None)
43
+
44
+ def pause_reading(self) -> None:
45
+ if not self._reading_paused and self.transport is not None:
46
+ try:
47
+ self.transport.pause_reading()
48
+ except (AttributeError, NotImplementedError, RuntimeError):
49
+ pass
50
+ self._reading_paused = True
51
+
52
+ def resume_reading(self) -> None:
53
+ if self._reading_paused and self.transport is not None:
54
+ try:
55
+ self.transport.resume_reading()
56
+ except (AttributeError, NotImplementedError, RuntimeError):
57
+ pass
58
+ self._reading_paused = False
59
+
60
+ def connection_made(self, transport: asyncio.BaseTransport) -> None:
61
+ tr = cast(asyncio.Transport, transport)
62
+ tcp_nodelay(tr, True)
63
+ self.transport = tr
64
+
65
+ def connection_lost(self, exc: Optional[BaseException]) -> None:
66
+ # Wake up the writer if currently paused.
67
+ self.transport = None
68
+ if not self._paused:
69
+ return
70
+ waiter = self._drain_waiter
71
+ if waiter is None:
72
+ return
73
+ self._drain_waiter = None
74
+ if waiter.done():
75
+ return
76
+ if exc is None:
77
+ waiter.set_result(None)
78
+ else:
79
+ waiter.set_exception(exc)
80
+
81
+ async def _drain_helper(self) -> None:
82
+ if not self.connected:
83
+ raise ConnectionResetError("Connection lost")
84
+ if not self._paused:
85
+ return
86
+ waiter = self._drain_waiter
87
+ if waiter is None:
88
+ waiter = self._loop.create_future()
89
+ self._drain_waiter = waiter
90
+ await asyncio.shield(waiter)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client.py ADDED
@@ -0,0 +1,1356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP Client for asyncio."""
2
+
3
+ import asyncio
4
+ import base64
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import sys
9
+ import traceback
10
+ import warnings
11
+ from contextlib import suppress
12
+ from types import SimpleNamespace, TracebackType
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Awaitable,
17
+ Callable,
18
+ Coroutine,
19
+ Final,
20
+ FrozenSet,
21
+ Generator,
22
+ Generic,
23
+ Iterable,
24
+ List,
25
+ Literal,
26
+ Mapping,
27
+ Optional,
28
+ Set,
29
+ Tuple,
30
+ Type,
31
+ TypeVar,
32
+ Union,
33
+ )
34
+
35
+ import attr
36
+ from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
37
+ from yarl import URL
38
+
39
+ from . import hdrs, http, payload
40
+ from .abc import AbstractCookieJar
41
+ from .client_exceptions import (
42
+ ClientConnectionError as ClientConnectionError,
43
+ ClientConnectorCertificateError as ClientConnectorCertificateError,
44
+ ClientConnectorError as ClientConnectorError,
45
+ ClientConnectorSSLError as ClientConnectorSSLError,
46
+ ClientError as ClientError,
47
+ ClientHttpProxyError as ClientHttpProxyError,
48
+ ClientOSError as ClientOSError,
49
+ ClientPayloadError as ClientPayloadError,
50
+ ClientProxyConnectionError as ClientProxyConnectionError,
51
+ ClientResponseError as ClientResponseError,
52
+ ClientSSLError as ClientSSLError,
53
+ ContentTypeError as ContentTypeError,
54
+ InvalidURL as InvalidURL,
55
+ ServerConnectionError as ServerConnectionError,
56
+ ServerDisconnectedError as ServerDisconnectedError,
57
+ ServerFingerprintMismatch as ServerFingerprintMismatch,
58
+ ServerTimeoutError as ServerTimeoutError,
59
+ TooManyRedirects as TooManyRedirects,
60
+ WSServerHandshakeError as WSServerHandshakeError,
61
+ )
62
+ from .client_reqrep import (
63
+ ClientRequest as ClientRequest,
64
+ ClientResponse as ClientResponse,
65
+ Fingerprint as Fingerprint,
66
+ RequestInfo as RequestInfo,
67
+ _merge_ssl_params,
68
+ )
69
+ from .client_ws import ClientWebSocketResponse as ClientWebSocketResponse
70
+ from .connector import (
71
+ BaseConnector as BaseConnector,
72
+ NamedPipeConnector as NamedPipeConnector,
73
+ TCPConnector as TCPConnector,
74
+ UnixConnector as UnixConnector,
75
+ )
76
+ from .cookiejar import CookieJar
77
+ from .helpers import (
78
+ _SENTINEL,
79
+ DEBUG,
80
+ BasicAuth,
81
+ TimeoutHandle,
82
+ ceil_timeout,
83
+ get_env_proxy_for_url,
84
+ get_running_loop,
85
+ method_must_be_empty_body,
86
+ sentinel,
87
+ strip_auth_from_url,
88
+ )
89
+ from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter
90
+ from .http_websocket import WSHandshakeError, WSMessage, ws_ext_gen, ws_ext_parse
91
+ from .streams import FlowControlDataQueue
92
+ from .tracing import Trace, TraceConfig
93
+ from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, StrOrURL
94
+
95
+ __all__ = (
96
+ # client_exceptions
97
+ "ClientConnectionError",
98
+ "ClientConnectorCertificateError",
99
+ "ClientConnectorError",
100
+ "ClientConnectorSSLError",
101
+ "ClientError",
102
+ "ClientHttpProxyError",
103
+ "ClientOSError",
104
+ "ClientPayloadError",
105
+ "ClientProxyConnectionError",
106
+ "ClientResponseError",
107
+ "ClientSSLError",
108
+ "ContentTypeError",
109
+ "InvalidURL",
110
+ "ServerConnectionError",
111
+ "ServerDisconnectedError",
112
+ "ServerFingerprintMismatch",
113
+ "ServerTimeoutError",
114
+ "TooManyRedirects",
115
+ "WSServerHandshakeError",
116
+ # client_reqrep
117
+ "ClientRequest",
118
+ "ClientResponse",
119
+ "Fingerprint",
120
+ "RequestInfo",
121
+ # connector
122
+ "BaseConnector",
123
+ "TCPConnector",
124
+ "UnixConnector",
125
+ "NamedPipeConnector",
126
+ # client_ws
127
+ "ClientWebSocketResponse",
128
+ # client
129
+ "ClientSession",
130
+ "ClientTimeout",
131
+ "request",
132
+ )
133
+
134
+
135
+ if TYPE_CHECKING:
136
+ from ssl import SSLContext
137
+ else:
138
+ SSLContext = None
139
+
140
+
141
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
142
+ class ClientTimeout:
143
+ total: Optional[float] = None
144
+ connect: Optional[float] = None
145
+ sock_read: Optional[float] = None
146
+ sock_connect: Optional[float] = None
147
+ ceil_threshold: float = 5
148
+
149
+ # pool_queue_timeout: Optional[float] = None
150
+ # dns_resolution_timeout: Optional[float] = None
151
+ # socket_connect_timeout: Optional[float] = None
152
+ # connection_acquiring_timeout: Optional[float] = None
153
+ # new_connection_timeout: Optional[float] = None
154
+ # http_header_timeout: Optional[float] = None
155
+ # response_body_timeout: Optional[float] = None
156
+
157
+ # to create a timeout specific for a single request, either
158
+ # - create a completely new one to overwrite the default
159
+ # - or use http://www.attrs.org/en/stable/api.html#attr.evolve
160
+ # to overwrite the defaults
161
+
162
+
163
+ # 5 Minute default read timeout
164
+ DEFAULT_TIMEOUT: Final[ClientTimeout] = ClientTimeout(total=5 * 60)
165
+
166
+ _RetType = TypeVar("_RetType")
167
+ _CharsetResolver = Callable[[ClientResponse, bytes], str]
168
+
169
+
170
+ class ClientSession:
171
+ """First-class interface for making HTTP requests."""
172
+
173
+ ATTRS = frozenset(
174
+ [
175
+ "_base_url",
176
+ "_source_traceback",
177
+ "_connector",
178
+ "requote_redirect_url",
179
+ "_loop",
180
+ "_cookie_jar",
181
+ "_connector_owner",
182
+ "_default_auth",
183
+ "_version",
184
+ "_json_serialize",
185
+ "_requote_redirect_url",
186
+ "_timeout",
187
+ "_raise_for_status",
188
+ "_auto_decompress",
189
+ "_trust_env",
190
+ "_default_headers",
191
+ "_skip_auto_headers",
192
+ "_request_class",
193
+ "_response_class",
194
+ "_ws_response_class",
195
+ "_trace_configs",
196
+ "_read_bufsize",
197
+ "_max_line_size",
198
+ "_max_field_size",
199
+ "_resolve_charset",
200
+ ]
201
+ )
202
+
203
+ _source_traceback: Optional[traceback.StackSummary] = None
204
+ _connector: Optional[BaseConnector] = None
205
+
206
+ def __init__(
207
+ self,
208
+ base_url: Optional[StrOrURL] = None,
209
+ *,
210
+ connector: Optional[BaseConnector] = None,
211
+ loop: Optional[asyncio.AbstractEventLoop] = None,
212
+ cookies: Optional[LooseCookies] = None,
213
+ headers: Optional[LooseHeaders] = None,
214
+ skip_auto_headers: Optional[Iterable[str]] = None,
215
+ auth: Optional[BasicAuth] = None,
216
+ json_serialize: JSONEncoder = json.dumps,
217
+ request_class: Type[ClientRequest] = ClientRequest,
218
+ response_class: Type[ClientResponse] = ClientResponse,
219
+ ws_response_class: Type[ClientWebSocketResponse] = ClientWebSocketResponse,
220
+ version: HttpVersion = http.HttpVersion11,
221
+ cookie_jar: Optional[AbstractCookieJar] = None,
222
+ connector_owner: bool = True,
223
+ raise_for_status: Union[
224
+ bool, Callable[[ClientResponse], Awaitable[None]]
225
+ ] = False,
226
+ read_timeout: Union[float, _SENTINEL] = sentinel,
227
+ conn_timeout: Optional[float] = None,
228
+ timeout: Union[object, ClientTimeout] = sentinel,
229
+ auto_decompress: bool = True,
230
+ trust_env: bool = False,
231
+ requote_redirect_url: bool = True,
232
+ trace_configs: Optional[List[TraceConfig]] = None,
233
+ read_bufsize: int = 2**16,
234
+ max_line_size: int = 8190,
235
+ max_field_size: int = 8190,
236
+ fallback_charset_resolver: _CharsetResolver = lambda r, b: "utf-8",
237
+ ) -> None:
238
+ if loop is None:
239
+ if connector is not None:
240
+ loop = connector._loop
241
+
242
+ loop = get_running_loop(loop)
243
+
244
+ if base_url is None or isinstance(base_url, URL):
245
+ self._base_url: Optional[URL] = base_url
246
+ else:
247
+ self._base_url = URL(base_url)
248
+ assert (
249
+ self._base_url.origin() == self._base_url
250
+ ), "Only absolute URLs without path part are supported"
251
+
252
+ if connector is None:
253
+ connector = TCPConnector(loop=loop)
254
+
255
+ if connector._loop is not loop:
256
+ raise RuntimeError("Session and connector has to use same event loop")
257
+
258
+ self._loop = loop
259
+
260
+ if loop.get_debug():
261
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
262
+
263
+ if cookie_jar is None:
264
+ cookie_jar = CookieJar(loop=loop)
265
+ self._cookie_jar = cookie_jar
266
+
267
+ if cookies is not None:
268
+ self._cookie_jar.update_cookies(cookies)
269
+
270
+ self._connector = connector
271
+ self._connector_owner = connector_owner
272
+ self._default_auth = auth
273
+ self._version = version
274
+ self._json_serialize = json_serialize
275
+ if timeout is sentinel:
276
+ self._timeout = DEFAULT_TIMEOUT
277
+ if read_timeout is not sentinel:
278
+ warnings.warn(
279
+ "read_timeout is deprecated, " "use timeout argument instead",
280
+ DeprecationWarning,
281
+ stacklevel=2,
282
+ )
283
+ self._timeout = attr.evolve(self._timeout, total=read_timeout)
284
+ if conn_timeout is not None:
285
+ self._timeout = attr.evolve(self._timeout, connect=conn_timeout)
286
+ warnings.warn(
287
+ "conn_timeout is deprecated, " "use timeout argument instead",
288
+ DeprecationWarning,
289
+ stacklevel=2,
290
+ )
291
+ else:
292
+ self._timeout = timeout # type: ignore[assignment]
293
+ if read_timeout is not sentinel:
294
+ raise ValueError(
295
+ "read_timeout and timeout parameters "
296
+ "conflict, please setup "
297
+ "timeout.read"
298
+ )
299
+ if conn_timeout is not None:
300
+ raise ValueError(
301
+ "conn_timeout and timeout parameters "
302
+ "conflict, please setup "
303
+ "timeout.connect"
304
+ )
305
+ self._raise_for_status = raise_for_status
306
+ self._auto_decompress = auto_decompress
307
+ self._trust_env = trust_env
308
+ self._requote_redirect_url = requote_redirect_url
309
+ self._read_bufsize = read_bufsize
310
+ self._max_line_size = max_line_size
311
+ self._max_field_size = max_field_size
312
+
313
+ # Convert to list of tuples
314
+ if headers:
315
+ real_headers: CIMultiDict[str] = CIMultiDict(headers)
316
+ else:
317
+ real_headers = CIMultiDict()
318
+ self._default_headers: CIMultiDict[str] = real_headers
319
+ if skip_auto_headers is not None:
320
+ self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers)
321
+ else:
322
+ self._skip_auto_headers = frozenset()
323
+
324
+ self._request_class = request_class
325
+ self._response_class = response_class
326
+ self._ws_response_class = ws_response_class
327
+
328
+ self._trace_configs = trace_configs or []
329
+ for trace_config in self._trace_configs:
330
+ trace_config.freeze()
331
+
332
+ self._resolve_charset = fallback_charset_resolver
333
+
334
+ def __init_subclass__(cls: Type["ClientSession"]) -> None:
335
+ warnings.warn(
336
+ "Inheritance class {} from ClientSession "
337
+ "is discouraged".format(cls.__name__),
338
+ DeprecationWarning,
339
+ stacklevel=2,
340
+ )
341
+
342
+ if DEBUG:
343
+
344
+ def __setattr__(self, name: str, val: Any) -> None:
345
+ if name not in self.ATTRS:
346
+ warnings.warn(
347
+ "Setting custom ClientSession.{} attribute "
348
+ "is discouraged".format(name),
349
+ DeprecationWarning,
350
+ stacklevel=2,
351
+ )
352
+ super().__setattr__(name, val)
353
+
354
+ def __del__(self, _warnings: Any = warnings) -> None:
355
+ if not self.closed:
356
+ kwargs = {"source": self}
357
+ _warnings.warn(
358
+ f"Unclosed client session {self!r}", ResourceWarning, **kwargs
359
+ )
360
+ context = {"client_session": self, "message": "Unclosed client session"}
361
+ if self._source_traceback is not None:
362
+ context["source_traceback"] = self._source_traceback
363
+ self._loop.call_exception_handler(context)
364
+
365
+ def request(
366
+ self, method: str, url: StrOrURL, **kwargs: Any
367
+ ) -> "_RequestContextManager":
368
+ """Perform HTTP request."""
369
+ return _RequestContextManager(self._request(method, url, **kwargs))
370
+
371
+ def _build_url(self, str_or_url: StrOrURL) -> URL:
372
+ url = URL(str_or_url)
373
+ if self._base_url is None:
374
+ return url
375
+ else:
376
+ assert not url.is_absolute() and url.path.startswith("/")
377
+ return self._base_url.join(url)
378
+
379
+ async def _request(
380
+ self,
381
+ method: str,
382
+ str_or_url: StrOrURL,
383
+ *,
384
+ params: Optional[Mapping[str, str]] = None,
385
+ data: Any = None,
386
+ json: Any = None,
387
+ cookies: Optional[LooseCookies] = None,
388
+ headers: Optional[LooseHeaders] = None,
389
+ skip_auto_headers: Optional[Iterable[str]] = None,
390
+ auth: Optional[BasicAuth] = None,
391
+ allow_redirects: bool = True,
392
+ max_redirects: int = 10,
393
+ compress: Optional[str] = None,
394
+ chunked: Optional[bool] = None,
395
+ expect100: bool = False,
396
+ raise_for_status: Union[
397
+ None, bool, Callable[[ClientResponse], Awaitable[None]]
398
+ ] = None,
399
+ read_until_eof: bool = True,
400
+ proxy: Optional[StrOrURL] = None,
401
+ proxy_auth: Optional[BasicAuth] = None,
402
+ timeout: Union[ClientTimeout, _SENTINEL] = sentinel,
403
+ verify_ssl: Optional[bool] = None,
404
+ fingerprint: Optional[bytes] = None,
405
+ ssl_context: Optional[SSLContext] = None,
406
+ ssl: Optional[Union[SSLContext, Literal[False], Fingerprint]] = None,
407
+ server_hostname: Optional[str] = None,
408
+ proxy_headers: Optional[LooseHeaders] = None,
409
+ trace_request_ctx: Optional[SimpleNamespace] = None,
410
+ read_bufsize: Optional[int] = None,
411
+ auto_decompress: Optional[bool] = None,
412
+ max_line_size: Optional[int] = None,
413
+ max_field_size: Optional[int] = None,
414
+ ) -> ClientResponse:
415
+
416
+ # NOTE: timeout clamps existing connect and read timeouts. We cannot
417
+ # set the default to None because we need to detect if the user wants
418
+ # to use the existing timeouts by setting timeout to None.
419
+
420
+ if self.closed:
421
+ raise RuntimeError("Session is closed")
422
+
423
+ ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
424
+
425
+ if data is not None and json is not None:
426
+ raise ValueError(
427
+ "data and json parameters can not be used at the same time"
428
+ )
429
+ elif json is not None:
430
+ data = payload.JsonPayload(json, dumps=self._json_serialize)
431
+
432
+ if not isinstance(chunked, bool) and chunked is not None:
433
+ warnings.warn("Chunk size is deprecated #1615", DeprecationWarning)
434
+
435
+ redirects = 0
436
+ history = []
437
+ version = self._version
438
+ params = params or {}
439
+
440
+ # Merge with default headers and transform to CIMultiDict
441
+ headers = self._prepare_headers(headers)
442
+ proxy_headers = self._prepare_headers(proxy_headers)
443
+
444
+ try:
445
+ url = self._build_url(str_or_url)
446
+ except ValueError as e:
447
+ raise InvalidURL(str_or_url) from e
448
+
449
+ skip_headers = set(self._skip_auto_headers)
450
+ if skip_auto_headers is not None:
451
+ for i in skip_auto_headers:
452
+ skip_headers.add(istr(i))
453
+
454
+ if proxy is not None:
455
+ try:
456
+ proxy = URL(proxy)
457
+ except ValueError as e:
458
+ raise InvalidURL(proxy) from e
459
+
460
+ if timeout is sentinel:
461
+ real_timeout: ClientTimeout = self._timeout
462
+ else:
463
+ if not isinstance(timeout, ClientTimeout):
464
+ real_timeout = ClientTimeout(total=timeout)
465
+ else:
466
+ real_timeout = timeout
467
+ # timeout is cumulative for all request operations
468
+ # (request, redirects, responses, data consuming)
469
+ tm = TimeoutHandle(
470
+ self._loop, real_timeout.total, ceil_threshold=real_timeout.ceil_threshold
471
+ )
472
+ handle = tm.start()
473
+
474
+ if read_bufsize is None:
475
+ read_bufsize = self._read_bufsize
476
+
477
+ if auto_decompress is None:
478
+ auto_decompress = self._auto_decompress
479
+
480
+ if max_line_size is None:
481
+ max_line_size = self._max_line_size
482
+
483
+ if max_field_size is None:
484
+ max_field_size = self._max_field_size
485
+
486
+ traces = [
487
+ Trace(
488
+ self,
489
+ trace_config,
490
+ trace_config.trace_config_ctx(trace_request_ctx=trace_request_ctx),
491
+ )
492
+ for trace_config in self._trace_configs
493
+ ]
494
+
495
+ for trace in traces:
496
+ await trace.send_request_start(method, url.update_query(params), headers)
497
+
498
+ timer = tm.timer()
499
+ try:
500
+ with timer:
501
+ while True:
502
+ url, auth_from_url = strip_auth_from_url(url)
503
+ if auth and auth_from_url:
504
+ raise ValueError(
505
+ "Cannot combine AUTH argument with "
506
+ "credentials encoded in URL"
507
+ )
508
+
509
+ if auth is None:
510
+ auth = auth_from_url
511
+ if auth is None:
512
+ auth = self._default_auth
513
+ # It would be confusing if we support explicit
514
+ # Authorization header with auth argument
515
+ if (
516
+ headers is not None
517
+ and auth is not None
518
+ and hdrs.AUTHORIZATION in headers
519
+ ):
520
+ raise ValueError(
521
+ "Cannot combine AUTHORIZATION header "
522
+ "with AUTH argument or credentials "
523
+ "encoded in URL"
524
+ )
525
+
526
+ all_cookies = self._cookie_jar.filter_cookies(url)
527
+
528
+ if cookies is not None:
529
+ tmp_cookie_jar = CookieJar()
530
+ tmp_cookie_jar.update_cookies(cookies)
531
+ req_cookies = tmp_cookie_jar.filter_cookies(url)
532
+ if req_cookies:
533
+ all_cookies.load(req_cookies)
534
+
535
+ if proxy is not None:
536
+ proxy = URL(proxy)
537
+ elif self._trust_env:
538
+ with suppress(LookupError):
539
+ proxy, proxy_auth = get_env_proxy_for_url(url)
540
+
541
+ req = self._request_class(
542
+ method,
543
+ url,
544
+ params=params,
545
+ headers=headers,
546
+ skip_auto_headers=skip_headers,
547
+ data=data,
548
+ cookies=all_cookies,
549
+ auth=auth,
550
+ version=version,
551
+ compress=compress,
552
+ chunked=chunked,
553
+ expect100=expect100,
554
+ loop=self._loop,
555
+ response_class=self._response_class,
556
+ proxy=proxy,
557
+ proxy_auth=proxy_auth,
558
+ timer=timer,
559
+ session=self,
560
+ ssl=ssl,
561
+ server_hostname=server_hostname,
562
+ proxy_headers=proxy_headers,
563
+ traces=traces,
564
+ trust_env=self.trust_env,
565
+ )
566
+
567
+ # connection timeout
568
+ try:
569
+ async with ceil_timeout(
570
+ real_timeout.connect,
571
+ ceil_threshold=real_timeout.ceil_threshold,
572
+ ):
573
+ assert self._connector is not None
574
+ conn = await self._connector.connect(
575
+ req, traces=traces, timeout=real_timeout
576
+ )
577
+ except asyncio.TimeoutError as exc:
578
+ raise ServerTimeoutError(
579
+ "Connection timeout " "to host {}".format(url)
580
+ ) from exc
581
+
582
+ assert conn.transport is not None
583
+
584
+ assert conn.protocol is not None
585
+ conn.protocol.set_response_params(
586
+ timer=timer,
587
+ skip_payload=method_must_be_empty_body(method),
588
+ read_until_eof=read_until_eof,
589
+ auto_decompress=auto_decompress,
590
+ read_timeout=real_timeout.sock_read,
591
+ read_bufsize=read_bufsize,
592
+ timeout_ceil_threshold=self._connector._timeout_ceil_threshold,
593
+ max_line_size=max_line_size,
594
+ max_field_size=max_field_size,
595
+ )
596
+
597
+ try:
598
+ try:
599
+ resp = await req.send(conn)
600
+ try:
601
+ await resp.start(conn)
602
+ except BaseException:
603
+ resp.close()
604
+ raise
605
+ except BaseException:
606
+ conn.close()
607
+ raise
608
+ except ClientError:
609
+ raise
610
+ except OSError as exc:
611
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
612
+ raise
613
+ raise ClientOSError(*exc.args) from exc
614
+
615
+ self._cookie_jar.update_cookies(resp.cookies, resp.url)
616
+
617
+ # redirects
618
+ if resp.status in (301, 302, 303, 307, 308) and allow_redirects:
619
+
620
+ for trace in traces:
621
+ await trace.send_request_redirect(
622
+ method, url.update_query(params), headers, resp
623
+ )
624
+
625
+ redirects += 1
626
+ history.append(resp)
627
+ if max_redirects and redirects >= max_redirects:
628
+ resp.close()
629
+ raise TooManyRedirects(
630
+ history[0].request_info, tuple(history)
631
+ )
632
+
633
+ # For 301 and 302, mimic IE, now changed in RFC
634
+ # https://github.com/kennethreitz/requests/pull/269
635
+ if (resp.status == 303 and resp.method != hdrs.METH_HEAD) or (
636
+ resp.status in (301, 302) and resp.method == hdrs.METH_POST
637
+ ):
638
+ method = hdrs.METH_GET
639
+ data = None
640
+ if headers.get(hdrs.CONTENT_LENGTH):
641
+ headers.pop(hdrs.CONTENT_LENGTH)
642
+
643
+ r_url = resp.headers.get(hdrs.LOCATION) or resp.headers.get(
644
+ hdrs.URI
645
+ )
646
+ if r_url is None:
647
+ # see github.com/aio-libs/aiohttp/issues/2022
648
+ break
649
+ else:
650
+ # reading from correct redirection
651
+ # response is forbidden
652
+ resp.release()
653
+
654
+ try:
655
+ parsed_url = URL(
656
+ r_url, encoded=not self._requote_redirect_url
657
+ )
658
+
659
+ except ValueError as e:
660
+ raise InvalidURL(r_url) from e
661
+
662
+ scheme = parsed_url.scheme
663
+ if scheme not in ("http", "https", ""):
664
+ resp.close()
665
+ raise ValueError("Can redirect only to http or https")
666
+ elif not scheme:
667
+ parsed_url = url.join(parsed_url)
668
+
669
+ if url.origin() != parsed_url.origin():
670
+ auth = None
671
+ headers.pop(hdrs.AUTHORIZATION, None)
672
+
673
+ url = parsed_url
674
+ params = {}
675
+ resp.release()
676
+ continue
677
+
678
+ break
679
+
680
+ # check response status
681
+ if raise_for_status is None:
682
+ raise_for_status = self._raise_for_status
683
+
684
+ if raise_for_status is None:
685
+ pass
686
+ elif callable(raise_for_status):
687
+ await raise_for_status(resp)
688
+ elif raise_for_status:
689
+ resp.raise_for_status()
690
+
691
+ # register connection
692
+ if handle is not None:
693
+ if resp.connection is not None:
694
+ resp.connection.add_callback(handle.cancel)
695
+ else:
696
+ handle.cancel()
697
+
698
+ resp._history = tuple(history)
699
+
700
+ for trace in traces:
701
+ await trace.send_request_end(
702
+ method, url.update_query(params), headers, resp
703
+ )
704
+ return resp
705
+
706
+ except BaseException as e:
707
+ # cleanup timer
708
+ tm.close()
709
+ if handle:
710
+ handle.cancel()
711
+ handle = None
712
+
713
+ for trace in traces:
714
+ await trace.send_request_exception(
715
+ method, url.update_query(params), headers, e
716
+ )
717
+ raise
718
+
719
+ def ws_connect(
720
+ self,
721
+ url: StrOrURL,
722
+ *,
723
+ method: str = hdrs.METH_GET,
724
+ protocols: Iterable[str] = (),
725
+ timeout: float = 10.0,
726
+ receive_timeout: Optional[float] = None,
727
+ autoclose: bool = True,
728
+ autoping: bool = True,
729
+ heartbeat: Optional[float] = None,
730
+ auth: Optional[BasicAuth] = None,
731
+ origin: Optional[str] = None,
732
+ params: Optional[Mapping[str, str]] = None,
733
+ headers: Optional[LooseHeaders] = None,
734
+ proxy: Optional[StrOrURL] = None,
735
+ proxy_auth: Optional[BasicAuth] = None,
736
+ ssl: Union[SSLContext, Literal[False], None, Fingerprint] = None,
737
+ verify_ssl: Optional[bool] = None,
738
+ fingerprint: Optional[bytes] = None,
739
+ ssl_context: Optional[SSLContext] = None,
740
+ proxy_headers: Optional[LooseHeaders] = None,
741
+ compress: int = 0,
742
+ max_msg_size: int = 4 * 1024 * 1024,
743
+ ) -> "_WSRequestContextManager":
744
+ """Initiate websocket connection."""
745
+ return _WSRequestContextManager(
746
+ self._ws_connect(
747
+ url,
748
+ method=method,
749
+ protocols=protocols,
750
+ timeout=timeout,
751
+ receive_timeout=receive_timeout,
752
+ autoclose=autoclose,
753
+ autoping=autoping,
754
+ heartbeat=heartbeat,
755
+ auth=auth,
756
+ origin=origin,
757
+ params=params,
758
+ headers=headers,
759
+ proxy=proxy,
760
+ proxy_auth=proxy_auth,
761
+ ssl=ssl,
762
+ verify_ssl=verify_ssl,
763
+ fingerprint=fingerprint,
764
+ ssl_context=ssl_context,
765
+ proxy_headers=proxy_headers,
766
+ compress=compress,
767
+ max_msg_size=max_msg_size,
768
+ )
769
+ )
770
+
771
+ async def _ws_connect(
772
+ self,
773
+ url: StrOrURL,
774
+ *,
775
+ method: str = hdrs.METH_GET,
776
+ protocols: Iterable[str] = (),
777
+ timeout: float = 10.0,
778
+ receive_timeout: Optional[float] = None,
779
+ autoclose: bool = True,
780
+ autoping: bool = True,
781
+ heartbeat: Optional[float] = None,
782
+ auth: Optional[BasicAuth] = None,
783
+ origin: Optional[str] = None,
784
+ params: Optional[Mapping[str, str]] = None,
785
+ headers: Optional[LooseHeaders] = None,
786
+ proxy: Optional[StrOrURL] = None,
787
+ proxy_auth: Optional[BasicAuth] = None,
788
+ ssl: Union[SSLContext, Literal[False], None, Fingerprint] = None,
789
+ verify_ssl: Optional[bool] = None,
790
+ fingerprint: Optional[bytes] = None,
791
+ ssl_context: Optional[SSLContext] = None,
792
+ proxy_headers: Optional[LooseHeaders] = None,
793
+ compress: int = 0,
794
+ max_msg_size: int = 4 * 1024 * 1024,
795
+ ) -> ClientWebSocketResponse:
796
+
797
+ if headers is None:
798
+ real_headers: CIMultiDict[str] = CIMultiDict()
799
+ else:
800
+ real_headers = CIMultiDict(headers)
801
+
802
+ default_headers = {
803
+ hdrs.UPGRADE: "websocket",
804
+ hdrs.CONNECTION: "Upgrade",
805
+ hdrs.SEC_WEBSOCKET_VERSION: "13",
806
+ }
807
+
808
+ for key, value in default_headers.items():
809
+ real_headers.setdefault(key, value)
810
+
811
+ sec_key = base64.b64encode(os.urandom(16))
812
+ real_headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode()
813
+
814
+ if protocols:
815
+ real_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ",".join(protocols)
816
+ if origin is not None:
817
+ real_headers[hdrs.ORIGIN] = origin
818
+ if compress:
819
+ extstr = ws_ext_gen(compress=compress)
820
+ real_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr
821
+
822
+ ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
823
+
824
+ # send request
825
+ resp = await self.request(
826
+ method,
827
+ url,
828
+ params=params,
829
+ headers=real_headers,
830
+ read_until_eof=False,
831
+ auth=auth,
832
+ proxy=proxy,
833
+ proxy_auth=proxy_auth,
834
+ ssl=ssl,
835
+ proxy_headers=proxy_headers,
836
+ )
837
+
838
+ try:
839
+ # check handshake
840
+ if resp.status != 101:
841
+ raise WSServerHandshakeError(
842
+ resp.request_info,
843
+ resp.history,
844
+ message="Invalid response status",
845
+ status=resp.status,
846
+ headers=resp.headers,
847
+ )
848
+
849
+ if resp.headers.get(hdrs.UPGRADE, "").lower() != "websocket":
850
+ raise WSServerHandshakeError(
851
+ resp.request_info,
852
+ resp.history,
853
+ message="Invalid upgrade header",
854
+ status=resp.status,
855
+ headers=resp.headers,
856
+ )
857
+
858
+ if resp.headers.get(hdrs.CONNECTION, "").lower() != "upgrade":
859
+ raise WSServerHandshakeError(
860
+ resp.request_info,
861
+ resp.history,
862
+ message="Invalid connection header",
863
+ status=resp.status,
864
+ headers=resp.headers,
865
+ )
866
+
867
+ # key calculation
868
+ r_key = resp.headers.get(hdrs.SEC_WEBSOCKET_ACCEPT, "")
869
+ match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()).decode()
870
+ if r_key != match:
871
+ raise WSServerHandshakeError(
872
+ resp.request_info,
873
+ resp.history,
874
+ message="Invalid challenge response",
875
+ status=resp.status,
876
+ headers=resp.headers,
877
+ )
878
+
879
+ # websocket protocol
880
+ protocol = None
881
+ if protocols and hdrs.SEC_WEBSOCKET_PROTOCOL in resp.headers:
882
+ resp_protocols = [
883
+ proto.strip()
884
+ for proto in resp.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",")
885
+ ]
886
+
887
+ for proto in resp_protocols:
888
+ if proto in protocols:
889
+ protocol = proto
890
+ break
891
+
892
+ # websocket compress
893
+ notakeover = False
894
+ if compress:
895
+ compress_hdrs = resp.headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)
896
+ if compress_hdrs:
897
+ try:
898
+ compress, notakeover = ws_ext_parse(compress_hdrs)
899
+ except WSHandshakeError as exc:
900
+ raise WSServerHandshakeError(
901
+ resp.request_info,
902
+ resp.history,
903
+ message=exc.args[0],
904
+ status=resp.status,
905
+ headers=resp.headers,
906
+ ) from exc
907
+ else:
908
+ compress = 0
909
+ notakeover = False
910
+
911
+ conn = resp.connection
912
+ assert conn is not None
913
+ conn_proto = conn.protocol
914
+ assert conn_proto is not None
915
+ transport = conn.transport
916
+ assert transport is not None
917
+ reader: FlowControlDataQueue[WSMessage] = FlowControlDataQueue(
918
+ conn_proto, 2**16, loop=self._loop
919
+ )
920
+ conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader)
921
+ writer = WebSocketWriter(
922
+ conn_proto,
923
+ transport,
924
+ use_mask=True,
925
+ compress=compress,
926
+ notakeover=notakeover,
927
+ )
928
+ except BaseException:
929
+ resp.close()
930
+ raise
931
+ else:
932
+ return self._ws_response_class(
933
+ reader,
934
+ writer,
935
+ protocol,
936
+ resp,
937
+ timeout,
938
+ autoclose,
939
+ autoping,
940
+ self._loop,
941
+ receive_timeout=receive_timeout,
942
+ heartbeat=heartbeat,
943
+ compress=compress,
944
+ client_notakeover=notakeover,
945
+ )
946
+
947
+ def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]":
948
+ """Add default headers and transform it to CIMultiDict"""
949
+ # Convert headers to MultiDict
950
+ result = CIMultiDict(self._default_headers)
951
+ if headers:
952
+ if not isinstance(headers, (MultiDictProxy, MultiDict)):
953
+ headers = CIMultiDict(headers)
954
+ added_names: Set[str] = set()
955
+ for key, value in headers.items():
956
+ if key in added_names:
957
+ result.add(key, value)
958
+ else:
959
+ result[key] = value
960
+ added_names.add(key)
961
+ return result
962
+
963
+ def get(
964
+ self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any
965
+ ) -> "_RequestContextManager":
966
+ """Perform HTTP GET request."""
967
+ return _RequestContextManager(
968
+ self._request(hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs)
969
+ )
970
+
971
+ def options(
972
+ self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any
973
+ ) -> "_RequestContextManager":
974
+ """Perform HTTP OPTIONS request."""
975
+ return _RequestContextManager(
976
+ self._request(
977
+ hdrs.METH_OPTIONS, url, allow_redirects=allow_redirects, **kwargs
978
+ )
979
+ )
980
+
981
+ def head(
982
+ self, url: StrOrURL, *, allow_redirects: bool = False, **kwargs: Any
983
+ ) -> "_RequestContextManager":
984
+ """Perform HTTP HEAD request."""
985
+ return _RequestContextManager(
986
+ self._request(
987
+ hdrs.METH_HEAD, url, allow_redirects=allow_redirects, **kwargs
988
+ )
989
+ )
990
+
991
+ def post(
992
+ self, url: StrOrURL, *, data: Any = None, **kwargs: Any
993
+ ) -> "_RequestContextManager":
994
+ """Perform HTTP POST request."""
995
+ return _RequestContextManager(
996
+ self._request(hdrs.METH_POST, url, data=data, **kwargs)
997
+ )
998
+
999
+ def put(
1000
+ self, url: StrOrURL, *, data: Any = None, **kwargs: Any
1001
+ ) -> "_RequestContextManager":
1002
+ """Perform HTTP PUT request."""
1003
+ return _RequestContextManager(
1004
+ self._request(hdrs.METH_PUT, url, data=data, **kwargs)
1005
+ )
1006
+
1007
+ def patch(
1008
+ self, url: StrOrURL, *, data: Any = None, **kwargs: Any
1009
+ ) -> "_RequestContextManager":
1010
+ """Perform HTTP PATCH request."""
1011
+ return _RequestContextManager(
1012
+ self._request(hdrs.METH_PATCH, url, data=data, **kwargs)
1013
+ )
1014
+
1015
+ def delete(self, url: StrOrURL, **kwargs: Any) -> "_RequestContextManager":
1016
+ """Perform HTTP DELETE request."""
1017
+ return _RequestContextManager(self._request(hdrs.METH_DELETE, url, **kwargs))
1018
+
1019
+ async def close(self) -> None:
1020
+ """Close underlying connector.
1021
+
1022
+ Release all acquired resources.
1023
+ """
1024
+ if not self.closed:
1025
+ if self._connector is not None and self._connector_owner:
1026
+ await self._connector.close()
1027
+ self._connector = None
1028
+
1029
+ @property
1030
+ def closed(self) -> bool:
1031
+ """Is client session closed.
1032
+
1033
+ A readonly property.
1034
+ """
1035
+ return self._connector is None or self._connector.closed
1036
+
1037
+ @property
1038
+ def connector(self) -> Optional[BaseConnector]:
1039
+ """Connector instance used for the session."""
1040
+ return self._connector
1041
+
1042
+ @property
1043
+ def cookie_jar(self) -> AbstractCookieJar:
1044
+ """The session cookies."""
1045
+ return self._cookie_jar
1046
+
1047
+ @property
1048
+ def version(self) -> Tuple[int, int]:
1049
+ """The session HTTP protocol version."""
1050
+ return self._version
1051
+
1052
+ @property
1053
+ def requote_redirect_url(self) -> bool:
1054
+ """Do URL requoting on redirection handling."""
1055
+ return self._requote_redirect_url
1056
+
1057
+ @requote_redirect_url.setter
1058
+ def requote_redirect_url(self, val: bool) -> None:
1059
+ """Do URL requoting on redirection handling."""
1060
+ warnings.warn(
1061
+ "session.requote_redirect_url modification " "is deprecated #2778",
1062
+ DeprecationWarning,
1063
+ stacklevel=2,
1064
+ )
1065
+ self._requote_redirect_url = val
1066
+
1067
+ @property
1068
+ def loop(self) -> asyncio.AbstractEventLoop:
1069
+ """Session's loop."""
1070
+ warnings.warn(
1071
+ "client.loop property is deprecated", DeprecationWarning, stacklevel=2
1072
+ )
1073
+ return self._loop
1074
+
1075
+ @property
1076
+ def timeout(self) -> ClientTimeout:
1077
+ """Timeout for the session."""
1078
+ return self._timeout
1079
+
1080
+ @property
1081
+ def headers(self) -> "CIMultiDict[str]":
1082
+ """The default headers of the client session."""
1083
+ return self._default_headers
1084
+
1085
+ @property
1086
+ def skip_auto_headers(self) -> FrozenSet[istr]:
1087
+ """Headers for which autogeneration should be skipped"""
1088
+ return self._skip_auto_headers
1089
+
1090
+ @property
1091
+ def auth(self) -> Optional[BasicAuth]:
1092
+ """An object that represents HTTP Basic Authorization"""
1093
+ return self._default_auth
1094
+
1095
+ @property
1096
+ def json_serialize(self) -> JSONEncoder:
1097
+ """Json serializer callable"""
1098
+ return self._json_serialize
1099
+
1100
+ @property
1101
+ def connector_owner(self) -> bool:
1102
+ """Should connector be closed on session closing"""
1103
+ return self._connector_owner
1104
+
1105
+ @property
1106
+ def raise_for_status(
1107
+ self,
1108
+ ) -> Union[bool, Callable[[ClientResponse], Awaitable[None]]]:
1109
+ """Should `ClientResponse.raise_for_status()` be called for each response."""
1110
+ return self._raise_for_status
1111
+
1112
+ @property
1113
+ def auto_decompress(self) -> bool:
1114
+ """Should the body response be automatically decompressed."""
1115
+ return self._auto_decompress
1116
+
1117
+ @property
1118
+ def trust_env(self) -> bool:
1119
+ """
1120
+ Should proxies information from environment or netrc be trusted.
1121
+
1122
+ Information is from HTTP_PROXY / HTTPS_PROXY environment variables
1123
+ or ~/.netrc file if present.
1124
+ """
1125
+ return self._trust_env
1126
+
1127
+ @property
1128
+ def trace_configs(self) -> List[TraceConfig]:
1129
+ """A list of TraceConfig instances used for client tracing"""
1130
+ return self._trace_configs
1131
+
1132
+ def detach(self) -> None:
1133
+ """Detach connector from session without closing the former.
1134
+
1135
+ Session is switched to closed state anyway.
1136
+ """
1137
+ self._connector = None
1138
+
1139
+ def __enter__(self) -> None:
1140
+ raise TypeError("Use async with instead")
1141
+
1142
+ def __exit__(
1143
+ self,
1144
+ exc_type: Optional[Type[BaseException]],
1145
+ exc_val: Optional[BaseException],
1146
+ exc_tb: Optional[TracebackType],
1147
+ ) -> None:
1148
+ # __exit__ should exist in pair with __enter__ but never executed
1149
+ pass # pragma: no cover
1150
+
1151
+ async def __aenter__(self) -> "ClientSession":
1152
+ return self
1153
+
1154
+ async def __aexit__(
1155
+ self,
1156
+ exc_type: Optional[Type[BaseException]],
1157
+ exc_val: Optional[BaseException],
1158
+ exc_tb: Optional[TracebackType],
1159
+ ) -> None:
1160
+ await self.close()
1161
+
1162
+
1163
+ class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]):
1164
+
1165
+ __slots__ = ("_coro", "_resp")
1166
+
1167
+ def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None:
1168
+ self._coro = coro
1169
+
1170
+ def send(self, arg: None) -> "asyncio.Future[Any]":
1171
+ return self._coro.send(arg)
1172
+
1173
+ def throw(self, *args: Any, **kwargs: Any) -> "asyncio.Future[Any]":
1174
+ return self._coro.throw(*args, **kwargs)
1175
+
1176
+ def close(self) -> None:
1177
+ return self._coro.close()
1178
+
1179
+ def __await__(self) -> Generator[Any, None, _RetType]:
1180
+ ret = self._coro.__await__()
1181
+ return ret
1182
+
1183
+ def __iter__(self) -> Generator[Any, None, _RetType]:
1184
+ return self.__await__()
1185
+
1186
+ async def __aenter__(self) -> _RetType:
1187
+ self._resp = await self._coro
1188
+ return self._resp
1189
+
1190
+
1191
+ class _RequestContextManager(_BaseRequestContextManager[ClientResponse]):
1192
+ __slots__ = ()
1193
+
1194
+ async def __aexit__(
1195
+ self,
1196
+ exc_type: Optional[Type[BaseException]],
1197
+ exc: Optional[BaseException],
1198
+ tb: Optional[TracebackType],
1199
+ ) -> None:
1200
+ # We're basing behavior on the exception as it can be caused by
1201
+ # user code unrelated to the status of the connection. If you
1202
+ # would like to close a connection you must do that
1203
+ # explicitly. Otherwise connection error handling should kick in
1204
+ # and close/recycle the connection as required.
1205
+ self._resp.release()
1206
+ await self._resp.wait_for_close()
1207
+
1208
+
1209
+ class _WSRequestContextManager(_BaseRequestContextManager[ClientWebSocketResponse]):
1210
+ __slots__ = ()
1211
+
1212
+ async def __aexit__(
1213
+ self,
1214
+ exc_type: Optional[Type[BaseException]],
1215
+ exc: Optional[BaseException],
1216
+ tb: Optional[TracebackType],
1217
+ ) -> None:
1218
+ await self._resp.close()
1219
+
1220
+
1221
+ class _SessionRequestContextManager:
1222
+
1223
+ __slots__ = ("_coro", "_resp", "_session")
1224
+
1225
+ def __init__(
1226
+ self,
1227
+ coro: Coroutine["asyncio.Future[Any]", None, ClientResponse],
1228
+ session: ClientSession,
1229
+ ) -> None:
1230
+ self._coro = coro
1231
+ self._resp: Optional[ClientResponse] = None
1232
+ self._session = session
1233
+
1234
+ async def __aenter__(self) -> ClientResponse:
1235
+ try:
1236
+ self._resp = await self._coro
1237
+ except BaseException:
1238
+ await self._session.close()
1239
+ raise
1240
+ else:
1241
+ return self._resp
1242
+
1243
+ async def __aexit__(
1244
+ self,
1245
+ exc_type: Optional[Type[BaseException]],
1246
+ exc: Optional[BaseException],
1247
+ tb: Optional[TracebackType],
1248
+ ) -> None:
1249
+ assert self._resp is not None
1250
+ self._resp.close()
1251
+ await self._session.close()
1252
+
1253
+
1254
+ def request(
1255
+ method: str,
1256
+ url: StrOrURL,
1257
+ *,
1258
+ params: Optional[Mapping[str, str]] = None,
1259
+ data: Any = None,
1260
+ json: Any = None,
1261
+ headers: Optional[LooseHeaders] = None,
1262
+ skip_auto_headers: Optional[Iterable[str]] = None,
1263
+ auth: Optional[BasicAuth] = None,
1264
+ allow_redirects: bool = True,
1265
+ max_redirects: int = 10,
1266
+ compress: Optional[str] = None,
1267
+ chunked: Optional[bool] = None,
1268
+ expect100: bool = False,
1269
+ raise_for_status: Optional[bool] = None,
1270
+ read_until_eof: bool = True,
1271
+ proxy: Optional[StrOrURL] = None,
1272
+ proxy_auth: Optional[BasicAuth] = None,
1273
+ timeout: Union[ClientTimeout, object] = sentinel,
1274
+ cookies: Optional[LooseCookies] = None,
1275
+ version: HttpVersion = http.HttpVersion11,
1276
+ connector: Optional[BaseConnector] = None,
1277
+ read_bufsize: Optional[int] = None,
1278
+ loop: Optional[asyncio.AbstractEventLoop] = None,
1279
+ max_line_size: int = 8190,
1280
+ max_field_size: int = 8190,
1281
+ ) -> _SessionRequestContextManager:
1282
+ """Constructs and sends a request.
1283
+
1284
+ Returns response object.
1285
+ method - HTTP method
1286
+ url - request url
1287
+ params - (optional) Dictionary or bytes to be sent in the query
1288
+ string of the new request
1289
+ data - (optional) Dictionary, bytes, or file-like object to
1290
+ send in the body of the request
1291
+ json - (optional) Any json compatible python object
1292
+ headers - (optional) Dictionary of HTTP Headers to send with
1293
+ the request
1294
+ cookies - (optional) Dict object to send with the request
1295
+ auth - (optional) BasicAuth named tuple represent HTTP Basic Auth
1296
+ auth - aiohttp.helpers.BasicAuth
1297
+ allow_redirects - (optional) If set to False, do not follow
1298
+ redirects
1299
+ version - Request HTTP version.
1300
+ compress - Set to True if request has to be compressed
1301
+ with deflate encoding.
1302
+ chunked - Set to chunk size for chunked transfer encoding.
1303
+ expect100 - Expect 100-continue response from server.
1304
+ connector - BaseConnector sub-class instance to support
1305
+ connection pooling.
1306
+ read_until_eof - Read response until eof if response
1307
+ does not have Content-Length header.
1308
+ loop - Optional event loop.
1309
+ timeout - Optional ClientTimeout settings structure, 5min
1310
+ total timeout by default.
1311
+ Usage::
1312
+ >>> import aiohttp
1313
+ >>> resp = await aiohttp.request('GET', 'http://python.org/')
1314
+ >>> resp
1315
+ <ClientResponse(python.org/) [200]>
1316
+ >>> data = await resp.read()
1317
+ """
1318
+ connector_owner = False
1319
+ if connector is None:
1320
+ connector_owner = True
1321
+ connector = TCPConnector(loop=loop, force_close=True)
1322
+
1323
+ session = ClientSession(
1324
+ loop=loop,
1325
+ cookies=cookies,
1326
+ version=version,
1327
+ timeout=timeout,
1328
+ connector=connector,
1329
+ connector_owner=connector_owner,
1330
+ )
1331
+
1332
+ return _SessionRequestContextManager(
1333
+ session._request(
1334
+ method,
1335
+ url,
1336
+ params=params,
1337
+ data=data,
1338
+ json=json,
1339
+ headers=headers,
1340
+ skip_auto_headers=skip_auto_headers,
1341
+ auth=auth,
1342
+ allow_redirects=allow_redirects,
1343
+ max_redirects=max_redirects,
1344
+ compress=compress,
1345
+ chunked=chunked,
1346
+ expect100=expect100,
1347
+ raise_for_status=raise_for_status,
1348
+ read_until_eof=read_until_eof,
1349
+ proxy=proxy,
1350
+ proxy_auth=proxy_auth,
1351
+ read_bufsize=read_bufsize,
1352
+ max_line_size=max_line_size,
1353
+ max_field_size=max_field_size,
1354
+ ),
1355
+ session,
1356
+ )
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_exceptions.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP related errors."""
2
+
3
+ import asyncio
4
+ import warnings
5
+ from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
6
+
7
+ from .http_parser import RawResponseMessage
8
+ from .typedefs import LooseHeaders
9
+
10
+ try:
11
+ import ssl
12
+
13
+ SSLContext = ssl.SSLContext
14
+ except ImportError: # pragma: no cover
15
+ ssl = SSLContext = None # type: ignore[assignment]
16
+
17
+
18
+ if TYPE_CHECKING: # pragma: no cover
19
+ from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo
20
+ else:
21
+ RequestInfo = ClientResponse = ConnectionKey = None
22
+
23
+ __all__ = (
24
+ "ClientError",
25
+ "ClientConnectionError",
26
+ "ClientOSError",
27
+ "ClientConnectorError",
28
+ "ClientProxyConnectionError",
29
+ "ClientSSLError",
30
+ "ClientConnectorSSLError",
31
+ "ClientConnectorCertificateError",
32
+ "ServerConnectionError",
33
+ "ServerTimeoutError",
34
+ "ServerDisconnectedError",
35
+ "ServerFingerprintMismatch",
36
+ "ClientResponseError",
37
+ "ClientHttpProxyError",
38
+ "WSServerHandshakeError",
39
+ "ContentTypeError",
40
+ "ClientPayloadError",
41
+ "InvalidURL",
42
+ )
43
+
44
+
45
+ class ClientError(Exception):
46
+ """Base class for client connection errors."""
47
+
48
+
49
+ class ClientResponseError(ClientError):
50
+ """Base class for exceptions that occur after getting a response.
51
+
52
+ request_info: An instance of RequestInfo.
53
+ history: A sequence of responses, if redirects occurred.
54
+ status: HTTP status code.
55
+ message: Error message.
56
+ headers: Response headers.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ request_info: RequestInfo,
62
+ history: Tuple[ClientResponse, ...],
63
+ *,
64
+ code: Optional[int] = None,
65
+ status: Optional[int] = None,
66
+ message: str = "",
67
+ headers: Optional[LooseHeaders] = None,
68
+ ) -> None:
69
+ self.request_info = request_info
70
+ if code is not None:
71
+ if status is not None:
72
+ raise ValueError(
73
+ "Both code and status arguments are provided; "
74
+ "code is deprecated, use status instead"
75
+ )
76
+ warnings.warn(
77
+ "code argument is deprecated, use status instead",
78
+ DeprecationWarning,
79
+ stacklevel=2,
80
+ )
81
+ if status is not None:
82
+ self.status = status
83
+ elif code is not None:
84
+ self.status = code
85
+ else:
86
+ self.status = 0
87
+ self.message = message
88
+ self.headers = headers
89
+ self.history = history
90
+ self.args = (request_info, history)
91
+
92
+ def __str__(self) -> str:
93
+ return "{}, message={!r}, url={!r}".format(
94
+ self.status,
95
+ self.message,
96
+ self.request_info.real_url,
97
+ )
98
+
99
+ def __repr__(self) -> str:
100
+ args = f"{self.request_info!r}, {self.history!r}"
101
+ if self.status != 0:
102
+ args += f", status={self.status!r}"
103
+ if self.message != "":
104
+ args += f", message={self.message!r}"
105
+ if self.headers is not None:
106
+ args += f", headers={self.headers!r}"
107
+ return f"{type(self).__name__}({args})"
108
+
109
+ @property
110
+ def code(self) -> int:
111
+ warnings.warn(
112
+ "code property is deprecated, use status instead",
113
+ DeprecationWarning,
114
+ stacklevel=2,
115
+ )
116
+ return self.status
117
+
118
+ @code.setter
119
+ def code(self, value: int) -> None:
120
+ warnings.warn(
121
+ "code property is deprecated, use status instead",
122
+ DeprecationWarning,
123
+ stacklevel=2,
124
+ )
125
+ self.status = value
126
+
127
+
128
+ class ContentTypeError(ClientResponseError):
129
+ """ContentType found is not valid."""
130
+
131
+
132
+ class WSServerHandshakeError(ClientResponseError):
133
+ """websocket server handshake error."""
134
+
135
+
136
+ class ClientHttpProxyError(ClientResponseError):
137
+ """HTTP proxy error.
138
+
139
+ Raised in :class:`aiohttp.connector.TCPConnector` if
140
+ proxy responds with status other than ``200 OK``
141
+ on ``CONNECT`` request.
142
+ """
143
+
144
+
145
+ class TooManyRedirects(ClientResponseError):
146
+ """Client was redirected too many times."""
147
+
148
+
149
+ class ClientConnectionError(ClientError):
150
+ """Base class for client socket errors."""
151
+
152
+
153
+ class ClientOSError(ClientConnectionError, OSError):
154
+ """OSError error."""
155
+
156
+
157
+ class ClientConnectorError(ClientOSError):
158
+ """Client connector error.
159
+
160
+ Raised in :class:`aiohttp.connector.TCPConnector` if
161
+ a connection can not be established.
162
+ """
163
+
164
+ def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None:
165
+ self._conn_key = connection_key
166
+ self._os_error = os_error
167
+ super().__init__(os_error.errno, os_error.strerror)
168
+ self.args = (connection_key, os_error)
169
+
170
+ @property
171
+ def os_error(self) -> OSError:
172
+ return self._os_error
173
+
174
+ @property
175
+ def host(self) -> str:
176
+ return self._conn_key.host
177
+
178
+ @property
179
+ def port(self) -> Optional[int]:
180
+ return self._conn_key.port
181
+
182
+ @property
183
+ def ssl(self) -> Union[SSLContext, None, bool, "Fingerprint"]:
184
+ return self._conn_key.ssl
185
+
186
+ def __str__(self) -> str:
187
+ return "Cannot connect to host {0.host}:{0.port} ssl:{1} [{2}]".format(
188
+ self, self.ssl if self.ssl is not None else "default", self.strerror
189
+ )
190
+
191
+ # OSError.__reduce__ does too much black magick
192
+ __reduce__ = BaseException.__reduce__
193
+
194
+
195
+ class ClientProxyConnectionError(ClientConnectorError):
196
+ """Proxy connection error.
197
+
198
+ Raised in :class:`aiohttp.connector.TCPConnector` if
199
+ connection to proxy can not be established.
200
+ """
201
+
202
+
203
+ class UnixClientConnectorError(ClientConnectorError):
204
+ """Unix connector error.
205
+
206
+ Raised in :py:class:`aiohttp.connector.UnixConnector`
207
+ if connection to unix socket can not be established.
208
+ """
209
+
210
+ def __init__(
211
+ self, path: str, connection_key: ConnectionKey, os_error: OSError
212
+ ) -> None:
213
+ self._path = path
214
+ super().__init__(connection_key, os_error)
215
+
216
+ @property
217
+ def path(self) -> str:
218
+ return self._path
219
+
220
+ def __str__(self) -> str:
221
+ return "Cannot connect to unix socket {0.path} ssl:{1} [{2}]".format(
222
+ self, self.ssl if self.ssl is not None else "default", self.strerror
223
+ )
224
+
225
+
226
+ class ServerConnectionError(ClientConnectionError):
227
+ """Server connection errors."""
228
+
229
+
230
+ class ServerDisconnectedError(ServerConnectionError):
231
+ """Server disconnected."""
232
+
233
+ def __init__(self, message: Union[RawResponseMessage, str, None] = None) -> None:
234
+ if message is None:
235
+ message = "Server disconnected"
236
+
237
+ self.args = (message,)
238
+ self.message = message
239
+
240
+
241
+ class ServerTimeoutError(ServerConnectionError, asyncio.TimeoutError):
242
+ """Server timeout error."""
243
+
244
+
245
+ class ServerFingerprintMismatch(ServerConnectionError):
246
+ """SSL certificate does not match expected fingerprint."""
247
+
248
+ def __init__(self, expected: bytes, got: bytes, host: str, port: int) -> None:
249
+ self.expected = expected
250
+ self.got = got
251
+ self.host = host
252
+ self.port = port
253
+ self.args = (expected, got, host, port)
254
+
255
+ def __repr__(self) -> str:
256
+ return "<{} expected={!r} got={!r} host={!r} port={!r}>".format(
257
+ self.__class__.__name__, self.expected, self.got, self.host, self.port
258
+ )
259
+
260
+
261
+ class ClientPayloadError(ClientError):
262
+ """Response payload error."""
263
+
264
+
265
+ class InvalidURL(ClientError, ValueError):
266
+ """Invalid URL.
267
+
268
+ URL used for fetching is malformed, e.g. it doesn't contains host
269
+ part.
270
+ """
271
+
272
+ # Derive from ValueError for backward compatibility
273
+
274
+ def __init__(self, url: Any) -> None:
275
+ # The type of url is not yarl.URL because the exception can be raised
276
+ # on URL(url) call
277
+ super().__init__(url)
278
+
279
+ @property
280
+ def url(self) -> Any:
281
+ return self.args[0]
282
+
283
+ def __repr__(self) -> str:
284
+ return f"<{self.__class__.__name__} {self.url}>"
285
+
286
+
287
+ class ClientSSLError(ClientConnectorError):
288
+ """Base error for ssl.*Errors."""
289
+
290
+
291
+ if ssl is not None:
292
+ cert_errors = (ssl.CertificateError,)
293
+ cert_errors_bases = (
294
+ ClientSSLError,
295
+ ssl.CertificateError,
296
+ )
297
+
298
+ ssl_errors = (ssl.SSLError,)
299
+ ssl_error_bases = (ClientSSLError, ssl.SSLError)
300
+ else: # pragma: no cover
301
+ cert_errors = tuple()
302
+ cert_errors_bases = (
303
+ ClientSSLError,
304
+ ValueError,
305
+ )
306
+
307
+ ssl_errors = tuple()
308
+ ssl_error_bases = (ClientSSLError,)
309
+
310
+
311
+ class ClientConnectorSSLError(*ssl_error_bases): # type: ignore[misc]
312
+ """Response ssl error."""
313
+
314
+
315
+ class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc]
316
+ """Response certificate error."""
317
+
318
+ def __init__(
319
+ self, connection_key: ConnectionKey, certificate_error: Exception
320
+ ) -> None:
321
+ self._conn_key = connection_key
322
+ self._certificate_error = certificate_error
323
+ self.args = (connection_key, certificate_error)
324
+
325
+ @property
326
+ def certificate_error(self) -> Exception:
327
+ return self._certificate_error
328
+
329
+ @property
330
+ def host(self) -> str:
331
+ return self._conn_key.host
332
+
333
+ @property
334
+ def port(self) -> Optional[int]:
335
+ return self._conn_key.port
336
+
337
+ @property
338
+ def ssl(self) -> bool:
339
+ return self._conn_key.is_ssl
340
+
341
+ def __str__(self) -> str:
342
+ return (
343
+ "Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} "
344
+ "[{0.certificate_error.__class__.__name__}: "
345
+ "{0.certificate_error.args}]".format(self)
346
+ )
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_proto.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from contextlib import suppress
3
+ from typing import Any, Optional, Tuple
4
+
5
+ from .base_protocol import BaseProtocol
6
+ from .client_exceptions import (
7
+ ClientOSError,
8
+ ClientPayloadError,
9
+ ServerDisconnectedError,
10
+ ServerTimeoutError,
11
+ )
12
+ from .helpers import BaseTimerContext, status_code_must_be_empty_body
13
+ from .http import HttpResponseParser, RawResponseMessage
14
+ from .streams import EMPTY_PAYLOAD, DataQueue, StreamReader
15
+
16
+
17
+ class ResponseHandler(BaseProtocol, DataQueue[Tuple[RawResponseMessage, StreamReader]]):
18
+ """Helper class to adapt between Protocol and StreamReader."""
19
+
20
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
21
+ BaseProtocol.__init__(self, loop=loop)
22
+ DataQueue.__init__(self, loop)
23
+
24
+ self._should_close = False
25
+
26
+ self._payload: Optional[StreamReader] = None
27
+ self._skip_payload = False
28
+ self._payload_parser = None
29
+
30
+ self._timer = None
31
+
32
+ self._tail = b""
33
+ self._upgraded = False
34
+ self._parser: Optional[HttpResponseParser] = None
35
+
36
+ self._read_timeout: Optional[float] = None
37
+ self._read_timeout_handle: Optional[asyncio.TimerHandle] = None
38
+
39
+ self._timeout_ceil_threshold: Optional[float] = 5
40
+
41
+ @property
42
+ def upgraded(self) -> bool:
43
+ return self._upgraded
44
+
45
+ @property
46
+ def should_close(self) -> bool:
47
+ if self._payload is not None and not self._payload.is_eof() or self._upgraded:
48
+ return True
49
+
50
+ return (
51
+ self._should_close
52
+ or self._upgraded
53
+ or self.exception() is not None
54
+ or self._payload_parser is not None
55
+ or len(self) > 0
56
+ or bool(self._tail)
57
+ )
58
+
59
+ def force_close(self) -> None:
60
+ self._should_close = True
61
+
62
+ def close(self) -> None:
63
+ transport = self.transport
64
+ if transport is not None:
65
+ transport.close()
66
+ self.transport = None
67
+ self._payload = None
68
+ self._drop_timeout()
69
+
70
+ def is_connected(self) -> bool:
71
+ return self.transport is not None and not self.transport.is_closing()
72
+
73
+ def connection_lost(self, exc: Optional[BaseException]) -> None:
74
+ self._drop_timeout()
75
+
76
+ if self._payload_parser is not None:
77
+ with suppress(Exception):
78
+ self._payload_parser.feed_eof()
79
+
80
+ uncompleted = None
81
+ if self._parser is not None:
82
+ try:
83
+ uncompleted = self._parser.feed_eof()
84
+ except Exception:
85
+ if self._payload is not None:
86
+ self._payload.set_exception(
87
+ ClientPayloadError("Response payload is not completed")
88
+ )
89
+
90
+ if not self.is_eof():
91
+ if isinstance(exc, OSError):
92
+ exc = ClientOSError(*exc.args)
93
+ if exc is None:
94
+ exc = ServerDisconnectedError(uncompleted)
95
+ # assigns self._should_close to True as side effect,
96
+ # we do it anyway below
97
+ self.set_exception(exc)
98
+
99
+ self._should_close = True
100
+ self._parser = None
101
+ self._payload = None
102
+ self._payload_parser = None
103
+ self._reading_paused = False
104
+
105
+ super().connection_lost(exc)
106
+
107
+ def eof_received(self) -> None:
108
+ # should call parser.feed_eof() most likely
109
+ self._drop_timeout()
110
+
111
+ def pause_reading(self) -> None:
112
+ super().pause_reading()
113
+ self._drop_timeout()
114
+
115
+ def resume_reading(self) -> None:
116
+ super().resume_reading()
117
+ self._reschedule_timeout()
118
+
119
+ def set_exception(self, exc: BaseException) -> None:
120
+ self._should_close = True
121
+ self._drop_timeout()
122
+ super().set_exception(exc)
123
+
124
+ def set_parser(self, parser: Any, payload: Any) -> None:
125
+ # TODO: actual types are:
126
+ # parser: WebSocketReader
127
+ # payload: FlowControlDataQueue
128
+ # but they are not generi enough
129
+ # Need an ABC for both types
130
+ self._payload = payload
131
+ self._payload_parser = parser
132
+
133
+ self._drop_timeout()
134
+
135
+ if self._tail:
136
+ data, self._tail = self._tail, b""
137
+ self.data_received(data)
138
+
139
+ def set_response_params(
140
+ self,
141
+ *,
142
+ timer: Optional[BaseTimerContext] = None,
143
+ skip_payload: bool = False,
144
+ read_until_eof: bool = False,
145
+ auto_decompress: bool = True,
146
+ read_timeout: Optional[float] = None,
147
+ read_bufsize: int = 2**16,
148
+ timeout_ceil_threshold: float = 5,
149
+ max_line_size: int = 8190,
150
+ max_field_size: int = 8190,
151
+ ) -> None:
152
+ self._skip_payload = skip_payload
153
+
154
+ self._read_timeout = read_timeout
155
+
156
+ self._timeout_ceil_threshold = timeout_ceil_threshold
157
+
158
+ self._parser = HttpResponseParser(
159
+ self,
160
+ self._loop,
161
+ read_bufsize,
162
+ timer=timer,
163
+ payload_exception=ClientPayloadError,
164
+ response_with_body=not skip_payload,
165
+ read_until_eof=read_until_eof,
166
+ auto_decompress=auto_decompress,
167
+ max_line_size=max_line_size,
168
+ max_field_size=max_field_size,
169
+ )
170
+
171
+ if self._tail:
172
+ data, self._tail = self._tail, b""
173
+ self.data_received(data)
174
+
175
+ def _drop_timeout(self) -> None:
176
+ if self._read_timeout_handle is not None:
177
+ self._read_timeout_handle.cancel()
178
+ self._read_timeout_handle = None
179
+
180
+ def _reschedule_timeout(self) -> None:
181
+ timeout = self._read_timeout
182
+ if self._read_timeout_handle is not None:
183
+ self._read_timeout_handle.cancel()
184
+
185
+ if timeout:
186
+ self._read_timeout_handle = self._loop.call_later(
187
+ timeout, self._on_read_timeout
188
+ )
189
+ else:
190
+ self._read_timeout_handle = None
191
+
192
+ def start_timeout(self) -> None:
193
+ self._reschedule_timeout()
194
+
195
+ def _on_read_timeout(self) -> None:
196
+ exc = ServerTimeoutError("Timeout on reading data from socket")
197
+ self.set_exception(exc)
198
+ if self._payload is not None:
199
+ self._payload.set_exception(exc)
200
+
201
+ def data_received(self, data: bytes) -> None:
202
+ self._reschedule_timeout()
203
+
204
+ if not data:
205
+ return
206
+
207
+ # custom payload parser
208
+ if self._payload_parser is not None:
209
+ eof, tail = self._payload_parser.feed_data(data)
210
+ if eof:
211
+ self._payload = None
212
+ self._payload_parser = None
213
+
214
+ if tail:
215
+ self.data_received(tail)
216
+ return
217
+ else:
218
+ if self._upgraded or self._parser is None:
219
+ # i.e. websocket connection, websocket parser is not set yet
220
+ self._tail += data
221
+ else:
222
+ # parse http messages
223
+ try:
224
+ messages, upgraded, tail = self._parser.feed_data(data)
225
+ except BaseException as exc:
226
+ if self.transport is not None:
227
+ # connection.release() could be called BEFORE
228
+ # data_received(), the transport is already
229
+ # closed in this case
230
+ self.transport.close()
231
+ # should_close is True after the call
232
+ self.set_exception(exc)
233
+ return
234
+
235
+ self._upgraded = upgraded
236
+
237
+ payload: Optional[StreamReader] = None
238
+ for message, payload in messages:
239
+ if message.should_close:
240
+ self._should_close = True
241
+
242
+ self._payload = payload
243
+
244
+ if self._skip_payload or status_code_must_be_empty_body(
245
+ message.code
246
+ ):
247
+ self.feed_data((message, EMPTY_PAYLOAD), 0)
248
+ else:
249
+ self.feed_data((message, payload), 0)
250
+ if payload is not None:
251
+ # new message(s) was processed
252
+ # register timeout handler unsubscribing
253
+ # either on end-of-stream or immediately for
254
+ # EMPTY_PAYLOAD
255
+ if payload is not EMPTY_PAYLOAD:
256
+ payload.on_eof(self._drop_timeout)
257
+ else:
258
+ self._drop_timeout()
259
+
260
+ if tail:
261
+ if upgraded:
262
+ self.data_received(tail)
263
+ else:
264
+ self._tail = tail
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_reqrep.py ADDED
@@ -0,0 +1,1196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import codecs
3
+ import contextlib
4
+ import functools
5
+ import io
6
+ import re
7
+ import sys
8
+ import traceback
9
+ import warnings
10
+ from hashlib import md5, sha1, sha256
11
+ from http.cookies import CookieError, Morsel, SimpleCookie
12
+ from types import MappingProxyType, TracebackType
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Callable,
17
+ Dict,
18
+ Iterable,
19
+ List,
20
+ Literal,
21
+ Mapping,
22
+ Optional,
23
+ Tuple,
24
+ Type,
25
+ Union,
26
+ cast,
27
+ )
28
+
29
+ import attr
30
+ from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
31
+ from yarl import URL
32
+
33
+ from . import hdrs, helpers, http, multipart, payload
34
+ from .abc import AbstractStreamWriter
35
+ from .client_exceptions import (
36
+ ClientConnectionError,
37
+ ClientOSError,
38
+ ClientResponseError,
39
+ ContentTypeError,
40
+ InvalidURL,
41
+ ServerFingerprintMismatch,
42
+ )
43
+ from .compression_utils import HAS_BROTLI
44
+ from .formdata import FormData
45
+ from .helpers import (
46
+ BaseTimerContext,
47
+ BasicAuth,
48
+ HeadersMixin,
49
+ TimerNoop,
50
+ basicauth_from_netrc,
51
+ netrc_from_env,
52
+ noop,
53
+ reify,
54
+ set_result,
55
+ )
56
+ from .http import (
57
+ SERVER_SOFTWARE,
58
+ HttpVersion,
59
+ HttpVersion10,
60
+ HttpVersion11,
61
+ StreamWriter,
62
+ )
63
+ from .log import client_logger
64
+ from .streams import StreamReader
65
+ from .typedefs import (
66
+ DEFAULT_JSON_DECODER,
67
+ JSONDecoder,
68
+ LooseCookies,
69
+ LooseHeaders,
70
+ RawHeaders,
71
+ )
72
+
73
+ try:
74
+ import ssl
75
+ from ssl import SSLContext
76
+ except ImportError: # pragma: no cover
77
+ ssl = None # type: ignore[assignment]
78
+ SSLContext = object # type: ignore[misc,assignment]
79
+
80
+
81
+ __all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint")
82
+
83
+
84
+ if TYPE_CHECKING: # pragma: no cover
85
+ from .client import ClientSession
86
+ from .connector import Connection
87
+ from .tracing import Trace
88
+
89
+
90
+ _CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
91
+ json_re = re.compile(r"^application/(?:[\w.+-]+?\+)?json")
92
+
93
+
94
+ def _gen_default_accept_encoding() -> str:
95
+ return "gzip, deflate, br" if HAS_BROTLI else "gzip, deflate"
96
+
97
+
98
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
99
+ class ContentDisposition:
100
+ type: Optional[str]
101
+ parameters: "MappingProxyType[str, str]"
102
+ filename: Optional[str]
103
+
104
+
105
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
106
+ class RequestInfo:
107
+ url: URL
108
+ method: str
109
+ headers: "CIMultiDictProxy[str]"
110
+ real_url: URL = attr.ib()
111
+
112
+ @real_url.default
113
+ def real_url_default(self) -> URL:
114
+ return self.url
115
+
116
+
117
+ class Fingerprint:
118
+ HASHFUNC_BY_DIGESTLEN = {
119
+ 16: md5,
120
+ 20: sha1,
121
+ 32: sha256,
122
+ }
123
+
124
+ def __init__(self, fingerprint: bytes) -> None:
125
+ digestlen = len(fingerprint)
126
+ hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen)
127
+ if not hashfunc:
128
+ raise ValueError("fingerprint has invalid length")
129
+ elif hashfunc is md5 or hashfunc is sha1:
130
+ raise ValueError(
131
+ "md5 and sha1 are insecure and " "not supported. Use sha256."
132
+ )
133
+ self._hashfunc = hashfunc
134
+ self._fingerprint = fingerprint
135
+
136
+ @property
137
+ def fingerprint(self) -> bytes:
138
+ return self._fingerprint
139
+
140
+ def check(self, transport: asyncio.Transport) -> None:
141
+ if not transport.get_extra_info("sslcontext"):
142
+ return
143
+ sslobj = transport.get_extra_info("ssl_object")
144
+ cert = sslobj.getpeercert(binary_form=True)
145
+ got = self._hashfunc(cert).digest()
146
+ if got != self._fingerprint:
147
+ host, port, *_ = transport.get_extra_info("peername")
148
+ raise ServerFingerprintMismatch(self._fingerprint, got, host, port)
149
+
150
+
151
+ if ssl is not None:
152
+ SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None))
153
+ else: # pragma: no cover
154
+ SSL_ALLOWED_TYPES = type(None)
155
+
156
+
157
+ def _merge_ssl_params(
158
+ ssl: Union["SSLContext", Literal[False], Fingerprint, None],
159
+ verify_ssl: Optional[bool],
160
+ ssl_context: Optional["SSLContext"],
161
+ fingerprint: Optional[bytes],
162
+ ) -> Union["SSLContext", Literal[False], Fingerprint, None]:
163
+ if verify_ssl is not None and not verify_ssl:
164
+ warnings.warn(
165
+ "verify_ssl is deprecated, use ssl=False instead",
166
+ DeprecationWarning,
167
+ stacklevel=3,
168
+ )
169
+ if ssl is not None:
170
+ raise ValueError(
171
+ "verify_ssl, ssl_context, fingerprint and ssl "
172
+ "parameters are mutually exclusive"
173
+ )
174
+ else:
175
+ ssl = False
176
+ if ssl_context is not None:
177
+ warnings.warn(
178
+ "ssl_context is deprecated, use ssl=context instead",
179
+ DeprecationWarning,
180
+ stacklevel=3,
181
+ )
182
+ if ssl is not None:
183
+ raise ValueError(
184
+ "verify_ssl, ssl_context, fingerprint and ssl "
185
+ "parameters are mutually exclusive"
186
+ )
187
+ else:
188
+ ssl = ssl_context
189
+ if fingerprint is not None:
190
+ warnings.warn(
191
+ "fingerprint is deprecated, " "use ssl=Fingerprint(fingerprint) instead",
192
+ DeprecationWarning,
193
+ stacklevel=3,
194
+ )
195
+ if ssl is not None:
196
+ raise ValueError(
197
+ "verify_ssl, ssl_context, fingerprint and ssl "
198
+ "parameters are mutually exclusive"
199
+ )
200
+ else:
201
+ ssl = Fingerprint(fingerprint)
202
+ if not isinstance(ssl, SSL_ALLOWED_TYPES):
203
+ raise TypeError(
204
+ "ssl should be SSLContext, bool, Fingerprint or None, "
205
+ "got {!r} instead.".format(ssl)
206
+ )
207
+ return ssl
208
+
209
+
210
+ @attr.s(auto_attribs=True, slots=True, frozen=True)
211
+ class ConnectionKey:
212
+ # the key should contain an information about used proxy / TLS
213
+ # to prevent reusing wrong connections from a pool
214
+ host: str
215
+ port: Optional[int]
216
+ is_ssl: bool
217
+ ssl: Union[SSLContext, None, Literal[False], Fingerprint]
218
+ proxy: Optional[URL]
219
+ proxy_auth: Optional[BasicAuth]
220
+ proxy_headers_hash: Optional[int] # hash(CIMultiDict)
221
+
222
+
223
+ def _is_expected_content_type(
224
+ response_content_type: str, expected_content_type: str
225
+ ) -> bool:
226
+ if expected_content_type == "application/json":
227
+ return json_re.match(response_content_type) is not None
228
+ return expected_content_type in response_content_type
229
+
230
+
231
+ class ClientRequest:
232
+ GET_METHODS = {
233
+ hdrs.METH_GET,
234
+ hdrs.METH_HEAD,
235
+ hdrs.METH_OPTIONS,
236
+ hdrs.METH_TRACE,
237
+ }
238
+ POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT}
239
+ ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE})
240
+
241
+ DEFAULT_HEADERS = {
242
+ hdrs.ACCEPT: "*/*",
243
+ hdrs.ACCEPT_ENCODING: _gen_default_accept_encoding(),
244
+ }
245
+
246
+ body = b""
247
+ auth = None
248
+ response = None
249
+
250
+ __writer = None # async task for streaming data
251
+ _continue = None # waiter future for '100 Continue' response
252
+
253
+ # N.B.
254
+ # Adding __del__ method with self._writer closing doesn't make sense
255
+ # because _writer is instance method, thus it keeps a reference to self.
256
+ # Until writer has finished finalizer will not be called.
257
+
258
+ def __init__(
259
+ self,
260
+ method: str,
261
+ url: URL,
262
+ *,
263
+ params: Optional[Mapping[str, str]] = None,
264
+ headers: Optional[LooseHeaders] = None,
265
+ skip_auto_headers: Iterable[str] = frozenset(),
266
+ data: Any = None,
267
+ cookies: Optional[LooseCookies] = None,
268
+ auth: Optional[BasicAuth] = None,
269
+ version: http.HttpVersion = http.HttpVersion11,
270
+ compress: Optional[str] = None,
271
+ chunked: Optional[bool] = None,
272
+ expect100: bool = False,
273
+ loop: Optional[asyncio.AbstractEventLoop] = None,
274
+ response_class: Optional[Type["ClientResponse"]] = None,
275
+ proxy: Optional[URL] = None,
276
+ proxy_auth: Optional[BasicAuth] = None,
277
+ timer: Optional[BaseTimerContext] = None,
278
+ session: Optional["ClientSession"] = None,
279
+ ssl: Union[SSLContext, Literal[False], Fingerprint, None] = None,
280
+ proxy_headers: Optional[LooseHeaders] = None,
281
+ traces: Optional[List["Trace"]] = None,
282
+ trust_env: bool = False,
283
+ server_hostname: Optional[str] = None,
284
+ ):
285
+ if loop is None:
286
+ loop = asyncio.get_event_loop()
287
+
288
+ match = _CONTAINS_CONTROL_CHAR_RE.search(method)
289
+ if match:
290
+ raise ValueError(
291
+ f"Method cannot contain non-token characters {method!r} "
292
+ "(found at least {match.group()!r})"
293
+ )
294
+
295
+ assert isinstance(url, URL), url
296
+ assert isinstance(proxy, (URL, type(None))), proxy
297
+ # FIXME: session is None in tests only, need to fix tests
298
+ # assert session is not None
299
+ self._session = cast("ClientSession", session)
300
+ if params:
301
+ q = MultiDict(url.query)
302
+ url2 = url.with_query(params)
303
+ q.extend(url2.query)
304
+ url = url.with_query(q)
305
+ self.original_url = url
306
+ self.url = url.with_fragment(None)
307
+ self.method = method.upper()
308
+ self.chunked = chunked
309
+ self.compress = compress
310
+ self.loop = loop
311
+ self.length = None
312
+ if response_class is None:
313
+ real_response_class = ClientResponse
314
+ else:
315
+ real_response_class = response_class
316
+ self.response_class: Type[ClientResponse] = real_response_class
317
+ self._timer = timer if timer is not None else TimerNoop()
318
+ self._ssl = ssl
319
+ self.server_hostname = server_hostname
320
+
321
+ if loop.get_debug():
322
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
323
+
324
+ self.update_version(version)
325
+ self.update_host(url)
326
+ self.update_headers(headers)
327
+ self.update_auto_headers(skip_auto_headers)
328
+ self.update_cookies(cookies)
329
+ self.update_content_encoding(data)
330
+ self.update_auth(auth, trust_env)
331
+ self.update_proxy(proxy, proxy_auth, proxy_headers)
332
+
333
+ self.update_body_from_data(data)
334
+ if data is not None or self.method not in self.GET_METHODS:
335
+ self.update_transfer_encoding()
336
+ self.update_expect_continue(expect100)
337
+ if traces is None:
338
+ traces = []
339
+ self._traces = traces
340
+
341
+ def __reset_writer(self, _: object = None) -> None:
342
+ self.__writer = None
343
+
344
+ @property
345
+ def _writer(self) -> Optional["asyncio.Task[None]"]:
346
+ return self.__writer
347
+
348
+ @_writer.setter
349
+ def _writer(self, writer: Optional["asyncio.Task[None]"]) -> None:
350
+ if self.__writer is not None:
351
+ self.__writer.remove_done_callback(self.__reset_writer)
352
+ self.__writer = writer
353
+ if writer is not None:
354
+ writer.add_done_callback(self.__reset_writer)
355
+
356
+ def is_ssl(self) -> bool:
357
+ return self.url.scheme in ("https", "wss")
358
+
359
+ @property
360
+ def ssl(self) -> Union["SSLContext", None, Literal[False], Fingerprint]:
361
+ return self._ssl
362
+
363
+ @property
364
+ def connection_key(self) -> ConnectionKey:
365
+ proxy_headers = self.proxy_headers
366
+ if proxy_headers:
367
+ h: Optional[int] = hash(tuple((k, v) for k, v in proxy_headers.items()))
368
+ else:
369
+ h = None
370
+ return ConnectionKey(
371
+ self.host,
372
+ self.port,
373
+ self.is_ssl(),
374
+ self.ssl,
375
+ self.proxy,
376
+ self.proxy_auth,
377
+ h,
378
+ )
379
+
380
+ @property
381
+ def host(self) -> str:
382
+ ret = self.url.raw_host
383
+ assert ret is not None
384
+ return ret
385
+
386
+ @property
387
+ def port(self) -> Optional[int]:
388
+ return self.url.port
389
+
390
+ @property
391
+ def request_info(self) -> RequestInfo:
392
+ headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers)
393
+ return RequestInfo(self.url, self.method, headers, self.original_url)
394
+
395
+ def update_host(self, url: URL) -> None:
396
+ """Update destination host, port and connection type (ssl)."""
397
+ # get host/port
398
+ if not url.raw_host:
399
+ raise InvalidURL(url)
400
+
401
+ # basic auth info
402
+ username, password = url.user, url.password
403
+ if username:
404
+ self.auth = helpers.BasicAuth(username, password or "")
405
+
406
+ def update_version(self, version: Union[http.HttpVersion, str]) -> None:
407
+ """Convert request version to two elements tuple.
408
+
409
+ parser HTTP version '1.1' => (1, 1)
410
+ """
411
+ if isinstance(version, str):
412
+ v = [part.strip() for part in version.split(".", 1)]
413
+ try:
414
+ version = http.HttpVersion(int(v[0]), int(v[1]))
415
+ except ValueError:
416
+ raise ValueError(
417
+ f"Can not parse http version number: {version}"
418
+ ) from None
419
+ self.version = version
420
+
421
+ def update_headers(self, headers: Optional[LooseHeaders]) -> None:
422
+ """Update request headers."""
423
+ self.headers: CIMultiDict[str] = CIMultiDict()
424
+
425
+ # add host
426
+ netloc = cast(str, self.url.raw_host)
427
+ if helpers.is_ipv6_address(netloc):
428
+ netloc = f"[{netloc}]"
429
+ # See https://github.com/aio-libs/aiohttp/issues/3636.
430
+ netloc = netloc.rstrip(".")
431
+ if self.url.port is not None and not self.url.is_default_port():
432
+ netloc += ":" + str(self.url.port)
433
+ self.headers[hdrs.HOST] = netloc
434
+
435
+ if headers:
436
+ if isinstance(headers, (dict, MultiDictProxy, MultiDict)):
437
+ headers = headers.items() # type: ignore[assignment]
438
+
439
+ for key, value in headers: # type: ignore[misc]
440
+ # A special case for Host header
441
+ if key.lower() == "host":
442
+ self.headers[key] = value
443
+ else:
444
+ self.headers.add(key, value)
445
+
446
+ def update_auto_headers(self, skip_auto_headers: Iterable[str]) -> None:
447
+ self.skip_auto_headers = CIMultiDict(
448
+ (hdr, None) for hdr in sorted(skip_auto_headers)
449
+ )
450
+ used_headers = self.headers.copy()
451
+ used_headers.extend(self.skip_auto_headers) # type: ignore[arg-type]
452
+
453
+ for hdr, val in self.DEFAULT_HEADERS.items():
454
+ if hdr not in used_headers:
455
+ self.headers.add(hdr, val)
456
+
457
+ if hdrs.USER_AGENT not in used_headers:
458
+ self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE
459
+
460
+ def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
461
+ """Update request cookies header."""
462
+ if not cookies:
463
+ return
464
+
465
+ c = SimpleCookie()
466
+ if hdrs.COOKIE in self.headers:
467
+ c.load(self.headers.get(hdrs.COOKIE, ""))
468
+ del self.headers[hdrs.COOKIE]
469
+
470
+ if isinstance(cookies, Mapping):
471
+ iter_cookies = cookies.items()
472
+ else:
473
+ iter_cookies = cookies # type: ignore[assignment]
474
+ for name, value in iter_cookies:
475
+ if isinstance(value, Morsel):
476
+ # Preserve coded_value
477
+ mrsl_val = value.get(value.key, Morsel())
478
+ mrsl_val.set(value.key, value.value, value.coded_value)
479
+ c[name] = mrsl_val
480
+ else:
481
+ c[name] = value # type: ignore[assignment]
482
+
483
+ self.headers[hdrs.COOKIE] = c.output(header="", sep=";").strip()
484
+
485
+ def update_content_encoding(self, data: Any) -> None:
486
+ """Set request content encoding."""
487
+ if data is None:
488
+ return
489
+
490
+ enc = self.headers.get(hdrs.CONTENT_ENCODING, "").lower()
491
+ if enc:
492
+ if self.compress:
493
+ raise ValueError(
494
+ "compress can not be set " "if Content-Encoding header is set"
495
+ )
496
+ elif self.compress:
497
+ if not isinstance(self.compress, str):
498
+ self.compress = "deflate"
499
+ self.headers[hdrs.CONTENT_ENCODING] = self.compress
500
+ self.chunked = True # enable chunked, no need to deal with length
501
+
502
+ def update_transfer_encoding(self) -> None:
503
+ """Analyze transfer-encoding header."""
504
+ te = self.headers.get(hdrs.TRANSFER_ENCODING, "").lower()
505
+
506
+ if "chunked" in te:
507
+ if self.chunked:
508
+ raise ValueError(
509
+ "chunked can not be set "
510
+ 'if "Transfer-Encoding: chunked" header is set'
511
+ )
512
+
513
+ elif self.chunked:
514
+ if hdrs.CONTENT_LENGTH in self.headers:
515
+ raise ValueError(
516
+ "chunked can not be set " "if Content-Length header is set"
517
+ )
518
+
519
+ self.headers[hdrs.TRANSFER_ENCODING] = "chunked"
520
+ else:
521
+ if hdrs.CONTENT_LENGTH not in self.headers:
522
+ self.headers[hdrs.CONTENT_LENGTH] = str(len(self.body))
523
+
524
+ def update_auth(self, auth: Optional[BasicAuth], trust_env: bool = False) -> None:
525
+ """Set basic auth."""
526
+ if auth is None:
527
+ auth = self.auth
528
+ if auth is None and trust_env and self.url.host is not None:
529
+ netrc_obj = netrc_from_env()
530
+ with contextlib.suppress(LookupError):
531
+ auth = basicauth_from_netrc(netrc_obj, self.url.host)
532
+ if auth is None:
533
+ return
534
+
535
+ if not isinstance(auth, helpers.BasicAuth):
536
+ raise TypeError("BasicAuth() tuple is required instead")
537
+
538
+ self.headers[hdrs.AUTHORIZATION] = auth.encode()
539
+
540
+ def update_body_from_data(self, body: Any) -> None:
541
+ if body is None:
542
+ return
543
+
544
+ # FormData
545
+ if isinstance(body, FormData):
546
+ body = body()
547
+
548
+ try:
549
+ body = payload.PAYLOAD_REGISTRY.get(body, disposition=None)
550
+ except payload.LookupError:
551
+ body = FormData(body)()
552
+
553
+ self.body = body
554
+
555
+ # enable chunked encoding if needed
556
+ if not self.chunked:
557
+ if hdrs.CONTENT_LENGTH not in self.headers:
558
+ size = body.size
559
+ if size is None:
560
+ self.chunked = True
561
+ else:
562
+ if hdrs.CONTENT_LENGTH not in self.headers:
563
+ self.headers[hdrs.CONTENT_LENGTH] = str(size)
564
+
565
+ # copy payload headers
566
+ assert body.headers
567
+ for (key, value) in body.headers.items():
568
+ if key in self.headers:
569
+ continue
570
+ if key in self.skip_auto_headers:
571
+ continue
572
+ self.headers[key] = value
573
+
574
+ def update_expect_continue(self, expect: bool = False) -> None:
575
+ if expect:
576
+ self.headers[hdrs.EXPECT] = "100-continue"
577
+ elif self.headers.get(hdrs.EXPECT, "").lower() == "100-continue":
578
+ expect = True
579
+
580
+ if expect:
581
+ self._continue = self.loop.create_future()
582
+
583
+ def update_proxy(
584
+ self,
585
+ proxy: Optional[URL],
586
+ proxy_auth: Optional[BasicAuth],
587
+ proxy_headers: Optional[LooseHeaders],
588
+ ) -> None:
589
+ if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth):
590
+ raise ValueError("proxy_auth must be None or BasicAuth() tuple")
591
+ self.proxy = proxy
592
+ self.proxy_auth = proxy_auth
593
+ self.proxy_headers = proxy_headers
594
+
595
+ def keep_alive(self) -> bool:
596
+ if self.version < HttpVersion10:
597
+ # keep alive not supported at all
598
+ return False
599
+ if self.version == HttpVersion10:
600
+ if self.headers.get(hdrs.CONNECTION) == "keep-alive":
601
+ return True
602
+ else: # no headers means we close for Http 1.0
603
+ return False
604
+ elif self.headers.get(hdrs.CONNECTION) == "close":
605
+ return False
606
+
607
+ return True
608
+
609
+ async def write_bytes(
610
+ self, writer: AbstractStreamWriter, conn: "Connection"
611
+ ) -> None:
612
+ """Support coroutines that yields bytes objects."""
613
+ # 100 response
614
+ if self._continue is not None:
615
+ try:
616
+ await writer.drain()
617
+ await self._continue
618
+ except asyncio.CancelledError:
619
+ return
620
+
621
+ protocol = conn.protocol
622
+ assert protocol is not None
623
+ try:
624
+ if isinstance(self.body, payload.Payload):
625
+ await self.body.write(writer)
626
+ else:
627
+ if isinstance(self.body, (bytes, bytearray)):
628
+ self.body = (self.body,) # type: ignore[assignment]
629
+
630
+ for chunk in self.body:
631
+ await writer.write(chunk) # type: ignore[arg-type]
632
+ except OSError as exc:
633
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
634
+ protocol.set_exception(exc)
635
+ else:
636
+ new_exc = ClientOSError(
637
+ exc.errno, "Can not write request body for %s" % self.url
638
+ )
639
+ new_exc.__context__ = exc
640
+ new_exc.__cause__ = exc
641
+ protocol.set_exception(new_exc)
642
+ except asyncio.CancelledError:
643
+ await writer.write_eof()
644
+ except Exception as exc:
645
+ protocol.set_exception(exc)
646
+ else:
647
+ await writer.write_eof()
648
+ protocol.start_timeout()
649
+
650
+ async def send(self, conn: "Connection") -> "ClientResponse":
651
+ # Specify request target:
652
+ # - CONNECT request must send authority form URI
653
+ # - not CONNECT proxy must send absolute form URI
654
+ # - most common is origin form URI
655
+ if self.method == hdrs.METH_CONNECT:
656
+ connect_host = self.url.raw_host
657
+ assert connect_host is not None
658
+ if helpers.is_ipv6_address(connect_host):
659
+ connect_host = f"[{connect_host}]"
660
+ path = f"{connect_host}:{self.url.port}"
661
+ elif self.proxy and not self.is_ssl():
662
+ path = str(self.url)
663
+ else:
664
+ path = self.url.raw_path
665
+ if self.url.raw_query_string:
666
+ path += "?" + self.url.raw_query_string
667
+
668
+ protocol = conn.protocol
669
+ assert protocol is not None
670
+ writer = StreamWriter(
671
+ protocol,
672
+ self.loop,
673
+ on_chunk_sent=functools.partial(
674
+ self._on_chunk_request_sent, self.method, self.url
675
+ ),
676
+ on_headers_sent=functools.partial(
677
+ self._on_headers_request_sent, self.method, self.url
678
+ ),
679
+ )
680
+
681
+ if self.compress:
682
+ writer.enable_compression(self.compress)
683
+
684
+ if self.chunked is not None:
685
+ writer.enable_chunking()
686
+
687
+ # set default content-type
688
+ if (
689
+ self.method in self.POST_METHODS
690
+ and hdrs.CONTENT_TYPE not in self.skip_auto_headers
691
+ and hdrs.CONTENT_TYPE not in self.headers
692
+ ):
693
+ self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream"
694
+
695
+ # set the connection header
696
+ connection = self.headers.get(hdrs.CONNECTION)
697
+ if not connection:
698
+ if self.keep_alive():
699
+ if self.version == HttpVersion10:
700
+ connection = "keep-alive"
701
+ else:
702
+ if self.version == HttpVersion11:
703
+ connection = "close"
704
+
705
+ if connection is not None:
706
+ self.headers[hdrs.CONNECTION] = connection
707
+
708
+ # status + headers
709
+ status_line = "{0} {1} HTTP/{v.major}.{v.minor}".format(
710
+ self.method, path, v=self.version
711
+ )
712
+ await writer.write_headers(status_line, self.headers)
713
+
714
+ self._writer = self.loop.create_task(self.write_bytes(writer, conn))
715
+
716
+ response_class = self.response_class
717
+ assert response_class is not None
718
+ self.response = response_class(
719
+ self.method,
720
+ self.original_url,
721
+ writer=self._writer,
722
+ continue100=self._continue,
723
+ timer=self._timer,
724
+ request_info=self.request_info,
725
+ traces=self._traces,
726
+ loop=self.loop,
727
+ session=self._session,
728
+ )
729
+ return self.response
730
+
731
+ async def close(self) -> None:
732
+ if self._writer is not None:
733
+ with contextlib.suppress(asyncio.CancelledError):
734
+ await self._writer
735
+
736
+ def terminate(self) -> None:
737
+ if self._writer is not None:
738
+ if not self.loop.is_closed():
739
+ self._writer.cancel()
740
+ self._writer.remove_done_callback(self.__reset_writer)
741
+ self._writer = None
742
+
743
+ async def _on_chunk_request_sent(self, method: str, url: URL, chunk: bytes) -> None:
744
+ for trace in self._traces:
745
+ await trace.send_request_chunk_sent(method, url, chunk)
746
+
747
+ async def _on_headers_request_sent(
748
+ self, method: str, url: URL, headers: "CIMultiDict[str]"
749
+ ) -> None:
750
+ for trace in self._traces:
751
+ await trace.send_request_headers(method, url, headers)
752
+
753
+
754
+ class ClientResponse(HeadersMixin):
755
+
756
+ # Some of these attributes are None when created,
757
+ # but will be set by the start() method.
758
+ # As the end user will likely never see the None values, we cheat the types below.
759
+ # from the Status-Line of the response
760
+ version: Optional[HttpVersion] = None # HTTP-Version
761
+ status: int = None # type: ignore[assignment] # Status-Code
762
+ reason: Optional[str] = None # Reason-Phrase
763
+
764
+ content: StreamReader = None # type: ignore[assignment] # Payload stream
765
+ _headers: CIMultiDictProxy[str] = None # type: ignore[assignment]
766
+ _raw_headers: RawHeaders = None # type: ignore[assignment]
767
+
768
+ _connection = None # current connection
769
+ _source_traceback: Optional[traceback.StackSummary] = None
770
+ # set up by ClientRequest after ClientResponse object creation
771
+ # post-init stage allows to not change ctor signature
772
+ _closed = True # to allow __del__ for non-initialized properly response
773
+ _released = False
774
+ __writer = None
775
+
776
+ def __init__(
777
+ self,
778
+ method: str,
779
+ url: URL,
780
+ *,
781
+ writer: "asyncio.Task[None]",
782
+ continue100: Optional["asyncio.Future[bool]"],
783
+ timer: BaseTimerContext,
784
+ request_info: RequestInfo,
785
+ traces: List["Trace"],
786
+ loop: asyncio.AbstractEventLoop,
787
+ session: "ClientSession",
788
+ ) -> None:
789
+ assert isinstance(url, URL)
790
+
791
+ self.method = method
792
+ self.cookies = SimpleCookie()
793
+
794
+ self._real_url = url
795
+ self._url = url.with_fragment(None)
796
+ self._body: Any = None
797
+ self._writer: Optional[asyncio.Task[None]] = writer
798
+ self._continue = continue100 # None by default
799
+ self._closed = True
800
+ self._history: Tuple[ClientResponse, ...] = ()
801
+ self._request_info = request_info
802
+ self._timer = timer if timer is not None else TimerNoop()
803
+ self._cache: Dict[str, Any] = {}
804
+ self._traces = traces
805
+ self._loop = loop
806
+ # store a reference to session #1985
807
+ self._session: Optional[ClientSession] = session
808
+ # Save reference to _resolve_charset, so that get_encoding() will still
809
+ # work after the response has finished reading the body.
810
+ if session is None:
811
+ # TODO: Fix session=None in tests (see ClientRequest.__init__).
812
+ self._resolve_charset: Callable[
813
+ ["ClientResponse", bytes], str
814
+ ] = lambda *_: "utf-8"
815
+ else:
816
+ self._resolve_charset = session._resolve_charset
817
+ if loop.get_debug():
818
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
819
+
820
+ def __reset_writer(self, _: object = None) -> None:
821
+ self.__writer = None
822
+
823
+ @property
824
+ def _writer(self) -> Optional["asyncio.Task[None]"]:
825
+ return self.__writer
826
+
827
+ @_writer.setter
828
+ def _writer(self, writer: Optional["asyncio.Task[None]"]) -> None:
829
+ if self.__writer is not None:
830
+ self.__writer.remove_done_callback(self.__reset_writer)
831
+ self.__writer = writer
832
+ if writer is not None:
833
+ writer.add_done_callback(self.__reset_writer)
834
+
835
+ @reify
836
+ def url(self) -> URL:
837
+ return self._url
838
+
839
+ @reify
840
+ def url_obj(self) -> URL:
841
+ warnings.warn("Deprecated, use .url #1654", DeprecationWarning, stacklevel=2)
842
+ return self._url
843
+
844
+ @reify
845
+ def real_url(self) -> URL:
846
+ return self._real_url
847
+
848
+ @reify
849
+ def host(self) -> str:
850
+ assert self._url.host is not None
851
+ return self._url.host
852
+
853
+ @reify
854
+ def headers(self) -> "CIMultiDictProxy[str]":
855
+ return self._headers
856
+
857
+ @reify
858
+ def raw_headers(self) -> RawHeaders:
859
+ return self._raw_headers
860
+
861
+ @reify
862
+ def request_info(self) -> RequestInfo:
863
+ return self._request_info
864
+
865
+ @reify
866
+ def content_disposition(self) -> Optional[ContentDisposition]:
867
+ raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
868
+ if raw is None:
869
+ return None
870
+ disposition_type, params_dct = multipart.parse_content_disposition(raw)
871
+ params = MappingProxyType(params_dct)
872
+ filename = multipart.content_disposition_filename(params)
873
+ return ContentDisposition(disposition_type, params, filename)
874
+
875
+ def __del__(self, _warnings: Any = warnings) -> None:
876
+ if self._closed:
877
+ return
878
+
879
+ if self._connection is not None:
880
+ self._connection.release()
881
+ self._cleanup_writer()
882
+
883
+ if self._loop.get_debug():
884
+ kwargs = {"source": self}
885
+ _warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs)
886
+ context = {"client_response": self, "message": "Unclosed response"}
887
+ if self._source_traceback:
888
+ context["source_traceback"] = self._source_traceback
889
+ self._loop.call_exception_handler(context)
890
+
891
+ def __repr__(self) -> str:
892
+ out = io.StringIO()
893
+ ascii_encodable_url = str(self.url)
894
+ if self.reason:
895
+ ascii_encodable_reason = self.reason.encode(
896
+ "ascii", "backslashreplace"
897
+ ).decode("ascii")
898
+ else:
899
+ ascii_encodable_reason = "None"
900
+ print(
901
+ "<ClientResponse({}) [{} {}]>".format(
902
+ ascii_encodable_url, self.status, ascii_encodable_reason
903
+ ),
904
+ file=out,
905
+ )
906
+ print(self.headers, file=out)
907
+ return out.getvalue()
908
+
909
+ @property
910
+ def connection(self) -> Optional["Connection"]:
911
+ return self._connection
912
+
913
+ @reify
914
+ def history(self) -> Tuple["ClientResponse", ...]:
915
+ """A sequence of of responses, if redirects occurred."""
916
+ return self._history
917
+
918
+ @reify
919
+ def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]":
920
+ links_str = ", ".join(self.headers.getall("link", []))
921
+
922
+ if not links_str:
923
+ return MultiDictProxy(MultiDict())
924
+
925
+ links: MultiDict[MultiDictProxy[Union[str, URL]]] = MultiDict()
926
+
927
+ for val in re.split(r",(?=\s*<)", links_str):
928
+ match = re.match(r"\s*<(.*)>(.*)", val)
929
+ if match is None: # pragma: no cover
930
+ # the check exists to suppress mypy error
931
+ continue
932
+ url, params_str = match.groups()
933
+ params = params_str.split(";")[1:]
934
+
935
+ link: MultiDict[Union[str, URL]] = MultiDict()
936
+
937
+ for param in params:
938
+ match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M)
939
+ if match is None: # pragma: no cover
940
+ # the check exists to suppress mypy error
941
+ continue
942
+ key, _, value, _ = match.groups()
943
+
944
+ link.add(key, value)
945
+
946
+ key = link.get("rel", url)
947
+
948
+ link.add("url", self.url.join(URL(url)))
949
+
950
+ links.add(str(key), MultiDictProxy(link))
951
+
952
+ return MultiDictProxy(links)
953
+
954
+ async def start(self, connection: "Connection") -> "ClientResponse":
955
+ """Start response processing."""
956
+ self._closed = False
957
+ self._protocol = connection.protocol
958
+ self._connection = connection
959
+
960
+ with self._timer:
961
+ while True:
962
+ # read response
963
+ try:
964
+ protocol = self._protocol
965
+ message, payload = await protocol.read() # type: ignore[union-attr]
966
+ except http.HttpProcessingError as exc:
967
+ raise ClientResponseError(
968
+ self.request_info,
969
+ self.history,
970
+ status=exc.code,
971
+ message=exc.message,
972
+ headers=exc.headers,
973
+ ) from exc
974
+
975
+ if message.code < 100 or message.code > 199 or message.code == 101:
976
+ break
977
+
978
+ if self._continue is not None:
979
+ set_result(self._continue, True)
980
+ self._continue = None
981
+
982
+ # payload eof handler
983
+ payload.on_eof(self._response_eof)
984
+
985
+ # response status
986
+ self.version = message.version
987
+ self.status = message.code
988
+ self.reason = message.reason
989
+
990
+ # headers
991
+ self._headers = message.headers # type is CIMultiDictProxy
992
+ self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes]
993
+
994
+ # payload
995
+ self.content = payload
996
+
997
+ # cookies
998
+ for hdr in self.headers.getall(hdrs.SET_COOKIE, ()):
999
+ try:
1000
+ self.cookies.load(hdr)
1001
+ except CookieError as exc:
1002
+ client_logger.warning("Can not load response cookies: %s", exc)
1003
+ return self
1004
+
1005
+ def _response_eof(self) -> None:
1006
+ if self._closed:
1007
+ return
1008
+
1009
+ # protocol could be None because connection could be detached
1010
+ protocol = self._connection and self._connection.protocol
1011
+ if protocol is not None and protocol.upgraded:
1012
+ return
1013
+
1014
+ self._closed = True
1015
+ self._cleanup_writer()
1016
+ self._release_connection()
1017
+
1018
+ @property
1019
+ def closed(self) -> bool:
1020
+ return self._closed
1021
+
1022
+ def close(self) -> None:
1023
+ if not self._released:
1024
+ self._notify_content()
1025
+
1026
+ self._closed = True
1027
+ if self._loop is None or self._loop.is_closed():
1028
+ return
1029
+
1030
+ self._cleanup_writer()
1031
+ if self._connection is not None:
1032
+ self._connection.close()
1033
+ self._connection = None
1034
+
1035
+ def release(self) -> Any:
1036
+ if not self._released:
1037
+ self._notify_content()
1038
+
1039
+ self._closed = True
1040
+
1041
+ self._cleanup_writer()
1042
+ self._release_connection()
1043
+ return noop()
1044
+
1045
+ @property
1046
+ def ok(self) -> bool:
1047
+ """Returns ``True`` if ``status`` is less than ``400``, ``False`` if not.
1048
+
1049
+ This is **not** a check for ``200 OK`` but a check that the response
1050
+ status is under 400.
1051
+ """
1052
+ return 400 > self.status
1053
+
1054
+ def raise_for_status(self) -> None:
1055
+ if not self.ok:
1056
+ # reason should always be not None for a started response
1057
+ assert self.reason is not None
1058
+ self.release()
1059
+ raise ClientResponseError(
1060
+ self.request_info,
1061
+ self.history,
1062
+ status=self.status,
1063
+ message=self.reason,
1064
+ headers=self.headers,
1065
+ )
1066
+
1067
+ def _release_connection(self) -> None:
1068
+ if self._connection is not None:
1069
+ if self._writer is None:
1070
+ self._connection.release()
1071
+ self._connection = None
1072
+ else:
1073
+ self._writer.add_done_callback(lambda f: self._release_connection())
1074
+
1075
+ async def _wait_released(self) -> None:
1076
+ if self._writer is not None:
1077
+ await self._writer
1078
+ self._release_connection()
1079
+
1080
+ def _cleanup_writer(self) -> None:
1081
+ if self._writer is not None:
1082
+ self._writer.cancel()
1083
+ self._session = None
1084
+
1085
+ def _notify_content(self) -> None:
1086
+ content = self.content
1087
+ if content and content.exception() is None:
1088
+ content.set_exception(ClientConnectionError("Connection closed"))
1089
+ self._released = True
1090
+
1091
+ async def wait_for_close(self) -> None:
1092
+ if self._writer is not None:
1093
+ await self._writer
1094
+ self.release()
1095
+
1096
+ async def read(self) -> bytes:
1097
+ """Read response payload."""
1098
+ if self._body is None:
1099
+ try:
1100
+ self._body = await self.content.read()
1101
+ for trace in self._traces:
1102
+ await trace.send_response_chunk_received(
1103
+ self.method, self.url, self._body
1104
+ )
1105
+ except BaseException:
1106
+ self.close()
1107
+ raise
1108
+ elif self._released: # Response explicitly released
1109
+ raise ClientConnectionError("Connection closed")
1110
+
1111
+ protocol = self._connection and self._connection.protocol
1112
+ if protocol is None or not protocol.upgraded:
1113
+ await self._wait_released() # Underlying connection released
1114
+ return self._body # type: ignore[no-any-return]
1115
+
1116
+ def get_encoding(self) -> str:
1117
+ ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower()
1118
+ mimetype = helpers.parse_mimetype(ctype)
1119
+
1120
+ encoding = mimetype.parameters.get("charset")
1121
+ if encoding:
1122
+ with contextlib.suppress(LookupError):
1123
+ return codecs.lookup(encoding).name
1124
+
1125
+ if mimetype.type == "application" and (
1126
+ mimetype.subtype == "json" or mimetype.subtype == "rdap"
1127
+ ):
1128
+ # RFC 7159 states that the default encoding is UTF-8.
1129
+ # RFC 7483 defines application/rdap+json
1130
+ return "utf-8"
1131
+
1132
+ if self._body is None:
1133
+ raise RuntimeError(
1134
+ "Cannot compute fallback encoding of a not yet read body"
1135
+ )
1136
+
1137
+ return self._resolve_charset(self, self._body)
1138
+
1139
+ async def text(self, encoding: Optional[str] = None, errors: str = "strict") -> str:
1140
+ """Read response payload and decode."""
1141
+ if self._body is None:
1142
+ await self.read()
1143
+
1144
+ if encoding is None:
1145
+ encoding = self.get_encoding()
1146
+
1147
+ return self._body.decode( # type: ignore[no-any-return,union-attr]
1148
+ encoding, errors=errors
1149
+ )
1150
+
1151
+ async def json(
1152
+ self,
1153
+ *,
1154
+ encoding: Optional[str] = None,
1155
+ loads: JSONDecoder = DEFAULT_JSON_DECODER,
1156
+ content_type: Optional[str] = "application/json",
1157
+ ) -> Any:
1158
+ """Read and decodes JSON response."""
1159
+ if self._body is None:
1160
+ await self.read()
1161
+
1162
+ if content_type:
1163
+ ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower()
1164
+ if not _is_expected_content_type(ctype, content_type):
1165
+ raise ContentTypeError(
1166
+ self.request_info,
1167
+ self.history,
1168
+ message=(
1169
+ "Attempt to decode JSON with " "unexpected mimetype: %s" % ctype
1170
+ ),
1171
+ headers=self.headers,
1172
+ )
1173
+
1174
+ stripped = self._body.strip() # type: ignore[union-attr]
1175
+ if not stripped:
1176
+ return None
1177
+
1178
+ if encoding is None:
1179
+ encoding = self.get_encoding()
1180
+
1181
+ return loads(stripped.decode(encoding))
1182
+
1183
+ async def __aenter__(self) -> "ClientResponse":
1184
+ return self
1185
+
1186
+ async def __aexit__(
1187
+ self,
1188
+ exc_type: Optional[Type[BaseException]],
1189
+ exc_val: Optional[BaseException],
1190
+ exc_tb: Optional[TracebackType],
1191
+ ) -> None:
1192
+ # similar to _RequestContextManager, we do not need to check
1193
+ # for exceptions, response object can close connection
1194
+ # if state is broken
1195
+ self.release()
1196
+ await self.wait_for_close()
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/client_ws.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebSocket client for asyncio."""
2
+
3
+ import asyncio
4
+ import sys
5
+ from typing import Any, Optional, cast
6
+
7
+ from .client_exceptions import ClientError
8
+ from .client_reqrep import ClientResponse
9
+ from .helpers import call_later, set_result
10
+ from .http import (
11
+ WS_CLOSED_MESSAGE,
12
+ WS_CLOSING_MESSAGE,
13
+ WebSocketError,
14
+ WSCloseCode,
15
+ WSMessage,
16
+ WSMsgType,
17
+ )
18
+ from .http_websocket import WebSocketWriter # WSMessage
19
+ from .streams import EofStream, FlowControlDataQueue
20
+ from .typedefs import (
21
+ DEFAULT_JSON_DECODER,
22
+ DEFAULT_JSON_ENCODER,
23
+ JSONDecoder,
24
+ JSONEncoder,
25
+ )
26
+
27
+ if sys.version_info >= (3, 11):
28
+ import asyncio as async_timeout
29
+ else:
30
+ import async_timeout
31
+
32
+
33
+ class ClientWebSocketResponse:
34
+ def __init__(
35
+ self,
36
+ reader: "FlowControlDataQueue[WSMessage]",
37
+ writer: WebSocketWriter,
38
+ protocol: Optional[str],
39
+ response: ClientResponse,
40
+ timeout: float,
41
+ autoclose: bool,
42
+ autoping: bool,
43
+ loop: asyncio.AbstractEventLoop,
44
+ *,
45
+ receive_timeout: Optional[float] = None,
46
+ heartbeat: Optional[float] = None,
47
+ compress: int = 0,
48
+ client_notakeover: bool = False,
49
+ ) -> None:
50
+ self._response = response
51
+ self._conn = response.connection
52
+
53
+ self._writer = writer
54
+ self._reader = reader
55
+ self._protocol = protocol
56
+ self._closed = False
57
+ self._closing = False
58
+ self._close_code: Optional[int] = None
59
+ self._timeout = timeout
60
+ self._receive_timeout = receive_timeout
61
+ self._autoclose = autoclose
62
+ self._autoping = autoping
63
+ self._heartbeat = heartbeat
64
+ self._heartbeat_cb: Optional[asyncio.TimerHandle] = None
65
+ if heartbeat is not None:
66
+ self._pong_heartbeat = heartbeat / 2.0
67
+ self._pong_response_cb: Optional[asyncio.TimerHandle] = None
68
+ self._loop = loop
69
+ self._waiting: Optional[asyncio.Future[bool]] = None
70
+ self._exception: Optional[BaseException] = None
71
+ self._compress = compress
72
+ self._client_notakeover = client_notakeover
73
+
74
+ self._reset_heartbeat()
75
+
76
+ def _cancel_heartbeat(self) -> None:
77
+ if self._pong_response_cb is not None:
78
+ self._pong_response_cb.cancel()
79
+ self._pong_response_cb = None
80
+
81
+ if self._heartbeat_cb is not None:
82
+ self._heartbeat_cb.cancel()
83
+ self._heartbeat_cb = None
84
+
85
+ def _reset_heartbeat(self) -> None:
86
+ self._cancel_heartbeat()
87
+
88
+ if self._heartbeat is not None:
89
+ self._heartbeat_cb = call_later(
90
+ self._send_heartbeat,
91
+ self._heartbeat,
92
+ self._loop,
93
+ timeout_ceil_threshold=self._conn._connector._timeout_ceil_threshold
94
+ if self._conn is not None
95
+ else 5,
96
+ )
97
+
98
+ def _send_heartbeat(self) -> None:
99
+ if self._heartbeat is not None and not self._closed:
100
+ # fire-and-forget a task is not perfect but maybe ok for
101
+ # sending ping. Otherwise we need a long-living heartbeat
102
+ # task in the class.
103
+ self._loop.create_task(self._writer.ping())
104
+
105
+ if self._pong_response_cb is not None:
106
+ self._pong_response_cb.cancel()
107
+ self._pong_response_cb = call_later(
108
+ self._pong_not_received,
109
+ self._pong_heartbeat,
110
+ self._loop,
111
+ timeout_ceil_threshold=self._conn._connector._timeout_ceil_threshold
112
+ if self._conn is not None
113
+ else 5,
114
+ )
115
+
116
+ def _pong_not_received(self) -> None:
117
+ if not self._closed:
118
+ self._closed = True
119
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
120
+ self._exception = asyncio.TimeoutError()
121
+ self._response.close()
122
+
123
+ @property
124
+ def closed(self) -> bool:
125
+ return self._closed
126
+
127
+ @property
128
+ def close_code(self) -> Optional[int]:
129
+ return self._close_code
130
+
131
+ @property
132
+ def protocol(self) -> Optional[str]:
133
+ return self._protocol
134
+
135
+ @property
136
+ def compress(self) -> int:
137
+ return self._compress
138
+
139
+ @property
140
+ def client_notakeover(self) -> bool:
141
+ return self._client_notakeover
142
+
143
+ def get_extra_info(self, name: str, default: Any = None) -> Any:
144
+ """extra info from connection transport"""
145
+ conn = self._response.connection
146
+ if conn is None:
147
+ return default
148
+ transport = conn.transport
149
+ if transport is None:
150
+ return default
151
+ return transport.get_extra_info(name, default)
152
+
153
+ def exception(self) -> Optional[BaseException]:
154
+ return self._exception
155
+
156
+ async def ping(self, message: bytes = b"") -> None:
157
+ await self._writer.ping(message)
158
+
159
+ async def pong(self, message: bytes = b"") -> None:
160
+ await self._writer.pong(message)
161
+
162
+ async def send_str(self, data: str, compress: Optional[int] = None) -> None:
163
+ if not isinstance(data, str):
164
+ raise TypeError("data argument must be str (%r)" % type(data))
165
+ await self._writer.send(data, binary=False, compress=compress)
166
+
167
+ async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:
168
+ if not isinstance(data, (bytes, bytearray, memoryview)):
169
+ raise TypeError("data argument must be byte-ish (%r)" % type(data))
170
+ await self._writer.send(data, binary=True, compress=compress)
171
+
172
+ async def send_json(
173
+ self,
174
+ data: Any,
175
+ compress: Optional[int] = None,
176
+ *,
177
+ dumps: JSONEncoder = DEFAULT_JSON_ENCODER,
178
+ ) -> None:
179
+ await self.send_str(dumps(data), compress=compress)
180
+
181
+ async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bool:
182
+ # we need to break `receive()` cycle first,
183
+ # `close()` may be called from different task
184
+ if self._waiting is not None and not self._closing:
185
+ self._closing = True
186
+ self._reader.feed_data(WS_CLOSING_MESSAGE, 0)
187
+ await self._waiting
188
+
189
+ if not self._closed:
190
+ self._cancel_heartbeat()
191
+ self._closed = True
192
+ try:
193
+ await self._writer.close(code, message)
194
+ except asyncio.CancelledError:
195
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
196
+ self._response.close()
197
+ raise
198
+ except Exception as exc:
199
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
200
+ self._exception = exc
201
+ self._response.close()
202
+ return True
203
+
204
+ if self._close_code:
205
+ self._response.close()
206
+ return True
207
+
208
+ while True:
209
+ try:
210
+ async with async_timeout.timeout(self._timeout):
211
+ msg = await self._reader.read()
212
+ except asyncio.CancelledError:
213
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
214
+ self._response.close()
215
+ raise
216
+ except Exception as exc:
217
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
218
+ self._exception = exc
219
+ self._response.close()
220
+ return True
221
+
222
+ if msg.type == WSMsgType.CLOSE:
223
+ self._close_code = msg.data
224
+ self._response.close()
225
+ return True
226
+ else:
227
+ return False
228
+
229
+ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
230
+ while True:
231
+ if self._waiting is not None:
232
+ raise RuntimeError("Concurrent call to receive() is not allowed")
233
+
234
+ if self._closed:
235
+ return WS_CLOSED_MESSAGE
236
+ elif self._closing:
237
+ await self.close()
238
+ return WS_CLOSED_MESSAGE
239
+
240
+ try:
241
+ self._waiting = self._loop.create_future()
242
+ try:
243
+ async with async_timeout.timeout(timeout or self._receive_timeout):
244
+ msg = await self._reader.read()
245
+ self._reset_heartbeat()
246
+ finally:
247
+ waiter = self._waiting
248
+ self._waiting = None
249
+ set_result(waiter, True)
250
+ except (asyncio.CancelledError, asyncio.TimeoutError):
251
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
252
+ raise
253
+ except EofStream:
254
+ self._close_code = WSCloseCode.OK
255
+ await self.close()
256
+ return WSMessage(WSMsgType.CLOSED, None, None)
257
+ except ClientError:
258
+ self._closed = True
259
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
260
+ return WS_CLOSED_MESSAGE
261
+ except WebSocketError as exc:
262
+ self._close_code = exc.code
263
+ await self.close(code=exc.code)
264
+ return WSMessage(WSMsgType.ERROR, exc, None)
265
+ except Exception as exc:
266
+ self._exception = exc
267
+ self._closing = True
268
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
269
+ await self.close()
270
+ return WSMessage(WSMsgType.ERROR, exc, None)
271
+
272
+ if msg.type == WSMsgType.CLOSE:
273
+ self._closing = True
274
+ self._close_code = msg.data
275
+ if not self._closed and self._autoclose:
276
+ await self.close()
277
+ elif msg.type == WSMsgType.CLOSING:
278
+ self._closing = True
279
+ elif msg.type == WSMsgType.PING and self._autoping:
280
+ await self.pong(msg.data)
281
+ continue
282
+ elif msg.type == WSMsgType.PONG and self._autoping:
283
+ continue
284
+
285
+ return msg
286
+
287
+ async def receive_str(self, *, timeout: Optional[float] = None) -> str:
288
+ msg = await self.receive(timeout)
289
+ if msg.type != WSMsgType.TEXT:
290
+ raise TypeError(f"Received message {msg.type}:{msg.data!r} is not str")
291
+ return cast(str, msg.data)
292
+
293
+ async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:
294
+ msg = await self.receive(timeout)
295
+ if msg.type != WSMsgType.BINARY:
296
+ raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes")
297
+ return cast(bytes, msg.data)
298
+
299
+ async def receive_json(
300
+ self,
301
+ *,
302
+ loads: JSONDecoder = DEFAULT_JSON_DECODER,
303
+ timeout: Optional[float] = None,
304
+ ) -> Any:
305
+ data = await self.receive_str(timeout=timeout)
306
+ return loads(data)
307
+
308
+ def __aiter__(self) -> "ClientWebSocketResponse":
309
+ return self
310
+
311
+ async def __anext__(self) -> WSMessage:
312
+ msg = await self.receive()
313
+ if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
314
+ raise StopAsyncIteration
315
+ return msg
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/compression_utils.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import zlib
3
+ from concurrent.futures import Executor
4
+ from typing import Optional, cast
5
+
6
+ try:
7
+ try:
8
+ import brotlicffi as brotli
9
+ except ImportError:
10
+ import brotli
11
+
12
+ HAS_BROTLI = True
13
+ except ImportError: # pragma: no cover
14
+ HAS_BROTLI = False
15
+
16
+ MAX_SYNC_CHUNK_SIZE = 1024
17
+
18
+
19
+ def encoding_to_mode(
20
+ encoding: Optional[str] = None,
21
+ suppress_deflate_header: bool = False,
22
+ ) -> int:
23
+ if encoding == "gzip":
24
+ return 16 + zlib.MAX_WBITS
25
+
26
+ return -zlib.MAX_WBITS if suppress_deflate_header else zlib.MAX_WBITS
27
+
28
+
29
+ class ZlibBaseHandler:
30
+ def __init__(
31
+ self,
32
+ mode: int,
33
+ executor: Optional[Executor] = None,
34
+ max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE,
35
+ ):
36
+ self._mode = mode
37
+ self._executor = executor
38
+ self._max_sync_chunk_size = max_sync_chunk_size
39
+
40
+
41
+ class ZLibCompressor(ZlibBaseHandler):
42
+ def __init__(
43
+ self,
44
+ encoding: Optional[str] = None,
45
+ suppress_deflate_header: bool = False,
46
+ level: Optional[int] = None,
47
+ wbits: Optional[int] = None,
48
+ strategy: int = zlib.Z_DEFAULT_STRATEGY,
49
+ executor: Optional[Executor] = None,
50
+ max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE,
51
+ ):
52
+ super().__init__(
53
+ mode=encoding_to_mode(encoding, suppress_deflate_header)
54
+ if wbits is None
55
+ else wbits,
56
+ executor=executor,
57
+ max_sync_chunk_size=max_sync_chunk_size,
58
+ )
59
+ if level is None:
60
+ self._compressor = zlib.compressobj(wbits=self._mode, strategy=strategy)
61
+ else:
62
+ self._compressor = zlib.compressobj(
63
+ wbits=self._mode, strategy=strategy, level=level
64
+ )
65
+ self._compress_lock = asyncio.Lock()
66
+
67
+ def compress_sync(self, data: bytes) -> bytes:
68
+ return self._compressor.compress(data)
69
+
70
+ async def compress(self, data: bytes) -> bytes:
71
+ async with self._compress_lock:
72
+ # To ensure the stream is consistent in the event
73
+ # there are multiple writers, we need to lock
74
+ # the compressor so that only one writer can
75
+ # compress at a time.
76
+ if (
77
+ self._max_sync_chunk_size is not None
78
+ and len(data) > self._max_sync_chunk_size
79
+ ):
80
+ return await asyncio.get_event_loop().run_in_executor(
81
+ self._executor, self.compress_sync, data
82
+ )
83
+ return self.compress_sync(data)
84
+
85
+ def flush(self, mode: int = zlib.Z_FINISH) -> bytes:
86
+ return self._compressor.flush(mode)
87
+
88
+
89
+ class ZLibDecompressor(ZlibBaseHandler):
90
+ def __init__(
91
+ self,
92
+ encoding: Optional[str] = None,
93
+ suppress_deflate_header: bool = False,
94
+ executor: Optional[Executor] = None,
95
+ max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE,
96
+ ):
97
+ super().__init__(
98
+ mode=encoding_to_mode(encoding, suppress_deflate_header),
99
+ executor=executor,
100
+ max_sync_chunk_size=max_sync_chunk_size,
101
+ )
102
+ self._decompressor = zlib.decompressobj(wbits=self._mode)
103
+
104
+ def decompress_sync(self, data: bytes, max_length: int = 0) -> bytes:
105
+ return self._decompressor.decompress(data, max_length)
106
+
107
+ async def decompress(self, data: bytes, max_length: int = 0) -> bytes:
108
+ if (
109
+ self._max_sync_chunk_size is not None
110
+ and len(data) > self._max_sync_chunk_size
111
+ ):
112
+ return await asyncio.get_event_loop().run_in_executor(
113
+ self._executor, self.decompress_sync, data, max_length
114
+ )
115
+ return self.decompress_sync(data, max_length)
116
+
117
+ def flush(self, length: int = 0) -> bytes:
118
+ return (
119
+ self._decompressor.flush(length)
120
+ if length > 0
121
+ else self._decompressor.flush()
122
+ )
123
+
124
+ @property
125
+ def eof(self) -> bool:
126
+ return self._decompressor.eof
127
+
128
+ @property
129
+ def unconsumed_tail(self) -> bytes:
130
+ return self._decompressor.unconsumed_tail
131
+
132
+ @property
133
+ def unused_data(self) -> bytes:
134
+ return self._decompressor.unused_data
135
+
136
+
137
+ class BrotliDecompressor:
138
+ # Supports both 'brotlipy' and 'Brotli' packages
139
+ # since they share an import name. The top branches
140
+ # are for 'brotlipy' and bottom branches for 'Brotli'
141
+ def __init__(self) -> None:
142
+ if not HAS_BROTLI:
143
+ raise RuntimeError(
144
+ "The brotli decompression is not available. "
145
+ "Please install `Brotli` module"
146
+ )
147
+ self._obj = brotli.Decompressor()
148
+
149
+ def decompress_sync(self, data: bytes) -> bytes:
150
+ if hasattr(self._obj, "decompress"):
151
+ return cast(bytes, self._obj.decompress(data))
152
+ return cast(bytes, self._obj.process(data))
153
+
154
+ def flush(self) -> bytes:
155
+ if hasattr(self._obj, "flush"):
156
+ return cast(bytes, self._obj.flush())
157
+ return b""
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/connector.py ADDED
@@ -0,0 +1,1489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import functools
3
+ import random
4
+ import sys
5
+ import traceback
6
+ import warnings
7
+ from collections import defaultdict, deque
8
+ from contextlib import suppress
9
+ from http import HTTPStatus
10
+ from http.cookies import SimpleCookie
11
+ from itertools import cycle, islice
12
+ from time import monotonic
13
+ from types import TracebackType
14
+ from typing import (
15
+ TYPE_CHECKING,
16
+ Any,
17
+ Awaitable,
18
+ Callable,
19
+ DefaultDict,
20
+ Dict,
21
+ Iterator,
22
+ List,
23
+ Literal,
24
+ Optional,
25
+ Set,
26
+ Tuple,
27
+ Type,
28
+ Union,
29
+ cast,
30
+ )
31
+
32
+ import attr
33
+
34
+ from . import hdrs, helpers
35
+ from .abc import AbstractResolver
36
+ from .client_exceptions import (
37
+ ClientConnectionError,
38
+ ClientConnectorCertificateError,
39
+ ClientConnectorError,
40
+ ClientConnectorSSLError,
41
+ ClientHttpProxyError,
42
+ ClientProxyConnectionError,
43
+ ServerFingerprintMismatch,
44
+ UnixClientConnectorError,
45
+ cert_errors,
46
+ ssl_errors,
47
+ )
48
+ from .client_proto import ResponseHandler
49
+ from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params
50
+ from .helpers import ceil_timeout, get_running_loop, is_ip_address, noop, sentinel
51
+ from .locks import EventResultOrError
52
+ from .resolver import DefaultResolver
53
+
54
+ try:
55
+ import ssl
56
+
57
+ SSLContext = ssl.SSLContext
58
+ except ImportError: # pragma: no cover
59
+ ssl = None # type: ignore[assignment]
60
+ SSLContext = object # type: ignore[misc,assignment]
61
+
62
+
63
+ __all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector")
64
+
65
+
66
+ if TYPE_CHECKING: # pragma: no cover
67
+ from .client import ClientTimeout
68
+ from .client_reqrep import ConnectionKey
69
+ from .tracing import Trace
70
+
71
+
72
+ class _DeprecationWaiter:
73
+ __slots__ = ("_awaitable", "_awaited")
74
+
75
+ def __init__(self, awaitable: Awaitable[Any]) -> None:
76
+ self._awaitable = awaitable
77
+ self._awaited = False
78
+
79
+ def __await__(self) -> Any:
80
+ self._awaited = True
81
+ return self._awaitable.__await__()
82
+
83
+ def __del__(self) -> None:
84
+ if not self._awaited:
85
+ warnings.warn(
86
+ "Connector.close() is a coroutine, "
87
+ "please use await connector.close()",
88
+ DeprecationWarning,
89
+ )
90
+
91
+
92
+ class Connection:
93
+
94
+ _source_traceback = None
95
+ _transport = None
96
+
97
+ def __init__(
98
+ self,
99
+ connector: "BaseConnector",
100
+ key: "ConnectionKey",
101
+ protocol: ResponseHandler,
102
+ loop: asyncio.AbstractEventLoop,
103
+ ) -> None:
104
+ self._key = key
105
+ self._connector = connector
106
+ self._loop = loop
107
+ self._protocol: Optional[ResponseHandler] = protocol
108
+ self._callbacks: List[Callable[[], None]] = []
109
+
110
+ if loop.get_debug():
111
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
112
+
113
+ def __repr__(self) -> str:
114
+ return f"Connection<{self._key}>"
115
+
116
+ def __del__(self, _warnings: Any = warnings) -> None:
117
+ if self._protocol is not None:
118
+ kwargs = {"source": self}
119
+ _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
120
+ if self._loop.is_closed():
121
+ return
122
+
123
+ self._connector._release(self._key, self._protocol, should_close=True)
124
+
125
+ context = {"client_connection": self, "message": "Unclosed connection"}
126
+ if self._source_traceback is not None:
127
+ context["source_traceback"] = self._source_traceback
128
+ self._loop.call_exception_handler(context)
129
+
130
+ def __bool__(self) -> Literal[True]:
131
+ """Force subclasses to not be falsy, to make checks simpler."""
132
+ return True
133
+
134
+ @property
135
+ def loop(self) -> asyncio.AbstractEventLoop:
136
+ warnings.warn(
137
+ "connector.loop property is deprecated", DeprecationWarning, stacklevel=2
138
+ )
139
+ return self._loop
140
+
141
+ @property
142
+ def transport(self) -> Optional[asyncio.Transport]:
143
+ if self._protocol is None:
144
+ return None
145
+ return self._protocol.transport
146
+
147
+ @property
148
+ def protocol(self) -> Optional[ResponseHandler]:
149
+ return self._protocol
150
+
151
+ def add_callback(self, callback: Callable[[], None]) -> None:
152
+ if callback is not None:
153
+ self._callbacks.append(callback)
154
+
155
+ def _notify_release(self) -> None:
156
+ callbacks, self._callbacks = self._callbacks[:], []
157
+
158
+ for cb in callbacks:
159
+ with suppress(Exception):
160
+ cb()
161
+
162
+ def close(self) -> None:
163
+ self._notify_release()
164
+
165
+ if self._protocol is not None:
166
+ self._connector._release(self._key, self._protocol, should_close=True)
167
+ self._protocol = None
168
+
169
+ def release(self) -> None:
170
+ self._notify_release()
171
+
172
+ if self._protocol is not None:
173
+ self._connector._release(
174
+ self._key, self._protocol, should_close=self._protocol.should_close
175
+ )
176
+ self._protocol = None
177
+
178
+ @property
179
+ def closed(self) -> bool:
180
+ return self._protocol is None or not self._protocol.is_connected()
181
+
182
+
183
+ class _TransportPlaceholder:
184
+ """placeholder for BaseConnector.connect function"""
185
+
186
+ def close(self) -> None:
187
+ pass
188
+
189
+
190
+ class BaseConnector:
191
+ """Base connector class.
192
+
193
+ keepalive_timeout - (optional) Keep-alive timeout.
194
+ force_close - Set to True to force close and do reconnect
195
+ after each request (and between redirects).
196
+ limit - The total number of simultaneous connections.
197
+ limit_per_host - Number of simultaneous connections to one host.
198
+ enable_cleanup_closed - Enables clean-up closed ssl transports.
199
+ Disabled by default.
200
+ timeout_ceil_threshold - Trigger ceiling of timeout values when
201
+ it's above timeout_ceil_threshold.
202
+ loop - Optional event loop.
203
+ """
204
+
205
+ _closed = True # prevent AttributeError in __del__ if ctor was failed
206
+ _source_traceback = None
207
+
208
+ # abort transport after 2 seconds (cleanup broken connections)
209
+ _cleanup_closed_period = 2.0
210
+
211
+ def __init__(
212
+ self,
213
+ *,
214
+ keepalive_timeout: Union[object, None, float] = sentinel,
215
+ force_close: bool = False,
216
+ limit: int = 100,
217
+ limit_per_host: int = 0,
218
+ enable_cleanup_closed: bool = False,
219
+ loop: Optional[asyncio.AbstractEventLoop] = None,
220
+ timeout_ceil_threshold: float = 5,
221
+ ) -> None:
222
+
223
+ if force_close:
224
+ if keepalive_timeout is not None and keepalive_timeout is not sentinel:
225
+ raise ValueError(
226
+ "keepalive_timeout cannot " "be set if force_close is True"
227
+ )
228
+ else:
229
+ if keepalive_timeout is sentinel:
230
+ keepalive_timeout = 15.0
231
+
232
+ loop = get_running_loop(loop)
233
+ self._timeout_ceil_threshold = timeout_ceil_threshold
234
+
235
+ self._closed = False
236
+ if loop.get_debug():
237
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
238
+
239
+ self._conns: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] = {}
240
+ self._limit = limit
241
+ self._limit_per_host = limit_per_host
242
+ self._acquired: Set[ResponseHandler] = set()
243
+ self._acquired_per_host: DefaultDict[
244
+ ConnectionKey, Set[ResponseHandler]
245
+ ] = defaultdict(set)
246
+ self._keepalive_timeout = cast(float, keepalive_timeout)
247
+ self._force_close = force_close
248
+
249
+ # {host_key: FIFO list of waiters}
250
+ self._waiters = defaultdict(deque) # type: ignore[var-annotated]
251
+
252
+ self._loop = loop
253
+ self._factory = functools.partial(ResponseHandler, loop=loop)
254
+
255
+ self.cookies = SimpleCookie()
256
+
257
+ # start keep-alive connection cleanup task
258
+ self._cleanup_handle: Optional[asyncio.TimerHandle] = None
259
+
260
+ # start cleanup closed transports task
261
+ self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
262
+ self._cleanup_closed_disabled = not enable_cleanup_closed
263
+ self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
264
+ self._cleanup_closed()
265
+
266
+ def __del__(self, _warnings: Any = warnings) -> None:
267
+ if self._closed:
268
+ return
269
+ if not self._conns:
270
+ return
271
+
272
+ conns = [repr(c) for c in self._conns.values()]
273
+
274
+ self._close()
275
+
276
+ kwargs = {"source": self}
277
+ _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
278
+ context = {
279
+ "connector": self,
280
+ "connections": conns,
281
+ "message": "Unclosed connector",
282
+ }
283
+ if self._source_traceback is not None:
284
+ context["source_traceback"] = self._source_traceback
285
+ self._loop.call_exception_handler(context)
286
+
287
+ def __enter__(self) -> "BaseConnector":
288
+ warnings.warn(
289
+ '"with Connector():" is deprecated, '
290
+ 'use "async with Connector():" instead',
291
+ DeprecationWarning,
292
+ )
293
+ return self
294
+
295
+ def __exit__(self, *exc: Any) -> None:
296
+ self._close()
297
+
298
+ async def __aenter__(self) -> "BaseConnector":
299
+ return self
300
+
301
+ async def __aexit__(
302
+ self,
303
+ exc_type: Optional[Type[BaseException]] = None,
304
+ exc_value: Optional[BaseException] = None,
305
+ exc_traceback: Optional[TracebackType] = None,
306
+ ) -> None:
307
+ await self.close()
308
+
309
+ @property
310
+ def force_close(self) -> bool:
311
+ """Ultimately close connection on releasing if True."""
312
+ return self._force_close
313
+
314
+ @property
315
+ def limit(self) -> int:
316
+ """The total number for simultaneous connections.
317
+
318
+ If limit is 0 the connector has no limit.
319
+ The default limit size is 100.
320
+ """
321
+ return self._limit
322
+
323
+ @property
324
+ def limit_per_host(self) -> int:
325
+ """The limit for simultaneous connections to the same endpoint.
326
+
327
+ Endpoints are the same if they are have equal
328
+ (host, port, is_ssl) triple.
329
+ """
330
+ return self._limit_per_host
331
+
332
+ def _cleanup(self) -> None:
333
+ """Cleanup unused transports."""
334
+ if self._cleanup_handle:
335
+ self._cleanup_handle.cancel()
336
+ # _cleanup_handle should be unset, otherwise _release() will not
337
+ # recreate it ever!
338
+ self._cleanup_handle = None
339
+
340
+ now = self._loop.time()
341
+ timeout = self._keepalive_timeout
342
+
343
+ if self._conns:
344
+ connections = {}
345
+ deadline = now - timeout
346
+ for key, conns in self._conns.items():
347
+ alive = []
348
+ for proto, use_time in conns:
349
+ if proto.is_connected():
350
+ if use_time - deadline < 0:
351
+ transport = proto.transport
352
+ proto.close()
353
+ if key.is_ssl and not self._cleanup_closed_disabled:
354
+ self._cleanup_closed_transports.append(transport)
355
+ else:
356
+ alive.append((proto, use_time))
357
+ else:
358
+ transport = proto.transport
359
+ proto.close()
360
+ if key.is_ssl and not self._cleanup_closed_disabled:
361
+ self._cleanup_closed_transports.append(transport)
362
+
363
+ if alive:
364
+ connections[key] = alive
365
+
366
+ self._conns = connections
367
+
368
+ if self._conns:
369
+ self._cleanup_handle = helpers.weakref_handle(
370
+ self,
371
+ "_cleanup",
372
+ timeout,
373
+ self._loop,
374
+ timeout_ceil_threshold=self._timeout_ceil_threshold,
375
+ )
376
+
377
+ def _drop_acquired_per_host(
378
+ self, key: "ConnectionKey", val: ResponseHandler
379
+ ) -> None:
380
+ acquired_per_host = self._acquired_per_host
381
+ if key not in acquired_per_host:
382
+ return
383
+ conns = acquired_per_host[key]
384
+ conns.remove(val)
385
+ if not conns:
386
+ del self._acquired_per_host[key]
387
+
388
+ def _cleanup_closed(self) -> None:
389
+ """Double confirmation for transport close.
390
+
391
+ Some broken ssl servers may leave socket open without proper close.
392
+ """
393
+ if self._cleanup_closed_handle:
394
+ self._cleanup_closed_handle.cancel()
395
+
396
+ for transport in self._cleanup_closed_transports:
397
+ if transport is not None:
398
+ transport.abort()
399
+
400
+ self._cleanup_closed_transports = []
401
+
402
+ if not self._cleanup_closed_disabled:
403
+ self._cleanup_closed_handle = helpers.weakref_handle(
404
+ self,
405
+ "_cleanup_closed",
406
+ self._cleanup_closed_period,
407
+ self._loop,
408
+ timeout_ceil_threshold=self._timeout_ceil_threshold,
409
+ )
410
+
411
+ def close(self) -> Awaitable[None]:
412
+ """Close all opened transports."""
413
+ self._close()
414
+ return _DeprecationWaiter(noop())
415
+
416
+ def _close(self) -> None:
417
+ if self._closed:
418
+ return
419
+
420
+ self._closed = True
421
+
422
+ try:
423
+ if self._loop.is_closed():
424
+ return
425
+
426
+ # cancel cleanup task
427
+ if self._cleanup_handle:
428
+ self._cleanup_handle.cancel()
429
+
430
+ # cancel cleanup close task
431
+ if self._cleanup_closed_handle:
432
+ self._cleanup_closed_handle.cancel()
433
+
434
+ for data in self._conns.values():
435
+ for proto, t0 in data:
436
+ proto.close()
437
+
438
+ for proto in self._acquired:
439
+ proto.close()
440
+
441
+ for transport in self._cleanup_closed_transports:
442
+ if transport is not None:
443
+ transport.abort()
444
+
445
+ finally:
446
+ self._conns.clear()
447
+ self._acquired.clear()
448
+ self._waiters.clear()
449
+ self._cleanup_handle = None
450
+ self._cleanup_closed_transports.clear()
451
+ self._cleanup_closed_handle = None
452
+
453
+ @property
454
+ def closed(self) -> bool:
455
+ """Is connector closed.
456
+
457
+ A readonly property.
458
+ """
459
+ return self._closed
460
+
461
+ def _available_connections(self, key: "ConnectionKey") -> int:
462
+ """
463
+ Return number of available connections.
464
+
465
+ The limit, limit_per_host and the connection key are taken into account.
466
+
467
+ If it returns less than 1 means that there are no connections
468
+ available.
469
+ """
470
+ if self._limit:
471
+ # total calc available connections
472
+ available = self._limit - len(self._acquired)
473
+
474
+ # check limit per host
475
+ if (
476
+ self._limit_per_host
477
+ and available > 0
478
+ and key in self._acquired_per_host
479
+ ):
480
+ acquired = self._acquired_per_host.get(key)
481
+ assert acquired is not None
482
+ available = self._limit_per_host - len(acquired)
483
+
484
+ elif self._limit_per_host and key in self._acquired_per_host:
485
+ # check limit per host
486
+ acquired = self._acquired_per_host.get(key)
487
+ assert acquired is not None
488
+ available = self._limit_per_host - len(acquired)
489
+ else:
490
+ available = 1
491
+
492
+ return available
493
+
494
+ async def connect(
495
+ self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
496
+ ) -> Connection:
497
+ """Get from pool or create new connection."""
498
+ key = req.connection_key
499
+ available = self._available_connections(key)
500
+
501
+ # Wait if there are no available connections or if there are/were
502
+ # waiters (i.e. don't steal connection from a waiter about to wake up)
503
+ if available <= 0 or key in self._waiters:
504
+ fut = self._loop.create_future()
505
+
506
+ # This connection will now count towards the limit.
507
+ self._waiters[key].append(fut)
508
+
509
+ if traces:
510
+ for trace in traces:
511
+ await trace.send_connection_queued_start()
512
+
513
+ try:
514
+ await fut
515
+ except BaseException as e:
516
+ if key in self._waiters:
517
+ # remove a waiter even if it was cancelled, normally it's
518
+ # removed when it's notified
519
+ try:
520
+ self._waiters[key].remove(fut)
521
+ except ValueError: # fut may no longer be in list
522
+ pass
523
+
524
+ raise e
525
+ finally:
526
+ if key in self._waiters and not self._waiters[key]:
527
+ del self._waiters[key]
528
+
529
+ if traces:
530
+ for trace in traces:
531
+ await trace.send_connection_queued_end()
532
+
533
+ proto = self._get(key)
534
+ if proto is None:
535
+ placeholder = cast(ResponseHandler, _TransportPlaceholder())
536
+ self._acquired.add(placeholder)
537
+ self._acquired_per_host[key].add(placeholder)
538
+
539
+ if traces:
540
+ for trace in traces:
541
+ await trace.send_connection_create_start()
542
+
543
+ try:
544
+ proto = await self._create_connection(req, traces, timeout)
545
+ if self._closed:
546
+ proto.close()
547
+ raise ClientConnectionError("Connector is closed.")
548
+ except BaseException:
549
+ if not self._closed:
550
+ self._acquired.remove(placeholder)
551
+ self._drop_acquired_per_host(key, placeholder)
552
+ self._release_waiter()
553
+ raise
554
+ else:
555
+ if not self._closed:
556
+ self._acquired.remove(placeholder)
557
+ self._drop_acquired_per_host(key, placeholder)
558
+
559
+ if traces:
560
+ for trace in traces:
561
+ await trace.send_connection_create_end()
562
+ else:
563
+ if traces:
564
+ # Acquire the connection to prevent race conditions with limits
565
+ placeholder = cast(ResponseHandler, _TransportPlaceholder())
566
+ self._acquired.add(placeholder)
567
+ self._acquired_per_host[key].add(placeholder)
568
+ for trace in traces:
569
+ await trace.send_connection_reuseconn()
570
+ self._acquired.remove(placeholder)
571
+ self._drop_acquired_per_host(key, placeholder)
572
+
573
+ self._acquired.add(proto)
574
+ self._acquired_per_host[key].add(proto)
575
+ return Connection(self, key, proto, self._loop)
576
+
577
+ def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
578
+ try:
579
+ conns = self._conns[key]
580
+ except KeyError:
581
+ return None
582
+
583
+ t1 = self._loop.time()
584
+ while conns:
585
+ proto, t0 = conns.pop()
586
+ if proto.is_connected():
587
+ if t1 - t0 > self._keepalive_timeout:
588
+ transport = proto.transport
589
+ proto.close()
590
+ # only for SSL transports
591
+ if key.is_ssl and not self._cleanup_closed_disabled:
592
+ self._cleanup_closed_transports.append(transport)
593
+ else:
594
+ if not conns:
595
+ # The very last connection was reclaimed: drop the key
596
+ del self._conns[key]
597
+ return proto
598
+ else:
599
+ transport = proto.transport
600
+ proto.close()
601
+ if key.is_ssl and not self._cleanup_closed_disabled:
602
+ self._cleanup_closed_transports.append(transport)
603
+
604
+ # No more connections: drop the key
605
+ del self._conns[key]
606
+ return None
607
+
608
+ def _release_waiter(self) -> None:
609
+ """
610
+ Iterates over all waiters until one to be released is found.
611
+
612
+ The one to be released is not finished and
613
+ belongs to a host that has available connections.
614
+ """
615
+ if not self._waiters:
616
+ return
617
+
618
+ # Having the dict keys ordered this avoids to iterate
619
+ # at the same order at each call.
620
+ queues = list(self._waiters.keys())
621
+ random.shuffle(queues)
622
+
623
+ for key in queues:
624
+ if self._available_connections(key) < 1:
625
+ continue
626
+
627
+ waiters = self._waiters[key]
628
+ while waiters:
629
+ waiter = waiters.popleft()
630
+ if not waiter.done():
631
+ waiter.set_result(None)
632
+ return
633
+
634
+ def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None:
635
+ if self._closed:
636
+ # acquired connection is already released on connector closing
637
+ return
638
+
639
+ try:
640
+ self._acquired.remove(proto)
641
+ self._drop_acquired_per_host(key, proto)
642
+ except KeyError: # pragma: no cover
643
+ # this may be result of undetermenistic order of objects
644
+ # finalization due garbage collection.
645
+ pass
646
+ else:
647
+ self._release_waiter()
648
+
649
+ def _release(
650
+ self,
651
+ key: "ConnectionKey",
652
+ protocol: ResponseHandler,
653
+ *,
654
+ should_close: bool = False,
655
+ ) -> None:
656
+ if self._closed:
657
+ # acquired connection is already released on connector closing
658
+ return
659
+
660
+ self._release_acquired(key, protocol)
661
+
662
+ if self._force_close:
663
+ should_close = True
664
+
665
+ if should_close or protocol.should_close:
666
+ transport = protocol.transport
667
+ protocol.close()
668
+
669
+ if key.is_ssl and not self._cleanup_closed_disabled:
670
+ self._cleanup_closed_transports.append(transport)
671
+ else:
672
+ conns = self._conns.get(key)
673
+ if conns is None:
674
+ conns = self._conns[key] = []
675
+ conns.append((protocol, self._loop.time()))
676
+
677
+ if self._cleanup_handle is None:
678
+ self._cleanup_handle = helpers.weakref_handle(
679
+ self,
680
+ "_cleanup",
681
+ self._keepalive_timeout,
682
+ self._loop,
683
+ timeout_ceil_threshold=self._timeout_ceil_threshold,
684
+ )
685
+
686
+ async def _create_connection(
687
+ self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
688
+ ) -> ResponseHandler:
689
+ raise NotImplementedError()
690
+
691
+
692
+ class _DNSCacheTable:
693
+ def __init__(self, ttl: Optional[float] = None) -> None:
694
+ self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] = {}
695
+ self._timestamps: Dict[Tuple[str, int], float] = {}
696
+ self._ttl = ttl
697
+
698
+ def __contains__(self, host: object) -> bool:
699
+ return host in self._addrs_rr
700
+
701
+ def add(self, key: Tuple[str, int], addrs: List[Dict[str, Any]]) -> None:
702
+ self._addrs_rr[key] = (cycle(addrs), len(addrs))
703
+
704
+ if self._ttl is not None:
705
+ self._timestamps[key] = monotonic()
706
+
707
+ def remove(self, key: Tuple[str, int]) -> None:
708
+ self._addrs_rr.pop(key, None)
709
+
710
+ if self._ttl is not None:
711
+ self._timestamps.pop(key, None)
712
+
713
+ def clear(self) -> None:
714
+ self._addrs_rr.clear()
715
+ self._timestamps.clear()
716
+
717
+ def next_addrs(self, key: Tuple[str, int]) -> List[Dict[str, Any]]:
718
+ loop, length = self._addrs_rr[key]
719
+ addrs = list(islice(loop, length))
720
+ # Consume one more element to shift internal state of `cycle`
721
+ next(loop)
722
+ return addrs
723
+
724
+ def expired(self, key: Tuple[str, int]) -> bool:
725
+ if self._ttl is None:
726
+ return False
727
+
728
+ return self._timestamps[key] + self._ttl < monotonic()
729
+
730
+
731
+ class TCPConnector(BaseConnector):
732
+ """TCP connector.
733
+
734
+ verify_ssl - Set to True to check ssl certifications.
735
+ fingerprint - Pass the binary sha256
736
+ digest of the expected certificate in DER format to verify
737
+ that the certificate the server presents matches. See also
738
+ https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning
739
+ resolver - Enable DNS lookups and use this
740
+ resolver
741
+ use_dns_cache - Use memory cache for DNS lookups.
742
+ ttl_dns_cache - Max seconds having cached a DNS entry, None forever.
743
+ family - socket address family
744
+ local_addr - local tuple of (host, port) to bind socket to
745
+
746
+ keepalive_timeout - (optional) Keep-alive timeout.
747
+ force_close - Set to True to force close and do reconnect
748
+ after each request (and between redirects).
749
+ limit - The total number of simultaneous connections.
750
+ limit_per_host - Number of simultaneous connections to one host.
751
+ enable_cleanup_closed - Enables clean-up closed ssl transports.
752
+ Disabled by default.
753
+ loop - Optional event loop.
754
+ """
755
+
756
+ def __init__(
757
+ self,
758
+ *,
759
+ verify_ssl: bool = True,
760
+ fingerprint: Optional[bytes] = None,
761
+ use_dns_cache: bool = True,
762
+ ttl_dns_cache: Optional[int] = 10,
763
+ family: int = 0,
764
+ ssl_context: Optional[SSLContext] = None,
765
+ ssl: Union[None, Literal[False], Fingerprint, SSLContext] = None,
766
+ local_addr: Optional[Tuple[str, int]] = None,
767
+ resolver: Optional[AbstractResolver] = None,
768
+ keepalive_timeout: Union[None, float, object] = sentinel,
769
+ force_close: bool = False,
770
+ limit: int = 100,
771
+ limit_per_host: int = 0,
772
+ enable_cleanup_closed: bool = False,
773
+ loop: Optional[asyncio.AbstractEventLoop] = None,
774
+ timeout_ceil_threshold: float = 5,
775
+ ):
776
+ super().__init__(
777
+ keepalive_timeout=keepalive_timeout,
778
+ force_close=force_close,
779
+ limit=limit,
780
+ limit_per_host=limit_per_host,
781
+ enable_cleanup_closed=enable_cleanup_closed,
782
+ loop=loop,
783
+ timeout_ceil_threshold=timeout_ceil_threshold,
784
+ )
785
+
786
+ self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
787
+ if resolver is None:
788
+ resolver = DefaultResolver(loop=self._loop)
789
+ self._resolver = resolver
790
+
791
+ self._use_dns_cache = use_dns_cache
792
+ self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
793
+ self._throttle_dns_events: Dict[Tuple[str, int], EventResultOrError] = {}
794
+ self._family = family
795
+ self._local_addr = local_addr
796
+
797
+ def close(self) -> Awaitable[None]:
798
+ """Close all ongoing DNS calls."""
799
+ for ev in self._throttle_dns_events.values():
800
+ ev.cancel()
801
+
802
+ return super().close()
803
+
804
+ @property
805
+ def family(self) -> int:
806
+ """Socket family like AF_INET."""
807
+ return self._family
808
+
809
+ @property
810
+ def use_dns_cache(self) -> bool:
811
+ """True if local DNS caching is enabled."""
812
+ return self._use_dns_cache
813
+
814
+ def clear_dns_cache(
815
+ self, host: Optional[str] = None, port: Optional[int] = None
816
+ ) -> None:
817
+ """Remove specified host/port or clear all dns local cache."""
818
+ if host is not None and port is not None:
819
+ self._cached_hosts.remove((host, port))
820
+ elif host is not None or port is not None:
821
+ raise ValueError("either both host and port " "or none of them are allowed")
822
+ else:
823
+ self._cached_hosts.clear()
824
+
825
+ async def _resolve_host(
826
+ self, host: str, port: int, traces: Optional[List["Trace"]] = None
827
+ ) -> List[Dict[str, Any]]:
828
+ if is_ip_address(host):
829
+ return [
830
+ {
831
+ "hostname": host,
832
+ "host": host,
833
+ "port": port,
834
+ "family": self._family,
835
+ "proto": 0,
836
+ "flags": 0,
837
+ }
838
+ ]
839
+
840
+ if not self._use_dns_cache:
841
+
842
+ if traces:
843
+ for trace in traces:
844
+ await trace.send_dns_resolvehost_start(host)
845
+
846
+ res = await self._resolver.resolve(host, port, family=self._family)
847
+
848
+ if traces:
849
+ for trace in traces:
850
+ await trace.send_dns_resolvehost_end(host)
851
+
852
+ return res
853
+
854
+ key = (host, port)
855
+
856
+ if (key in self._cached_hosts) and (not self._cached_hosts.expired(key)):
857
+ # get result early, before any await (#4014)
858
+ result = self._cached_hosts.next_addrs(key)
859
+
860
+ if traces:
861
+ for trace in traces:
862
+ await trace.send_dns_cache_hit(host)
863
+ return result
864
+
865
+ if key in self._throttle_dns_events:
866
+ # get event early, before any await (#4014)
867
+ event = self._throttle_dns_events[key]
868
+ if traces:
869
+ for trace in traces:
870
+ await trace.send_dns_cache_hit(host)
871
+ await event.wait()
872
+ else:
873
+ # update dict early, before any await (#4014)
874
+ self._throttle_dns_events[key] = EventResultOrError(self._loop)
875
+ if traces:
876
+ for trace in traces:
877
+ await trace.send_dns_cache_miss(host)
878
+ try:
879
+
880
+ if traces:
881
+ for trace in traces:
882
+ await trace.send_dns_resolvehost_start(host)
883
+
884
+ addrs = await self._resolver.resolve(host, port, family=self._family)
885
+ if traces:
886
+ for trace in traces:
887
+ await trace.send_dns_resolvehost_end(host)
888
+
889
+ self._cached_hosts.add(key, addrs)
890
+ self._throttle_dns_events[key].set()
891
+ except BaseException as e:
892
+ # any DNS exception, independently of the implementation
893
+ # is set for the waiters to raise the same exception.
894
+ self._throttle_dns_events[key].set(exc=e)
895
+ raise
896
+ finally:
897
+ self._throttle_dns_events.pop(key)
898
+
899
+ return self._cached_hosts.next_addrs(key)
900
+
901
+ async def _create_connection(
902
+ self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
903
+ ) -> ResponseHandler:
904
+ """Create connection.
905
+
906
+ Has same keyword arguments as BaseEventLoop.create_connection.
907
+ """
908
+ if req.proxy:
909
+ _, proto = await self._create_proxy_connection(req, traces, timeout)
910
+ else:
911
+ _, proto = await self._create_direct_connection(req, traces, timeout)
912
+
913
+ return proto
914
+
915
+ @staticmethod
916
+ @functools.lru_cache(None)
917
+ def _make_ssl_context(verified: bool) -> SSLContext:
918
+ if verified:
919
+ return ssl.create_default_context()
920
+ else:
921
+ sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
922
+ sslcontext.options |= ssl.OP_NO_SSLv2
923
+ sslcontext.options |= ssl.OP_NO_SSLv3
924
+ sslcontext.check_hostname = False
925
+ sslcontext.verify_mode = ssl.CERT_NONE
926
+ try:
927
+ sslcontext.options |= ssl.OP_NO_COMPRESSION
928
+ except AttributeError as attr_err:
929
+ warnings.warn(
930
+ "{!s}: The Python interpreter is compiled "
931
+ "against OpenSSL < 1.0.0. Ref: "
932
+ "https://docs.python.org/3/library/ssl.html"
933
+ "#ssl.OP_NO_COMPRESSION".format(attr_err),
934
+ )
935
+ sslcontext.set_default_verify_paths()
936
+ return sslcontext
937
+
938
+ def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]:
939
+ """Logic to get the correct SSL context
940
+
941
+ 0. if req.ssl is false, return None
942
+
943
+ 1. if ssl_context is specified in req, use it
944
+ 2. if _ssl_context is specified in self, use it
945
+ 3. otherwise:
946
+ 1. if verify_ssl is not specified in req, use self.ssl_context
947
+ (will generate a default context according to self.verify_ssl)
948
+ 2. if verify_ssl is True in req, generate a default SSL context
949
+ 3. if verify_ssl is False in req, generate a SSL context that
950
+ won't verify
951
+ """
952
+ if req.is_ssl():
953
+ if ssl is None: # pragma: no cover
954
+ raise RuntimeError("SSL is not supported.")
955
+ sslcontext = req.ssl
956
+ if isinstance(sslcontext, ssl.SSLContext):
957
+ return sslcontext
958
+ if sslcontext is not None:
959
+ # not verified or fingerprinted
960
+ return self._make_ssl_context(False)
961
+ sslcontext = self._ssl
962
+ if isinstance(sslcontext, ssl.SSLContext):
963
+ return sslcontext
964
+ if sslcontext is not None:
965
+ # not verified or fingerprinted
966
+ return self._make_ssl_context(False)
967
+ return self._make_ssl_context(True)
968
+ else:
969
+ return None
970
+
971
+ def _get_fingerprint(self, req: ClientRequest) -> Optional["Fingerprint"]:
972
+ ret = req.ssl
973
+ if isinstance(ret, Fingerprint):
974
+ return ret
975
+ ret = self._ssl
976
+ if isinstance(ret, Fingerprint):
977
+ return ret
978
+ return None
979
+
980
+ async def _wrap_create_connection(
981
+ self,
982
+ *args: Any,
983
+ req: ClientRequest,
984
+ timeout: "ClientTimeout",
985
+ client_error: Type[Exception] = ClientConnectorError,
986
+ **kwargs: Any,
987
+ ) -> Tuple[asyncio.Transport, ResponseHandler]:
988
+ try:
989
+ async with ceil_timeout(
990
+ timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
991
+ ):
992
+ return await self._loop.create_connection(*args, **kwargs)
993
+ except cert_errors as exc:
994
+ raise ClientConnectorCertificateError(req.connection_key, exc) from exc
995
+ except ssl_errors as exc:
996
+ raise ClientConnectorSSLError(req.connection_key, exc) from exc
997
+ except OSError as exc:
998
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
999
+ raise
1000
+ raise client_error(req.connection_key, exc) from exc
1001
+
1002
+ def _fail_on_no_start_tls(self, req: "ClientRequest") -> None:
1003
+ """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.
1004
+
1005
+ It is necessary for TLS-in-TLS so that it is possible to
1006
+ send HTTPS queries through HTTPS proxies.
1007
+
1008
+ This doesn't affect regular HTTP requests, though.
1009
+ """
1010
+ if not req.is_ssl():
1011
+ return
1012
+
1013
+ proxy_url = req.proxy
1014
+ assert proxy_url is not None
1015
+ if proxy_url.scheme != "https":
1016
+ return
1017
+
1018
+ self._check_loop_for_start_tls()
1019
+
1020
+ def _check_loop_for_start_tls(self) -> None:
1021
+ try:
1022
+ self._loop.start_tls
1023
+ except AttributeError as attr_exc:
1024
+ raise RuntimeError(
1025
+ "An HTTPS request is being sent through an HTTPS proxy. "
1026
+ "This needs support for TLS in TLS but it is not implemented "
1027
+ "in your runtime for the stdlib asyncio.\n\n"
1028
+ "Please upgrade to Python 3.11 or higher. For more details, "
1029
+ "please see:\n"
1030
+ "* https://bugs.python.org/issue37179\n"
1031
+ "* https://github.com/python/cpython/pull/28073\n"
1032
+ "* https://docs.aiohttp.org/en/stable/"
1033
+ "client_advanced.html#proxy-support\n"
1034
+ "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
1035
+ ) from attr_exc
1036
+
1037
+ def _loop_supports_start_tls(self) -> bool:
1038
+ try:
1039
+ self._check_loop_for_start_tls()
1040
+ except RuntimeError:
1041
+ return False
1042
+ else:
1043
+ return True
1044
+
1045
+ def _warn_about_tls_in_tls(
1046
+ self,
1047
+ underlying_transport: asyncio.Transport,
1048
+ req: ClientRequest,
1049
+ ) -> None:
1050
+ """Issue a warning if the requested URL has HTTPS scheme."""
1051
+ if req.request_info.url.scheme != "https":
1052
+ return
1053
+
1054
+ asyncio_supports_tls_in_tls = getattr(
1055
+ underlying_transport,
1056
+ "_start_tls_compatible",
1057
+ False,
1058
+ )
1059
+
1060
+ if asyncio_supports_tls_in_tls:
1061
+ return
1062
+
1063
+ warnings.warn(
1064
+ "An HTTPS request is being sent through an HTTPS proxy. "
1065
+ "This support for TLS in TLS is known to be disabled "
1066
+ "in the stdlib asyncio (Python <3.11). This is why you'll probably see "
1067
+ "an error in the log below.\n\n"
1068
+ "It is possible to enable it via monkeypatching. "
1069
+ "For more details, see:\n"
1070
+ "* https://bugs.python.org/issue37179\n"
1071
+ "* https://github.com/python/cpython/pull/28073\n\n"
1072
+ "You can temporarily patch this as follows:\n"
1073
+ "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n"
1074
+ "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
1075
+ RuntimeWarning,
1076
+ source=self,
1077
+ # Why `4`? At least 3 of the calls in the stack originate
1078
+ # from the methods in this class.
1079
+ stacklevel=3,
1080
+ )
1081
+
1082
+ async def _start_tls_connection(
1083
+ self,
1084
+ underlying_transport: asyncio.Transport,
1085
+ req: ClientRequest,
1086
+ timeout: "ClientTimeout",
1087
+ client_error: Type[Exception] = ClientConnectorError,
1088
+ ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1089
+ """Wrap the raw TCP transport with TLS."""
1090
+ tls_proto = self._factory() # Create a brand new proto for TLS
1091
+
1092
+ # Safety of the `cast()` call here is based on the fact that
1093
+ # internally `_get_ssl_context()` only returns `None` when
1094
+ # `req.is_ssl()` evaluates to `False` which is never gonna happen
1095
+ # in this code path. Of course, it's rather fragile
1096
+ # maintainability-wise but this is to be solved separately.
1097
+ sslcontext = cast(ssl.SSLContext, self._get_ssl_context(req))
1098
+
1099
+ try:
1100
+ async with ceil_timeout(
1101
+ timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1102
+ ):
1103
+ try:
1104
+ tls_transport = await self._loop.start_tls(
1105
+ underlying_transport,
1106
+ tls_proto,
1107
+ sslcontext,
1108
+ server_hostname=req.server_hostname or req.host,
1109
+ ssl_handshake_timeout=timeout.total,
1110
+ )
1111
+ except BaseException:
1112
+ # We need to close the underlying transport since
1113
+ # `start_tls()` probably failed before it had a
1114
+ # chance to do this:
1115
+ underlying_transport.close()
1116
+ raise
1117
+ except cert_errors as exc:
1118
+ raise ClientConnectorCertificateError(req.connection_key, exc) from exc
1119
+ except ssl_errors as exc:
1120
+ raise ClientConnectorSSLError(req.connection_key, exc) from exc
1121
+ except OSError as exc:
1122
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1123
+ raise
1124
+ raise client_error(req.connection_key, exc) from exc
1125
+ except TypeError as type_err:
1126
+ # Example cause looks like this:
1127
+ # TypeError: transport <asyncio.sslproto._SSLProtocolTransport
1128
+ # object at 0x7f760615e460> is not supported by start_tls()
1129
+
1130
+ raise ClientConnectionError(
1131
+ "Cannot initialize a TLS-in-TLS connection to host "
1132
+ f"{req.host!s}:{req.port:d} through an underlying connection "
1133
+ f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} "
1134
+ f"[{type_err!s}]"
1135
+ ) from type_err
1136
+ else:
1137
+ if tls_transport is None:
1138
+ msg = "Failed to start TLS (possibly caused by closing transport)"
1139
+ raise client_error(req.connection_key, OSError(msg))
1140
+ tls_proto.connection_made(
1141
+ tls_transport
1142
+ ) # Kick the state machine of the new TLS protocol
1143
+
1144
+ return tls_transport, tls_proto
1145
+
1146
+ async def _create_direct_connection(
1147
+ self,
1148
+ req: ClientRequest,
1149
+ traces: List["Trace"],
1150
+ timeout: "ClientTimeout",
1151
+ *,
1152
+ client_error: Type[Exception] = ClientConnectorError,
1153
+ ) -> Tuple[asyncio.Transport, ResponseHandler]:
1154
+ sslcontext = self._get_ssl_context(req)
1155
+ fingerprint = self._get_fingerprint(req)
1156
+
1157
+ host = req.url.raw_host
1158
+ assert host is not None
1159
+ # Replace multiple trailing dots with a single one.
1160
+ # A trailing dot is only present for fully-qualified domain names.
1161
+ # See https://github.com/aio-libs/aiohttp/pull/7364.
1162
+ if host.endswith(".."):
1163
+ host = host.rstrip(".") + "."
1164
+ port = req.port
1165
+ assert port is not None
1166
+ host_resolved = asyncio.ensure_future(
1167
+ self._resolve_host(host, port, traces=traces), loop=self._loop
1168
+ )
1169
+ try:
1170
+ # Cancelling this lookup should not cancel the underlying lookup
1171
+ # or else the cancel event will get broadcast to all the waiters
1172
+ # across all connections.
1173
+ hosts = await asyncio.shield(host_resolved)
1174
+ except asyncio.CancelledError:
1175
+
1176
+ def drop_exception(fut: "asyncio.Future[List[Dict[str, Any]]]") -> None:
1177
+ with suppress(Exception, asyncio.CancelledError):
1178
+ fut.result()
1179
+
1180
+ host_resolved.add_done_callback(drop_exception)
1181
+ raise
1182
+ except OSError as exc:
1183
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1184
+ raise
1185
+ # in case of proxy it is not ClientProxyConnectionError
1186
+ # it is problem of resolving proxy ip itself
1187
+ raise ClientConnectorError(req.connection_key, exc) from exc
1188
+
1189
+ last_exc: Optional[Exception] = None
1190
+
1191
+ for hinfo in hosts:
1192
+ host = hinfo["host"]
1193
+ port = hinfo["port"]
1194
+
1195
+ # Strip trailing dots, certificates contain FQDN without dots.
1196
+ # See https://github.com/aio-libs/aiohttp/issues/3636
1197
+ server_hostname = (
1198
+ (req.server_hostname or hinfo["hostname"]).rstrip(".")
1199
+ if sslcontext
1200
+ else None
1201
+ )
1202
+
1203
+ try:
1204
+ transp, proto = await self._wrap_create_connection(
1205
+ self._factory,
1206
+ host,
1207
+ port,
1208
+ timeout=timeout,
1209
+ ssl=sslcontext,
1210
+ family=hinfo["family"],
1211
+ proto=hinfo["proto"],
1212
+ flags=hinfo["flags"],
1213
+ server_hostname=server_hostname,
1214
+ local_addr=self._local_addr,
1215
+ req=req,
1216
+ client_error=client_error,
1217
+ )
1218
+ except ClientConnectorError as exc:
1219
+ last_exc = exc
1220
+ continue
1221
+
1222
+ if req.is_ssl() and fingerprint:
1223
+ try:
1224
+ fingerprint.check(transp)
1225
+ except ServerFingerprintMismatch as exc:
1226
+ transp.close()
1227
+ if not self._cleanup_closed_disabled:
1228
+ self._cleanup_closed_transports.append(transp)
1229
+ last_exc = exc
1230
+ continue
1231
+
1232
+ return transp, proto
1233
+ else:
1234
+ assert last_exc is not None
1235
+ raise last_exc
1236
+
1237
+ async def _create_proxy_connection(
1238
+ self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1239
+ ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1240
+ self._fail_on_no_start_tls(req)
1241
+ runtime_has_start_tls = self._loop_supports_start_tls()
1242
+
1243
+ headers: Dict[str, str] = {}
1244
+ if req.proxy_headers is not None:
1245
+ headers = req.proxy_headers # type: ignore[assignment]
1246
+ headers[hdrs.HOST] = req.headers[hdrs.HOST]
1247
+
1248
+ url = req.proxy
1249
+ assert url is not None
1250
+ proxy_req = ClientRequest(
1251
+ hdrs.METH_GET,
1252
+ url,
1253
+ headers=headers,
1254
+ auth=req.proxy_auth,
1255
+ loop=self._loop,
1256
+ ssl=req.ssl,
1257
+ )
1258
+
1259
+ # create connection to proxy server
1260
+ transport, proto = await self._create_direct_connection(
1261
+ proxy_req, [], timeout, client_error=ClientProxyConnectionError
1262
+ )
1263
+
1264
+ # Many HTTP proxies has buggy keepalive support. Let's not
1265
+ # reuse connection but close it after processing every
1266
+ # response.
1267
+ proto.force_close()
1268
+
1269
+ auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)
1270
+ if auth is not None:
1271
+ if not req.is_ssl():
1272
+ req.headers[hdrs.PROXY_AUTHORIZATION] = auth
1273
+ else:
1274
+ proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth
1275
+
1276
+ if req.is_ssl():
1277
+ if runtime_has_start_tls:
1278
+ self._warn_about_tls_in_tls(transport, req)
1279
+
1280
+ # For HTTPS requests over HTTP proxy
1281
+ # we must notify proxy to tunnel connection
1282
+ # so we send CONNECT command:
1283
+ # CONNECT www.python.org:443 HTTP/1.1
1284
+ # Host: www.python.org
1285
+ #
1286
+ # next we must do TLS handshake and so on
1287
+ # to do this we must wrap raw socket into secure one
1288
+ # asyncio handles this perfectly
1289
+ proxy_req.method = hdrs.METH_CONNECT
1290
+ proxy_req.url = req.url
1291
+ key = attr.evolve(
1292
+ req.connection_key, proxy=None, proxy_auth=None, proxy_headers_hash=None
1293
+ )
1294
+ conn = Connection(self, key, proto, self._loop)
1295
+ proxy_resp = await proxy_req.send(conn)
1296
+ try:
1297
+ protocol = conn._protocol
1298
+ assert protocol is not None
1299
+
1300
+ # read_until_eof=True will ensure the connection isn't closed
1301
+ # once the response is received and processed allowing
1302
+ # START_TLS to work on the connection below.
1303
+ protocol.set_response_params(
1304
+ read_until_eof=runtime_has_start_tls,
1305
+ timeout_ceil_threshold=self._timeout_ceil_threshold,
1306
+ )
1307
+ resp = await proxy_resp.start(conn)
1308
+ except BaseException:
1309
+ proxy_resp.close()
1310
+ conn.close()
1311
+ raise
1312
+ else:
1313
+ conn._protocol = None
1314
+ conn._transport = None
1315
+ try:
1316
+ if resp.status != 200:
1317
+ message = resp.reason
1318
+ if message is None:
1319
+ message = HTTPStatus(resp.status).phrase
1320
+ raise ClientHttpProxyError(
1321
+ proxy_resp.request_info,
1322
+ resp.history,
1323
+ status=resp.status,
1324
+ message=message,
1325
+ headers=resp.headers,
1326
+ )
1327
+ if not runtime_has_start_tls:
1328
+ rawsock = transport.get_extra_info("socket", default=None)
1329
+ if rawsock is None:
1330
+ raise RuntimeError(
1331
+ "Transport does not expose socket instance"
1332
+ )
1333
+ # Duplicate the socket, so now we can close proxy transport
1334
+ rawsock = rawsock.dup()
1335
+ except BaseException:
1336
+ # It shouldn't be closed in `finally` because it's fed to
1337
+ # `loop.start_tls()` and the docs say not to touch it after
1338
+ # passing there.
1339
+ transport.close()
1340
+ raise
1341
+ finally:
1342
+ if not runtime_has_start_tls:
1343
+ transport.close()
1344
+
1345
+ if not runtime_has_start_tls:
1346
+ # HTTP proxy with support for upgrade to HTTPS
1347
+ sslcontext = self._get_ssl_context(req)
1348
+ return await self._wrap_create_connection(
1349
+ self._factory,
1350
+ timeout=timeout,
1351
+ ssl=sslcontext,
1352
+ sock=rawsock,
1353
+ server_hostname=req.host,
1354
+ req=req,
1355
+ )
1356
+
1357
+ return await self._start_tls_connection(
1358
+ # Access the old transport for the last time before it's
1359
+ # closed and forgotten forever:
1360
+ transport,
1361
+ req=req,
1362
+ timeout=timeout,
1363
+ )
1364
+ finally:
1365
+ proxy_resp.close()
1366
+
1367
+ return transport, proto
1368
+
1369
+
1370
+ class UnixConnector(BaseConnector):
1371
+ """Unix socket connector.
1372
+
1373
+ path - Unix socket path.
1374
+ keepalive_timeout - (optional) Keep-alive timeout.
1375
+ force_close - Set to True to force close and do reconnect
1376
+ after each request (and between redirects).
1377
+ limit - The total number of simultaneous connections.
1378
+ limit_per_host - Number of simultaneous connections to one host.
1379
+ loop - Optional event loop.
1380
+ """
1381
+
1382
+ def __init__(
1383
+ self,
1384
+ path: str,
1385
+ force_close: bool = False,
1386
+ keepalive_timeout: Union[object, float, None] = sentinel,
1387
+ limit: int = 100,
1388
+ limit_per_host: int = 0,
1389
+ loop: Optional[asyncio.AbstractEventLoop] = None,
1390
+ ) -> None:
1391
+ super().__init__(
1392
+ force_close=force_close,
1393
+ keepalive_timeout=keepalive_timeout,
1394
+ limit=limit,
1395
+ limit_per_host=limit_per_host,
1396
+ loop=loop,
1397
+ )
1398
+ self._path = path
1399
+
1400
+ @property
1401
+ def path(self) -> str:
1402
+ """Path to unix socket."""
1403
+ return self._path
1404
+
1405
+ async def _create_connection(
1406
+ self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1407
+ ) -> ResponseHandler:
1408
+ try:
1409
+ async with ceil_timeout(
1410
+ timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1411
+ ):
1412
+ _, proto = await self._loop.create_unix_connection(
1413
+ self._factory, self._path
1414
+ )
1415
+ except OSError as exc:
1416
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1417
+ raise
1418
+ raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc
1419
+
1420
+ return proto
1421
+
1422
+
1423
+ class NamedPipeConnector(BaseConnector):
1424
+ """Named pipe connector.
1425
+
1426
+ Only supported by the proactor event loop.
1427
+ See also: https://docs.python.org/3/library/asyncio-eventloop.html
1428
+
1429
+ path - Windows named pipe path.
1430
+ keepalive_timeout - (optional) Keep-alive timeout.
1431
+ force_close - Set to True to force close and do reconnect
1432
+ after each request (and between redirects).
1433
+ limit - The total number of simultaneous connections.
1434
+ limit_per_host - Number of simultaneous connections to one host.
1435
+ loop - Optional event loop.
1436
+ """
1437
+
1438
+ def __init__(
1439
+ self,
1440
+ path: str,
1441
+ force_close: bool = False,
1442
+ keepalive_timeout: Union[object, float, None] = sentinel,
1443
+ limit: int = 100,
1444
+ limit_per_host: int = 0,
1445
+ loop: Optional[asyncio.AbstractEventLoop] = None,
1446
+ ) -> None:
1447
+ super().__init__(
1448
+ force_close=force_close,
1449
+ keepalive_timeout=keepalive_timeout,
1450
+ limit=limit,
1451
+ limit_per_host=limit_per_host,
1452
+ loop=loop,
1453
+ )
1454
+ if not isinstance(
1455
+ self._loop, asyncio.ProactorEventLoop # type: ignore[attr-defined]
1456
+ ):
1457
+ raise RuntimeError(
1458
+ "Named Pipes only available in proactor " "loop under windows"
1459
+ )
1460
+ self._path = path
1461
+
1462
+ @property
1463
+ def path(self) -> str:
1464
+ """Path to the named pipe."""
1465
+ return self._path
1466
+
1467
+ async def _create_connection(
1468
+ self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout"
1469
+ ) -> ResponseHandler:
1470
+ try:
1471
+ async with ceil_timeout(
1472
+ timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
1473
+ ):
1474
+ _, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined]
1475
+ self._factory, self._path
1476
+ )
1477
+ # the drain is required so that the connection_made is called
1478
+ # and transport is set otherwise it is not set before the
1479
+ # `assert conn.transport is not None`
1480
+ # in client.py's _request method
1481
+ await asyncio.sleep(0)
1482
+ # other option is to manually set transport like
1483
+ # `proto.transport = trans`
1484
+ except OSError as exc:
1485
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1486
+ raise
1487
+ raise ClientConnectorError(req.connection_key, exc) from exc
1488
+
1489
+ return cast(ResponseHandler, proto)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/cookiejar.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import calendar
3
+ import contextlib
4
+ import datetime
5
+ import os # noqa
6
+ import pathlib
7
+ import pickle
8
+ import re
9
+ import time
10
+ from collections import defaultdict
11
+ from http.cookies import BaseCookie, Morsel, SimpleCookie
12
+ from math import ceil
13
+ from typing import ( # noqa
14
+ DefaultDict,
15
+ Dict,
16
+ Iterable,
17
+ Iterator,
18
+ List,
19
+ Mapping,
20
+ Optional,
21
+ Set,
22
+ Tuple,
23
+ Union,
24
+ cast,
25
+ )
26
+
27
+ from yarl import URL
28
+
29
+ from .abc import AbstractCookieJar, ClearCookiePredicate
30
+ from .helpers import is_ip_address
31
+ from .typedefs import LooseCookies, PathLike, StrOrURL
32
+
33
+ __all__ = ("CookieJar", "DummyCookieJar")
34
+
35
+
36
+ CookieItem = Union[str, "Morsel[str]"]
37
+
38
+
39
+ class CookieJar(AbstractCookieJar):
40
+ """Implements cookie storage adhering to RFC 6265."""
41
+
42
+ DATE_TOKENS_RE = re.compile(
43
+ r"[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*"
44
+ r"(?P<token>[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)"
45
+ )
46
+
47
+ DATE_HMS_TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})")
48
+
49
+ DATE_DAY_OF_MONTH_RE = re.compile(r"(\d{1,2})")
50
+
51
+ DATE_MONTH_RE = re.compile(
52
+ "(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|" "(aug)|(sep)|(oct)|(nov)|(dec)",
53
+ re.I,
54
+ )
55
+
56
+ DATE_YEAR_RE = re.compile(r"(\d{2,4})")
57
+
58
+ # calendar.timegm() fails for timestamps after datetime.datetime.max
59
+ # Minus one as a loss of precision occurs when timestamp() is called.
60
+ MAX_TIME = (
61
+ int(datetime.datetime.max.replace(tzinfo=datetime.timezone.utc).timestamp()) - 1
62
+ )
63
+ try:
64
+ calendar.timegm(time.gmtime(MAX_TIME))
65
+ except (OSError, ValueError):
66
+ # Hit the maximum representable time on Windows
67
+ # https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-localtime32-localtime64
68
+ # Throws ValueError on PyPy 3.8 and 3.9, OSError elsewhere
69
+ MAX_TIME = calendar.timegm((3000, 12, 31, 23, 59, 59, -1, -1, -1))
70
+ except OverflowError:
71
+ # #4515: datetime.max may not be representable on 32-bit platforms
72
+ MAX_TIME = 2**31 - 1
73
+ # Avoid minuses in the future, 3x faster
74
+ SUB_MAX_TIME = MAX_TIME - 1
75
+
76
+ def __init__(
77
+ self,
78
+ *,
79
+ unsafe: bool = False,
80
+ quote_cookie: bool = True,
81
+ treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None,
82
+ loop: Optional[asyncio.AbstractEventLoop] = None,
83
+ ) -> None:
84
+ super().__init__(loop=loop)
85
+ self._cookies: DefaultDict[Tuple[str, str], SimpleCookie] = defaultdict(
86
+ SimpleCookie
87
+ )
88
+ self._host_only_cookies: Set[Tuple[str, str]] = set()
89
+ self._unsafe = unsafe
90
+ self._quote_cookie = quote_cookie
91
+ if treat_as_secure_origin is None:
92
+ treat_as_secure_origin = []
93
+ elif isinstance(treat_as_secure_origin, URL):
94
+ treat_as_secure_origin = [treat_as_secure_origin.origin()]
95
+ elif isinstance(treat_as_secure_origin, str):
96
+ treat_as_secure_origin = [URL(treat_as_secure_origin).origin()]
97
+ else:
98
+ treat_as_secure_origin = [
99
+ URL(url).origin() if isinstance(url, str) else url.origin()
100
+ for url in treat_as_secure_origin
101
+ ]
102
+ self._treat_as_secure_origin = treat_as_secure_origin
103
+ self._next_expiration: float = ceil(time.time())
104
+ self._expirations: Dict[Tuple[str, str, str], float] = {}
105
+
106
+ def save(self, file_path: PathLike) -> None:
107
+ file_path = pathlib.Path(file_path)
108
+ with file_path.open(mode="wb") as f:
109
+ pickle.dump(self._cookies, f, pickle.HIGHEST_PROTOCOL)
110
+
111
+ def load(self, file_path: PathLike) -> None:
112
+ file_path = pathlib.Path(file_path)
113
+ with file_path.open(mode="rb") as f:
114
+ self._cookies = pickle.load(f)
115
+
116
+ def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
117
+ if predicate is None:
118
+ self._next_expiration = ceil(time.time())
119
+ self._cookies.clear()
120
+ self._host_only_cookies.clear()
121
+ self._expirations.clear()
122
+ return
123
+
124
+ to_del = []
125
+ now = time.time()
126
+ for (domain, path), cookie in self._cookies.items():
127
+ for name, morsel in cookie.items():
128
+ key = (domain, path, name)
129
+ if (
130
+ key in self._expirations and self._expirations[key] <= now
131
+ ) or predicate(morsel):
132
+ to_del.append(key)
133
+
134
+ for domain, path, name in to_del:
135
+ self._host_only_cookies.discard((domain, name))
136
+ key = (domain, path, name)
137
+ if key in self._expirations:
138
+ del self._expirations[(domain, path, name)]
139
+ self._cookies[(domain, path)].pop(name, None)
140
+
141
+ self._next_expiration = (
142
+ min(*self._expirations.values(), self.SUB_MAX_TIME) + 1
143
+ if self._expirations
144
+ else self.MAX_TIME
145
+ )
146
+
147
+ def clear_domain(self, domain: str) -> None:
148
+ self.clear(lambda x: self._is_domain_match(domain, x["domain"]))
149
+
150
+ def __iter__(self) -> "Iterator[Morsel[str]]":
151
+ self._do_expiration()
152
+ for val in self._cookies.values():
153
+ yield from val.values()
154
+
155
+ def __len__(self) -> int:
156
+ return sum(1 for i in self)
157
+
158
+ def _do_expiration(self) -> None:
159
+ self.clear(lambda x: False)
160
+
161
+ def _expire_cookie(self, when: float, domain: str, path: str, name: str) -> None:
162
+ self._next_expiration = min(self._next_expiration, when)
163
+ self._expirations[(domain, path, name)] = when
164
+
165
+ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
166
+ """Update cookies."""
167
+ hostname = response_url.raw_host
168
+
169
+ if not self._unsafe and is_ip_address(hostname):
170
+ # Don't accept cookies from IPs
171
+ return
172
+
173
+ if isinstance(cookies, Mapping):
174
+ cookies = cookies.items()
175
+
176
+ for name, cookie in cookies:
177
+ if not isinstance(cookie, Morsel):
178
+ tmp = SimpleCookie()
179
+ tmp[name] = cookie # type: ignore[assignment]
180
+ cookie = tmp[name]
181
+
182
+ domain = cookie["domain"]
183
+
184
+ # ignore domains with trailing dots
185
+ if domain.endswith("."):
186
+ domain = ""
187
+ del cookie["domain"]
188
+
189
+ if not domain and hostname is not None:
190
+ # Set the cookie's domain to the response hostname
191
+ # and set its host-only-flag
192
+ self._host_only_cookies.add((hostname, name))
193
+ domain = cookie["domain"] = hostname
194
+
195
+ if domain.startswith("."):
196
+ # Remove leading dot
197
+ domain = domain[1:]
198
+ cookie["domain"] = domain
199
+
200
+ if hostname and not self._is_domain_match(domain, hostname):
201
+ # Setting cookies for different domains is not allowed
202
+ continue
203
+
204
+ path = cookie["path"]
205
+ if not path or not path.startswith("/"):
206
+ # Set the cookie's path to the response path
207
+ path = response_url.path
208
+ if not path.startswith("/"):
209
+ path = "/"
210
+ else:
211
+ # Cut everything from the last slash to the end
212
+ path = "/" + path[1 : path.rfind("/")]
213
+ cookie["path"] = path
214
+
215
+ max_age = cookie["max-age"]
216
+ if max_age:
217
+ try:
218
+ delta_seconds = int(max_age)
219
+ max_age_expiration = min(time.time() + delta_seconds, self.MAX_TIME)
220
+ self._expire_cookie(max_age_expiration, domain, path, name)
221
+ except ValueError:
222
+ cookie["max-age"] = ""
223
+
224
+ else:
225
+ expires = cookie["expires"]
226
+ if expires:
227
+ expire_time = self._parse_date(expires)
228
+ if expire_time:
229
+ self._expire_cookie(expire_time, domain, path, name)
230
+ else:
231
+ cookie["expires"] = ""
232
+
233
+ self._cookies[(domain, path)][name] = cookie
234
+
235
+ self._do_expiration()
236
+
237
+ def filter_cookies(self, request_url: URL = URL()) -> "BaseCookie[str]":
238
+ """Returns this jar's cookies filtered by their attributes."""
239
+ filtered: Union[SimpleCookie, "BaseCookie[str]"] = (
240
+ SimpleCookie() if self._quote_cookie else BaseCookie()
241
+ )
242
+ if not self._cookies:
243
+ # Skip do_expiration() if there are no cookies.
244
+ return filtered
245
+ self._do_expiration()
246
+ if not self._cookies:
247
+ # Skip rest of function if no non-expired cookies.
248
+ return filtered
249
+ request_url = URL(request_url)
250
+ hostname = request_url.raw_host or ""
251
+
252
+ is_not_secure = request_url.scheme not in ("https", "wss")
253
+ if is_not_secure and self._treat_as_secure_origin:
254
+ request_origin = URL()
255
+ with contextlib.suppress(ValueError):
256
+ request_origin = request_url.origin()
257
+ is_not_secure = request_origin not in self._treat_as_secure_origin
258
+
259
+ # Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4
260
+ for cookie in sorted(self, key=lambda c: len(c["path"])):
261
+ name = cookie.key
262
+ domain = cookie["domain"]
263
+
264
+ # Send shared cookies
265
+ if not domain:
266
+ filtered[name] = cookie.value
267
+ continue
268
+
269
+ if not self._unsafe and is_ip_address(hostname):
270
+ continue
271
+
272
+ if (domain, name) in self._host_only_cookies:
273
+ if domain != hostname:
274
+ continue
275
+ elif not self._is_domain_match(domain, hostname):
276
+ continue
277
+
278
+ if not self._is_path_match(request_url.path, cookie["path"]):
279
+ continue
280
+
281
+ if is_not_secure and cookie["secure"]:
282
+ continue
283
+
284
+ # It's critical we use the Morsel so the coded_value
285
+ # (based on cookie version) is preserved
286
+ mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel()))
287
+ mrsl_val.set(cookie.key, cookie.value, cookie.coded_value)
288
+ filtered[name] = mrsl_val
289
+
290
+ return filtered
291
+
292
+ @staticmethod
293
+ def _is_domain_match(domain: str, hostname: str) -> bool:
294
+ """Implements domain matching adhering to RFC 6265."""
295
+ if hostname == domain:
296
+ return True
297
+
298
+ if not hostname.endswith(domain):
299
+ return False
300
+
301
+ non_matching = hostname[: -len(domain)]
302
+
303
+ if not non_matching.endswith("."):
304
+ return False
305
+
306
+ return not is_ip_address(hostname)
307
+
308
+ @staticmethod
309
+ def _is_path_match(req_path: str, cookie_path: str) -> bool:
310
+ """Implements path matching adhering to RFC 6265."""
311
+ if not req_path.startswith("/"):
312
+ req_path = "/"
313
+
314
+ if req_path == cookie_path:
315
+ return True
316
+
317
+ if not req_path.startswith(cookie_path):
318
+ return False
319
+
320
+ if cookie_path.endswith("/"):
321
+ return True
322
+
323
+ non_matching = req_path[len(cookie_path) :]
324
+
325
+ return non_matching.startswith("/")
326
+
327
+ @classmethod
328
+ def _parse_date(cls, date_str: str) -> Optional[int]:
329
+ """Implements date string parsing adhering to RFC 6265."""
330
+ if not date_str:
331
+ return None
332
+
333
+ found_time = False
334
+ found_day = False
335
+ found_month = False
336
+ found_year = False
337
+
338
+ hour = minute = second = 0
339
+ day = 0
340
+ month = 0
341
+ year = 0
342
+
343
+ for token_match in cls.DATE_TOKENS_RE.finditer(date_str):
344
+
345
+ token = token_match.group("token")
346
+
347
+ if not found_time:
348
+ time_match = cls.DATE_HMS_TIME_RE.match(token)
349
+ if time_match:
350
+ found_time = True
351
+ hour, minute, second = (int(s) for s in time_match.groups())
352
+ continue
353
+
354
+ if not found_day:
355
+ day_match = cls.DATE_DAY_OF_MONTH_RE.match(token)
356
+ if day_match:
357
+ found_day = True
358
+ day = int(day_match.group())
359
+ continue
360
+
361
+ if not found_month:
362
+ month_match = cls.DATE_MONTH_RE.match(token)
363
+ if month_match:
364
+ found_month = True
365
+ assert month_match.lastindex is not None
366
+ month = month_match.lastindex
367
+ continue
368
+
369
+ if not found_year:
370
+ year_match = cls.DATE_YEAR_RE.match(token)
371
+ if year_match:
372
+ found_year = True
373
+ year = int(year_match.group())
374
+
375
+ if 70 <= year <= 99:
376
+ year += 1900
377
+ elif 0 <= year <= 69:
378
+ year += 2000
379
+
380
+ if False in (found_day, found_month, found_year, found_time):
381
+ return None
382
+
383
+ if not 1 <= day <= 31:
384
+ return None
385
+
386
+ if year < 1601 or hour > 23 or minute > 59 or second > 59:
387
+ return None
388
+
389
+ return calendar.timegm((year, month, day, hour, minute, second, -1, -1, -1))
390
+
391
+
392
+ class DummyCookieJar(AbstractCookieJar):
393
+ """Implements a dummy cookie storage.
394
+
395
+ It can be used with the ClientSession when no cookie processing is needed.
396
+
397
+ """
398
+
399
+ def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
400
+ super().__init__(loop=loop)
401
+
402
+ def __iter__(self) -> "Iterator[Morsel[str]]":
403
+ while False:
404
+ yield None
405
+
406
+ def __len__(self) -> int:
407
+ return 0
408
+
409
+ def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
410
+ pass
411
+
412
+ def clear_domain(self, domain: str) -> None:
413
+ pass
414
+
415
+ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
416
+ pass
417
+
418
+ def filter_cookies(self, request_url: URL) -> "BaseCookie[str]":
419
+ return SimpleCookie()
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/formdata.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from typing import Any, Iterable, List, Optional
3
+ from urllib.parse import urlencode
4
+
5
+ from multidict import MultiDict, MultiDictProxy
6
+
7
+ from . import hdrs, multipart, payload
8
+ from .helpers import guess_filename
9
+ from .payload import Payload
10
+
11
+ __all__ = ("FormData",)
12
+
13
+
14
+ class FormData:
15
+ """Helper class for form body generation.
16
+
17
+ Supports multipart/form-data and application/x-www-form-urlencoded.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ fields: Iterable[Any] = (),
23
+ quote_fields: bool = True,
24
+ charset: Optional[str] = None,
25
+ ) -> None:
26
+ self._writer = multipart.MultipartWriter("form-data")
27
+ self._fields: List[Any] = []
28
+ self._is_multipart = False
29
+ self._is_processed = False
30
+ self._quote_fields = quote_fields
31
+ self._charset = charset
32
+
33
+ if isinstance(fields, dict):
34
+ fields = list(fields.items())
35
+ elif not isinstance(fields, (list, tuple)):
36
+ fields = (fields,)
37
+ self.add_fields(*fields)
38
+
39
+ @property
40
+ def is_multipart(self) -> bool:
41
+ return self._is_multipart
42
+
43
+ def add_field(
44
+ self,
45
+ name: str,
46
+ value: Any,
47
+ *,
48
+ content_type: Optional[str] = None,
49
+ filename: Optional[str] = None,
50
+ content_transfer_encoding: Optional[str] = None,
51
+ ) -> None:
52
+
53
+ if isinstance(value, io.IOBase):
54
+ self._is_multipart = True
55
+ elif isinstance(value, (bytes, bytearray, memoryview)):
56
+ if filename is None and content_transfer_encoding is None:
57
+ filename = name
58
+
59
+ type_options: MultiDict[str] = MultiDict({"name": name})
60
+ if filename is not None and not isinstance(filename, str):
61
+ raise TypeError(
62
+ "filename must be an instance of str. " "Got: %s" % filename
63
+ )
64
+ if filename is None and isinstance(value, io.IOBase):
65
+ filename = guess_filename(value, name)
66
+ if filename is not None:
67
+ type_options["filename"] = filename
68
+ self._is_multipart = True
69
+
70
+ headers = {}
71
+ if content_type is not None:
72
+ if not isinstance(content_type, str):
73
+ raise TypeError(
74
+ "content_type must be an instance of str. " "Got: %s" % content_type
75
+ )
76
+ headers[hdrs.CONTENT_TYPE] = content_type
77
+ self._is_multipart = True
78
+ if content_transfer_encoding is not None:
79
+ if not isinstance(content_transfer_encoding, str):
80
+ raise TypeError(
81
+ "content_transfer_encoding must be an instance"
82
+ " of str. Got: %s" % content_transfer_encoding
83
+ )
84
+ headers[hdrs.CONTENT_TRANSFER_ENCODING] = content_transfer_encoding
85
+ self._is_multipart = True
86
+
87
+ self._fields.append((type_options, headers, value))
88
+
89
+ def add_fields(self, *fields: Any) -> None:
90
+ to_add = list(fields)
91
+
92
+ while to_add:
93
+ rec = to_add.pop(0)
94
+
95
+ if isinstance(rec, io.IOBase):
96
+ k = guess_filename(rec, "unknown")
97
+ self.add_field(k, rec) # type: ignore[arg-type]
98
+
99
+ elif isinstance(rec, (MultiDictProxy, MultiDict)):
100
+ to_add.extend(rec.items())
101
+
102
+ elif isinstance(rec, (list, tuple)) and len(rec) == 2:
103
+ k, fp = rec
104
+ self.add_field(k, fp) # type: ignore[arg-type]
105
+
106
+ else:
107
+ raise TypeError(
108
+ "Only io.IOBase, multidict and (name, file) "
109
+ "pairs allowed, use .add_field() for passing "
110
+ "more complex parameters, got {!r}".format(rec)
111
+ )
112
+
113
+ def _gen_form_urlencoded(self) -> payload.BytesPayload:
114
+ # form data (x-www-form-urlencoded)
115
+ data = []
116
+ for type_options, _, value in self._fields:
117
+ data.append((type_options["name"], value))
118
+
119
+ charset = self._charset if self._charset is not None else "utf-8"
120
+
121
+ if charset == "utf-8":
122
+ content_type = "application/x-www-form-urlencoded"
123
+ else:
124
+ content_type = "application/x-www-form-urlencoded; " "charset=%s" % charset
125
+
126
+ return payload.BytesPayload(
127
+ urlencode(data, doseq=True, encoding=charset).encode(),
128
+ content_type=content_type,
129
+ )
130
+
131
+ def _gen_form_data(self) -> multipart.MultipartWriter:
132
+ """Encode a list of fields using the multipart/form-data MIME format"""
133
+ if self._is_processed:
134
+ raise RuntimeError("Form data has been processed already")
135
+ for dispparams, headers, value in self._fields:
136
+ try:
137
+ if hdrs.CONTENT_TYPE in headers:
138
+ part = payload.get_payload(
139
+ value,
140
+ content_type=headers[hdrs.CONTENT_TYPE],
141
+ headers=headers,
142
+ encoding=self._charset,
143
+ )
144
+ else:
145
+ part = payload.get_payload(
146
+ value, headers=headers, encoding=self._charset
147
+ )
148
+ except Exception as exc:
149
+ raise TypeError(
150
+ "Can not serialize value type: %r\n "
151
+ "headers: %r\n value: %r" % (type(value), headers, value)
152
+ ) from exc
153
+
154
+ if dispparams:
155
+ part.set_content_disposition(
156
+ "form-data", quote_fields=self._quote_fields, **dispparams
157
+ )
158
+ # FIXME cgi.FieldStorage doesn't likes body parts with
159
+ # Content-Length which were sent via chunked transfer encoding
160
+ assert part.headers is not None
161
+ part.headers.popall(hdrs.CONTENT_LENGTH, None)
162
+
163
+ self._writer.append_payload(part)
164
+
165
+ self._is_processed = True
166
+ return self._writer
167
+
168
+ def __call__(self) -> Payload:
169
+ if self._is_multipart:
170
+ return self._gen_form_data()
171
+ else:
172
+ return self._gen_form_urlencoded()
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/hdrs.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP Headers constants."""
2
+
3
+ # After changing the file content call ./tools/gen.py
4
+ # to regenerate the headers parser
5
+ from typing import Final, Set
6
+
7
+ from multidict import istr
8
+
9
+ METH_ANY: Final[str] = "*"
10
+ METH_CONNECT: Final[str] = "CONNECT"
11
+ METH_HEAD: Final[str] = "HEAD"
12
+ METH_GET: Final[str] = "GET"
13
+ METH_DELETE: Final[str] = "DELETE"
14
+ METH_OPTIONS: Final[str] = "OPTIONS"
15
+ METH_PATCH: Final[str] = "PATCH"
16
+ METH_POST: Final[str] = "POST"
17
+ METH_PUT: Final[str] = "PUT"
18
+ METH_TRACE: Final[str] = "TRACE"
19
+
20
+ METH_ALL: Final[Set[str]] = {
21
+ METH_CONNECT,
22
+ METH_HEAD,
23
+ METH_GET,
24
+ METH_DELETE,
25
+ METH_OPTIONS,
26
+ METH_PATCH,
27
+ METH_POST,
28
+ METH_PUT,
29
+ METH_TRACE,
30
+ }
31
+
32
+ ACCEPT: Final[istr] = istr("Accept")
33
+ ACCEPT_CHARSET: Final[istr] = istr("Accept-Charset")
34
+ ACCEPT_ENCODING: Final[istr] = istr("Accept-Encoding")
35
+ ACCEPT_LANGUAGE: Final[istr] = istr("Accept-Language")
36
+ ACCEPT_RANGES: Final[istr] = istr("Accept-Ranges")
37
+ ACCESS_CONTROL_MAX_AGE: Final[istr] = istr("Access-Control-Max-Age")
38
+ ACCESS_CONTROL_ALLOW_CREDENTIALS: Final[istr] = istr("Access-Control-Allow-Credentials")
39
+ ACCESS_CONTROL_ALLOW_HEADERS: Final[istr] = istr("Access-Control-Allow-Headers")
40
+ ACCESS_CONTROL_ALLOW_METHODS: Final[istr] = istr("Access-Control-Allow-Methods")
41
+ ACCESS_CONTROL_ALLOW_ORIGIN: Final[istr] = istr("Access-Control-Allow-Origin")
42
+ ACCESS_CONTROL_EXPOSE_HEADERS: Final[istr] = istr("Access-Control-Expose-Headers")
43
+ ACCESS_CONTROL_REQUEST_HEADERS: Final[istr] = istr("Access-Control-Request-Headers")
44
+ ACCESS_CONTROL_REQUEST_METHOD: Final[istr] = istr("Access-Control-Request-Method")
45
+ AGE: Final[istr] = istr("Age")
46
+ ALLOW: Final[istr] = istr("Allow")
47
+ AUTHORIZATION: Final[istr] = istr("Authorization")
48
+ CACHE_CONTROL: Final[istr] = istr("Cache-Control")
49
+ CONNECTION: Final[istr] = istr("Connection")
50
+ CONTENT_DISPOSITION: Final[istr] = istr("Content-Disposition")
51
+ CONTENT_ENCODING: Final[istr] = istr("Content-Encoding")
52
+ CONTENT_LANGUAGE: Final[istr] = istr("Content-Language")
53
+ CONTENT_LENGTH: Final[istr] = istr("Content-Length")
54
+ CONTENT_LOCATION: Final[istr] = istr("Content-Location")
55
+ CONTENT_MD5: Final[istr] = istr("Content-MD5")
56
+ CONTENT_RANGE: Final[istr] = istr("Content-Range")
57
+ CONTENT_TRANSFER_ENCODING: Final[istr] = istr("Content-Transfer-Encoding")
58
+ CONTENT_TYPE: Final[istr] = istr("Content-Type")
59
+ COOKIE: Final[istr] = istr("Cookie")
60
+ DATE: Final[istr] = istr("Date")
61
+ DESTINATION: Final[istr] = istr("Destination")
62
+ DIGEST: Final[istr] = istr("Digest")
63
+ ETAG: Final[istr] = istr("Etag")
64
+ EXPECT: Final[istr] = istr("Expect")
65
+ EXPIRES: Final[istr] = istr("Expires")
66
+ FORWARDED: Final[istr] = istr("Forwarded")
67
+ FROM: Final[istr] = istr("From")
68
+ HOST: Final[istr] = istr("Host")
69
+ IF_MATCH: Final[istr] = istr("If-Match")
70
+ IF_MODIFIED_SINCE: Final[istr] = istr("If-Modified-Since")
71
+ IF_NONE_MATCH: Final[istr] = istr("If-None-Match")
72
+ IF_RANGE: Final[istr] = istr("If-Range")
73
+ IF_UNMODIFIED_SINCE: Final[istr] = istr("If-Unmodified-Since")
74
+ KEEP_ALIVE: Final[istr] = istr("Keep-Alive")
75
+ LAST_EVENT_ID: Final[istr] = istr("Last-Event-ID")
76
+ LAST_MODIFIED: Final[istr] = istr("Last-Modified")
77
+ LINK: Final[istr] = istr("Link")
78
+ LOCATION: Final[istr] = istr("Location")
79
+ MAX_FORWARDS: Final[istr] = istr("Max-Forwards")
80
+ ORIGIN: Final[istr] = istr("Origin")
81
+ PRAGMA: Final[istr] = istr("Pragma")
82
+ PROXY_AUTHENTICATE: Final[istr] = istr("Proxy-Authenticate")
83
+ PROXY_AUTHORIZATION: Final[istr] = istr("Proxy-Authorization")
84
+ RANGE: Final[istr] = istr("Range")
85
+ REFERER: Final[istr] = istr("Referer")
86
+ RETRY_AFTER: Final[istr] = istr("Retry-After")
87
+ SEC_WEBSOCKET_ACCEPT: Final[istr] = istr("Sec-WebSocket-Accept")
88
+ SEC_WEBSOCKET_VERSION: Final[istr] = istr("Sec-WebSocket-Version")
89
+ SEC_WEBSOCKET_PROTOCOL: Final[istr] = istr("Sec-WebSocket-Protocol")
90
+ SEC_WEBSOCKET_EXTENSIONS: Final[istr] = istr("Sec-WebSocket-Extensions")
91
+ SEC_WEBSOCKET_KEY: Final[istr] = istr("Sec-WebSocket-Key")
92
+ SEC_WEBSOCKET_KEY1: Final[istr] = istr("Sec-WebSocket-Key1")
93
+ SERVER: Final[istr] = istr("Server")
94
+ SET_COOKIE: Final[istr] = istr("Set-Cookie")
95
+ TE: Final[istr] = istr("TE")
96
+ TRAILER: Final[istr] = istr("Trailer")
97
+ TRANSFER_ENCODING: Final[istr] = istr("Transfer-Encoding")
98
+ UPGRADE: Final[istr] = istr("Upgrade")
99
+ URI: Final[istr] = istr("URI")
100
+ USER_AGENT: Final[istr] = istr("User-Agent")
101
+ VARY: Final[istr] = istr("Vary")
102
+ VIA: Final[istr] = istr("Via")
103
+ WANT_DIGEST: Final[istr] = istr("Want-Digest")
104
+ WARNING: Final[istr] = istr("Warning")
105
+ WWW_AUTHENTICATE: Final[istr] = istr("WWW-Authenticate")
106
+ X_FORWARDED_FOR: Final[istr] = istr("X-Forwarded-For")
107
+ X_FORWARDED_HOST: Final[istr] = istr("X-Forwarded-Host")
108
+ X_FORWARDED_PROTO: Final[istr] = istr("X-Forwarded-Proto")
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/helpers.py ADDED
@@ -0,0 +1,999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various helper functions"""
2
+
3
+ import asyncio
4
+ import base64
5
+ import binascii
6
+ import contextlib
7
+ import datetime
8
+ import enum
9
+ import functools
10
+ import inspect
11
+ import netrc
12
+ import os
13
+ import platform
14
+ import re
15
+ import sys
16
+ import time
17
+ import warnings
18
+ import weakref
19
+ from collections import namedtuple
20
+ from contextlib import suppress
21
+ from email.parser import HeaderParser
22
+ from email.utils import parsedate
23
+ from math import ceil
24
+ from pathlib import Path
25
+ from types import TracebackType
26
+ from typing import (
27
+ Any,
28
+ Callable,
29
+ ContextManager,
30
+ Dict,
31
+ Generator,
32
+ Generic,
33
+ Iterable,
34
+ Iterator,
35
+ List,
36
+ Mapping,
37
+ Optional,
38
+ Pattern,
39
+ Protocol,
40
+ Tuple,
41
+ Type,
42
+ TypeVar,
43
+ Union,
44
+ get_args,
45
+ overload,
46
+ )
47
+ from urllib.parse import quote
48
+ from urllib.request import getproxies, proxy_bypass
49
+
50
+ import attr
51
+ from multidict import MultiDict, MultiDictProxy, MultiMapping
52
+ from yarl import URL
53
+
54
+ from . import hdrs
55
+ from .log import client_logger, internal_logger
56
+
57
+ if sys.version_info >= (3, 11):
58
+ import asyncio as async_timeout
59
+ else:
60
+ import async_timeout
61
+
62
+ __all__ = ("BasicAuth", "ChainMapProxy", "ETag")
63
+
64
+ IS_MACOS = platform.system() == "Darwin"
65
+ IS_WINDOWS = platform.system() == "Windows"
66
+
67
+ PY_310 = sys.version_info >= (3, 10)
68
+ PY_311 = sys.version_info >= (3, 11)
69
+
70
+
71
+ _T = TypeVar("_T")
72
+ _S = TypeVar("_S")
73
+
74
+ _SENTINEL = enum.Enum("_SENTINEL", "sentinel")
75
+ sentinel = _SENTINEL.sentinel
76
+
77
+ NO_EXTENSIONS = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS"))
78
+
79
+ DEBUG = sys.flags.dev_mode or (
80
+ not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG"))
81
+ )
82
+
83
+
84
+ CHAR = {chr(i) for i in range(0, 128)}
85
+ CTL = {chr(i) for i in range(0, 32)} | {
86
+ chr(127),
87
+ }
88
+ SEPARATORS = {
89
+ "(",
90
+ ")",
91
+ "<",
92
+ ">",
93
+ "@",
94
+ ",",
95
+ ";",
96
+ ":",
97
+ "\\",
98
+ '"',
99
+ "/",
100
+ "[",
101
+ "]",
102
+ "?",
103
+ "=",
104
+ "{",
105
+ "}",
106
+ " ",
107
+ chr(9),
108
+ }
109
+ TOKEN = CHAR ^ CTL ^ SEPARATORS
110
+
111
+
112
+ class noop:
113
+ def __await__(self) -> Generator[None, None, None]:
114
+ yield
115
+
116
+
117
+ class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])):
118
+ """Http basic authentication helper."""
119
+
120
+ def __new__(
121
+ cls, login: str, password: str = "", encoding: str = "latin1"
122
+ ) -> "BasicAuth":
123
+ if login is None:
124
+ raise ValueError("None is not allowed as login value")
125
+
126
+ if password is None:
127
+ raise ValueError("None is not allowed as password value")
128
+
129
+ if ":" in login:
130
+ raise ValueError('A ":" is not allowed in login (RFC 1945#section-11.1)')
131
+
132
+ return super().__new__(cls, login, password, encoding)
133
+
134
+ @classmethod
135
+ def decode(cls, auth_header: str, encoding: str = "latin1") -> "BasicAuth":
136
+ """Create a BasicAuth object from an Authorization HTTP header."""
137
+ try:
138
+ auth_type, encoded_credentials = auth_header.split(" ", 1)
139
+ except ValueError:
140
+ raise ValueError("Could not parse authorization header.")
141
+
142
+ if auth_type.lower() != "basic":
143
+ raise ValueError("Unknown authorization method %s" % auth_type)
144
+
145
+ try:
146
+ decoded = base64.b64decode(
147
+ encoded_credentials.encode("ascii"), validate=True
148
+ ).decode(encoding)
149
+ except binascii.Error:
150
+ raise ValueError("Invalid base64 encoding.")
151
+
152
+ try:
153
+ # RFC 2617 HTTP Authentication
154
+ # https://www.ietf.org/rfc/rfc2617.txt
155
+ # the colon must be present, but the username and password may be
156
+ # otherwise blank.
157
+ username, password = decoded.split(":", 1)
158
+ except ValueError:
159
+ raise ValueError("Invalid credentials.")
160
+
161
+ return cls(username, password, encoding=encoding)
162
+
163
+ @classmethod
164
+ def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]:
165
+ """Create BasicAuth from url."""
166
+ if not isinstance(url, URL):
167
+ raise TypeError("url should be yarl.URL instance")
168
+ if url.user is None:
169
+ return None
170
+ return cls(url.user, url.password or "", encoding=encoding)
171
+
172
+ def encode(self) -> str:
173
+ """Encode credentials."""
174
+ creds = (f"{self.login}:{self.password}").encode(self.encoding)
175
+ return "Basic %s" % base64.b64encode(creds).decode(self.encoding)
176
+
177
+
178
+ def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
179
+ auth = BasicAuth.from_url(url)
180
+ if auth is None:
181
+ return url, None
182
+ else:
183
+ return url.with_user(None), auth
184
+
185
+
186
+ def netrc_from_env() -> Optional[netrc.netrc]:
187
+ """Load netrc from file.
188
+
189
+ Attempt to load it from the path specified by the env-var
190
+ NETRC or in the default location in the user's home directory.
191
+
192
+ Returns None if it couldn't be found or fails to parse.
193
+ """
194
+ netrc_env = os.environ.get("NETRC")
195
+
196
+ if netrc_env is not None:
197
+ netrc_path = Path(netrc_env)
198
+ else:
199
+ try:
200
+ home_dir = Path.home()
201
+ except RuntimeError as e: # pragma: no cover
202
+ # if pathlib can't resolve home, it may raise a RuntimeError
203
+ client_logger.debug(
204
+ "Could not resolve home directory when "
205
+ "trying to look for .netrc file: %s",
206
+ e,
207
+ )
208
+ return None
209
+
210
+ netrc_path = home_dir / ("_netrc" if IS_WINDOWS else ".netrc")
211
+
212
+ try:
213
+ return netrc.netrc(str(netrc_path))
214
+ except netrc.NetrcParseError as e:
215
+ client_logger.warning("Could not parse .netrc file: %s", e)
216
+ except OSError as e:
217
+ netrc_exists = False
218
+ with contextlib.suppress(OSError):
219
+ netrc_exists = netrc_path.is_file()
220
+ # we couldn't read the file (doesn't exist, permissions, etc.)
221
+ if netrc_env or netrc_exists:
222
+ # only warn if the environment wanted us to load it,
223
+ # or it appears like the default file does actually exist
224
+ client_logger.warning("Could not read .netrc file: %s", e)
225
+
226
+ return None
227
+
228
+
229
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
230
+ class ProxyInfo:
231
+ proxy: URL
232
+ proxy_auth: Optional[BasicAuth]
233
+
234
+
235
+ def basicauth_from_netrc(netrc_obj: Optional[netrc.netrc], host: str) -> BasicAuth:
236
+ """
237
+ Return :py:class:`~aiohttp.BasicAuth` credentials for ``host`` from ``netrc_obj``.
238
+
239
+ :raises LookupError: if ``netrc_obj`` is :py:data:`None` or if no
240
+ entry is found for the ``host``.
241
+ """
242
+ if netrc_obj is None:
243
+ raise LookupError("No .netrc file found")
244
+ auth_from_netrc = netrc_obj.authenticators(host)
245
+
246
+ if auth_from_netrc is None:
247
+ raise LookupError(f"No entry for {host!s} found in the `.netrc` file.")
248
+ login, account, password = auth_from_netrc
249
+
250
+ # TODO(PY311): username = login or account
251
+ # Up to python 3.10, account could be None if not specified,
252
+ # and login will be empty string if not specified. From 3.11,
253
+ # login and account will be empty string if not specified.
254
+ username = login if (login or account is None) else account
255
+
256
+ # TODO(PY311): Remove this, as password will be empty string
257
+ # if not specified
258
+ if password is None:
259
+ password = ""
260
+
261
+ return BasicAuth(username, password)
262
+
263
+
264
+ def proxies_from_env() -> Dict[str, ProxyInfo]:
265
+ proxy_urls = {
266
+ k: URL(v)
267
+ for k, v in getproxies().items()
268
+ if k in ("http", "https", "ws", "wss")
269
+ }
270
+ netrc_obj = netrc_from_env()
271
+ stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()}
272
+ ret = {}
273
+ for proto, val in stripped.items():
274
+ proxy, auth = val
275
+ if proxy.scheme in ("https", "wss"):
276
+ client_logger.warning(
277
+ "%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy
278
+ )
279
+ continue
280
+ if netrc_obj and auth is None:
281
+ if proxy.host is not None:
282
+ try:
283
+ auth = basicauth_from_netrc(netrc_obj, proxy.host)
284
+ except LookupError:
285
+ auth = None
286
+ ret[proto] = ProxyInfo(proxy, auth)
287
+ return ret
288
+
289
+
290
+ def current_task(
291
+ loop: Optional[asyncio.AbstractEventLoop] = None,
292
+ ) -> "Optional[asyncio.Task[Any]]":
293
+ return asyncio.current_task(loop=loop)
294
+
295
+
296
+ def get_running_loop(
297
+ loop: Optional[asyncio.AbstractEventLoop] = None,
298
+ ) -> asyncio.AbstractEventLoop:
299
+ if loop is None:
300
+ loop = asyncio.get_event_loop()
301
+ if not loop.is_running():
302
+ warnings.warn(
303
+ "The object should be created within an async function",
304
+ DeprecationWarning,
305
+ stacklevel=3,
306
+ )
307
+ if loop.get_debug():
308
+ internal_logger.warning(
309
+ "The object should be created within an async function", stack_info=True
310
+ )
311
+ return loop
312
+
313
+
314
+ def isasyncgenfunction(obj: Any) -> bool:
315
+ func = getattr(inspect, "isasyncgenfunction", None)
316
+ if func is not None:
317
+ return func(obj) # type: ignore[no-any-return]
318
+ else:
319
+ return False
320
+
321
+
322
+ def get_env_proxy_for_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
323
+ """Get a permitted proxy for the given URL from the env."""
324
+ if url.host is not None and proxy_bypass(url.host):
325
+ raise LookupError(f"Proxying is disallowed for `{url.host!r}`")
326
+
327
+ proxies_in_env = proxies_from_env()
328
+ try:
329
+ proxy_info = proxies_in_env[url.scheme]
330
+ except KeyError:
331
+ raise LookupError(f"No proxies found for `{url!s}` in the env")
332
+ else:
333
+ return proxy_info.proxy, proxy_info.proxy_auth
334
+
335
+
336
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
337
+ class MimeType:
338
+ type: str
339
+ subtype: str
340
+ suffix: str
341
+ parameters: "MultiDictProxy[str]"
342
+
343
+
344
+ @functools.lru_cache(maxsize=56)
345
+ def parse_mimetype(mimetype: str) -> MimeType:
346
+ """Parses a MIME type into its components.
347
+
348
+ mimetype is a MIME type string.
349
+
350
+ Returns a MimeType object.
351
+
352
+ Example:
353
+
354
+ >>> parse_mimetype('text/html; charset=utf-8')
355
+ MimeType(type='text', subtype='html', suffix='',
356
+ parameters={'charset': 'utf-8'})
357
+
358
+ """
359
+ if not mimetype:
360
+ return MimeType(
361
+ type="", subtype="", suffix="", parameters=MultiDictProxy(MultiDict())
362
+ )
363
+
364
+ parts = mimetype.split(";")
365
+ params: MultiDict[str] = MultiDict()
366
+ for item in parts[1:]:
367
+ if not item:
368
+ continue
369
+ key, _, value = item.partition("=")
370
+ params.add(key.lower().strip(), value.strip(' "'))
371
+
372
+ fulltype = parts[0].strip().lower()
373
+ if fulltype == "*":
374
+ fulltype = "*/*"
375
+
376
+ mtype, _, stype = fulltype.partition("/")
377
+ stype, _, suffix = stype.partition("+")
378
+
379
+ return MimeType(
380
+ type=mtype, subtype=stype, suffix=suffix, parameters=MultiDictProxy(params)
381
+ )
382
+
383
+
384
+ def guess_filename(obj: Any, default: Optional[str] = None) -> Optional[str]:
385
+ name = getattr(obj, "name", None)
386
+ if name and isinstance(name, str) and name[0] != "<" and name[-1] != ">":
387
+ return Path(name).name
388
+ return default
389
+
390
+
391
+ not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]")
392
+ QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"}
393
+
394
+
395
+ def quoted_string(content: str) -> str:
396
+ """Return 7-bit content as quoted-string.
397
+
398
+ Format content into a quoted-string as defined in RFC5322 for
399
+ Internet Message Format. Notice that this is not the 8-bit HTTP
400
+ format, but the 7-bit email format. Content must be in usascii or
401
+ a ValueError is raised.
402
+ """
403
+ if not (QCONTENT > set(content)):
404
+ raise ValueError(f"bad content for quoted-string {content!r}")
405
+ return not_qtext_re.sub(lambda x: "\\" + x.group(0), content)
406
+
407
+
408
+ def content_disposition_header(
409
+ disptype: str, quote_fields: bool = True, _charset: str = "utf-8", **params: str
410
+ ) -> str:
411
+ """Sets ``Content-Disposition`` header for MIME.
412
+
413
+ This is the MIME payload Content-Disposition header from RFC 2183
414
+ and RFC 7579 section 4.2, not the HTTP Content-Disposition from
415
+ RFC 6266.
416
+
417
+ disptype is a disposition type: inline, attachment, form-data.
418
+ Should be valid extension token (see RFC 2183)
419
+
420
+ quote_fields performs value quoting to 7-bit MIME headers
421
+ according to RFC 7578. Set to quote_fields to False if recipient
422
+ can take 8-bit file names and field values.
423
+
424
+ _charset specifies the charset to use when quote_fields is True.
425
+
426
+ params is a dict with disposition params.
427
+ """
428
+ if not disptype or not (TOKEN > set(disptype)):
429
+ raise ValueError("bad content disposition type {!r}" "".format(disptype))
430
+
431
+ value = disptype
432
+ if params:
433
+ lparams = []
434
+ for key, val in params.items():
435
+ if not key or not (TOKEN > set(key)):
436
+ raise ValueError(
437
+ "bad content disposition parameter" " {!r}={!r}".format(key, val)
438
+ )
439
+ if quote_fields:
440
+ if key.lower() == "filename":
441
+ qval = quote(val, "", encoding=_charset)
442
+ lparams.append((key, '"%s"' % qval))
443
+ else:
444
+ try:
445
+ qval = quoted_string(val)
446
+ except ValueError:
447
+ qval = "".join(
448
+ (_charset, "''", quote(val, "", encoding=_charset))
449
+ )
450
+ lparams.append((key + "*", qval))
451
+ else:
452
+ lparams.append((key, '"%s"' % qval))
453
+ else:
454
+ qval = val.replace("\\", "\\\\").replace('"', '\\"')
455
+ lparams.append((key, '"%s"' % qval))
456
+ sparams = "; ".join("=".join(pair) for pair in lparams)
457
+ value = "; ".join((value, sparams))
458
+ return value
459
+
460
+
461
+ class _TSelf(Protocol, Generic[_T]):
462
+ _cache: Dict[str, _T]
463
+
464
+
465
+ class reify(Generic[_T]):
466
+ """Use as a class method decorator.
467
+
468
+ It operates almost exactly like
469
+ the Python `@property` decorator, but it puts the result of the
470
+ method it decorates into the instance dict after the first call,
471
+ effectively replacing the function it decorates with an instance
472
+ variable. It is, in Python parlance, a data descriptor.
473
+ """
474
+
475
+ def __init__(self, wrapped: Callable[..., _T]) -> None:
476
+ self.wrapped = wrapped
477
+ self.__doc__ = wrapped.__doc__
478
+ self.name = wrapped.__name__
479
+
480
+ def __get__(self, inst: _TSelf[_T], owner: Optional[Type[Any]] = None) -> _T:
481
+ try:
482
+ try:
483
+ return inst._cache[self.name]
484
+ except KeyError:
485
+ val = self.wrapped(inst)
486
+ inst._cache[self.name] = val
487
+ return val
488
+ except AttributeError:
489
+ if inst is None:
490
+ return self
491
+ raise
492
+
493
+ def __set__(self, inst: _TSelf[_T], value: _T) -> None:
494
+ raise AttributeError("reified property is read-only")
495
+
496
+
497
+ reify_py = reify
498
+
499
+ try:
500
+ from ._helpers import reify as reify_c
501
+
502
+ if not NO_EXTENSIONS:
503
+ reify = reify_c # type: ignore[misc,assignment]
504
+ except ImportError:
505
+ pass
506
+
507
+ _ipv4_pattern = (
508
+ r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}"
509
+ r"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
510
+ )
511
+ _ipv6_pattern = (
512
+ r"^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}"
513
+ r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)"
514
+ r"((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})"
515
+ r"(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}"
516
+ r"(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}"
517
+ r"[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)"
518
+ r"(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}"
519
+ r":|:(:[A-F0-9]{1,4}){7})$"
520
+ )
521
+ _ipv4_regex = re.compile(_ipv4_pattern)
522
+ _ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE)
523
+ _ipv4_regexb = re.compile(_ipv4_pattern.encode("ascii"))
524
+ _ipv6_regexb = re.compile(_ipv6_pattern.encode("ascii"), flags=re.IGNORECASE)
525
+
526
+
527
+ def _is_ip_address(
528
+ regex: Pattern[str], regexb: Pattern[bytes], host: Optional[Union[str, bytes]]
529
+ ) -> bool:
530
+ if host is None:
531
+ return False
532
+ if isinstance(host, str):
533
+ return bool(regex.match(host))
534
+ elif isinstance(host, (bytes, bytearray, memoryview)):
535
+ return bool(regexb.match(host))
536
+ else:
537
+ raise TypeError(f"{host} [{type(host)}] is not a str or bytes")
538
+
539
+
540
+ is_ipv4_address = functools.partial(_is_ip_address, _ipv4_regex, _ipv4_regexb)
541
+ is_ipv6_address = functools.partial(_is_ip_address, _ipv6_regex, _ipv6_regexb)
542
+
543
+
544
+ def is_ip_address(host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool:
545
+ return is_ipv4_address(host) or is_ipv6_address(host)
546
+
547
+
548
+ _cached_current_datetime: Optional[int] = None
549
+ _cached_formatted_datetime = ""
550
+
551
+
552
+ def rfc822_formatted_time() -> str:
553
+ global _cached_current_datetime
554
+ global _cached_formatted_datetime
555
+
556
+ now = int(time.time())
557
+ if now != _cached_current_datetime:
558
+ # Weekday and month names for HTTP date/time formatting;
559
+ # always English!
560
+ # Tuples are constants stored in codeobject!
561
+ _weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
562
+ _monthname = (
563
+ "", # Dummy so we can use 1-based month numbers
564
+ "Jan",
565
+ "Feb",
566
+ "Mar",
567
+ "Apr",
568
+ "May",
569
+ "Jun",
570
+ "Jul",
571
+ "Aug",
572
+ "Sep",
573
+ "Oct",
574
+ "Nov",
575
+ "Dec",
576
+ )
577
+
578
+ year, month, day, hh, mm, ss, wd, *tail = time.gmtime(now)
579
+ _cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
580
+ _weekdayname[wd],
581
+ day,
582
+ _monthname[month],
583
+ year,
584
+ hh,
585
+ mm,
586
+ ss,
587
+ )
588
+ _cached_current_datetime = now
589
+ return _cached_formatted_datetime
590
+
591
+
592
+ def _weakref_handle(info: "Tuple[weakref.ref[object], str]") -> None:
593
+ ref, name = info
594
+ ob = ref()
595
+ if ob is not None:
596
+ with suppress(Exception):
597
+ getattr(ob, name)()
598
+
599
+
600
+ def weakref_handle(
601
+ ob: object,
602
+ name: str,
603
+ timeout: float,
604
+ loop: asyncio.AbstractEventLoop,
605
+ timeout_ceil_threshold: float = 5,
606
+ ) -> Optional[asyncio.TimerHandle]:
607
+ if timeout is not None and timeout > 0:
608
+ when = loop.time() + timeout
609
+ if timeout >= timeout_ceil_threshold:
610
+ when = ceil(when)
611
+
612
+ return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name))
613
+ return None
614
+
615
+
616
+ def call_later(
617
+ cb: Callable[[], Any],
618
+ timeout: float,
619
+ loop: asyncio.AbstractEventLoop,
620
+ timeout_ceil_threshold: float = 5,
621
+ ) -> Optional[asyncio.TimerHandle]:
622
+ if timeout is not None and timeout > 0:
623
+ when = loop.time() + timeout
624
+ if timeout > timeout_ceil_threshold:
625
+ when = ceil(when)
626
+ return loop.call_at(when, cb)
627
+ return None
628
+
629
+
630
+ class TimeoutHandle:
631
+ """Timeout handle"""
632
+
633
+ def __init__(
634
+ self,
635
+ loop: asyncio.AbstractEventLoop,
636
+ timeout: Optional[float],
637
+ ceil_threshold: float = 5,
638
+ ) -> None:
639
+ self._timeout = timeout
640
+ self._loop = loop
641
+ self._ceil_threshold = ceil_threshold
642
+ self._callbacks: List[
643
+ Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]]
644
+ ] = []
645
+
646
+ def register(
647
+ self, callback: Callable[..., None], *args: Any, **kwargs: Any
648
+ ) -> None:
649
+ self._callbacks.append((callback, args, kwargs))
650
+
651
+ def close(self) -> None:
652
+ self._callbacks.clear()
653
+
654
+ def start(self) -> Optional[asyncio.Handle]:
655
+ timeout = self._timeout
656
+ if timeout is not None and timeout > 0:
657
+ when = self._loop.time() + timeout
658
+ if timeout >= self._ceil_threshold:
659
+ when = ceil(when)
660
+ return self._loop.call_at(when, self.__call__)
661
+ else:
662
+ return None
663
+
664
+ def timer(self) -> "BaseTimerContext":
665
+ if self._timeout is not None and self._timeout > 0:
666
+ timer = TimerContext(self._loop)
667
+ self.register(timer.timeout)
668
+ return timer
669
+ else:
670
+ return TimerNoop()
671
+
672
+ def __call__(self) -> None:
673
+ for cb, args, kwargs in self._callbacks:
674
+ with suppress(Exception):
675
+ cb(*args, **kwargs)
676
+
677
+ self._callbacks.clear()
678
+
679
+
680
+ class BaseTimerContext(ContextManager["BaseTimerContext"]):
681
+ def assert_timeout(self) -> None:
682
+ """Raise TimeoutError if timeout has been exceeded."""
683
+
684
+
685
+ class TimerNoop(BaseTimerContext):
686
+ def __enter__(self) -> BaseTimerContext:
687
+ return self
688
+
689
+ def __exit__(
690
+ self,
691
+ exc_type: Optional[Type[BaseException]],
692
+ exc_val: Optional[BaseException],
693
+ exc_tb: Optional[TracebackType],
694
+ ) -> None:
695
+ return
696
+
697
+
698
+ class TimerContext(BaseTimerContext):
699
+ """Low resolution timeout context manager"""
700
+
701
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
702
+ self._loop = loop
703
+ self._tasks: List[asyncio.Task[Any]] = []
704
+ self._cancelled = False
705
+
706
+ def assert_timeout(self) -> None:
707
+ """Raise TimeoutError if timer has already been cancelled."""
708
+ if self._cancelled:
709
+ raise asyncio.TimeoutError from None
710
+
711
+ def __enter__(self) -> BaseTimerContext:
712
+ task = current_task(loop=self._loop)
713
+
714
+ if task is None:
715
+ raise RuntimeError(
716
+ "Timeout context manager should be used " "inside a task"
717
+ )
718
+
719
+ if self._cancelled:
720
+ raise asyncio.TimeoutError from None
721
+
722
+ self._tasks.append(task)
723
+ return self
724
+
725
+ def __exit__(
726
+ self,
727
+ exc_type: Optional[Type[BaseException]],
728
+ exc_val: Optional[BaseException],
729
+ exc_tb: Optional[TracebackType],
730
+ ) -> Optional[bool]:
731
+ if self._tasks:
732
+ self._tasks.pop()
733
+
734
+ if exc_type is asyncio.CancelledError and self._cancelled:
735
+ raise asyncio.TimeoutError from None
736
+ return None
737
+
738
+ def timeout(self) -> None:
739
+ if not self._cancelled:
740
+ for task in set(self._tasks):
741
+ task.cancel()
742
+
743
+ self._cancelled = True
744
+
745
+
746
+ def ceil_timeout(
747
+ delay: Optional[float], ceil_threshold: float = 5
748
+ ) -> async_timeout.Timeout:
749
+ if delay is None or delay <= 0:
750
+ return async_timeout.timeout(None)
751
+
752
+ loop = get_running_loop()
753
+ now = loop.time()
754
+ when = now + delay
755
+ if delay > ceil_threshold:
756
+ when = ceil(when)
757
+ return async_timeout.timeout_at(when)
758
+
759
+
760
+ class HeadersMixin:
761
+ ATTRS = frozenset(["_content_type", "_content_dict", "_stored_content_type"])
762
+
763
+ _headers: MultiMapping[str]
764
+
765
+ _content_type: Optional[str] = None
766
+ _content_dict: Optional[Dict[str, str]] = None
767
+ _stored_content_type: Union[str, None, _SENTINEL] = sentinel
768
+
769
+ def _parse_content_type(self, raw: Optional[str]) -> None:
770
+ self._stored_content_type = raw
771
+ if raw is None:
772
+ # default value according to RFC 2616
773
+ self._content_type = "application/octet-stream"
774
+ self._content_dict = {}
775
+ else:
776
+ msg = HeaderParser().parsestr("Content-Type: " + raw)
777
+ self._content_type = msg.get_content_type()
778
+ params = msg.get_params(())
779
+ self._content_dict = dict(params[1:]) # First element is content type again
780
+
781
+ @property
782
+ def content_type(self) -> str:
783
+ """The value of content part for Content-Type HTTP header."""
784
+ raw = self._headers.get(hdrs.CONTENT_TYPE)
785
+ if self._stored_content_type != raw:
786
+ self._parse_content_type(raw)
787
+ return self._content_type # type: ignore[return-value]
788
+
789
+ @property
790
+ def charset(self) -> Optional[str]:
791
+ """The value of charset part for Content-Type HTTP header."""
792
+ raw = self._headers.get(hdrs.CONTENT_TYPE)
793
+ if self._stored_content_type != raw:
794
+ self._parse_content_type(raw)
795
+ return self._content_dict.get("charset") # type: ignore[union-attr]
796
+
797
+ @property
798
+ def content_length(self) -> Optional[int]:
799
+ """The value of Content-Length HTTP header."""
800
+ content_length = self._headers.get(hdrs.CONTENT_LENGTH)
801
+
802
+ if content_length is not None:
803
+ return int(content_length)
804
+ else:
805
+ return None
806
+
807
+
808
+ def set_result(fut: "asyncio.Future[_T]", result: _T) -> None:
809
+ if not fut.done():
810
+ fut.set_result(result)
811
+
812
+
813
+ def set_exception(fut: "asyncio.Future[_T]", exc: BaseException) -> None:
814
+ if not fut.done():
815
+ fut.set_exception(exc)
816
+
817
+
818
+ @functools.total_ordering
819
+ class AppKey(Generic[_T]):
820
+ """Keys for static typing support in Application."""
821
+
822
+ __slots__ = ("_name", "_t", "__orig_class__")
823
+
824
+ # This may be set by Python when instantiating with a generic type. We need to
825
+ # support this, in order to support types that are not concrete classes,
826
+ # like Iterable, which can't be passed as the second parameter to __init__.
827
+ __orig_class__: Type[object]
828
+
829
+ def __init__(self, name: str, t: Optional[Type[_T]] = None):
830
+ # Prefix with module name to help deduplicate key names.
831
+ frame = inspect.currentframe()
832
+ while frame:
833
+ if frame.f_code.co_name == "<module>":
834
+ module: str = frame.f_globals["__name__"]
835
+ break
836
+ frame = frame.f_back
837
+
838
+ self._name = module + "." + name
839
+ self._t = t
840
+
841
+ def __lt__(self, other: object) -> bool:
842
+ if isinstance(other, AppKey):
843
+ return self._name < other._name
844
+ return True # Order AppKey above other types.
845
+
846
+ def __repr__(self) -> str:
847
+ t = self._t
848
+ if t is None:
849
+ with suppress(AttributeError):
850
+ # Set to type arg.
851
+ t = get_args(self.__orig_class__)[0]
852
+
853
+ if t is None:
854
+ t_repr = "<<Unknown>>"
855
+ elif isinstance(t, type):
856
+ if t.__module__ == "builtins":
857
+ t_repr = t.__qualname__
858
+ else:
859
+ t_repr = f"{t.__module__}.{t.__qualname__}"
860
+ else:
861
+ t_repr = repr(t)
862
+ return f"<AppKey({self._name}, type={t_repr})>"
863
+
864
+
865
+ class ChainMapProxy(Mapping[Union[str, AppKey[Any]], Any]):
866
+ __slots__ = ("_maps",)
867
+
868
+ def __init__(self, maps: Iterable[Mapping[Union[str, AppKey[Any]], Any]]) -> None:
869
+ self._maps = tuple(maps)
870
+
871
+ def __init_subclass__(cls) -> None:
872
+ raise TypeError(
873
+ "Inheritance class {} from ChainMapProxy "
874
+ "is forbidden".format(cls.__name__)
875
+ )
876
+
877
+ @overload # type: ignore[override]
878
+ def __getitem__(self, key: AppKey[_T]) -> _T:
879
+ ...
880
+
881
+ @overload
882
+ def __getitem__(self, key: str) -> Any:
883
+ ...
884
+
885
+ def __getitem__(self, key: Union[str, AppKey[_T]]) -> Any:
886
+ for mapping in self._maps:
887
+ try:
888
+ return mapping[key]
889
+ except KeyError:
890
+ pass
891
+ raise KeyError(key)
892
+
893
+ @overload # type: ignore[override]
894
+ def get(self, key: AppKey[_T], default: _S) -> Union[_T, _S]:
895
+ ...
896
+
897
+ @overload
898
+ def get(self, key: AppKey[_T], default: None = ...) -> Optional[_T]:
899
+ ...
900
+
901
+ @overload
902
+ def get(self, key: str, default: Any = ...) -> Any:
903
+ ...
904
+
905
+ def get(self, key: Union[str, AppKey[_T]], default: Any = None) -> Any:
906
+ try:
907
+ return self[key]
908
+ except KeyError:
909
+ return default
910
+
911
+ def __len__(self) -> int:
912
+ # reuses stored hash values if possible
913
+ return len(set().union(*self._maps))
914
+
915
+ def __iter__(self) -> Iterator[Union[str, AppKey[Any]]]:
916
+ d: Dict[Union[str, AppKey[Any]], Any] = {}
917
+ for mapping in reversed(self._maps):
918
+ # reuses stored hash values if possible
919
+ d.update(mapping)
920
+ return iter(d)
921
+
922
+ def __contains__(self, key: object) -> bool:
923
+ return any(key in m for m in self._maps)
924
+
925
+ def __bool__(self) -> bool:
926
+ return any(self._maps)
927
+
928
+ def __repr__(self) -> str:
929
+ content = ", ".join(map(repr, self._maps))
930
+ return f"ChainMapProxy({content})"
931
+
932
+
933
+ # https://tools.ietf.org/html/rfc7232#section-2.3
934
+ _ETAGC = r"[!\x23-\x7E\x80-\xff]+"
935
+ _ETAGC_RE = re.compile(_ETAGC)
936
+ _QUOTED_ETAG = rf'(W/)?"({_ETAGC})"'
937
+ QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG)
938
+ LIST_QUOTED_ETAG_RE = re.compile(rf"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)")
939
+
940
+ ETAG_ANY = "*"
941
+
942
+
943
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
944
+ class ETag:
945
+ value: str
946
+ is_weak: bool = False
947
+
948
+
949
+ def validate_etag_value(value: str) -> None:
950
+ if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value):
951
+ raise ValueError(
952
+ f"Value {value!r} is not a valid etag. Maybe it contains '\"'?"
953
+ )
954
+
955
+
956
+ def parse_http_date(date_str: Optional[str]) -> Optional[datetime.datetime]:
957
+ """Process a date string, return a datetime object"""
958
+ if date_str is not None:
959
+ timetuple = parsedate(date_str)
960
+ if timetuple is not None:
961
+ with suppress(ValueError):
962
+ return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc)
963
+ return None
964
+
965
+
966
+ def must_be_empty_body(method: str, code: int) -> bool:
967
+ """Check if a request must return an empty body."""
968
+ return (
969
+ status_code_must_be_empty_body(code)
970
+ or method_must_be_empty_body(method)
971
+ or (200 <= code < 300 and method.upper() == hdrs.METH_CONNECT)
972
+ )
973
+
974
+
975
+ def method_must_be_empty_body(method: str) -> bool:
976
+ """Check if a method must return an empty body."""
977
+ # https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1
978
+ # https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.2
979
+ return method.upper() == hdrs.METH_HEAD
980
+
981
+
982
+ def status_code_must_be_empty_body(code: int) -> bool:
983
+ """Check if a status code must return an empty body."""
984
+ # https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1
985
+ return code in {204, 304} or 100 <= code < 200
986
+
987
+
988
+ def should_remove_content_length(method: str, code: int) -> bool:
989
+ """Check if a Content-Length header should be removed.
990
+
991
+ This should always be a subset of must_be_empty_body
992
+ """
993
+ # https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-8
994
+ # https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4.5-4
995
+ return (
996
+ code in {204, 304}
997
+ or 100 <= code < 200
998
+ or (200 <= code < 300 and method.upper() == hdrs.METH_CONNECT)
999
+ )
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from http import HTTPStatus
3
+ from typing import Mapping, Tuple
4
+
5
+ from . import __version__
6
+ from .http_exceptions import HttpProcessingError as HttpProcessingError
7
+ from .http_parser import (
8
+ HeadersParser as HeadersParser,
9
+ HttpParser as HttpParser,
10
+ HttpRequestParser as HttpRequestParser,
11
+ HttpResponseParser as HttpResponseParser,
12
+ RawRequestMessage as RawRequestMessage,
13
+ RawResponseMessage as RawResponseMessage,
14
+ )
15
+ from .http_websocket import (
16
+ WS_CLOSED_MESSAGE as WS_CLOSED_MESSAGE,
17
+ WS_CLOSING_MESSAGE as WS_CLOSING_MESSAGE,
18
+ WS_KEY as WS_KEY,
19
+ WebSocketError as WebSocketError,
20
+ WebSocketReader as WebSocketReader,
21
+ WebSocketWriter as WebSocketWriter,
22
+ WSCloseCode as WSCloseCode,
23
+ WSMessage as WSMessage,
24
+ WSMsgType as WSMsgType,
25
+ ws_ext_gen as ws_ext_gen,
26
+ ws_ext_parse as ws_ext_parse,
27
+ )
28
+ from .http_writer import (
29
+ HttpVersion as HttpVersion,
30
+ HttpVersion10 as HttpVersion10,
31
+ HttpVersion11 as HttpVersion11,
32
+ StreamWriter as StreamWriter,
33
+ )
34
+
35
+ __all__ = (
36
+ "HttpProcessingError",
37
+ "RESPONSES",
38
+ "SERVER_SOFTWARE",
39
+ # .http_writer
40
+ "StreamWriter",
41
+ "HttpVersion",
42
+ "HttpVersion10",
43
+ "HttpVersion11",
44
+ # .http_parser
45
+ "HeadersParser",
46
+ "HttpParser",
47
+ "HttpRequestParser",
48
+ "HttpResponseParser",
49
+ "RawRequestMessage",
50
+ "RawResponseMessage",
51
+ # .http_websocket
52
+ "WS_CLOSED_MESSAGE",
53
+ "WS_CLOSING_MESSAGE",
54
+ "WS_KEY",
55
+ "WebSocketReader",
56
+ "WebSocketWriter",
57
+ "ws_ext_gen",
58
+ "ws_ext_parse",
59
+ "WSMessage",
60
+ "WebSocketError",
61
+ "WSMsgType",
62
+ "WSCloseCode",
63
+ )
64
+
65
+
66
+ SERVER_SOFTWARE: str = "Python/{0[0]}.{0[1]} aiohttp/{1}".format(
67
+ sys.version_info, __version__
68
+ )
69
+
70
+ RESPONSES: Mapping[int, Tuple[str, str]] = {
71
+ v: (v.phrase, v.description) for v in HTTPStatus.__members__.values()
72
+ }
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_exceptions.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Low-level http related exceptions."""
2
+
3
+
4
+ from textwrap import indent
5
+ from typing import Optional, Union
6
+
7
+ from .typedefs import _CIMultiDict
8
+
9
+ __all__ = ("HttpProcessingError",)
10
+
11
+
12
+ class HttpProcessingError(Exception):
13
+ """HTTP error.
14
+
15
+ Shortcut for raising HTTP errors with custom code, message and headers.
16
+
17
+ code: HTTP Error code.
18
+ message: (optional) Error message.
19
+ headers: (optional) Headers to be sent in response, a list of pairs
20
+ """
21
+
22
+ code = 0
23
+ message = ""
24
+ headers = None
25
+
26
+ def __init__(
27
+ self,
28
+ *,
29
+ code: Optional[int] = None,
30
+ message: str = "",
31
+ headers: Optional[_CIMultiDict] = None,
32
+ ) -> None:
33
+ if code is not None:
34
+ self.code = code
35
+ self.headers = headers
36
+ self.message = message
37
+
38
+ def __str__(self) -> str:
39
+ msg = indent(self.message, " ")
40
+ return f"{self.code}, message:\n{msg}"
41
+
42
+ def __repr__(self) -> str:
43
+ return f"<{self.__class__.__name__}: {self.code}, message={self.message!r}>"
44
+
45
+
46
+ class BadHttpMessage(HttpProcessingError):
47
+
48
+ code = 400
49
+ message = "Bad Request"
50
+
51
+ def __init__(self, message: str, *, headers: Optional[_CIMultiDict] = None) -> None:
52
+ super().__init__(message=message, headers=headers)
53
+ self.args = (message,)
54
+
55
+
56
+ class HttpBadRequest(BadHttpMessage):
57
+
58
+ code = 400
59
+ message = "Bad Request"
60
+
61
+
62
+ class PayloadEncodingError(BadHttpMessage):
63
+ """Base class for payload errors"""
64
+
65
+
66
+ class ContentEncodingError(PayloadEncodingError):
67
+ """Content encoding error."""
68
+
69
+
70
+ class TransferEncodingError(PayloadEncodingError):
71
+ """transfer encoding error."""
72
+
73
+
74
+ class ContentLengthError(PayloadEncodingError):
75
+ """Not enough data for satisfy content length header."""
76
+
77
+
78
+ class LineTooLong(BadHttpMessage):
79
+ def __init__(
80
+ self, line: str, limit: str = "Unknown", actual_size: str = "Unknown"
81
+ ) -> None:
82
+ super().__init__(
83
+ f"Got more than {limit} bytes ({actual_size}) when reading {line}."
84
+ )
85
+ self.args = (line, limit, actual_size)
86
+
87
+
88
+ class InvalidHeader(BadHttpMessage):
89
+ def __init__(self, hdr: Union[bytes, str]) -> None:
90
+ hdr_s = hdr.decode(errors="backslashreplace") if isinstance(hdr, bytes) else hdr
91
+ super().__init__(f"Invalid HTTP header: {hdr!r}")
92
+ self.hdr = hdr_s
93
+ self.args = (hdr,)
94
+
95
+
96
+ class BadStatusLine(BadHttpMessage):
97
+ def __init__(self, line: str = "", error: Optional[str] = None) -> None:
98
+ if not isinstance(line, str):
99
+ line = repr(line)
100
+ super().__init__(error or f"Bad status line {line!r}")
101
+ self.args = (line,)
102
+ self.line = line
103
+
104
+
105
+ class InvalidURLError(BadHttpMessage):
106
+ pass
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_parser.py ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import asyncio
3
+ import re
4
+ import string
5
+ from contextlib import suppress
6
+ from enum import IntEnum
7
+ from typing import (
8
+ Any,
9
+ ClassVar,
10
+ Final,
11
+ Generic,
12
+ List,
13
+ Literal,
14
+ NamedTuple,
15
+ Optional,
16
+ Pattern,
17
+ Set,
18
+ Tuple,
19
+ Type,
20
+ TypeVar,
21
+ Union,
22
+ )
23
+
24
+ from multidict import CIMultiDict, CIMultiDictProxy, istr
25
+ from yarl import URL
26
+
27
+ from . import hdrs
28
+ from .base_protocol import BaseProtocol
29
+ from .compression_utils import HAS_BROTLI, BrotliDecompressor, ZLibDecompressor
30
+ from .helpers import (
31
+ DEBUG,
32
+ NO_EXTENSIONS,
33
+ BaseTimerContext,
34
+ method_must_be_empty_body,
35
+ status_code_must_be_empty_body,
36
+ )
37
+ from .http_exceptions import (
38
+ BadHttpMessage,
39
+ BadStatusLine,
40
+ ContentEncodingError,
41
+ ContentLengthError,
42
+ InvalidHeader,
43
+ InvalidURLError,
44
+ LineTooLong,
45
+ TransferEncodingError,
46
+ )
47
+ from .http_writer import HttpVersion, HttpVersion10
48
+ from .log import internal_logger
49
+ from .streams import EMPTY_PAYLOAD, StreamReader
50
+ from .typedefs import RawHeaders
51
+
52
+ __all__ = (
53
+ "HeadersParser",
54
+ "HttpParser",
55
+ "HttpRequestParser",
56
+ "HttpResponseParser",
57
+ "RawRequestMessage",
58
+ "RawResponseMessage",
59
+ )
60
+
61
+ _SEP = Literal[b"\r\n", b"\n"]
62
+
63
+ ASCIISET: Final[Set[str]] = set(string.printable)
64
+
65
+ # See https://www.rfc-editor.org/rfc/rfc9110.html#name-overview
66
+ # and https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens
67
+ #
68
+ # method = token
69
+ # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
70
+ # "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
71
+ # token = 1*tchar
72
+ METHRE: Final[Pattern[str]] = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")
73
+ VERSRE: Final[Pattern[str]] = re.compile(r"HTTP/(\d).(\d)")
74
+ HDRRE: Final[Pattern[bytes]] = re.compile(
75
+ rb"[\x00-\x1F\x7F-\xFF()<>@,;:\[\]={} \t\"\\]"
76
+ )
77
+ HEXDIGIT = re.compile(rb"[0-9a-fA-F]+")
78
+
79
+
80
+ class RawRequestMessage(NamedTuple):
81
+ method: str
82
+ path: str
83
+ version: HttpVersion
84
+ headers: "CIMultiDictProxy[str]"
85
+ raw_headers: RawHeaders
86
+ should_close: bool
87
+ compression: Optional[str]
88
+ upgrade: bool
89
+ chunked: bool
90
+ url: URL
91
+
92
+
93
+ class RawResponseMessage(NamedTuple):
94
+ version: HttpVersion
95
+ code: int
96
+ reason: str
97
+ headers: CIMultiDictProxy[str]
98
+ raw_headers: RawHeaders
99
+ should_close: bool
100
+ compression: Optional[str]
101
+ upgrade: bool
102
+ chunked: bool
103
+
104
+
105
+ _MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage)
106
+
107
+
108
+ class ParseState(IntEnum):
109
+
110
+ PARSE_NONE = 0
111
+ PARSE_LENGTH = 1
112
+ PARSE_CHUNKED = 2
113
+ PARSE_UNTIL_EOF = 3
114
+
115
+
116
+ class ChunkState(IntEnum):
117
+ PARSE_CHUNKED_SIZE = 0
118
+ PARSE_CHUNKED_CHUNK = 1
119
+ PARSE_CHUNKED_CHUNK_EOF = 2
120
+ PARSE_MAYBE_TRAILERS = 3
121
+ PARSE_TRAILERS = 4
122
+
123
+
124
+ class HeadersParser:
125
+ def __init__(
126
+ self,
127
+ max_line_size: int = 8190,
128
+ max_headers: int = 32768,
129
+ max_field_size: int = 8190,
130
+ ) -> None:
131
+ self.max_line_size = max_line_size
132
+ self.max_headers = max_headers
133
+ self.max_field_size = max_field_size
134
+
135
+ def parse_headers(
136
+ self, lines: List[bytes]
137
+ ) -> Tuple["CIMultiDictProxy[str]", RawHeaders]:
138
+ headers: CIMultiDict[str] = CIMultiDict()
139
+ raw_headers = []
140
+
141
+ lines_idx = 1
142
+ line = lines[1]
143
+ line_count = len(lines)
144
+
145
+ while line:
146
+ # Parse initial header name : value pair.
147
+ try:
148
+ bname, bvalue = line.split(b":", 1)
149
+ except ValueError:
150
+ raise InvalidHeader(line) from None
151
+
152
+ # https://www.rfc-editor.org/rfc/rfc9112.html#section-5.1-2
153
+ if {bname[0], bname[-1]} & {32, 9}: # {" ", "\t"}
154
+ raise InvalidHeader(line)
155
+
156
+ bvalue = bvalue.lstrip(b" \t")
157
+ if HDRRE.search(bname):
158
+ raise InvalidHeader(bname)
159
+ if len(bname) > self.max_field_size:
160
+ raise LineTooLong(
161
+ "request header name {}".format(
162
+ bname.decode("utf8", "backslashreplace")
163
+ ),
164
+ str(self.max_field_size),
165
+ str(len(bname)),
166
+ )
167
+
168
+ header_length = len(bvalue)
169
+
170
+ # next line
171
+ lines_idx += 1
172
+ line = lines[lines_idx]
173
+
174
+ # consume continuation lines
175
+ continuation = line and line[0] in (32, 9) # (' ', '\t')
176
+
177
+ # Deprecated: https://www.rfc-editor.org/rfc/rfc9112.html#name-obsolete-line-folding
178
+ if continuation:
179
+ bvalue_lst = [bvalue]
180
+ while continuation:
181
+ header_length += len(line)
182
+ if header_length > self.max_field_size:
183
+ raise LineTooLong(
184
+ "request header field {}".format(
185
+ bname.decode("utf8", "backslashreplace")
186
+ ),
187
+ str(self.max_field_size),
188
+ str(header_length),
189
+ )
190
+ bvalue_lst.append(line)
191
+
192
+ # next line
193
+ lines_idx += 1
194
+ if lines_idx < line_count:
195
+ line = lines[lines_idx]
196
+ if line:
197
+ continuation = line[0] in (32, 9) # (' ', '\t')
198
+ else:
199
+ line = b""
200
+ break
201
+ bvalue = b"".join(bvalue_lst)
202
+ else:
203
+ if header_length > self.max_field_size:
204
+ raise LineTooLong(
205
+ "request header field {}".format(
206
+ bname.decode("utf8", "backslashreplace")
207
+ ),
208
+ str(self.max_field_size),
209
+ str(header_length),
210
+ )
211
+
212
+ bvalue = bvalue.strip(b" \t")
213
+ name = bname.decode("utf-8", "surrogateescape")
214
+ value = bvalue.decode("utf-8", "surrogateescape")
215
+
216
+ # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-5
217
+ if "\n" in value or "\r" in value or "\x00" in value:
218
+ raise InvalidHeader(bvalue)
219
+
220
+ headers.add(name, value)
221
+ raw_headers.append((bname, bvalue))
222
+
223
+ return (CIMultiDictProxy(headers), tuple(raw_headers))
224
+
225
+
226
+ class HttpParser(abc.ABC, Generic[_MsgT]):
227
+ lax: ClassVar[bool] = False
228
+
229
+ def __init__(
230
+ self,
231
+ protocol: Optional[BaseProtocol] = None,
232
+ loop: Optional[asyncio.AbstractEventLoop] = None,
233
+ limit: int = 2**16,
234
+ max_line_size: int = 8190,
235
+ max_headers: int = 32768,
236
+ max_field_size: int = 8190,
237
+ timer: Optional[BaseTimerContext] = None,
238
+ code: Optional[int] = None,
239
+ method: Optional[str] = None,
240
+ readall: bool = False,
241
+ payload_exception: Optional[Type[BaseException]] = None,
242
+ response_with_body: bool = True,
243
+ read_until_eof: bool = False,
244
+ auto_decompress: bool = True,
245
+ ) -> None:
246
+ self.protocol = protocol
247
+ self.loop = loop
248
+ self.max_line_size = max_line_size
249
+ self.max_headers = max_headers
250
+ self.max_field_size = max_field_size
251
+ self.timer = timer
252
+ self.code = code
253
+ self.method = method
254
+ self.readall = readall
255
+ self.payload_exception = payload_exception
256
+ self.response_with_body = response_with_body
257
+ self.read_until_eof = read_until_eof
258
+
259
+ self._lines: List[bytes] = []
260
+ self._tail = b""
261
+ self._upgraded = False
262
+ self._payload = None
263
+ self._payload_parser: Optional[HttpPayloadParser] = None
264
+ self._auto_decompress = auto_decompress
265
+ self._limit = limit
266
+ self._headers_parser = HeadersParser(max_line_size, max_headers, max_field_size)
267
+
268
+ @abc.abstractmethod
269
+ def parse_message(self, lines: List[bytes]) -> _MsgT:
270
+ pass
271
+
272
+ def feed_eof(self) -> Optional[_MsgT]:
273
+ if self._payload_parser is not None:
274
+ self._payload_parser.feed_eof()
275
+ self._payload_parser = None
276
+ else:
277
+ # try to extract partial message
278
+ if self._tail:
279
+ self._lines.append(self._tail)
280
+
281
+ if self._lines:
282
+ if self._lines[-1] != "\r\n":
283
+ self._lines.append(b"")
284
+ with suppress(Exception):
285
+ return self.parse_message(self._lines)
286
+ return None
287
+
288
+ def feed_data(
289
+ self,
290
+ data: bytes,
291
+ SEP: _SEP = b"\r\n",
292
+ EMPTY: bytes = b"",
293
+ CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH,
294
+ METH_CONNECT: str = hdrs.METH_CONNECT,
295
+ SEC_WEBSOCKET_KEY1: istr = hdrs.SEC_WEBSOCKET_KEY1,
296
+ ) -> Tuple[List[Tuple[_MsgT, StreamReader]], bool, bytes]:
297
+
298
+ messages = []
299
+
300
+ if self._tail:
301
+ data, self._tail = self._tail + data, b""
302
+
303
+ data_len = len(data)
304
+ start_pos = 0
305
+ loop = self.loop
306
+
307
+ while start_pos < data_len:
308
+
309
+ # read HTTP message (request/response line + headers), \r\n\r\n
310
+ # and split by lines
311
+ if self._payload_parser is None and not self._upgraded:
312
+ pos = data.find(SEP, start_pos)
313
+ # consume \r\n
314
+ if pos == start_pos and not self._lines:
315
+ start_pos = pos + len(SEP)
316
+ continue
317
+
318
+ if pos >= start_pos:
319
+ # line found
320
+ line = data[start_pos:pos]
321
+ if SEP == b"\n": # For lax response parsing
322
+ line = line.rstrip(b"\r")
323
+ self._lines.append(line)
324
+ start_pos = pos + len(SEP)
325
+
326
+ # \r\n\r\n found
327
+ if self._lines[-1] == EMPTY:
328
+ try:
329
+ msg: _MsgT = self.parse_message(self._lines)
330
+ finally:
331
+ self._lines.clear()
332
+
333
+ def get_content_length() -> Optional[int]:
334
+ # payload length
335
+ length_hdr = msg.headers.get(CONTENT_LENGTH)
336
+ if length_hdr is None:
337
+ return None
338
+
339
+ # Shouldn't allow +/- or other number formats.
340
+ # https://www.rfc-editor.org/rfc/rfc9110#section-8.6-2
341
+ if not length_hdr.strip(" \t").isdecimal():
342
+ raise InvalidHeader(CONTENT_LENGTH)
343
+
344
+ return int(length_hdr)
345
+
346
+ length = get_content_length()
347
+ # do not support old websocket spec
348
+ if SEC_WEBSOCKET_KEY1 in msg.headers:
349
+ raise InvalidHeader(SEC_WEBSOCKET_KEY1)
350
+
351
+ self._upgraded = msg.upgrade
352
+
353
+ method = getattr(msg, "method", self.method)
354
+ # code is only present on responses
355
+ code = getattr(msg, "code", 0)
356
+
357
+ assert self.protocol is not None
358
+ # calculate payload
359
+ empty_body = status_code_must_be_empty_body(code) or bool(
360
+ method and method_must_be_empty_body(method)
361
+ )
362
+ if not empty_body and (
363
+ (length is not None and length > 0)
364
+ or msg.chunked
365
+ and not msg.upgrade
366
+ ):
367
+ payload = StreamReader(
368
+ self.protocol,
369
+ timer=self.timer,
370
+ loop=loop,
371
+ limit=self._limit,
372
+ )
373
+ payload_parser = HttpPayloadParser(
374
+ payload,
375
+ length=length,
376
+ chunked=msg.chunked,
377
+ method=method,
378
+ compression=msg.compression,
379
+ code=self.code,
380
+ readall=self.readall,
381
+ response_with_body=self.response_with_body,
382
+ auto_decompress=self._auto_decompress,
383
+ lax=self.lax,
384
+ )
385
+ if not payload_parser.done:
386
+ self._payload_parser = payload_parser
387
+ elif method == METH_CONNECT:
388
+ assert isinstance(msg, RawRequestMessage)
389
+ payload = StreamReader(
390
+ self.protocol,
391
+ timer=self.timer,
392
+ loop=loop,
393
+ limit=self._limit,
394
+ )
395
+ self._upgraded = True
396
+ self._payload_parser = HttpPayloadParser(
397
+ payload,
398
+ method=msg.method,
399
+ compression=msg.compression,
400
+ readall=True,
401
+ auto_decompress=self._auto_decompress,
402
+ lax=self.lax,
403
+ )
404
+ elif not empty_body and length is None and self.read_until_eof:
405
+ payload = StreamReader(
406
+ self.protocol,
407
+ timer=self.timer,
408
+ loop=loop,
409
+ limit=self._limit,
410
+ )
411
+ payload_parser = HttpPayloadParser(
412
+ payload,
413
+ length=length,
414
+ chunked=msg.chunked,
415
+ method=method,
416
+ compression=msg.compression,
417
+ code=self.code,
418
+ readall=True,
419
+ response_with_body=self.response_with_body,
420
+ auto_decompress=self._auto_decompress,
421
+ lax=self.lax,
422
+ )
423
+ if not payload_parser.done:
424
+ self._payload_parser = payload_parser
425
+ else:
426
+ payload = EMPTY_PAYLOAD
427
+
428
+ messages.append((msg, payload))
429
+ else:
430
+ self._tail = data[start_pos:]
431
+ data = EMPTY
432
+ break
433
+
434
+ # no parser, just store
435
+ elif self._payload_parser is None and self._upgraded:
436
+ assert not self._lines
437
+ break
438
+
439
+ # feed payload
440
+ elif data and start_pos < data_len:
441
+ assert not self._lines
442
+ assert self._payload_parser is not None
443
+ try:
444
+ eof, data = self._payload_parser.feed_data(data[start_pos:], SEP)
445
+ except BaseException as exc:
446
+ if self.payload_exception is not None:
447
+ self._payload_parser.payload.set_exception(
448
+ self.payload_exception(str(exc))
449
+ )
450
+ else:
451
+ self._payload_parser.payload.set_exception(exc)
452
+
453
+ eof = True
454
+ data = b""
455
+
456
+ if eof:
457
+ start_pos = 0
458
+ data_len = len(data)
459
+ self._payload_parser = None
460
+ continue
461
+ else:
462
+ break
463
+
464
+ if data and start_pos < data_len:
465
+ data = data[start_pos:]
466
+ else:
467
+ data = EMPTY
468
+
469
+ return messages, self._upgraded, data
470
+
471
+ def parse_headers(
472
+ self, lines: List[bytes]
473
+ ) -> Tuple[
474
+ "CIMultiDictProxy[str]", RawHeaders, Optional[bool], Optional[str], bool, bool
475
+ ]:
476
+ """Parses RFC 5322 headers from a stream.
477
+
478
+ Line continuations are supported. Returns list of header name
479
+ and value pairs. Header name is in upper case.
480
+ """
481
+ headers, raw_headers = self._headers_parser.parse_headers(lines)
482
+ close_conn = None
483
+ encoding = None
484
+ upgrade = False
485
+ chunked = False
486
+
487
+ # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-6
488
+ # https://www.rfc-editor.org/rfc/rfc9110.html#name-collected-abnf
489
+ singletons = (
490
+ hdrs.CONTENT_LENGTH,
491
+ hdrs.CONTENT_LOCATION,
492
+ hdrs.CONTENT_RANGE,
493
+ hdrs.CONTENT_TYPE,
494
+ hdrs.ETAG,
495
+ hdrs.HOST,
496
+ hdrs.MAX_FORWARDS,
497
+ hdrs.SERVER,
498
+ hdrs.TRANSFER_ENCODING,
499
+ hdrs.USER_AGENT,
500
+ )
501
+ bad_hdr = next((h for h in singletons if len(headers.getall(h, ())) > 1), None)
502
+ if bad_hdr is not None:
503
+ raise BadHttpMessage(f"Duplicate '{bad_hdr}' header found.")
504
+
505
+ # keep-alive
506
+ conn = headers.get(hdrs.CONNECTION)
507
+ if conn:
508
+ v = conn.lower()
509
+ if v == "close":
510
+ close_conn = True
511
+ elif v == "keep-alive":
512
+ close_conn = False
513
+ # https://www.rfc-editor.org/rfc/rfc9110.html#name-101-switching-protocols
514
+ elif v == "upgrade" and headers.get(hdrs.UPGRADE):
515
+ upgrade = True
516
+
517
+ # encoding
518
+ enc = headers.get(hdrs.CONTENT_ENCODING)
519
+ if enc:
520
+ enc = enc.lower()
521
+ if enc in ("gzip", "deflate", "br"):
522
+ encoding = enc
523
+
524
+ # chunking
525
+ te = headers.get(hdrs.TRANSFER_ENCODING)
526
+ if te is not None:
527
+ if "chunked" == te.lower():
528
+ chunked = True
529
+ else:
530
+ raise BadHttpMessage("Request has invalid `Transfer-Encoding`")
531
+
532
+ if hdrs.CONTENT_LENGTH in headers:
533
+ raise BadHttpMessage(
534
+ "Transfer-Encoding can't be present with Content-Length",
535
+ )
536
+
537
+ return (headers, raw_headers, close_conn, encoding, upgrade, chunked)
538
+
539
+ def set_upgraded(self, val: bool) -> None:
540
+ """Set connection upgraded (to websocket) mode.
541
+
542
+ :param bool val: new state.
543
+ """
544
+ self._upgraded = val
545
+
546
+
547
+ class HttpRequestParser(HttpParser[RawRequestMessage]):
548
+ """Read request status line.
549
+
550
+ Exception .http_exceptions.BadStatusLine
551
+ could be raised in case of any errors in status line.
552
+ Returns RawRequestMessage.
553
+ """
554
+
555
+ def parse_message(self, lines: List[bytes]) -> RawRequestMessage:
556
+ # request line
557
+ line = lines[0].decode("utf-8", "surrogateescape")
558
+ try:
559
+ method, path, version = line.split(" ", maxsplit=2)
560
+ except ValueError:
561
+ raise BadStatusLine(line) from None
562
+
563
+ if len(path) > self.max_line_size:
564
+ raise LineTooLong(
565
+ "Status line is too long", str(self.max_line_size), str(len(path))
566
+ )
567
+
568
+ # method
569
+ if not METHRE.fullmatch(method):
570
+ raise BadStatusLine(method)
571
+
572
+ # version
573
+ match = VERSRE.fullmatch(version)
574
+ if match is None:
575
+ raise BadStatusLine(line)
576
+ version_o = HttpVersion(int(match.group(1)), int(match.group(2)))
577
+
578
+ if method == "CONNECT":
579
+ # authority-form,
580
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
581
+ url = URL.build(authority=path, encoded=True)
582
+ elif path.startswith("/"):
583
+ # origin-form,
584
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
585
+ path_part, _hash_separator, url_fragment = path.partition("#")
586
+ path_part, _question_mark_separator, qs_part = path_part.partition("?")
587
+
588
+ # NOTE: `yarl.URL.build()` is used to mimic what the Cython-based
589
+ # NOTE: parser does, otherwise it results into the same
590
+ # NOTE: HTTP Request-Line input producing different
591
+ # NOTE: `yarl.URL()` objects
592
+ url = URL.build(
593
+ path=path_part,
594
+ query_string=qs_part,
595
+ fragment=url_fragment,
596
+ encoded=True,
597
+ )
598
+ elif path == "*" and method == "OPTIONS":
599
+ # asterisk-form,
600
+ url = URL(path, encoded=True)
601
+ else:
602
+ # absolute-form for proxy maybe,
603
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
604
+ url = URL(path, encoded=True)
605
+ if url.scheme == "":
606
+ # not absolute-form
607
+ raise InvalidURLError(
608
+ path.encode(errors="surrogateescape").decode("latin1")
609
+ )
610
+
611
+ # read headers
612
+ (
613
+ headers,
614
+ raw_headers,
615
+ close,
616
+ compression,
617
+ upgrade,
618
+ chunked,
619
+ ) = self.parse_headers(lines)
620
+
621
+ if close is None: # then the headers weren't set in the request
622
+ if version_o <= HttpVersion10: # HTTP 1.0 must asks to not close
623
+ close = True
624
+ else: # HTTP 1.1 must ask to close.
625
+ close = False
626
+
627
+ return RawRequestMessage(
628
+ method,
629
+ path,
630
+ version_o,
631
+ headers,
632
+ raw_headers,
633
+ close,
634
+ compression,
635
+ upgrade,
636
+ chunked,
637
+ url,
638
+ )
639
+
640
+
641
+ class HttpResponseParser(HttpParser[RawResponseMessage]):
642
+ """Read response status line and headers.
643
+
644
+ BadStatusLine could be raised in case of any errors in status line.
645
+ Returns RawResponseMessage.
646
+ """
647
+
648
+ # Lax mode should only be enabled on response parser.
649
+ lax = not DEBUG
650
+
651
+ def feed_data(
652
+ self,
653
+ data: bytes,
654
+ SEP: Optional[_SEP] = None,
655
+ *args: Any,
656
+ **kwargs: Any,
657
+ ) -> Tuple[List[Tuple[RawResponseMessage, StreamReader]], bool, bytes]:
658
+ if SEP is None:
659
+ SEP = b"\r\n" if DEBUG else b"\n"
660
+ return super().feed_data(data, SEP, *args, **kwargs)
661
+
662
+ def parse_message(self, lines: List[bytes]) -> RawResponseMessage:
663
+ line = lines[0].decode("utf-8", "surrogateescape")
664
+ try:
665
+ version, status = line.split(maxsplit=1)
666
+ except ValueError:
667
+ raise BadStatusLine(line) from None
668
+
669
+ try:
670
+ status, reason = status.split(maxsplit=1)
671
+ except ValueError:
672
+ status = status.strip()
673
+ reason = ""
674
+
675
+ if len(reason) > self.max_line_size:
676
+ raise LineTooLong(
677
+ "Status line is too long", str(self.max_line_size), str(len(reason))
678
+ )
679
+
680
+ # version
681
+ match = VERSRE.fullmatch(version)
682
+ if match is None:
683
+ raise BadStatusLine(line)
684
+ version_o = HttpVersion(int(match.group(1)), int(match.group(2)))
685
+
686
+ # The status code is a three-digit number
687
+ if len(status) != 3 or not status.isdecimal():
688
+ raise BadStatusLine(line)
689
+ status_i = int(status)
690
+
691
+ # read headers
692
+ (
693
+ headers,
694
+ raw_headers,
695
+ close,
696
+ compression,
697
+ upgrade,
698
+ chunked,
699
+ ) = self.parse_headers(lines)
700
+
701
+ if close is None:
702
+ close = version_o <= HttpVersion10
703
+
704
+ return RawResponseMessage(
705
+ version_o,
706
+ status_i,
707
+ reason.strip(),
708
+ headers,
709
+ raw_headers,
710
+ close,
711
+ compression,
712
+ upgrade,
713
+ chunked,
714
+ )
715
+
716
+
717
+ class HttpPayloadParser:
718
+ def __init__(
719
+ self,
720
+ payload: StreamReader,
721
+ length: Optional[int] = None,
722
+ chunked: bool = False,
723
+ compression: Optional[str] = None,
724
+ code: Optional[int] = None,
725
+ method: Optional[str] = None,
726
+ readall: bool = False,
727
+ response_with_body: bool = True,
728
+ auto_decompress: bool = True,
729
+ lax: bool = False,
730
+ ) -> None:
731
+ self._length = 0
732
+ self._type = ParseState.PARSE_NONE
733
+ self._chunk = ChunkState.PARSE_CHUNKED_SIZE
734
+ self._chunk_size = 0
735
+ self._chunk_tail = b""
736
+ self._auto_decompress = auto_decompress
737
+ self._lax = lax
738
+ self.done = False
739
+
740
+ # payload decompression wrapper
741
+ if response_with_body and compression and self._auto_decompress:
742
+ real_payload: Union[StreamReader, DeflateBuffer] = DeflateBuffer(
743
+ payload, compression
744
+ )
745
+ else:
746
+ real_payload = payload
747
+
748
+ # payload parser
749
+ if not response_with_body:
750
+ # don't parse payload if it's not expected to be received
751
+ self._type = ParseState.PARSE_NONE
752
+ real_payload.feed_eof()
753
+ self.done = True
754
+
755
+ elif chunked:
756
+ self._type = ParseState.PARSE_CHUNKED
757
+ elif length is not None:
758
+ self._type = ParseState.PARSE_LENGTH
759
+ self._length = length
760
+ if self._length == 0:
761
+ real_payload.feed_eof()
762
+ self.done = True
763
+ else:
764
+ if readall and code != 204:
765
+ self._type = ParseState.PARSE_UNTIL_EOF
766
+ elif method in ("PUT", "POST"):
767
+ internal_logger.warning( # pragma: no cover
768
+ "Content-Length or Transfer-Encoding header is required"
769
+ )
770
+ self._type = ParseState.PARSE_NONE
771
+ real_payload.feed_eof()
772
+ self.done = True
773
+
774
+ self.payload = real_payload
775
+
776
+ def feed_eof(self) -> None:
777
+ if self._type == ParseState.PARSE_UNTIL_EOF:
778
+ self.payload.feed_eof()
779
+ elif self._type == ParseState.PARSE_LENGTH:
780
+ raise ContentLengthError(
781
+ "Not enough data for satisfy content length header."
782
+ )
783
+ elif self._type == ParseState.PARSE_CHUNKED:
784
+ raise TransferEncodingError(
785
+ "Not enough data for satisfy transfer length header."
786
+ )
787
+
788
+ def feed_data(
789
+ self, chunk: bytes, SEP: _SEP = b"\r\n", CHUNK_EXT: bytes = b";"
790
+ ) -> Tuple[bool, bytes]:
791
+ # Read specified amount of bytes
792
+ if self._type == ParseState.PARSE_LENGTH:
793
+ required = self._length
794
+ chunk_len = len(chunk)
795
+
796
+ if required >= chunk_len:
797
+ self._length = required - chunk_len
798
+ self.payload.feed_data(chunk, chunk_len)
799
+ if self._length == 0:
800
+ self.payload.feed_eof()
801
+ return True, b""
802
+ else:
803
+ self._length = 0
804
+ self.payload.feed_data(chunk[:required], required)
805
+ self.payload.feed_eof()
806
+ return True, chunk[required:]
807
+
808
+ # Chunked transfer encoding parser
809
+ elif self._type == ParseState.PARSE_CHUNKED:
810
+ if self._chunk_tail:
811
+ chunk = self._chunk_tail + chunk
812
+ self._chunk_tail = b""
813
+
814
+ while chunk:
815
+
816
+ # read next chunk size
817
+ if self._chunk == ChunkState.PARSE_CHUNKED_SIZE:
818
+ pos = chunk.find(SEP)
819
+ if pos >= 0:
820
+ i = chunk.find(CHUNK_EXT, 0, pos)
821
+ if i >= 0:
822
+ size_b = chunk[:i] # strip chunk-extensions
823
+ else:
824
+ size_b = chunk[:pos]
825
+
826
+ if self._lax: # Allow whitespace in lax mode.
827
+ size_b = size_b.strip()
828
+
829
+ if not re.fullmatch(HEXDIGIT, size_b):
830
+ exc = TransferEncodingError(
831
+ chunk[:pos].decode("ascii", "surrogateescape")
832
+ )
833
+ self.payload.set_exception(exc)
834
+ raise exc
835
+ size = int(bytes(size_b), 16)
836
+
837
+ chunk = chunk[pos + len(SEP) :]
838
+ if size == 0: # eof marker
839
+ self._chunk = ChunkState.PARSE_MAYBE_TRAILERS
840
+ if self._lax and chunk.startswith(b"\r"):
841
+ chunk = chunk[1:]
842
+ else:
843
+ self._chunk = ChunkState.PARSE_CHUNKED_CHUNK
844
+ self._chunk_size = size
845
+ self.payload.begin_http_chunk_receiving()
846
+ else:
847
+ self._chunk_tail = chunk
848
+ return False, b""
849
+
850
+ # read chunk and feed buffer
851
+ if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK:
852
+ required = self._chunk_size
853
+ chunk_len = len(chunk)
854
+
855
+ if required > chunk_len:
856
+ self._chunk_size = required - chunk_len
857
+ self.payload.feed_data(chunk, chunk_len)
858
+ return False, b""
859
+ else:
860
+ self._chunk_size = 0
861
+ self.payload.feed_data(chunk[:required], required)
862
+ chunk = chunk[required:]
863
+ if self._lax and chunk.startswith(b"\r"):
864
+ chunk = chunk[1:]
865
+ self._chunk = ChunkState.PARSE_CHUNKED_CHUNK_EOF
866
+ self.payload.end_http_chunk_receiving()
867
+
868
+ # toss the CRLF at the end of the chunk
869
+ if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK_EOF:
870
+ if chunk[: len(SEP)] == SEP:
871
+ chunk = chunk[len(SEP) :]
872
+ self._chunk = ChunkState.PARSE_CHUNKED_SIZE
873
+ else:
874
+ self._chunk_tail = chunk
875
+ return False, b""
876
+
877
+ # if stream does not contain trailer, after 0\r\n
878
+ # we should get another \r\n otherwise
879
+ # trailers needs to be skipped until \r\n\r\n
880
+ if self._chunk == ChunkState.PARSE_MAYBE_TRAILERS:
881
+ head = chunk[: len(SEP)]
882
+ if head == SEP:
883
+ # end of stream
884
+ self.payload.feed_eof()
885
+ return True, chunk[len(SEP) :]
886
+ # Both CR and LF, or only LF may not be received yet. It is
887
+ # expected that CRLF or LF will be shown at the very first
888
+ # byte next time, otherwise trailers should come. The last
889
+ # CRLF which marks the end of response might not be
890
+ # contained in the same TCP segment which delivered the
891
+ # size indicator.
892
+ if not head:
893
+ return False, b""
894
+ if head == SEP[:1]:
895
+ self._chunk_tail = head
896
+ return False, b""
897
+ self._chunk = ChunkState.PARSE_TRAILERS
898
+
899
+ # read and discard trailer up to the CRLF terminator
900
+ if self._chunk == ChunkState.PARSE_TRAILERS:
901
+ pos = chunk.find(SEP)
902
+ if pos >= 0:
903
+ chunk = chunk[pos + len(SEP) :]
904
+ self._chunk = ChunkState.PARSE_MAYBE_TRAILERS
905
+ else:
906
+ self._chunk_tail = chunk
907
+ return False, b""
908
+
909
+ # Read all bytes until eof
910
+ elif self._type == ParseState.PARSE_UNTIL_EOF:
911
+ self.payload.feed_data(chunk, len(chunk))
912
+
913
+ return False, b""
914
+
915
+
916
+ class DeflateBuffer:
917
+ """DeflateStream decompress stream and feed data into specified stream."""
918
+
919
+ decompressor: Any
920
+
921
+ def __init__(self, out: StreamReader, encoding: Optional[str]) -> None:
922
+ self.out = out
923
+ self.size = 0
924
+ self.encoding = encoding
925
+ self._started_decoding = False
926
+
927
+ self.decompressor: Union[BrotliDecompressor, ZLibDecompressor]
928
+ if encoding == "br":
929
+ if not HAS_BROTLI: # pragma: no cover
930
+ raise ContentEncodingError(
931
+ "Can not decode content-encoding: brotli (br). "
932
+ "Please install `Brotli`"
933
+ )
934
+ self.decompressor = BrotliDecompressor()
935
+ else:
936
+ self.decompressor = ZLibDecompressor(encoding=encoding)
937
+
938
+ def set_exception(self, exc: BaseException) -> None:
939
+ self.out.set_exception(exc)
940
+
941
+ def feed_data(self, chunk: bytes, size: int) -> None:
942
+ if not size:
943
+ return
944
+
945
+ self.size += size
946
+
947
+ # RFC1950
948
+ # bits 0..3 = CM = 0b1000 = 8 = "deflate"
949
+ # bits 4..7 = CINFO = 1..7 = windows size.
950
+ if (
951
+ not self._started_decoding
952
+ and self.encoding == "deflate"
953
+ and chunk[0] & 0xF != 8
954
+ ):
955
+ # Change the decoder to decompress incorrectly compressed data
956
+ # Actually we should issue a warning about non-RFC-compliant data.
957
+ self.decompressor = ZLibDecompressor(
958
+ encoding=self.encoding, suppress_deflate_header=True
959
+ )
960
+
961
+ try:
962
+ chunk = self.decompressor.decompress_sync(chunk)
963
+ except Exception:
964
+ raise ContentEncodingError(
965
+ "Can not decode content-encoding: %s" % self.encoding
966
+ )
967
+
968
+ self._started_decoding = True
969
+
970
+ if chunk:
971
+ self.out.feed_data(chunk, len(chunk))
972
+
973
+ def feed_eof(self) -> None:
974
+ chunk = self.decompressor.flush()
975
+
976
+ if chunk or self.size > 0:
977
+ self.out.feed_data(chunk, len(chunk))
978
+ if self.encoding == "deflate" and not self.decompressor.eof:
979
+ raise ContentEncodingError("deflate")
980
+
981
+ self.out.feed_eof()
982
+
983
+ def begin_http_chunk_receiving(self) -> None:
984
+ self.out.begin_http_chunk_receiving()
985
+
986
+ def end_http_chunk_receiving(self) -> None:
987
+ self.out.end_http_chunk_receiving()
988
+
989
+
990
+ HttpRequestParserPy = HttpRequestParser
991
+ HttpResponseParserPy = HttpResponseParser
992
+ RawRequestMessagePy = RawRequestMessage
993
+ RawResponseMessagePy = RawResponseMessage
994
+
995
+ try:
996
+ if not NO_EXTENSIONS:
997
+ from ._http_parser import ( # type: ignore[import-not-found,no-redef]
998
+ HttpRequestParser,
999
+ HttpResponseParser,
1000
+ RawRequestMessage,
1001
+ RawResponseMessage,
1002
+ )
1003
+
1004
+ HttpRequestParserC = HttpRequestParser
1005
+ HttpResponseParserC = HttpResponseParser
1006
+ RawRequestMessageC = RawRequestMessage
1007
+ RawResponseMessageC = RawResponseMessage
1008
+ except ImportError: # pragma: no cover
1009
+ pass
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_websocket.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebSocket protocol versions 13 and 8."""
2
+
3
+ import asyncio
4
+ import functools
5
+ import json
6
+ import random
7
+ import re
8
+ import sys
9
+ import zlib
10
+ from enum import IntEnum
11
+ from struct import Struct
12
+ from typing import (
13
+ Any,
14
+ Callable,
15
+ Final,
16
+ List,
17
+ NamedTuple,
18
+ Optional,
19
+ Pattern,
20
+ Set,
21
+ Tuple,
22
+ Union,
23
+ cast,
24
+ )
25
+
26
+ from .base_protocol import BaseProtocol
27
+ from .compression_utils import ZLibCompressor, ZLibDecompressor
28
+ from .helpers import NO_EXTENSIONS
29
+ from .streams import DataQueue
30
+
31
+ __all__ = (
32
+ "WS_CLOSED_MESSAGE",
33
+ "WS_CLOSING_MESSAGE",
34
+ "WS_KEY",
35
+ "WebSocketReader",
36
+ "WebSocketWriter",
37
+ "WSMessage",
38
+ "WebSocketError",
39
+ "WSMsgType",
40
+ "WSCloseCode",
41
+ )
42
+
43
+
44
+ class WSCloseCode(IntEnum):
45
+ OK = 1000
46
+ GOING_AWAY = 1001
47
+ PROTOCOL_ERROR = 1002
48
+ UNSUPPORTED_DATA = 1003
49
+ ABNORMAL_CLOSURE = 1006
50
+ INVALID_TEXT = 1007
51
+ POLICY_VIOLATION = 1008
52
+ MESSAGE_TOO_BIG = 1009
53
+ MANDATORY_EXTENSION = 1010
54
+ INTERNAL_ERROR = 1011
55
+ SERVICE_RESTART = 1012
56
+ TRY_AGAIN_LATER = 1013
57
+ BAD_GATEWAY = 1014
58
+
59
+
60
+ ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode}
61
+
62
+ # For websockets, keeping latency low is extremely important as implementations
63
+ # generally expect to be able to send and receive messages quickly. We use a
64
+ # larger chunk size than the default to reduce the number of executor calls
65
+ # since the executor is a significant source of latency and overhead when
66
+ # the chunks are small. A size of 5KiB was chosen because it is also the
67
+ # same value python-zlib-ng choose to use as the threshold to release the GIL.
68
+
69
+ WEBSOCKET_MAX_SYNC_CHUNK_SIZE = 5 * 1024
70
+
71
+
72
+ class WSMsgType(IntEnum):
73
+ # websocket spec types
74
+ CONTINUATION = 0x0
75
+ TEXT = 0x1
76
+ BINARY = 0x2
77
+ PING = 0x9
78
+ PONG = 0xA
79
+ CLOSE = 0x8
80
+
81
+ # aiohttp specific types
82
+ CLOSING = 0x100
83
+ CLOSED = 0x101
84
+ ERROR = 0x102
85
+
86
+ text = TEXT
87
+ binary = BINARY
88
+ ping = PING
89
+ pong = PONG
90
+ close = CLOSE
91
+ closing = CLOSING
92
+ closed = CLOSED
93
+ error = ERROR
94
+
95
+
96
+ WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
97
+
98
+
99
+ UNPACK_LEN2 = Struct("!H").unpack_from
100
+ UNPACK_LEN3 = Struct("!Q").unpack_from
101
+ UNPACK_CLOSE_CODE = Struct("!H").unpack
102
+ PACK_LEN1 = Struct("!BB").pack
103
+ PACK_LEN2 = Struct("!BBH").pack
104
+ PACK_LEN3 = Struct("!BBQ").pack
105
+ PACK_CLOSE_CODE = Struct("!H").pack
106
+ MSG_SIZE: Final[int] = 2**14
107
+ DEFAULT_LIMIT: Final[int] = 2**16
108
+
109
+
110
+ class WSMessage(NamedTuple):
111
+ type: WSMsgType
112
+ # To type correctly, this would need some kind of tagged union for each type.
113
+ data: Any
114
+ extra: Optional[str]
115
+
116
+ def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any:
117
+ """Return parsed JSON data.
118
+
119
+ .. versionadded:: 0.22
120
+ """
121
+ return loads(self.data)
122
+
123
+
124
+ WS_CLOSED_MESSAGE = WSMessage(WSMsgType.CLOSED, None, None)
125
+ WS_CLOSING_MESSAGE = WSMessage(WSMsgType.CLOSING, None, None)
126
+
127
+
128
+ class WebSocketError(Exception):
129
+ """WebSocket protocol parser error."""
130
+
131
+ def __init__(self, code: int, message: str) -> None:
132
+ self.code = code
133
+ super().__init__(code, message)
134
+
135
+ def __str__(self) -> str:
136
+ return cast(str, self.args[1])
137
+
138
+
139
+ class WSHandshakeError(Exception):
140
+ """WebSocket protocol handshake error."""
141
+
142
+
143
+ native_byteorder: Final[str] = sys.byteorder
144
+
145
+
146
+ # Used by _websocket_mask_python
147
+ @functools.lru_cache
148
+ def _xor_table() -> List[bytes]:
149
+ return [bytes(a ^ b for a in range(256)) for b in range(256)]
150
+
151
+
152
+ def _websocket_mask_python(mask: bytes, data: bytearray) -> None:
153
+ """Websocket masking function.
154
+
155
+ `mask` is a `bytes` object of length 4; `data` is a `bytearray`
156
+ object of any length. The contents of `data` are masked with `mask`,
157
+ as specified in section 5.3 of RFC 6455.
158
+
159
+ Note that this function mutates the `data` argument.
160
+
161
+ This pure-python implementation may be replaced by an optimized
162
+ version when available.
163
+
164
+ """
165
+ assert isinstance(data, bytearray), data
166
+ assert len(mask) == 4, mask
167
+
168
+ if data:
169
+ _XOR_TABLE = _xor_table()
170
+ a, b, c, d = (_XOR_TABLE[n] for n in mask)
171
+ data[::4] = data[::4].translate(a)
172
+ data[1::4] = data[1::4].translate(b)
173
+ data[2::4] = data[2::4].translate(c)
174
+ data[3::4] = data[3::4].translate(d)
175
+
176
+
177
+ if NO_EXTENSIONS: # pragma: no cover
178
+ _websocket_mask = _websocket_mask_python
179
+ else:
180
+ try:
181
+ from ._websocket import _websocket_mask_cython # type: ignore[import-not-found]
182
+
183
+ _websocket_mask = _websocket_mask_cython
184
+ except ImportError: # pragma: no cover
185
+ _websocket_mask = _websocket_mask_python
186
+
187
+ _WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF])
188
+
189
+
190
+ _WS_EXT_RE: Final[Pattern[str]] = re.compile(
191
+ r"^(?:;\s*(?:"
192
+ r"(server_no_context_takeover)|"
193
+ r"(client_no_context_takeover)|"
194
+ r"(server_max_window_bits(?:=(\d+))?)|"
195
+ r"(client_max_window_bits(?:=(\d+))?)))*$"
196
+ )
197
+
198
+ _WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?")
199
+
200
+
201
+ def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]:
202
+ if not extstr:
203
+ return 0, False
204
+
205
+ compress = 0
206
+ notakeover = False
207
+ for ext in _WS_EXT_RE_SPLIT.finditer(extstr):
208
+ defext = ext.group(1)
209
+ # Return compress = 15 when get `permessage-deflate`
210
+ if not defext:
211
+ compress = 15
212
+ break
213
+ match = _WS_EXT_RE.match(defext)
214
+ if match:
215
+ compress = 15
216
+ if isserver:
217
+ # Server never fail to detect compress handshake.
218
+ # Server does not need to send max wbit to client
219
+ if match.group(4):
220
+ compress = int(match.group(4))
221
+ # Group3 must match if group4 matches
222
+ # Compress wbit 8 does not support in zlib
223
+ # If compress level not support,
224
+ # CONTINUE to next extension
225
+ if compress > 15 or compress < 9:
226
+ compress = 0
227
+ continue
228
+ if match.group(1):
229
+ notakeover = True
230
+ # Ignore regex group 5 & 6 for client_max_window_bits
231
+ break
232
+ else:
233
+ if match.group(6):
234
+ compress = int(match.group(6))
235
+ # Group5 must match if group6 matches
236
+ # Compress wbit 8 does not support in zlib
237
+ # If compress level not support,
238
+ # FAIL the parse progress
239
+ if compress > 15 or compress < 9:
240
+ raise WSHandshakeError("Invalid window size")
241
+ if match.group(2):
242
+ notakeover = True
243
+ # Ignore regex group 5 & 6 for client_max_window_bits
244
+ break
245
+ # Return Fail if client side and not match
246
+ elif not isserver:
247
+ raise WSHandshakeError("Extension for deflate not supported" + ext.group(1))
248
+
249
+ return compress, notakeover
250
+
251
+
252
+ def ws_ext_gen(
253
+ compress: int = 15, isserver: bool = False, server_notakeover: bool = False
254
+ ) -> str:
255
+ # client_notakeover=False not used for server
256
+ # compress wbit 8 does not support in zlib
257
+ if compress < 9 or compress > 15:
258
+ raise ValueError(
259
+ "Compress wbits must between 9 and 15, " "zlib does not support wbits=8"
260
+ )
261
+ enabledext = ["permessage-deflate"]
262
+ if not isserver:
263
+ enabledext.append("client_max_window_bits")
264
+
265
+ if compress < 15:
266
+ enabledext.append("server_max_window_bits=" + str(compress))
267
+ if server_notakeover:
268
+ enabledext.append("server_no_context_takeover")
269
+ # if client_notakeover:
270
+ # enabledext.append('client_no_context_takeover')
271
+ return "; ".join(enabledext)
272
+
273
+
274
+ class WSParserState(IntEnum):
275
+ READ_HEADER = 1
276
+ READ_PAYLOAD_LENGTH = 2
277
+ READ_PAYLOAD_MASK = 3
278
+ READ_PAYLOAD = 4
279
+
280
+
281
+ class WebSocketReader:
282
+ def __init__(
283
+ self, queue: DataQueue[WSMessage], max_msg_size: int, compress: bool = True
284
+ ) -> None:
285
+ self.queue = queue
286
+ self._max_msg_size = max_msg_size
287
+
288
+ self._exc: Optional[BaseException] = None
289
+ self._partial = bytearray()
290
+ self._state = WSParserState.READ_HEADER
291
+
292
+ self._opcode: Optional[int] = None
293
+ self._frame_fin = False
294
+ self._frame_opcode: Optional[int] = None
295
+ self._frame_payload = bytearray()
296
+
297
+ self._tail = b""
298
+ self._has_mask = False
299
+ self._frame_mask: Optional[bytes] = None
300
+ self._payload_length = 0
301
+ self._payload_length_flag = 0
302
+ self._compressed: Optional[bool] = None
303
+ self._decompressobj: Optional[ZLibDecompressor] = None
304
+ self._compress = compress
305
+
306
+ def feed_eof(self) -> None:
307
+ self.queue.feed_eof()
308
+
309
+ def feed_data(self, data: bytes) -> Tuple[bool, bytes]:
310
+ if self._exc:
311
+ return True, data
312
+
313
+ try:
314
+ return self._feed_data(data)
315
+ except Exception as exc:
316
+ self._exc = exc
317
+ self.queue.set_exception(exc)
318
+ return True, b""
319
+
320
+ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
321
+ for fin, opcode, payload, compressed in self.parse_frame(data):
322
+ if compressed and not self._decompressobj:
323
+ self._decompressobj = ZLibDecompressor(suppress_deflate_header=True)
324
+ if opcode == WSMsgType.CLOSE:
325
+ if len(payload) >= 2:
326
+ close_code = UNPACK_CLOSE_CODE(payload[:2])[0]
327
+ if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES:
328
+ raise WebSocketError(
329
+ WSCloseCode.PROTOCOL_ERROR,
330
+ f"Invalid close code: {close_code}",
331
+ )
332
+ try:
333
+ close_message = payload[2:].decode("utf-8")
334
+ except UnicodeDecodeError as exc:
335
+ raise WebSocketError(
336
+ WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message"
337
+ ) from exc
338
+ msg = WSMessage(WSMsgType.CLOSE, close_code, close_message)
339
+ elif payload:
340
+ raise WebSocketError(
341
+ WSCloseCode.PROTOCOL_ERROR,
342
+ f"Invalid close frame: {fin} {opcode} {payload!r}",
343
+ )
344
+ else:
345
+ msg = WSMessage(WSMsgType.CLOSE, 0, "")
346
+
347
+ self.queue.feed_data(msg, 0)
348
+
349
+ elif opcode == WSMsgType.PING:
350
+ self.queue.feed_data(
351
+ WSMessage(WSMsgType.PING, payload, ""), len(payload)
352
+ )
353
+
354
+ elif opcode == WSMsgType.PONG:
355
+ self.queue.feed_data(
356
+ WSMessage(WSMsgType.PONG, payload, ""), len(payload)
357
+ )
358
+
359
+ elif (
360
+ opcode not in (WSMsgType.TEXT, WSMsgType.BINARY)
361
+ and self._opcode is None
362
+ ):
363
+ raise WebSocketError(
364
+ WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}"
365
+ )
366
+ else:
367
+ # load text/binary
368
+ if not fin:
369
+ # got partial frame payload
370
+ if opcode != WSMsgType.CONTINUATION:
371
+ self._opcode = opcode
372
+ self._partial.extend(payload)
373
+ if self._max_msg_size and len(self._partial) >= self._max_msg_size:
374
+ raise WebSocketError(
375
+ WSCloseCode.MESSAGE_TOO_BIG,
376
+ "Message size {} exceeds limit {}".format(
377
+ len(self._partial), self._max_msg_size
378
+ ),
379
+ )
380
+ else:
381
+ # previous frame was non finished
382
+ # we should get continuation opcode
383
+ if self._partial:
384
+ if opcode != WSMsgType.CONTINUATION:
385
+ raise WebSocketError(
386
+ WSCloseCode.PROTOCOL_ERROR,
387
+ "The opcode in non-fin frame is expected "
388
+ "to be zero, got {!r}".format(opcode),
389
+ )
390
+
391
+ if opcode == WSMsgType.CONTINUATION:
392
+ assert self._opcode is not None
393
+ opcode = self._opcode
394
+ self._opcode = None
395
+
396
+ self._partial.extend(payload)
397
+ if self._max_msg_size and len(self._partial) >= self._max_msg_size:
398
+ raise WebSocketError(
399
+ WSCloseCode.MESSAGE_TOO_BIG,
400
+ "Message size {} exceeds limit {}".format(
401
+ len(self._partial), self._max_msg_size
402
+ ),
403
+ )
404
+
405
+ # Decompress process must to be done after all packets
406
+ # received.
407
+ if compressed:
408
+ assert self._decompressobj is not None
409
+ self._partial.extend(_WS_DEFLATE_TRAILING)
410
+ payload_merged = self._decompressobj.decompress_sync(
411
+ self._partial, self._max_msg_size
412
+ )
413
+ if self._decompressobj.unconsumed_tail:
414
+ left = len(self._decompressobj.unconsumed_tail)
415
+ raise WebSocketError(
416
+ WSCloseCode.MESSAGE_TOO_BIG,
417
+ "Decompressed message size {} exceeds limit {}".format(
418
+ self._max_msg_size + left, self._max_msg_size
419
+ ),
420
+ )
421
+ else:
422
+ payload_merged = bytes(self._partial)
423
+
424
+ self._partial.clear()
425
+
426
+ if opcode == WSMsgType.TEXT:
427
+ try:
428
+ text = payload_merged.decode("utf-8")
429
+ self.queue.feed_data(
430
+ WSMessage(WSMsgType.TEXT, text, ""), len(text)
431
+ )
432
+ except UnicodeDecodeError as exc:
433
+ raise WebSocketError(
434
+ WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message"
435
+ ) from exc
436
+ else:
437
+ self.queue.feed_data(
438
+ WSMessage(WSMsgType.BINARY, payload_merged, ""),
439
+ len(payload_merged),
440
+ )
441
+
442
+ return False, b""
443
+
444
+ def parse_frame(
445
+ self, buf: bytes
446
+ ) -> List[Tuple[bool, Optional[int], bytearray, Optional[bool]]]:
447
+ """Return the next frame from the socket."""
448
+ frames = []
449
+ if self._tail:
450
+ buf, self._tail = self._tail + buf, b""
451
+
452
+ start_pos = 0
453
+ buf_length = len(buf)
454
+
455
+ while True:
456
+ # read header
457
+ if self._state == WSParserState.READ_HEADER:
458
+ if buf_length - start_pos >= 2:
459
+ data = buf[start_pos : start_pos + 2]
460
+ start_pos += 2
461
+ first_byte, second_byte = data
462
+
463
+ fin = (first_byte >> 7) & 1
464
+ rsv1 = (first_byte >> 6) & 1
465
+ rsv2 = (first_byte >> 5) & 1
466
+ rsv3 = (first_byte >> 4) & 1
467
+ opcode = first_byte & 0xF
468
+
469
+ # frame-fin = %x0 ; more frames of this message follow
470
+ # / %x1 ; final frame of this message
471
+ # frame-rsv1 = %x0 ;
472
+ # 1 bit, MUST be 0 unless negotiated otherwise
473
+ # frame-rsv2 = %x0 ;
474
+ # 1 bit, MUST be 0 unless negotiated otherwise
475
+ # frame-rsv3 = %x0 ;
476
+ # 1 bit, MUST be 0 unless negotiated otherwise
477
+ #
478
+ # Remove rsv1 from this test for deflate development
479
+ if rsv2 or rsv3 or (rsv1 and not self._compress):
480
+ raise WebSocketError(
481
+ WSCloseCode.PROTOCOL_ERROR,
482
+ "Received frame with non-zero reserved bits",
483
+ )
484
+
485
+ if opcode > 0x7 and fin == 0:
486
+ raise WebSocketError(
487
+ WSCloseCode.PROTOCOL_ERROR,
488
+ "Received fragmented control frame",
489
+ )
490
+
491
+ has_mask = (second_byte >> 7) & 1
492
+ length = second_byte & 0x7F
493
+
494
+ # Control frames MUST have a payload
495
+ # length of 125 bytes or less
496
+ if opcode > 0x7 and length > 125:
497
+ raise WebSocketError(
498
+ WSCloseCode.PROTOCOL_ERROR,
499
+ "Control frame payload cannot be " "larger than 125 bytes",
500
+ )
501
+
502
+ # Set compress status if last package is FIN
503
+ # OR set compress status if this is first fragment
504
+ # Raise error if not first fragment with rsv1 = 0x1
505
+ if self._frame_fin or self._compressed is None:
506
+ self._compressed = True if rsv1 else False
507
+ elif rsv1:
508
+ raise WebSocketError(
509
+ WSCloseCode.PROTOCOL_ERROR,
510
+ "Received frame with non-zero reserved bits",
511
+ )
512
+
513
+ self._frame_fin = bool(fin)
514
+ self._frame_opcode = opcode
515
+ self._has_mask = bool(has_mask)
516
+ self._payload_length_flag = length
517
+ self._state = WSParserState.READ_PAYLOAD_LENGTH
518
+ else:
519
+ break
520
+
521
+ # read payload length
522
+ if self._state == WSParserState.READ_PAYLOAD_LENGTH:
523
+ length = self._payload_length_flag
524
+ if length == 126:
525
+ if buf_length - start_pos >= 2:
526
+ data = buf[start_pos : start_pos + 2]
527
+ start_pos += 2
528
+ length = UNPACK_LEN2(data)[0]
529
+ self._payload_length = length
530
+ self._state = (
531
+ WSParserState.READ_PAYLOAD_MASK
532
+ if self._has_mask
533
+ else WSParserState.READ_PAYLOAD
534
+ )
535
+ else:
536
+ break
537
+ elif length > 126:
538
+ if buf_length - start_pos >= 8:
539
+ data = buf[start_pos : start_pos + 8]
540
+ start_pos += 8
541
+ length = UNPACK_LEN3(data)[0]
542
+ self._payload_length = length
543
+ self._state = (
544
+ WSParserState.READ_PAYLOAD_MASK
545
+ if self._has_mask
546
+ else WSParserState.READ_PAYLOAD
547
+ )
548
+ else:
549
+ break
550
+ else:
551
+ self._payload_length = length
552
+ self._state = (
553
+ WSParserState.READ_PAYLOAD_MASK
554
+ if self._has_mask
555
+ else WSParserState.READ_PAYLOAD
556
+ )
557
+
558
+ # read payload mask
559
+ if self._state == WSParserState.READ_PAYLOAD_MASK:
560
+ if buf_length - start_pos >= 4:
561
+ self._frame_mask = buf[start_pos : start_pos + 4]
562
+ start_pos += 4
563
+ self._state = WSParserState.READ_PAYLOAD
564
+ else:
565
+ break
566
+
567
+ if self._state == WSParserState.READ_PAYLOAD:
568
+ length = self._payload_length
569
+ payload = self._frame_payload
570
+
571
+ chunk_len = buf_length - start_pos
572
+ if length >= chunk_len:
573
+ self._payload_length = length - chunk_len
574
+ payload.extend(buf[start_pos:])
575
+ start_pos = buf_length
576
+ else:
577
+ self._payload_length = 0
578
+ payload.extend(buf[start_pos : start_pos + length])
579
+ start_pos = start_pos + length
580
+
581
+ if self._payload_length == 0:
582
+ if self._has_mask:
583
+ assert self._frame_mask is not None
584
+ _websocket_mask(self._frame_mask, payload)
585
+
586
+ frames.append(
587
+ (self._frame_fin, self._frame_opcode, payload, self._compressed)
588
+ )
589
+
590
+ self._frame_payload = bytearray()
591
+ self._state = WSParserState.READ_HEADER
592
+ else:
593
+ break
594
+
595
+ self._tail = buf[start_pos:]
596
+
597
+ return frames
598
+
599
+
600
+ class WebSocketWriter:
601
+ def __init__(
602
+ self,
603
+ protocol: BaseProtocol,
604
+ transport: asyncio.Transport,
605
+ *,
606
+ use_mask: bool = False,
607
+ limit: int = DEFAULT_LIMIT,
608
+ random: Any = random.Random(),
609
+ compress: int = 0,
610
+ notakeover: bool = False,
611
+ ) -> None:
612
+ self.protocol = protocol
613
+ self.transport = transport
614
+ self.use_mask = use_mask
615
+ self.randrange = random.randrange
616
+ self.compress = compress
617
+ self.notakeover = notakeover
618
+ self._closing = False
619
+ self._limit = limit
620
+ self._output_size = 0
621
+ self._compressobj: Any = None # actually compressobj
622
+
623
+ async def _send_frame(
624
+ self, message: bytes, opcode: int, compress: Optional[int] = None
625
+ ) -> None:
626
+ """Send a frame over the websocket with message as its payload."""
627
+ if self._closing and not (opcode & WSMsgType.CLOSE):
628
+ raise ConnectionResetError("Cannot write to closing transport")
629
+
630
+ rsv = 0
631
+
632
+ # Only compress larger packets (disabled)
633
+ # Does small packet needs to be compressed?
634
+ # if self.compress and opcode < 8 and len(message) > 124:
635
+ if (compress or self.compress) and opcode < 8:
636
+ if compress:
637
+ # Do not set self._compress if compressing is for this frame
638
+ compressobj = self._make_compress_obj(compress)
639
+ else: # self.compress
640
+ if not self._compressobj:
641
+ self._compressobj = self._make_compress_obj(self.compress)
642
+ compressobj = self._compressobj
643
+
644
+ message = await compressobj.compress(message)
645
+ # Its critical that we do not return control to the event
646
+ # loop until we have finished sending all the compressed
647
+ # data. Otherwise we could end up mixing compressed frames
648
+ # if there are multiple coroutines compressing data.
649
+ message += compressobj.flush(
650
+ zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH
651
+ )
652
+ if message.endswith(_WS_DEFLATE_TRAILING):
653
+ message = message[:-4]
654
+ rsv = rsv | 0x40
655
+
656
+ msg_length = len(message)
657
+
658
+ use_mask = self.use_mask
659
+ if use_mask:
660
+ mask_bit = 0x80
661
+ else:
662
+ mask_bit = 0
663
+
664
+ if msg_length < 126:
665
+ header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit)
666
+ elif msg_length < (1 << 16):
667
+ header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length)
668
+ else:
669
+ header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length)
670
+ if use_mask:
671
+ mask = self.randrange(0, 0xFFFFFFFF)
672
+ mask = mask.to_bytes(4, "big")
673
+ message = bytearray(message)
674
+ _websocket_mask(mask, message)
675
+ self._write(header + mask + message)
676
+ self._output_size += len(header) + len(mask) + len(message)
677
+ else:
678
+ if len(message) > MSG_SIZE:
679
+ self._write(header)
680
+ self._write(message)
681
+ else:
682
+ self._write(header + message)
683
+
684
+ self._output_size += len(header) + len(message)
685
+
686
+ # It is safe to return control to the event loop when using compression
687
+ # after this point as we have already sent or buffered all the data.
688
+
689
+ if self._output_size > self._limit:
690
+ self._output_size = 0
691
+ await self.protocol._drain_helper()
692
+
693
+ def _make_compress_obj(self, compress: int) -> ZLibCompressor:
694
+ return ZLibCompressor(
695
+ level=zlib.Z_BEST_SPEED,
696
+ wbits=-compress,
697
+ max_sync_chunk_size=WEBSOCKET_MAX_SYNC_CHUNK_SIZE,
698
+ )
699
+
700
+ def _write(self, data: bytes) -> None:
701
+ if self.transport is None or self.transport.is_closing():
702
+ raise ConnectionResetError("Cannot write to closing transport")
703
+ self.transport.write(data)
704
+
705
+ async def pong(self, message: Union[bytes, str] = b"") -> None:
706
+ """Send pong message."""
707
+ if isinstance(message, str):
708
+ message = message.encode("utf-8")
709
+ await self._send_frame(message, WSMsgType.PONG)
710
+
711
+ async def ping(self, message: Union[bytes, str] = b"") -> None:
712
+ """Send ping message."""
713
+ if isinstance(message, str):
714
+ message = message.encode("utf-8")
715
+ await self._send_frame(message, WSMsgType.PING)
716
+
717
+ async def send(
718
+ self,
719
+ message: Union[str, bytes],
720
+ binary: bool = False,
721
+ compress: Optional[int] = None,
722
+ ) -> None:
723
+ """Send a frame over the websocket with message as its payload."""
724
+ if isinstance(message, str):
725
+ message = message.encode("utf-8")
726
+ if binary:
727
+ await self._send_frame(message, WSMsgType.BINARY, compress)
728
+ else:
729
+ await self._send_frame(message, WSMsgType.TEXT, compress)
730
+
731
+ async def close(self, code: int = 1000, message: Union[bytes, str] = b"") -> None:
732
+ """Close the websocket, sending the specified code and message."""
733
+ if isinstance(message, str):
734
+ message = message.encode("utf-8")
735
+ try:
736
+ await self._send_frame(
737
+ PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE
738
+ )
739
+ finally:
740
+ self._closing = True
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/http_writer.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Http related parsers and protocol."""
2
+
3
+ import asyncio
4
+ import zlib
5
+ from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
6
+
7
+ from multidict import CIMultiDict
8
+
9
+ from .abc import AbstractStreamWriter
10
+ from .base_protocol import BaseProtocol
11
+ from .compression_utils import ZLibCompressor
12
+ from .helpers import NO_EXTENSIONS
13
+
14
+ __all__ = ("StreamWriter", "HttpVersion", "HttpVersion10", "HttpVersion11")
15
+
16
+
17
+ class HttpVersion(NamedTuple):
18
+ major: int
19
+ minor: int
20
+
21
+
22
+ HttpVersion10 = HttpVersion(1, 0)
23
+ HttpVersion11 = HttpVersion(1, 1)
24
+
25
+
26
+ _T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]]
27
+ _T_OnHeadersSent = Optional[Callable[["CIMultiDict[str]"], Awaitable[None]]]
28
+
29
+
30
+ class StreamWriter(AbstractStreamWriter):
31
+ def __init__(
32
+ self,
33
+ protocol: BaseProtocol,
34
+ loop: asyncio.AbstractEventLoop,
35
+ on_chunk_sent: _T_OnChunkSent = None,
36
+ on_headers_sent: _T_OnHeadersSent = None,
37
+ ) -> None:
38
+ self._protocol = protocol
39
+
40
+ self.loop = loop
41
+ self.length = None
42
+ self.chunked = False
43
+ self.buffer_size = 0
44
+ self.output_size = 0
45
+
46
+ self._eof = False
47
+ self._compress: Optional[ZLibCompressor] = None
48
+ self._drain_waiter = None
49
+
50
+ self._on_chunk_sent: _T_OnChunkSent = on_chunk_sent
51
+ self._on_headers_sent: _T_OnHeadersSent = on_headers_sent
52
+
53
+ @property
54
+ def transport(self) -> Optional[asyncio.Transport]:
55
+ return self._protocol.transport
56
+
57
+ @property
58
+ def protocol(self) -> BaseProtocol:
59
+ return self._protocol
60
+
61
+ def enable_chunking(self) -> None:
62
+ self.chunked = True
63
+
64
+ def enable_compression(
65
+ self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY
66
+ ) -> None:
67
+ self._compress = ZLibCompressor(encoding=encoding, strategy=strategy)
68
+
69
+ def _write(self, chunk: bytes) -> None:
70
+ size = len(chunk)
71
+ self.buffer_size += size
72
+ self.output_size += size
73
+ transport = self.transport
74
+ if not self._protocol.connected or transport is None or transport.is_closing():
75
+ raise ConnectionResetError("Cannot write to closing transport")
76
+ transport.write(chunk)
77
+
78
+ async def write(
79
+ self, chunk: bytes, *, drain: bool = True, LIMIT: int = 0x10000
80
+ ) -> None:
81
+ """Writes chunk of data to a stream.
82
+
83
+ write_eof() indicates end of stream.
84
+ writer can't be used after write_eof() method being called.
85
+ write() return drain future.
86
+ """
87
+ if self._on_chunk_sent is not None:
88
+ await self._on_chunk_sent(chunk)
89
+
90
+ if isinstance(chunk, memoryview):
91
+ if chunk.nbytes != len(chunk):
92
+ # just reshape it
93
+ chunk = chunk.cast("c")
94
+
95
+ if self._compress is not None:
96
+ chunk = await self._compress.compress(chunk)
97
+ if not chunk:
98
+ return
99
+
100
+ if self.length is not None:
101
+ chunk_len = len(chunk)
102
+ if self.length >= chunk_len:
103
+ self.length = self.length - chunk_len
104
+ else:
105
+ chunk = chunk[: self.length]
106
+ self.length = 0
107
+ if not chunk:
108
+ return
109
+
110
+ if chunk:
111
+ if self.chunked:
112
+ chunk_len_pre = ("%x\r\n" % len(chunk)).encode("ascii")
113
+ chunk = chunk_len_pre + chunk + b"\r\n"
114
+
115
+ self._write(chunk)
116
+
117
+ if self.buffer_size > LIMIT and drain:
118
+ self.buffer_size = 0
119
+ await self.drain()
120
+
121
+ async def write_headers(
122
+ self, status_line: str, headers: "CIMultiDict[str]"
123
+ ) -> None:
124
+ """Write request/response status and headers."""
125
+ if self._on_headers_sent is not None:
126
+ await self._on_headers_sent(headers)
127
+
128
+ # status + headers
129
+ buf = _serialize_headers(status_line, headers)
130
+ self._write(buf)
131
+
132
+ async def write_eof(self, chunk: bytes = b"") -> None:
133
+ if self._eof:
134
+ return
135
+
136
+ if chunk and self._on_chunk_sent is not None:
137
+ await self._on_chunk_sent(chunk)
138
+
139
+ if self._compress:
140
+ if chunk:
141
+ chunk = await self._compress.compress(chunk)
142
+
143
+ chunk += self._compress.flush()
144
+ if chunk and self.chunked:
145
+ chunk_len = ("%x\r\n" % len(chunk)).encode("ascii")
146
+ chunk = chunk_len + chunk + b"\r\n0\r\n\r\n"
147
+ else:
148
+ if self.chunked:
149
+ if chunk:
150
+ chunk_len = ("%x\r\n" % len(chunk)).encode("ascii")
151
+ chunk = chunk_len + chunk + b"\r\n0\r\n\r\n"
152
+ else:
153
+ chunk = b"0\r\n\r\n"
154
+
155
+ if chunk:
156
+ self._write(chunk)
157
+
158
+ await self.drain()
159
+
160
+ self._eof = True
161
+
162
+ async def drain(self) -> None:
163
+ """Flush the write buffer.
164
+
165
+ The intended use is to write
166
+
167
+ await w.write(data)
168
+ await w.drain()
169
+ """
170
+ if self._protocol.transport is not None:
171
+ await self._protocol._drain_helper()
172
+
173
+
174
+ def _safe_header(string: str) -> str:
175
+ if "\r" in string or "\n" in string:
176
+ raise ValueError(
177
+ "Newline or carriage return detected in headers. "
178
+ "Potential header injection attack."
179
+ )
180
+ return string
181
+
182
+
183
+ def _py_serialize_headers(status_line: str, headers: "CIMultiDict[str]") -> bytes:
184
+ headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items())
185
+ line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n"
186
+ return line.encode("utf-8")
187
+
188
+
189
+ _serialize_headers = _py_serialize_headers
190
+
191
+ try:
192
+ import aiohttp._http_writer as _http_writer # type: ignore[import-not-found]
193
+
194
+ _c_serialize_headers = _http_writer._serialize_headers
195
+ if not NO_EXTENSIONS:
196
+ _serialize_headers = _c_serialize_headers
197
+ except ImportError:
198
+ pass
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/locks.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import collections
3
+ from typing import Any, Deque, Optional
4
+
5
+
6
+ class EventResultOrError:
7
+ """Event asyncio lock helper class.
8
+
9
+ Wraps the Event asyncio lock allowing either to awake the
10
+ locked Tasks without any error or raising an exception.
11
+
12
+ thanks to @vorpalsmith for the simple design.
13
+ """
14
+
15
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
16
+ self._loop = loop
17
+ self._exc: Optional[BaseException] = None
18
+ self._event = asyncio.Event()
19
+ self._waiters: Deque[asyncio.Future[Any]] = collections.deque()
20
+
21
+ def set(self, exc: Optional[BaseException] = None) -> None:
22
+ self._exc = exc
23
+ self._event.set()
24
+
25
+ async def wait(self) -> Any:
26
+ waiter = self._loop.create_task(self._event.wait())
27
+ self._waiters.append(waiter)
28
+ try:
29
+ val = await waiter
30
+ finally:
31
+ self._waiters.remove(waiter)
32
+
33
+ if self._exc is not None:
34
+ raise self._exc
35
+
36
+ return val
37
+
38
+ def cancel(self) -> None:
39
+ """Cancel all waiters"""
40
+ for waiter in self._waiters:
41
+ waiter.cancel()
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/log.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ access_logger = logging.getLogger("aiohttp.access")
4
+ client_logger = logging.getLogger("aiohttp.client")
5
+ internal_logger = logging.getLogger("aiohttp.internal")
6
+ server_logger = logging.getLogger("aiohttp.server")
7
+ web_logger = logging.getLogger("aiohttp.web")
8
+ ws_logger = logging.getLogger("aiohttp.websocket")
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/multipart.py ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import binascii
3
+ import json
4
+ import re
5
+ import uuid
6
+ import warnings
7
+ import zlib
8
+ from collections import deque
9
+ from types import TracebackType
10
+ from typing import (
11
+ TYPE_CHECKING,
12
+ Any,
13
+ AsyncIterator,
14
+ Deque,
15
+ Dict,
16
+ Iterator,
17
+ List,
18
+ Mapping,
19
+ Optional,
20
+ Sequence,
21
+ Tuple,
22
+ Type,
23
+ Union,
24
+ cast,
25
+ )
26
+ from urllib.parse import parse_qsl, unquote, urlencode
27
+
28
+ from multidict import CIMultiDict, CIMultiDictProxy, MultiMapping
29
+
30
+ from .compression_utils import ZLibCompressor, ZLibDecompressor
31
+ from .hdrs import (
32
+ CONTENT_DISPOSITION,
33
+ CONTENT_ENCODING,
34
+ CONTENT_LENGTH,
35
+ CONTENT_TRANSFER_ENCODING,
36
+ CONTENT_TYPE,
37
+ )
38
+ from .helpers import CHAR, TOKEN, parse_mimetype, reify
39
+ from .http import HeadersParser
40
+ from .payload import (
41
+ JsonPayload,
42
+ LookupError,
43
+ Order,
44
+ Payload,
45
+ StringPayload,
46
+ get_payload,
47
+ payload_type,
48
+ )
49
+ from .streams import StreamReader
50
+
51
+ __all__ = (
52
+ "MultipartReader",
53
+ "MultipartWriter",
54
+ "BodyPartReader",
55
+ "BadContentDispositionHeader",
56
+ "BadContentDispositionParam",
57
+ "parse_content_disposition",
58
+ "content_disposition_filename",
59
+ )
60
+
61
+
62
+ if TYPE_CHECKING: # pragma: no cover
63
+ from .client_reqrep import ClientResponse
64
+
65
+
66
+ class BadContentDispositionHeader(RuntimeWarning):
67
+ pass
68
+
69
+
70
+ class BadContentDispositionParam(RuntimeWarning):
71
+ pass
72
+
73
+
74
+ def parse_content_disposition(
75
+ header: Optional[str],
76
+ ) -> Tuple[Optional[str], Dict[str, str]]:
77
+ def is_token(string: str) -> bool:
78
+ return bool(string) and TOKEN >= set(string)
79
+
80
+ def is_quoted(string: str) -> bool:
81
+ return string[0] == string[-1] == '"'
82
+
83
+ def is_rfc5987(string: str) -> bool:
84
+ return is_token(string) and string.count("'") == 2
85
+
86
+ def is_extended_param(string: str) -> bool:
87
+ return string.endswith("*")
88
+
89
+ def is_continuous_param(string: str) -> bool:
90
+ pos = string.find("*") + 1
91
+ if not pos:
92
+ return False
93
+ substring = string[pos:-1] if string.endswith("*") else string[pos:]
94
+ return substring.isdigit()
95
+
96
+ def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str:
97
+ return re.sub(f"\\\\([{chars}])", "\\1", text)
98
+
99
+ if not header:
100
+ return None, {}
101
+
102
+ disptype, *parts = header.split(";")
103
+ if not is_token(disptype):
104
+ warnings.warn(BadContentDispositionHeader(header))
105
+ return None, {}
106
+
107
+ params: Dict[str, str] = {}
108
+ while parts:
109
+ item = parts.pop(0)
110
+
111
+ if "=" not in item:
112
+ warnings.warn(BadContentDispositionHeader(header))
113
+ return None, {}
114
+
115
+ key, value = item.split("=", 1)
116
+ key = key.lower().strip()
117
+ value = value.lstrip()
118
+
119
+ if key in params:
120
+ warnings.warn(BadContentDispositionHeader(header))
121
+ return None, {}
122
+
123
+ if not is_token(key):
124
+ warnings.warn(BadContentDispositionParam(item))
125
+ continue
126
+
127
+ elif is_continuous_param(key):
128
+ if is_quoted(value):
129
+ value = unescape(value[1:-1])
130
+ elif not is_token(value):
131
+ warnings.warn(BadContentDispositionParam(item))
132
+ continue
133
+
134
+ elif is_extended_param(key):
135
+ if is_rfc5987(value):
136
+ encoding, _, value = value.split("'", 2)
137
+ encoding = encoding or "utf-8"
138
+ else:
139
+ warnings.warn(BadContentDispositionParam(item))
140
+ continue
141
+
142
+ try:
143
+ value = unquote(value, encoding, "strict")
144
+ except UnicodeDecodeError: # pragma: nocover
145
+ warnings.warn(BadContentDispositionParam(item))
146
+ continue
147
+
148
+ else:
149
+ failed = True
150
+ if is_quoted(value):
151
+ failed = False
152
+ value = unescape(value[1:-1].lstrip("\\/"))
153
+ elif is_token(value):
154
+ failed = False
155
+ elif parts:
156
+ # maybe just ; in filename, in any case this is just
157
+ # one case fix, for proper fix we need to redesign parser
158
+ _value = f"{value};{parts[0]}"
159
+ if is_quoted(_value):
160
+ parts.pop(0)
161
+ value = unescape(_value[1:-1].lstrip("\\/"))
162
+ failed = False
163
+
164
+ if failed:
165
+ warnings.warn(BadContentDispositionHeader(header))
166
+ return None, {}
167
+
168
+ params[key] = value
169
+
170
+ return disptype.lower(), params
171
+
172
+
173
+ def content_disposition_filename(
174
+ params: Mapping[str, str], name: str = "filename"
175
+ ) -> Optional[str]:
176
+ name_suf = "%s*" % name
177
+ if not params:
178
+ return None
179
+ elif name_suf in params:
180
+ return params[name_suf]
181
+ elif name in params:
182
+ return params[name]
183
+ else:
184
+ parts = []
185
+ fnparams = sorted(
186
+ (key, value) for key, value in params.items() if key.startswith(name_suf)
187
+ )
188
+ for num, (key, value) in enumerate(fnparams):
189
+ _, tail = key.split("*", 1)
190
+ if tail.endswith("*"):
191
+ tail = tail[:-1]
192
+ if tail == str(num):
193
+ parts.append(value)
194
+ else:
195
+ break
196
+ if not parts:
197
+ return None
198
+ value = "".join(parts)
199
+ if "'" in value:
200
+ encoding, _, value = value.split("'", 2)
201
+ encoding = encoding or "utf-8"
202
+ return unquote(value, encoding, "strict")
203
+ return value
204
+
205
+
206
+ class MultipartResponseWrapper:
207
+ """Wrapper around the MultipartReader.
208
+
209
+ It takes care about
210
+ underlying connection and close it when it needs in.
211
+ """
212
+
213
+ def __init__(
214
+ self,
215
+ resp: "ClientResponse",
216
+ stream: "MultipartReader",
217
+ ) -> None:
218
+ self.resp = resp
219
+ self.stream = stream
220
+
221
+ def __aiter__(self) -> "MultipartResponseWrapper":
222
+ return self
223
+
224
+ async def __anext__(
225
+ self,
226
+ ) -> Union["MultipartReader", "BodyPartReader"]:
227
+ part = await self.next()
228
+ if part is None:
229
+ raise StopAsyncIteration
230
+ return part
231
+
232
+ def at_eof(self) -> bool:
233
+ """Returns True when all response data had been read."""
234
+ return self.resp.content.at_eof()
235
+
236
+ async def next(
237
+ self,
238
+ ) -> Optional[Union["MultipartReader", "BodyPartReader"]]:
239
+ """Emits next multipart reader object."""
240
+ item = await self.stream.next()
241
+ if self.stream.at_eof():
242
+ await self.release()
243
+ return item
244
+
245
+ async def release(self) -> None:
246
+ """Release the connection gracefully.
247
+
248
+ All remaining content is read to the void.
249
+ """
250
+ await self.resp.release()
251
+
252
+
253
+ class BodyPartReader:
254
+ """Multipart reader for single body part."""
255
+
256
+ chunk_size = 8192
257
+
258
+ def __init__(
259
+ self, boundary: bytes, headers: "CIMultiDictProxy[str]", content: StreamReader
260
+ ) -> None:
261
+ self.headers = headers
262
+ self._boundary = boundary
263
+ self._content = content
264
+ self._at_eof = False
265
+ length = self.headers.get(CONTENT_LENGTH, None)
266
+ self._length = int(length) if length is not None else None
267
+ self._read_bytes = 0
268
+ self._unread: Deque[bytes] = deque()
269
+ self._prev_chunk: Optional[bytes] = None
270
+ self._content_eof = 0
271
+ self._cache: Dict[str, Any] = {}
272
+
273
+ def __aiter__(self) -> AsyncIterator["BodyPartReader"]:
274
+ return self # type: ignore[return-value]
275
+
276
+ async def __anext__(self) -> bytes:
277
+ part = await self.next()
278
+ if part is None:
279
+ raise StopAsyncIteration
280
+ return part
281
+
282
+ async def next(self) -> Optional[bytes]:
283
+ item = await self.read()
284
+ if not item:
285
+ return None
286
+ return item
287
+
288
+ async def read(self, *, decode: bool = False) -> bytes:
289
+ """Reads body part data.
290
+
291
+ decode: Decodes data following by encoding
292
+ method from Content-Encoding header. If it missed
293
+ data remains untouched
294
+ """
295
+ if self._at_eof:
296
+ return b""
297
+ data = bytearray()
298
+ while not self._at_eof:
299
+ data.extend(await self.read_chunk(self.chunk_size))
300
+ if decode:
301
+ return self.decode(data)
302
+ return data
303
+
304
+ async def read_chunk(self, size: int = chunk_size) -> bytes:
305
+ """Reads body part content chunk of the specified size.
306
+
307
+ size: chunk size
308
+ """
309
+ if self._at_eof:
310
+ return b""
311
+ if self._length:
312
+ chunk = await self._read_chunk_from_length(size)
313
+ else:
314
+ chunk = await self._read_chunk_from_stream(size)
315
+
316
+ self._read_bytes += len(chunk)
317
+ if self._read_bytes == self._length:
318
+ self._at_eof = True
319
+ if self._at_eof:
320
+ clrf = await self._content.readline()
321
+ assert (
322
+ b"\r\n" == clrf
323
+ ), "reader did not read all the data or it is malformed"
324
+ return chunk
325
+
326
+ async def _read_chunk_from_length(self, size: int) -> bytes:
327
+ # Reads body part content chunk of the specified size.
328
+ # The body part must has Content-Length header with proper value.
329
+ assert self._length is not None, "Content-Length required for chunked read"
330
+ chunk_size = min(size, self._length - self._read_bytes)
331
+ chunk = await self._content.read(chunk_size)
332
+ return chunk
333
+
334
+ async def _read_chunk_from_stream(self, size: int) -> bytes:
335
+ # Reads content chunk of body part with unknown length.
336
+ # The Content-Length header for body part is not necessary.
337
+ assert (
338
+ size >= len(self._boundary) + 2
339
+ ), "Chunk size must be greater or equal than boundary length + 2"
340
+ first_chunk = self._prev_chunk is None
341
+ if first_chunk:
342
+ self._prev_chunk = await self._content.read(size)
343
+
344
+ chunk = await self._content.read(size)
345
+ self._content_eof += int(self._content.at_eof())
346
+ assert self._content_eof < 3, "Reading after EOF"
347
+ assert self._prev_chunk is not None
348
+ window = self._prev_chunk + chunk
349
+ sub = b"\r\n" + self._boundary
350
+ if first_chunk:
351
+ idx = window.find(sub)
352
+ else:
353
+ idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub)))
354
+ if idx >= 0:
355
+ # pushing boundary back to content
356
+ with warnings.catch_warnings():
357
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
358
+ self._content.unread_data(window[idx:])
359
+ if size > idx:
360
+ self._prev_chunk = self._prev_chunk[:idx]
361
+ chunk = window[len(self._prev_chunk) : idx]
362
+ if not chunk:
363
+ self._at_eof = True
364
+ result = self._prev_chunk
365
+ self._prev_chunk = chunk
366
+ return result
367
+
368
+ async def readline(self) -> bytes:
369
+ """Reads body part by line by line."""
370
+ if self._at_eof:
371
+ return b""
372
+
373
+ if self._unread:
374
+ line = self._unread.popleft()
375
+ else:
376
+ line = await self._content.readline()
377
+
378
+ if line.startswith(self._boundary):
379
+ # the very last boundary may not come with \r\n,
380
+ # so set single rules for everyone
381
+ sline = line.rstrip(b"\r\n")
382
+ boundary = self._boundary
383
+ last_boundary = self._boundary + b"--"
384
+ # ensure that we read exactly the boundary, not something alike
385
+ if sline == boundary or sline == last_boundary:
386
+ self._at_eof = True
387
+ self._unread.append(line)
388
+ return b""
389
+ else:
390
+ next_line = await self._content.readline()
391
+ if next_line.startswith(self._boundary):
392
+ line = line[:-2] # strip CRLF but only once
393
+ self._unread.append(next_line)
394
+
395
+ return line
396
+
397
+ async def release(self) -> None:
398
+ """Like read(), but reads all the data to the void."""
399
+ if self._at_eof:
400
+ return
401
+ while not self._at_eof:
402
+ await self.read_chunk(self.chunk_size)
403
+
404
+ async def text(self, *, encoding: Optional[str] = None) -> str:
405
+ """Like read(), but assumes that body part contains text data."""
406
+ data = await self.read(decode=True)
407
+ # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm
408
+ # and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-send
409
+ encoding = encoding or self.get_charset(default="utf-8")
410
+ return data.decode(encoding)
411
+
412
+ async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, Any]]:
413
+ """Like read(), but assumes that body parts contains JSON data."""
414
+ data = await self.read(decode=True)
415
+ if not data:
416
+ return None
417
+ encoding = encoding or self.get_charset(default="utf-8")
418
+ return cast(Dict[str, Any], json.loads(data.decode(encoding)))
419
+
420
+ async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]:
421
+ """Like read(), but assumes that body parts contain form urlencoded data."""
422
+ data = await self.read(decode=True)
423
+ if not data:
424
+ return []
425
+ if encoding is not None:
426
+ real_encoding = encoding
427
+ else:
428
+ real_encoding = self.get_charset(default="utf-8")
429
+ try:
430
+ decoded_data = data.rstrip().decode(real_encoding)
431
+ except UnicodeDecodeError:
432
+ raise ValueError("data cannot be decoded with %s encoding" % real_encoding)
433
+
434
+ return parse_qsl(
435
+ decoded_data,
436
+ keep_blank_values=True,
437
+ encoding=real_encoding,
438
+ )
439
+
440
+ def at_eof(self) -> bool:
441
+ """Returns True if the boundary was reached or False otherwise."""
442
+ return self._at_eof
443
+
444
+ def decode(self, data: bytes) -> bytes:
445
+ """Decodes data.
446
+
447
+ Decoding is done according the specified Content-Encoding
448
+ or Content-Transfer-Encoding headers value.
449
+ """
450
+ if CONTENT_TRANSFER_ENCODING in self.headers:
451
+ data = self._decode_content_transfer(data)
452
+ if CONTENT_ENCODING in self.headers:
453
+ return self._decode_content(data)
454
+ return data
455
+
456
+ def _decode_content(self, data: bytes) -> bytes:
457
+ encoding = self.headers.get(CONTENT_ENCODING, "").lower()
458
+ if encoding == "identity":
459
+ return data
460
+ if encoding in {"deflate", "gzip"}:
461
+ return ZLibDecompressor(
462
+ encoding=encoding,
463
+ suppress_deflate_header=True,
464
+ ).decompress_sync(data)
465
+
466
+ raise RuntimeError(f"unknown content encoding: {encoding}")
467
+
468
+ def _decode_content_transfer(self, data: bytes) -> bytes:
469
+ encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower()
470
+
471
+ if encoding == "base64":
472
+ return base64.b64decode(data)
473
+ elif encoding == "quoted-printable":
474
+ return binascii.a2b_qp(data)
475
+ elif encoding in ("binary", "8bit", "7bit"):
476
+ return data
477
+ else:
478
+ raise RuntimeError(
479
+ "unknown content transfer encoding: {}" "".format(encoding)
480
+ )
481
+
482
+ def get_charset(self, default: str) -> str:
483
+ """Returns charset parameter from Content-Type header or default."""
484
+ ctype = self.headers.get(CONTENT_TYPE, "")
485
+ mimetype = parse_mimetype(ctype)
486
+ return mimetype.parameters.get("charset", default)
487
+
488
+ @reify
489
+ def name(self) -> Optional[str]:
490
+ """Returns name specified in Content-Disposition header.
491
+
492
+ If the header is missing or malformed, returns None.
493
+ """
494
+ _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION))
495
+ return content_disposition_filename(params, "name")
496
+
497
+ @reify
498
+ def filename(self) -> Optional[str]:
499
+ """Returns filename specified in Content-Disposition header.
500
+
501
+ Returns None if the header is missing or malformed.
502
+ """
503
+ _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION))
504
+ return content_disposition_filename(params, "filename")
505
+
506
+
507
+ @payload_type(BodyPartReader, order=Order.try_first)
508
+ class BodyPartReaderPayload(Payload):
509
+ def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None:
510
+ super().__init__(value, *args, **kwargs)
511
+
512
+ params: Dict[str, str] = {}
513
+ if value.name is not None:
514
+ params["name"] = value.name
515
+ if value.filename is not None:
516
+ params["filename"] = value.filename
517
+
518
+ if params:
519
+ self.set_content_disposition("attachment", True, **params)
520
+
521
+ async def write(self, writer: Any) -> None:
522
+ field = self._value
523
+ chunk = await field.read_chunk(size=2**16)
524
+ while chunk:
525
+ await writer.write(field.decode(chunk))
526
+ chunk = await field.read_chunk(size=2**16)
527
+
528
+
529
+ class MultipartReader:
530
+ """Multipart body reader."""
531
+
532
+ #: Response wrapper, used when multipart readers constructs from response.
533
+ response_wrapper_cls = MultipartResponseWrapper
534
+ #: Multipart reader class, used to handle multipart/* body parts.
535
+ #: None points to type(self)
536
+ multipart_reader_cls = None
537
+ #: Body part reader class for non multipart/* content types.
538
+ part_reader_cls = BodyPartReader
539
+
540
+ def __init__(self, headers: Mapping[str, str], content: StreamReader) -> None:
541
+ self.headers = headers
542
+ self._boundary = ("--" + self._get_boundary()).encode()
543
+ self._content = content
544
+ self._last_part: Optional[Union["MultipartReader", BodyPartReader]] = None
545
+ self._at_eof = False
546
+ self._at_bof = True
547
+ self._unread: List[bytes] = []
548
+
549
+ def __aiter__(
550
+ self,
551
+ ) -> AsyncIterator["BodyPartReader"]:
552
+ return self # type: ignore[return-value]
553
+
554
+ async def __anext__(
555
+ self,
556
+ ) -> Optional[Union["MultipartReader", BodyPartReader]]:
557
+ part = await self.next()
558
+ if part is None:
559
+ raise StopAsyncIteration
560
+ return part
561
+
562
+ @classmethod
563
+ def from_response(
564
+ cls,
565
+ response: "ClientResponse",
566
+ ) -> MultipartResponseWrapper:
567
+ """Constructs reader instance from HTTP response.
568
+
569
+ :param response: :class:`~aiohttp.client.ClientResponse` instance
570
+ """
571
+ obj = cls.response_wrapper_cls(
572
+ response, cls(response.headers, response.content)
573
+ )
574
+ return obj
575
+
576
+ def at_eof(self) -> bool:
577
+ """Returns True if the final boundary was reached, false otherwise."""
578
+ return self._at_eof
579
+
580
+ async def next(
581
+ self,
582
+ ) -> Optional[Union["MultipartReader", BodyPartReader]]:
583
+ """Emits the next multipart body part."""
584
+ # So, if we're at BOF, we need to skip till the boundary.
585
+ if self._at_eof:
586
+ return None
587
+ await self._maybe_release_last_part()
588
+ if self._at_bof:
589
+ await self._read_until_first_boundary()
590
+ self._at_bof = False
591
+ else:
592
+ await self._read_boundary()
593
+ if self._at_eof: # we just read the last boundary, nothing to do there
594
+ return None
595
+ self._last_part = await self.fetch_next_part()
596
+ return self._last_part
597
+
598
+ async def release(self) -> None:
599
+ """Reads all the body parts to the void till the final boundary."""
600
+ while not self._at_eof:
601
+ item = await self.next()
602
+ if item is None:
603
+ break
604
+ await item.release()
605
+
606
+ async def fetch_next_part(
607
+ self,
608
+ ) -> Union["MultipartReader", BodyPartReader]:
609
+ """Returns the next body part reader."""
610
+ headers = await self._read_headers()
611
+ return self._get_part_reader(headers)
612
+
613
+ def _get_part_reader(
614
+ self,
615
+ headers: "CIMultiDictProxy[str]",
616
+ ) -> Union["MultipartReader", BodyPartReader]:
617
+ """Dispatches the response by the `Content-Type` header.
618
+
619
+ Returns a suitable reader instance.
620
+
621
+ :param dict headers: Response headers
622
+ """
623
+ ctype = headers.get(CONTENT_TYPE, "")
624
+ mimetype = parse_mimetype(ctype)
625
+
626
+ if mimetype.type == "multipart":
627
+ if self.multipart_reader_cls is None:
628
+ return type(self)(headers, self._content)
629
+ return self.multipart_reader_cls(headers, self._content)
630
+ else:
631
+ return self.part_reader_cls(self._boundary, headers, self._content)
632
+
633
+ def _get_boundary(self) -> str:
634
+ mimetype = parse_mimetype(self.headers[CONTENT_TYPE])
635
+
636
+ assert mimetype.type == "multipart", "multipart/* content type expected"
637
+
638
+ if "boundary" not in mimetype.parameters:
639
+ raise ValueError(
640
+ "boundary missed for Content-Type: %s" % self.headers[CONTENT_TYPE]
641
+ )
642
+
643
+ boundary = mimetype.parameters["boundary"]
644
+ if len(boundary) > 70:
645
+ raise ValueError("boundary %r is too long (70 chars max)" % boundary)
646
+
647
+ return boundary
648
+
649
+ async def _readline(self) -> bytes:
650
+ if self._unread:
651
+ return self._unread.pop()
652
+ return await self._content.readline()
653
+
654
+ async def _read_until_first_boundary(self) -> None:
655
+ while True:
656
+ chunk = await self._readline()
657
+ if chunk == b"":
658
+ raise ValueError(
659
+ "Could not find starting boundary %r" % (self._boundary)
660
+ )
661
+ chunk = chunk.rstrip()
662
+ if chunk == self._boundary:
663
+ return
664
+ elif chunk == self._boundary + b"--":
665
+ self._at_eof = True
666
+ return
667
+
668
+ async def _read_boundary(self) -> None:
669
+ chunk = (await self._readline()).rstrip()
670
+ if chunk == self._boundary:
671
+ pass
672
+ elif chunk == self._boundary + b"--":
673
+ self._at_eof = True
674
+ epilogue = await self._readline()
675
+ next_line = await self._readline()
676
+
677
+ # the epilogue is expected and then either the end of input or the
678
+ # parent multipart boundary, if the parent boundary is found then
679
+ # it should be marked as unread and handed to the parent for
680
+ # processing
681
+ if next_line[:2] == b"--":
682
+ self._unread.append(next_line)
683
+ # otherwise the request is likely missing an epilogue and both
684
+ # lines should be passed to the parent for processing
685
+ # (this handles the old behavior gracefully)
686
+ else:
687
+ self._unread.extend([next_line, epilogue])
688
+ else:
689
+ raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}")
690
+
691
+ async def _read_headers(self) -> "CIMultiDictProxy[str]":
692
+ lines = [b""]
693
+ while True:
694
+ chunk = await self._content.readline()
695
+ chunk = chunk.strip()
696
+ lines.append(chunk)
697
+ if not chunk:
698
+ break
699
+ parser = HeadersParser()
700
+ headers, raw_headers = parser.parse_headers(lines)
701
+ return headers
702
+
703
+ async def _maybe_release_last_part(self) -> None:
704
+ """Ensures that the last read body part is read completely."""
705
+ if self._last_part is not None:
706
+ if not self._last_part.at_eof():
707
+ await self._last_part.release()
708
+ self._unread.extend(self._last_part._unread)
709
+ self._last_part = None
710
+
711
+
712
+ _Part = Tuple[Payload, str, str]
713
+
714
+
715
+ class MultipartWriter(Payload):
716
+ """Multipart body writer."""
717
+
718
+ def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> None:
719
+ boundary = boundary if boundary is not None else uuid.uuid4().hex
720
+ # The underlying Payload API demands a str (utf-8), not bytes,
721
+ # so we need to ensure we don't lose anything during conversion.
722
+ # As a result, require the boundary to be ASCII only.
723
+ # In both situations.
724
+
725
+ try:
726
+ self._boundary = boundary.encode("ascii")
727
+ except UnicodeEncodeError:
728
+ raise ValueError("boundary should contain ASCII only chars") from None
729
+ ctype = f"multipart/{subtype}; boundary={self._boundary_value}"
730
+
731
+ super().__init__(None, content_type=ctype)
732
+
733
+ self._parts: List[_Part] = []
734
+
735
+ def __enter__(self) -> "MultipartWriter":
736
+ return self
737
+
738
+ def __exit__(
739
+ self,
740
+ exc_type: Optional[Type[BaseException]],
741
+ exc_val: Optional[BaseException],
742
+ exc_tb: Optional[TracebackType],
743
+ ) -> None:
744
+ pass
745
+
746
+ def __iter__(self) -> Iterator[_Part]:
747
+ return iter(self._parts)
748
+
749
+ def __len__(self) -> int:
750
+ return len(self._parts)
751
+
752
+ def __bool__(self) -> bool:
753
+ return True
754
+
755
+ _valid_tchar_regex = re.compile(rb"\A[!#$%&'*+\-.^_`|~\w]+\Z")
756
+ _invalid_qdtext_char_regex = re.compile(rb"[\x00-\x08\x0A-\x1F\x7F]")
757
+
758
+ @property
759
+ def _boundary_value(self) -> str:
760
+ """Wrap boundary parameter value in quotes, if necessary.
761
+
762
+ Reads self.boundary and returns a unicode string.
763
+ """
764
+ # Refer to RFCs 7231, 7230, 5234.
765
+ #
766
+ # parameter = token "=" ( token / quoted-string )
767
+ # token = 1*tchar
768
+ # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
769
+ # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
770
+ # obs-text = %x80-FF
771
+ # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
772
+ # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
773
+ # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
774
+ # / DIGIT / ALPHA
775
+ # ; any VCHAR, except delimiters
776
+ # VCHAR = %x21-7E
777
+ value = self._boundary
778
+ if re.match(self._valid_tchar_regex, value):
779
+ return value.decode("ascii") # cannot fail
780
+
781
+ if re.search(self._invalid_qdtext_char_regex, value):
782
+ raise ValueError("boundary value contains invalid characters")
783
+
784
+ # escape %x5C and %x22
785
+ quoted_value_content = value.replace(b"\\", b"\\\\")
786
+ quoted_value_content = quoted_value_content.replace(b'"', b'\\"')
787
+
788
+ return '"' + quoted_value_content.decode("ascii") + '"'
789
+
790
+ @property
791
+ def boundary(self) -> str:
792
+ return self._boundary.decode("ascii")
793
+
794
+ def append(self, obj: Any, headers: Optional[MultiMapping[str]] = None) -> Payload:
795
+ if headers is None:
796
+ headers = CIMultiDict()
797
+
798
+ if isinstance(obj, Payload):
799
+ obj.headers.update(headers)
800
+ return self.append_payload(obj)
801
+ else:
802
+ try:
803
+ payload = get_payload(obj, headers=headers)
804
+ except LookupError:
805
+ raise TypeError("Cannot create payload from %r" % obj)
806
+ else:
807
+ return self.append_payload(payload)
808
+
809
+ def append_payload(self, payload: Payload) -> Payload:
810
+ """Adds a new body part to multipart writer."""
811
+ # compression
812
+ encoding: Optional[str] = payload.headers.get(
813
+ CONTENT_ENCODING,
814
+ "",
815
+ ).lower()
816
+ if encoding and encoding not in ("deflate", "gzip", "identity"):
817
+ raise RuntimeError(f"unknown content encoding: {encoding}")
818
+ if encoding == "identity":
819
+ encoding = None
820
+
821
+ # te encoding
822
+ te_encoding: Optional[str] = payload.headers.get(
823
+ CONTENT_TRANSFER_ENCODING,
824
+ "",
825
+ ).lower()
826
+ if te_encoding not in ("", "base64", "quoted-printable", "binary"):
827
+ raise RuntimeError(
828
+ "unknown content transfer encoding: {}" "".format(te_encoding)
829
+ )
830
+ if te_encoding == "binary":
831
+ te_encoding = None
832
+
833
+ # size
834
+ size = payload.size
835
+ if size is not None and not (encoding or te_encoding):
836
+ payload.headers[CONTENT_LENGTH] = str(size)
837
+
838
+ self._parts.append((payload, encoding, te_encoding)) # type: ignore[arg-type]
839
+ return payload
840
+
841
+ def append_json(
842
+ self, obj: Any, headers: Optional[MultiMapping[str]] = None
843
+ ) -> Payload:
844
+ """Helper to append JSON part."""
845
+ if headers is None:
846
+ headers = CIMultiDict()
847
+
848
+ return self.append_payload(JsonPayload(obj, headers=headers))
849
+
850
+ def append_form(
851
+ self,
852
+ obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]],
853
+ headers: Optional[MultiMapping[str]] = None,
854
+ ) -> Payload:
855
+ """Helper to append form urlencoded part."""
856
+ assert isinstance(obj, (Sequence, Mapping))
857
+
858
+ if headers is None:
859
+ headers = CIMultiDict()
860
+
861
+ if isinstance(obj, Mapping):
862
+ obj = list(obj.items())
863
+ data = urlencode(obj, doseq=True)
864
+
865
+ return self.append_payload(
866
+ StringPayload(
867
+ data, headers=headers, content_type="application/x-www-form-urlencoded"
868
+ )
869
+ )
870
+
871
+ @property
872
+ def size(self) -> Optional[int]:
873
+ """Size of the payload."""
874
+ total = 0
875
+ for part, encoding, te_encoding in self._parts:
876
+ if encoding or te_encoding or part.size is None:
877
+ return None
878
+
879
+ total += int(
880
+ 2
881
+ + len(self._boundary)
882
+ + 2
883
+ + part.size # b'--'+self._boundary+b'\r\n'
884
+ + len(part._binary_headers)
885
+ + 2 # b'\r\n'
886
+ )
887
+
888
+ total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n'
889
+ return total
890
+
891
+ async def write(self, writer: Any, close_boundary: bool = True) -> None:
892
+ """Write body."""
893
+ for part, encoding, te_encoding in self._parts:
894
+ await writer.write(b"--" + self._boundary + b"\r\n")
895
+ await writer.write(part._binary_headers)
896
+
897
+ if encoding or te_encoding:
898
+ w = MultipartPayloadWriter(writer)
899
+ if encoding:
900
+ w.enable_compression(encoding)
901
+ if te_encoding:
902
+ w.enable_encoding(te_encoding)
903
+ await part.write(w) # type: ignore[arg-type]
904
+ await w.write_eof()
905
+ else:
906
+ await part.write(writer)
907
+
908
+ await writer.write(b"\r\n")
909
+
910
+ if close_boundary:
911
+ await writer.write(b"--" + self._boundary + b"--\r\n")
912
+
913
+
914
+ class MultipartPayloadWriter:
915
+ def __init__(self, writer: Any) -> None:
916
+ self._writer = writer
917
+ self._encoding: Optional[str] = None
918
+ self._compress: Optional[ZLibCompressor] = None
919
+ self._encoding_buffer: Optional[bytearray] = None
920
+
921
+ def enable_encoding(self, encoding: str) -> None:
922
+ if encoding == "base64":
923
+ self._encoding = encoding
924
+ self._encoding_buffer = bytearray()
925
+ elif encoding == "quoted-printable":
926
+ self._encoding = "quoted-printable"
927
+
928
+ def enable_compression(
929
+ self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY
930
+ ) -> None:
931
+ self._compress = ZLibCompressor(
932
+ encoding=encoding,
933
+ suppress_deflate_header=True,
934
+ strategy=strategy,
935
+ )
936
+
937
+ async def write_eof(self) -> None:
938
+ if self._compress is not None:
939
+ chunk = self._compress.flush()
940
+ if chunk:
941
+ self._compress = None
942
+ await self.write(chunk)
943
+
944
+ if self._encoding == "base64":
945
+ if self._encoding_buffer:
946
+ await self._writer.write(base64.b64encode(self._encoding_buffer))
947
+
948
+ async def write(self, chunk: bytes) -> None:
949
+ if self._compress is not None:
950
+ if chunk:
951
+ chunk = await self._compress.compress(chunk)
952
+ if not chunk:
953
+ return
954
+
955
+ if self._encoding == "base64":
956
+ buf = self._encoding_buffer
957
+ assert buf is not None
958
+ buf.extend(chunk)
959
+
960
+ if buf:
961
+ div, mod = divmod(len(buf), 3)
962
+ enc_chunk, self._encoding_buffer = (buf[: div * 3], buf[div * 3 :])
963
+ if enc_chunk:
964
+ b64chunk = base64.b64encode(enc_chunk)
965
+ await self._writer.write(b64chunk)
966
+ elif self._encoding == "quoted-printable":
967
+ await self._writer.write(binascii.b2a_qp(chunk))
968
+ else:
969
+ await self._writer.write(chunk)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/payload.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import enum
3
+ import io
4
+ import json
5
+ import mimetypes
6
+ import os
7
+ import warnings
8
+ from abc import ABC, abstractmethod
9
+ from itertools import chain
10
+ from typing import (
11
+ IO,
12
+ TYPE_CHECKING,
13
+ Any,
14
+ ByteString,
15
+ Dict,
16
+ Final,
17
+ Iterable,
18
+ Optional,
19
+ TextIO,
20
+ Tuple,
21
+ Type,
22
+ Union,
23
+ )
24
+
25
+ from multidict import CIMultiDict
26
+
27
+ from . import hdrs
28
+ from .abc import AbstractStreamWriter
29
+ from .helpers import (
30
+ _SENTINEL,
31
+ content_disposition_header,
32
+ guess_filename,
33
+ parse_mimetype,
34
+ sentinel,
35
+ )
36
+ from .streams import StreamReader
37
+ from .typedefs import JSONEncoder, _CIMultiDict
38
+
39
+ __all__ = (
40
+ "PAYLOAD_REGISTRY",
41
+ "get_payload",
42
+ "payload_type",
43
+ "Payload",
44
+ "BytesPayload",
45
+ "StringPayload",
46
+ "IOBasePayload",
47
+ "BytesIOPayload",
48
+ "BufferedReaderPayload",
49
+ "TextIOPayload",
50
+ "StringIOPayload",
51
+ "JsonPayload",
52
+ "AsyncIterablePayload",
53
+ )
54
+
55
+ TOO_LARGE_BYTES_BODY: Final[int] = 2**20 # 1 MB
56
+
57
+ if TYPE_CHECKING: # pragma: no cover
58
+ from typing import List
59
+
60
+
61
+ class LookupError(Exception):
62
+ pass
63
+
64
+
65
+ class Order(str, enum.Enum):
66
+ normal = "normal"
67
+ try_first = "try_first"
68
+ try_last = "try_last"
69
+
70
+
71
+ def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload":
72
+ return PAYLOAD_REGISTRY.get(data, *args, **kwargs)
73
+
74
+
75
+ def register_payload(
76
+ factory: Type["Payload"], type: Any, *, order: Order = Order.normal
77
+ ) -> None:
78
+ PAYLOAD_REGISTRY.register(factory, type, order=order)
79
+
80
+
81
+ class payload_type:
82
+ def __init__(self, type: Any, *, order: Order = Order.normal) -> None:
83
+ self.type = type
84
+ self.order = order
85
+
86
+ def __call__(self, factory: Type["Payload"]) -> Type["Payload"]:
87
+ register_payload(factory, self.type, order=self.order)
88
+ return factory
89
+
90
+
91
+ PayloadType = Type["Payload"]
92
+ _PayloadRegistryItem = Tuple[PayloadType, Any]
93
+
94
+
95
+ class PayloadRegistry:
96
+ """Payload registry.
97
+
98
+ note: we need zope.interface for more efficient adapter search
99
+ """
100
+
101
+ def __init__(self) -> None:
102
+ self._first: List[_PayloadRegistryItem] = []
103
+ self._normal: List[_PayloadRegistryItem] = []
104
+ self._last: List[_PayloadRegistryItem] = []
105
+
106
+ def get(
107
+ self,
108
+ data: Any,
109
+ *args: Any,
110
+ _CHAIN: "Type[chain[_PayloadRegistryItem]]" = chain,
111
+ **kwargs: Any,
112
+ ) -> "Payload":
113
+ if isinstance(data, Payload):
114
+ return data
115
+ for factory, type in _CHAIN(self._first, self._normal, self._last):
116
+ if isinstance(data, type):
117
+ return factory(data, *args, **kwargs)
118
+
119
+ raise LookupError()
120
+
121
+ def register(
122
+ self, factory: PayloadType, type: Any, *, order: Order = Order.normal
123
+ ) -> None:
124
+ if order is Order.try_first:
125
+ self._first.append((factory, type))
126
+ elif order is Order.normal:
127
+ self._normal.append((factory, type))
128
+ elif order is Order.try_last:
129
+ self._last.append((factory, type))
130
+ else:
131
+ raise ValueError(f"Unsupported order {order!r}")
132
+
133
+
134
+ class Payload(ABC):
135
+
136
+ _default_content_type: str = "application/octet-stream"
137
+ _size: Optional[int] = None
138
+
139
+ def __init__(
140
+ self,
141
+ value: Any,
142
+ headers: Optional[
143
+ Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]]
144
+ ] = None,
145
+ content_type: Union[str, None, _SENTINEL] = sentinel,
146
+ filename: Optional[str] = None,
147
+ encoding: Optional[str] = None,
148
+ **kwargs: Any,
149
+ ) -> None:
150
+ self._encoding = encoding
151
+ self._filename = filename
152
+ self._headers: _CIMultiDict = CIMultiDict()
153
+ self._value = value
154
+ if content_type is not sentinel and content_type is not None:
155
+ self._headers[hdrs.CONTENT_TYPE] = content_type
156
+ elif self._filename is not None:
157
+ content_type = mimetypes.guess_type(self._filename)[0]
158
+ if content_type is None:
159
+ content_type = self._default_content_type
160
+ self._headers[hdrs.CONTENT_TYPE] = content_type
161
+ else:
162
+ self._headers[hdrs.CONTENT_TYPE] = self._default_content_type
163
+ self._headers.update(headers or {})
164
+
165
+ @property
166
+ def size(self) -> Optional[int]:
167
+ """Size of the payload."""
168
+ return self._size
169
+
170
+ @property
171
+ def filename(self) -> Optional[str]:
172
+ """Filename of the payload."""
173
+ return self._filename
174
+
175
+ @property
176
+ def headers(self) -> _CIMultiDict:
177
+ """Custom item headers"""
178
+ return self._headers
179
+
180
+ @property
181
+ def _binary_headers(self) -> bytes:
182
+ return (
183
+ "".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode(
184
+ "utf-8"
185
+ )
186
+ + b"\r\n"
187
+ )
188
+
189
+ @property
190
+ def encoding(self) -> Optional[str]:
191
+ """Payload encoding"""
192
+ return self._encoding
193
+
194
+ @property
195
+ def content_type(self) -> str:
196
+ """Content type"""
197
+ return self._headers[hdrs.CONTENT_TYPE]
198
+
199
+ def set_content_disposition(
200
+ self,
201
+ disptype: str,
202
+ quote_fields: bool = True,
203
+ _charset: str = "utf-8",
204
+ **params: Any,
205
+ ) -> None:
206
+ """Sets ``Content-Disposition`` header."""
207
+ self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_header(
208
+ disptype, quote_fields=quote_fields, _charset=_charset, **params
209
+ )
210
+
211
+ @abstractmethod
212
+ async def write(self, writer: AbstractStreamWriter) -> None:
213
+ """Write payload.
214
+
215
+ writer is an AbstractStreamWriter instance:
216
+ """
217
+
218
+
219
+ class BytesPayload(Payload):
220
+ def __init__(self, value: ByteString, *args: Any, **kwargs: Any) -> None:
221
+ if not isinstance(value, (bytes, bytearray, memoryview)):
222
+ raise TypeError(f"value argument must be byte-ish, not {type(value)!r}")
223
+
224
+ if "content_type" not in kwargs:
225
+ kwargs["content_type"] = "application/octet-stream"
226
+
227
+ super().__init__(value, *args, **kwargs)
228
+
229
+ if isinstance(value, memoryview):
230
+ self._size = value.nbytes
231
+ else:
232
+ self._size = len(value)
233
+
234
+ if self._size > TOO_LARGE_BYTES_BODY:
235
+ kwargs = {"source": self}
236
+ warnings.warn(
237
+ "Sending a large body directly with raw bytes might"
238
+ " lock the event loop. You should probably pass an "
239
+ "io.BytesIO object instead",
240
+ ResourceWarning,
241
+ **kwargs,
242
+ )
243
+
244
+ async def write(self, writer: AbstractStreamWriter) -> None:
245
+ await writer.write(self._value)
246
+
247
+
248
+ class StringPayload(BytesPayload):
249
+ def __init__(
250
+ self,
251
+ value: str,
252
+ *args: Any,
253
+ encoding: Optional[str] = None,
254
+ content_type: Optional[str] = None,
255
+ **kwargs: Any,
256
+ ) -> None:
257
+
258
+ if encoding is None:
259
+ if content_type is None:
260
+ real_encoding = "utf-8"
261
+ content_type = "text/plain; charset=utf-8"
262
+ else:
263
+ mimetype = parse_mimetype(content_type)
264
+ real_encoding = mimetype.parameters.get("charset", "utf-8")
265
+ else:
266
+ if content_type is None:
267
+ content_type = "text/plain; charset=%s" % encoding
268
+ real_encoding = encoding
269
+
270
+ super().__init__(
271
+ value.encode(real_encoding),
272
+ encoding=real_encoding,
273
+ content_type=content_type,
274
+ *args,
275
+ **kwargs,
276
+ )
277
+
278
+
279
+ class StringIOPayload(StringPayload):
280
+ def __init__(self, value: IO[str], *args: Any, **kwargs: Any) -> None:
281
+ super().__init__(value.read(), *args, **kwargs)
282
+
283
+
284
+ class IOBasePayload(Payload):
285
+ _value: IO[Any]
286
+
287
+ def __init__(
288
+ self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any
289
+ ) -> None:
290
+ if "filename" not in kwargs:
291
+ kwargs["filename"] = guess_filename(value)
292
+
293
+ super().__init__(value, *args, **kwargs)
294
+
295
+ if self._filename is not None and disposition is not None:
296
+ if hdrs.CONTENT_DISPOSITION not in self.headers:
297
+ self.set_content_disposition(disposition, filename=self._filename)
298
+
299
+ async def write(self, writer: AbstractStreamWriter) -> None:
300
+ loop = asyncio.get_event_loop()
301
+ try:
302
+ chunk = await loop.run_in_executor(None, self._value.read, 2**16)
303
+ while chunk:
304
+ await writer.write(chunk)
305
+ chunk = await loop.run_in_executor(None, self._value.read, 2**16)
306
+ finally:
307
+ await loop.run_in_executor(None, self._value.close)
308
+
309
+
310
+ class TextIOPayload(IOBasePayload):
311
+ _value: TextIO
312
+
313
+ def __init__(
314
+ self,
315
+ value: TextIO,
316
+ *args: Any,
317
+ encoding: Optional[str] = None,
318
+ content_type: Optional[str] = None,
319
+ **kwargs: Any,
320
+ ) -> None:
321
+
322
+ if encoding is None:
323
+ if content_type is None:
324
+ encoding = "utf-8"
325
+ content_type = "text/plain; charset=utf-8"
326
+ else:
327
+ mimetype = parse_mimetype(content_type)
328
+ encoding = mimetype.parameters.get("charset", "utf-8")
329
+ else:
330
+ if content_type is None:
331
+ content_type = "text/plain; charset=%s" % encoding
332
+
333
+ super().__init__(
334
+ value,
335
+ content_type=content_type,
336
+ encoding=encoding,
337
+ *args,
338
+ **kwargs,
339
+ )
340
+
341
+ @property
342
+ def size(self) -> Optional[int]:
343
+ try:
344
+ return os.fstat(self._value.fileno()).st_size - self._value.tell()
345
+ except OSError:
346
+ return None
347
+
348
+ async def write(self, writer: AbstractStreamWriter) -> None:
349
+ loop = asyncio.get_event_loop()
350
+ try:
351
+ chunk = await loop.run_in_executor(None, self._value.read, 2**16)
352
+ while chunk:
353
+ data = (
354
+ chunk.encode(encoding=self._encoding)
355
+ if self._encoding
356
+ else chunk.encode()
357
+ )
358
+ await writer.write(data)
359
+ chunk = await loop.run_in_executor(None, self._value.read, 2**16)
360
+ finally:
361
+ await loop.run_in_executor(None, self._value.close)
362
+
363
+
364
+ class BytesIOPayload(IOBasePayload):
365
+ @property
366
+ def size(self) -> int:
367
+ position = self._value.tell()
368
+ end = self._value.seek(0, os.SEEK_END)
369
+ self._value.seek(position)
370
+ return end - position
371
+
372
+
373
+ class BufferedReaderPayload(IOBasePayload):
374
+ @property
375
+ def size(self) -> Optional[int]:
376
+ try:
377
+ return os.fstat(self._value.fileno()).st_size - self._value.tell()
378
+ except OSError:
379
+ # data.fileno() is not supported, e.g.
380
+ # io.BufferedReader(io.BytesIO(b'data'))
381
+ return None
382
+
383
+
384
+ class JsonPayload(BytesPayload):
385
+ def __init__(
386
+ self,
387
+ value: Any,
388
+ encoding: str = "utf-8",
389
+ content_type: str = "application/json",
390
+ dumps: JSONEncoder = json.dumps,
391
+ *args: Any,
392
+ **kwargs: Any,
393
+ ) -> None:
394
+
395
+ super().__init__(
396
+ dumps(value).encode(encoding),
397
+ content_type=content_type,
398
+ encoding=encoding,
399
+ *args,
400
+ **kwargs,
401
+ )
402
+
403
+
404
+ if TYPE_CHECKING: # pragma: no cover
405
+ from typing import AsyncIterable, AsyncIterator
406
+
407
+ _AsyncIterator = AsyncIterator[bytes]
408
+ _AsyncIterable = AsyncIterable[bytes]
409
+ else:
410
+ from collections.abc import AsyncIterable, AsyncIterator
411
+
412
+ _AsyncIterator = AsyncIterator
413
+ _AsyncIterable = AsyncIterable
414
+
415
+
416
+ class AsyncIterablePayload(Payload):
417
+
418
+ _iter: Optional[_AsyncIterator] = None
419
+
420
+ def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None:
421
+ if not isinstance(value, AsyncIterable):
422
+ raise TypeError(
423
+ "value argument must support "
424
+ "collections.abc.AsyncIterable interface, "
425
+ "got {!r}".format(type(value))
426
+ )
427
+
428
+ if "content_type" not in kwargs:
429
+ kwargs["content_type"] = "application/octet-stream"
430
+
431
+ super().__init__(value, *args, **kwargs)
432
+
433
+ self._iter = value.__aiter__()
434
+
435
+ async def write(self, writer: AbstractStreamWriter) -> None:
436
+ if self._iter:
437
+ try:
438
+ # iter is not None check prevents rare cases
439
+ # when the case iterable is used twice
440
+ while True:
441
+ chunk = await self._iter.__anext__()
442
+ await writer.write(chunk)
443
+ except StopAsyncIteration:
444
+ self._iter = None
445
+
446
+
447
+ class StreamReaderPayload(AsyncIterablePayload):
448
+ def __init__(self, value: StreamReader, *args: Any, **kwargs: Any) -> None:
449
+ super().__init__(value.iter_any(), *args, **kwargs)
450
+
451
+
452
+ PAYLOAD_REGISTRY = PayloadRegistry()
453
+ PAYLOAD_REGISTRY.register(BytesPayload, (bytes, bytearray, memoryview))
454
+ PAYLOAD_REGISTRY.register(StringPayload, str)
455
+ PAYLOAD_REGISTRY.register(StringIOPayload, io.StringIO)
456
+ PAYLOAD_REGISTRY.register(TextIOPayload, io.TextIOBase)
457
+ PAYLOAD_REGISTRY.register(BytesIOPayload, io.BytesIO)
458
+ PAYLOAD_REGISTRY.register(BufferedReaderPayload, (io.BufferedReader, io.BufferedRandom))
459
+ PAYLOAD_REGISTRY.register(IOBasePayload, io.IOBase)
460
+ PAYLOAD_REGISTRY.register(StreamReaderPayload, StreamReader)
461
+ # try_last for giving a chance to more specialized async interables like
462
+ # multidict.BodyPartReaderPayload override the default
463
+ PAYLOAD_REGISTRY.register(AsyncIterablePayload, AsyncIterable, order=Order.try_last)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/payload_streamer.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Payload implementation for coroutines as data provider.
3
+
4
+ As a simple case, you can upload data from file::
5
+
6
+ @aiohttp.streamer
7
+ async def file_sender(writer, file_name=None):
8
+ with open(file_name, 'rb') as f:
9
+ chunk = f.read(2**16)
10
+ while chunk:
11
+ await writer.write(chunk)
12
+
13
+ chunk = f.read(2**16)
14
+
15
+ Then you can use `file_sender` like this:
16
+
17
+ async with session.post('http://httpbin.org/post',
18
+ data=file_sender(file_name='huge_file')) as resp:
19
+ print(await resp.text())
20
+
21
+ ..note:: Coroutine must accept `writer` as first argument
22
+
23
+ """
24
+
25
+ import types
26
+ import warnings
27
+ from typing import Any, Awaitable, Callable, Dict, Tuple
28
+
29
+ from .abc import AbstractStreamWriter
30
+ from .payload import Payload, payload_type
31
+
32
+ __all__ = ("streamer",)
33
+
34
+
35
+ class _stream_wrapper:
36
+ def __init__(
37
+ self,
38
+ coro: Callable[..., Awaitable[None]],
39
+ args: Tuple[Any, ...],
40
+ kwargs: Dict[str, Any],
41
+ ) -> None:
42
+ self.coro = types.coroutine(coro)
43
+ self.args = args
44
+ self.kwargs = kwargs
45
+
46
+ async def __call__(self, writer: AbstractStreamWriter) -> None:
47
+ await self.coro(writer, *self.args, **self.kwargs)
48
+
49
+
50
+ class streamer:
51
+ def __init__(self, coro: Callable[..., Awaitable[None]]) -> None:
52
+ warnings.warn(
53
+ "@streamer is deprecated, use async generators instead",
54
+ DeprecationWarning,
55
+ stacklevel=2,
56
+ )
57
+ self.coro = coro
58
+
59
+ def __call__(self, *args: Any, **kwargs: Any) -> _stream_wrapper:
60
+ return _stream_wrapper(self.coro, args, kwargs)
61
+
62
+
63
+ @payload_type(_stream_wrapper)
64
+ class StreamWrapperPayload(Payload):
65
+ async def write(self, writer: AbstractStreamWriter) -> None:
66
+ await self._value(writer)
67
+
68
+
69
+ @payload_type(streamer)
70
+ class StreamPayload(StreamWrapperPayload):
71
+ def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None:
72
+ super().__init__(value(), *args, **kwargs)
73
+
74
+ async def write(self, writer: AbstractStreamWriter) -> None:
75
+ await self._value(writer)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/py.typed ADDED
@@ -0,0 +1 @@
 
 
1
+ Marker
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/pytest_plugin.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import contextlib
3
+ import warnings
4
+ from typing import Any, Awaitable, Callable, Dict, Iterator, Optional, Type, Union
5
+
6
+ import pytest
7
+
8
+ from aiohttp.helpers import isasyncgenfunction
9
+ from aiohttp.web import Application
10
+
11
+ from .test_utils import (
12
+ BaseTestServer,
13
+ RawTestServer,
14
+ TestClient,
15
+ TestServer,
16
+ loop_context,
17
+ setup_test_loop,
18
+ teardown_test_loop,
19
+ unused_port as _unused_port,
20
+ )
21
+
22
+ try:
23
+ import uvloop
24
+ except ImportError: # pragma: no cover
25
+ uvloop = None # type: ignore[assignment]
26
+
27
+ AiohttpClient = Callable[[Union[Application, BaseTestServer]], Awaitable[TestClient]]
28
+ AiohttpRawServer = Callable[[Application], Awaitable[RawTestServer]]
29
+ AiohttpServer = Callable[[Application], Awaitable[TestServer]]
30
+
31
+
32
+ def pytest_addoption(parser): # type: ignore[no-untyped-def]
33
+ parser.addoption(
34
+ "--aiohttp-fast",
35
+ action="store_true",
36
+ default=False,
37
+ help="run tests faster by disabling extra checks",
38
+ )
39
+ parser.addoption(
40
+ "--aiohttp-loop",
41
+ action="store",
42
+ default="pyloop",
43
+ help="run tests with specific loop: pyloop, uvloop or all",
44
+ )
45
+ parser.addoption(
46
+ "--aiohttp-enable-loop-debug",
47
+ action="store_true",
48
+ default=False,
49
+ help="enable event loop debug mode",
50
+ )
51
+
52
+
53
+ def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def]
54
+ """Set up pytest fixture.
55
+
56
+ Allow fixtures to be coroutines. Run coroutine fixtures in an event loop.
57
+ """
58
+ func = fixturedef.func
59
+
60
+ if isasyncgenfunction(func):
61
+ # async generator fixture
62
+ is_async_gen = True
63
+ elif asyncio.iscoroutinefunction(func):
64
+ # regular async fixture
65
+ is_async_gen = False
66
+ else:
67
+ # not an async fixture, nothing to do
68
+ return
69
+
70
+ strip_request = False
71
+ if "request" not in fixturedef.argnames:
72
+ fixturedef.argnames += ("request",)
73
+ strip_request = True
74
+
75
+ def wrapper(*args, **kwargs): # type: ignore[no-untyped-def]
76
+ request = kwargs["request"]
77
+ if strip_request:
78
+ del kwargs["request"]
79
+
80
+ # if neither the fixture nor the test use the 'loop' fixture,
81
+ # 'getfixturevalue' will fail because the test is not parameterized
82
+ # (this can be removed someday if 'loop' is no longer parameterized)
83
+ if "loop" not in request.fixturenames:
84
+ raise Exception(
85
+ "Asynchronous fixtures must depend on the 'loop' fixture or "
86
+ "be used in tests depending from it."
87
+ )
88
+
89
+ _loop = request.getfixturevalue("loop")
90
+
91
+ if is_async_gen:
92
+ # for async generators, we need to advance the generator once,
93
+ # then advance it again in a finalizer
94
+ gen = func(*args, **kwargs)
95
+
96
+ def finalizer(): # type: ignore[no-untyped-def]
97
+ try:
98
+ return _loop.run_until_complete(gen.__anext__())
99
+ except StopAsyncIteration:
100
+ pass
101
+
102
+ request.addfinalizer(finalizer)
103
+ return _loop.run_until_complete(gen.__anext__())
104
+ else:
105
+ return _loop.run_until_complete(func(*args, **kwargs))
106
+
107
+ fixturedef.func = wrapper
108
+
109
+
110
+ @pytest.fixture
111
+ def fast(request): # type: ignore[no-untyped-def]
112
+ """--fast config option"""
113
+ return request.config.getoption("--aiohttp-fast")
114
+
115
+
116
+ @pytest.fixture
117
+ def loop_debug(request): # type: ignore[no-untyped-def]
118
+ """--enable-loop-debug config option"""
119
+ return request.config.getoption("--aiohttp-enable-loop-debug")
120
+
121
+
122
+ @contextlib.contextmanager
123
+ def _runtime_warning_context(): # type: ignore[no-untyped-def]
124
+ """Context manager which checks for RuntimeWarnings.
125
+
126
+ This exists specifically to
127
+ avoid "coroutine 'X' was never awaited" warnings being missed.
128
+
129
+ If RuntimeWarnings occur in the context a RuntimeError is raised.
130
+ """
131
+ with warnings.catch_warnings(record=True) as _warnings:
132
+ yield
133
+ rw = [
134
+ "{w.filename}:{w.lineno}:{w.message}".format(w=w)
135
+ for w in _warnings
136
+ if w.category == RuntimeWarning
137
+ ]
138
+ if rw:
139
+ raise RuntimeError(
140
+ "{} Runtime Warning{},\n{}".format(
141
+ len(rw), "" if len(rw) == 1 else "s", "\n".join(rw)
142
+ )
143
+ )
144
+
145
+
146
+ @contextlib.contextmanager
147
+ def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def]
148
+ """Passthrough loop context.
149
+
150
+ Sets up and tears down a loop unless one is passed in via the loop
151
+ argument when it's passed straight through.
152
+ """
153
+ if loop:
154
+ # loop already exists, pass it straight through
155
+ yield loop
156
+ else:
157
+ # this shadows loop_context's standard behavior
158
+ loop = setup_test_loop()
159
+ yield loop
160
+ teardown_test_loop(loop, fast=fast)
161
+
162
+
163
+ def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def]
164
+ """Fix pytest collecting for coroutines."""
165
+ if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj):
166
+ return list(collector._genfunctions(name, obj))
167
+
168
+
169
+ def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def]
170
+ """Run coroutines in an event loop instead of a normal function call."""
171
+ fast = pyfuncitem.config.getoption("--aiohttp-fast")
172
+ if asyncio.iscoroutinefunction(pyfuncitem.function):
173
+ existing_loop = pyfuncitem.funcargs.get(
174
+ "proactor_loop"
175
+ ) or pyfuncitem.funcargs.get("loop", None)
176
+ with _runtime_warning_context():
177
+ with _passthrough_loop_context(existing_loop, fast=fast) as _loop:
178
+ testargs = {
179
+ arg: pyfuncitem.funcargs[arg]
180
+ for arg in pyfuncitem._fixtureinfo.argnames
181
+ }
182
+ _loop.run_until_complete(pyfuncitem.obj(**testargs))
183
+
184
+ return True
185
+
186
+
187
+ def pytest_generate_tests(metafunc): # type: ignore[no-untyped-def]
188
+ if "loop_factory" not in metafunc.fixturenames:
189
+ return
190
+
191
+ loops = metafunc.config.option.aiohttp_loop
192
+ avail_factories: Dict[str, Type[asyncio.AbstractEventLoopPolicy]]
193
+ avail_factories = {"pyloop": asyncio.DefaultEventLoopPolicy}
194
+
195
+ if uvloop is not None: # pragma: no cover
196
+ avail_factories["uvloop"] = uvloop.EventLoopPolicy
197
+
198
+ if loops == "all":
199
+ loops = "pyloop,uvloop?"
200
+
201
+ factories = {} # type: ignore[var-annotated]
202
+ for name in loops.split(","):
203
+ required = not name.endswith("?")
204
+ name = name.strip(" ?")
205
+ if name not in avail_factories: # pragma: no cover
206
+ if required:
207
+ raise ValueError(
208
+ "Unknown loop '%s', available loops: %s"
209
+ % (name, list(factories.keys()))
210
+ )
211
+ else:
212
+ continue
213
+ factories[name] = avail_factories[name]
214
+ metafunc.parametrize(
215
+ "loop_factory", list(factories.values()), ids=list(factories.keys())
216
+ )
217
+
218
+
219
+ @pytest.fixture
220
+ def loop(loop_factory, fast, loop_debug): # type: ignore[no-untyped-def]
221
+ """Return an instance of the event loop."""
222
+ policy = loop_factory()
223
+ asyncio.set_event_loop_policy(policy)
224
+ with loop_context(fast=fast) as _loop:
225
+ if loop_debug:
226
+ _loop.set_debug(True) # pragma: no cover
227
+ asyncio.set_event_loop(_loop)
228
+ yield _loop
229
+
230
+
231
+ @pytest.fixture
232
+ def proactor_loop(): # type: ignore[no-untyped-def]
233
+ policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore[attr-defined]
234
+ asyncio.set_event_loop_policy(policy)
235
+
236
+ with loop_context(policy.new_event_loop) as _loop:
237
+ asyncio.set_event_loop(_loop)
238
+ yield _loop
239
+
240
+
241
+ @pytest.fixture
242
+ def unused_port(aiohttp_unused_port: Callable[[], int]) -> Callable[[], int]:
243
+ warnings.warn(
244
+ "Deprecated, use aiohttp_unused_port fixture instead",
245
+ DeprecationWarning,
246
+ stacklevel=2,
247
+ )
248
+ return aiohttp_unused_port
249
+
250
+
251
+ @pytest.fixture
252
+ def aiohttp_unused_port() -> Callable[[], int]:
253
+ """Return a port that is unused on the current host."""
254
+ return _unused_port
255
+
256
+
257
+ @pytest.fixture
258
+ def aiohttp_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpServer]:
259
+ """Factory to create a TestServer instance, given an app.
260
+
261
+ aiohttp_server(app, **kwargs)
262
+ """
263
+ servers = []
264
+
265
+ async def go(app, *, port=None, **kwargs): # type: ignore[no-untyped-def]
266
+ server = TestServer(app, port=port)
267
+ await server.start_server(loop=loop, **kwargs)
268
+ servers.append(server)
269
+ return server
270
+
271
+ yield go
272
+
273
+ async def finalize() -> None:
274
+ while servers:
275
+ await servers.pop().close()
276
+
277
+ loop.run_until_complete(finalize())
278
+
279
+
280
+ @pytest.fixture
281
+ def test_server(aiohttp_server): # type: ignore[no-untyped-def] # pragma: no cover
282
+ warnings.warn(
283
+ "Deprecated, use aiohttp_server fixture instead",
284
+ DeprecationWarning,
285
+ stacklevel=2,
286
+ )
287
+ return aiohttp_server
288
+
289
+
290
+ @pytest.fixture
291
+ def aiohttp_raw_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpRawServer]:
292
+ """Factory to create a RawTestServer instance, given a web handler.
293
+
294
+ aiohttp_raw_server(handler, **kwargs)
295
+ """
296
+ servers = []
297
+
298
+ async def go(handler, *, port=None, **kwargs): # type: ignore[no-untyped-def]
299
+ server = RawTestServer(handler, port=port)
300
+ await server.start_server(loop=loop, **kwargs)
301
+ servers.append(server)
302
+ return server
303
+
304
+ yield go
305
+
306
+ async def finalize() -> None:
307
+ while servers:
308
+ await servers.pop().close()
309
+
310
+ loop.run_until_complete(finalize())
311
+
312
+
313
+ @pytest.fixture
314
+ def raw_test_server( # type: ignore[no-untyped-def] # pragma: no cover
315
+ aiohttp_raw_server,
316
+ ):
317
+ warnings.warn(
318
+ "Deprecated, use aiohttp_raw_server fixture instead",
319
+ DeprecationWarning,
320
+ stacklevel=2,
321
+ )
322
+ return aiohttp_raw_server
323
+
324
+
325
+ @pytest.fixture
326
+ def aiohttp_client(
327
+ loop: asyncio.AbstractEventLoop,
328
+ ) -> Iterator[AiohttpClient]:
329
+ """Factory to create a TestClient instance.
330
+
331
+ aiohttp_client(app, **kwargs)
332
+ aiohttp_client(server, **kwargs)
333
+ aiohttp_client(raw_server, **kwargs)
334
+ """
335
+ clients = []
336
+
337
+ async def go(
338
+ __param: Union[Application, BaseTestServer],
339
+ *args: Any,
340
+ server_kwargs: Optional[Dict[str, Any]] = None,
341
+ **kwargs: Any
342
+ ) -> TestClient:
343
+
344
+ if isinstance(__param, Callable) and not isinstance( # type: ignore[arg-type]
345
+ __param, (Application, BaseTestServer)
346
+ ):
347
+ __param = __param(loop, *args, **kwargs)
348
+ kwargs = {}
349
+ else:
350
+ assert not args, "args should be empty"
351
+
352
+ if isinstance(__param, Application):
353
+ server_kwargs = server_kwargs or {}
354
+ server = TestServer(__param, loop=loop, **server_kwargs)
355
+ client = TestClient(server, loop=loop, **kwargs)
356
+ elif isinstance(__param, BaseTestServer):
357
+ client = TestClient(__param, loop=loop, **kwargs)
358
+ else:
359
+ raise ValueError("Unknown argument type: %r" % type(__param))
360
+
361
+ await client.start_server()
362
+ clients.append(client)
363
+ return client
364
+
365
+ yield go
366
+
367
+ async def finalize() -> None:
368
+ while clients:
369
+ await clients.pop().close()
370
+
371
+ loop.run_until_complete(finalize())
372
+
373
+
374
+ @pytest.fixture
375
+ def test_client(aiohttp_client): # type: ignore[no-untyped-def] # pragma: no cover
376
+ warnings.warn(
377
+ "Deprecated, use aiohttp_client fixture instead",
378
+ DeprecationWarning,
379
+ stacklevel=2,
380
+ )
381
+ return aiohttp_client
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/resolver.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import socket
3
+ from typing import Any, Dict, List, Optional, Type, Union
4
+
5
+ from .abc import AbstractResolver
6
+ from .helpers import get_running_loop
7
+
8
+ __all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver")
9
+
10
+ try:
11
+ import aiodns
12
+
13
+ # aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname')
14
+ except ImportError: # pragma: no cover
15
+ aiodns = None
16
+
17
+ aiodns_default = False
18
+
19
+
20
+ class ThreadedResolver(AbstractResolver):
21
+ """Threaded resolver.
22
+
23
+ Uses an Executor for synchronous getaddrinfo() calls.
24
+ concurrent.futures.ThreadPoolExecutor is used by default.
25
+ """
26
+
27
+ def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
28
+ self._loop = get_running_loop(loop)
29
+
30
+ async def resolve(
31
+ self, hostname: str, port: int = 0, family: int = socket.AF_INET
32
+ ) -> List[Dict[str, Any]]:
33
+ infos = await self._loop.getaddrinfo(
34
+ hostname,
35
+ port,
36
+ type=socket.SOCK_STREAM,
37
+ family=family,
38
+ flags=socket.AI_ADDRCONFIG,
39
+ )
40
+
41
+ hosts = []
42
+ for family, _, proto, _, address in infos:
43
+ if family == socket.AF_INET6:
44
+ if len(address) < 3:
45
+ # IPv6 is not supported by Python build,
46
+ # or IPv6 is not enabled in the host
47
+ continue
48
+ if address[3]:
49
+ # This is essential for link-local IPv6 addresses.
50
+ # LL IPv6 is a VERY rare case. Strictly speaking, we should use
51
+ # getnameinfo() unconditionally, but performance makes sense.
52
+ host, _port = socket.getnameinfo(
53
+ address, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV
54
+ )
55
+ port = int(_port)
56
+ else:
57
+ host, port = address[:2]
58
+ else: # IPv4
59
+ assert family == socket.AF_INET
60
+ host, port = address # type: ignore[misc]
61
+ hosts.append(
62
+ {
63
+ "hostname": hostname,
64
+ "host": host,
65
+ "port": port,
66
+ "family": family,
67
+ "proto": proto,
68
+ "flags": socket.AI_NUMERICHOST | socket.AI_NUMERICSERV,
69
+ }
70
+ )
71
+
72
+ return hosts
73
+
74
+ async def close(self) -> None:
75
+ pass
76
+
77
+
78
+ class AsyncResolver(AbstractResolver):
79
+ """Use the `aiodns` package to make asynchronous DNS lookups"""
80
+
81
+ def __init__(
82
+ self,
83
+ loop: Optional[asyncio.AbstractEventLoop] = None,
84
+ *args: Any,
85
+ **kwargs: Any
86
+ ) -> None:
87
+ if aiodns is None:
88
+ raise RuntimeError("Resolver requires aiodns library")
89
+
90
+ self._loop = get_running_loop(loop)
91
+ self._resolver = aiodns.DNSResolver(*args, loop=loop, **kwargs)
92
+
93
+ if not hasattr(self._resolver, "gethostbyname"):
94
+ # aiodns 1.1 is not available, fallback to DNSResolver.query
95
+ self.resolve = self._resolve_with_query # type: ignore
96
+
97
+ async def resolve(
98
+ self, host: str, port: int = 0, family: int = socket.AF_INET
99
+ ) -> List[Dict[str, Any]]:
100
+ try:
101
+ resp = await self._resolver.gethostbyname(host, family)
102
+ except aiodns.error.DNSError as exc:
103
+ msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed"
104
+ raise OSError(msg) from exc
105
+ hosts = []
106
+ for address in resp.addresses:
107
+ hosts.append(
108
+ {
109
+ "hostname": host,
110
+ "host": address,
111
+ "port": port,
112
+ "family": family,
113
+ "proto": 0,
114
+ "flags": socket.AI_NUMERICHOST | socket.AI_NUMERICSERV,
115
+ }
116
+ )
117
+
118
+ if not hosts:
119
+ raise OSError("DNS lookup failed")
120
+
121
+ return hosts
122
+
123
+ async def _resolve_with_query(
124
+ self, host: str, port: int = 0, family: int = socket.AF_INET
125
+ ) -> List[Dict[str, Any]]:
126
+ if family == socket.AF_INET6:
127
+ qtype = "AAAA"
128
+ else:
129
+ qtype = "A"
130
+
131
+ try:
132
+ resp = await self._resolver.query(host, qtype)
133
+ except aiodns.error.DNSError as exc:
134
+ msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed"
135
+ raise OSError(msg) from exc
136
+
137
+ hosts = []
138
+ for rr in resp:
139
+ hosts.append(
140
+ {
141
+ "hostname": host,
142
+ "host": rr.host,
143
+ "port": port,
144
+ "family": family,
145
+ "proto": 0,
146
+ "flags": socket.AI_NUMERICHOST,
147
+ }
148
+ )
149
+
150
+ if not hosts:
151
+ raise OSError("DNS lookup failed")
152
+
153
+ return hosts
154
+
155
+ async def close(self) -> None:
156
+ self._resolver.cancel()
157
+
158
+
159
+ _DefaultType = Type[Union[AsyncResolver, ThreadedResolver]]
160
+ DefaultResolver: _DefaultType = AsyncResolver if aiodns_default else ThreadedResolver
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/streams.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import collections
3
+ import warnings
4
+ from typing import (
5
+ Awaitable,
6
+ Callable,
7
+ Deque,
8
+ Final,
9
+ Generic,
10
+ List,
11
+ Optional,
12
+ Tuple,
13
+ TypeVar,
14
+ )
15
+
16
+ from .base_protocol import BaseProtocol
17
+ from .helpers import BaseTimerContext, TimerNoop, set_exception, set_result
18
+ from .log import internal_logger
19
+
20
+ __all__ = (
21
+ "EMPTY_PAYLOAD",
22
+ "EofStream",
23
+ "StreamReader",
24
+ "DataQueue",
25
+ "FlowControlDataQueue",
26
+ )
27
+
28
+ _T = TypeVar("_T")
29
+
30
+
31
+ class EofStream(Exception):
32
+ """eof stream indication."""
33
+
34
+
35
+ class AsyncStreamIterator(Generic[_T]):
36
+ def __init__(self, read_func: Callable[[], Awaitable[_T]]) -> None:
37
+ self.read_func = read_func
38
+
39
+ def __aiter__(self) -> "AsyncStreamIterator[_T]":
40
+ return self
41
+
42
+ async def __anext__(self) -> _T:
43
+ try:
44
+ rv = await self.read_func()
45
+ except EofStream:
46
+ raise StopAsyncIteration
47
+ if rv == b"":
48
+ raise StopAsyncIteration
49
+ return rv
50
+
51
+
52
+ class ChunkTupleAsyncStreamIterator:
53
+ def __init__(self, stream: "StreamReader") -> None:
54
+ self._stream = stream
55
+
56
+ def __aiter__(self) -> "ChunkTupleAsyncStreamIterator":
57
+ return self
58
+
59
+ async def __anext__(self) -> Tuple[bytes, bool]:
60
+ rv = await self._stream.readchunk()
61
+ if rv == (b"", False):
62
+ raise StopAsyncIteration
63
+ return rv
64
+
65
+
66
+ class AsyncStreamReaderMixin:
67
+ def __aiter__(self) -> AsyncStreamIterator[bytes]:
68
+ return AsyncStreamIterator(self.readline) # type: ignore[attr-defined]
69
+
70
+ def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]:
71
+ """Returns an asynchronous iterator that yields chunks of size n."""
72
+ return AsyncStreamIterator(lambda: self.read(n)) # type: ignore[attr-defined]
73
+
74
+ def iter_any(self) -> AsyncStreamIterator[bytes]:
75
+ """Yield all available data as soon as it is received."""
76
+ return AsyncStreamIterator(self.readany) # type: ignore[attr-defined]
77
+
78
+ def iter_chunks(self) -> ChunkTupleAsyncStreamIterator:
79
+ """Yield chunks of data as they are received by the server.
80
+
81
+ The yielded objects are tuples
82
+ of (bytes, bool) as returned by the StreamReader.readchunk method.
83
+ """
84
+ return ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-type]
85
+
86
+
87
+ class StreamReader(AsyncStreamReaderMixin):
88
+ """An enhancement of asyncio.StreamReader.
89
+
90
+ Supports asynchronous iteration by line, chunk or as available::
91
+
92
+ async for line in reader:
93
+ ...
94
+ async for chunk in reader.iter_chunked(1024):
95
+ ...
96
+ async for slice in reader.iter_any():
97
+ ...
98
+
99
+ """
100
+
101
+ total_bytes = 0
102
+
103
+ def __init__(
104
+ self,
105
+ protocol: BaseProtocol,
106
+ limit: int,
107
+ *,
108
+ timer: Optional[BaseTimerContext] = None,
109
+ loop: Optional[asyncio.AbstractEventLoop] = None,
110
+ ) -> None:
111
+ self._protocol = protocol
112
+ self._low_water = limit
113
+ self._high_water = limit * 2
114
+ if loop is None:
115
+ loop = asyncio.get_event_loop()
116
+ self._loop = loop
117
+ self._size = 0
118
+ self._cursor = 0
119
+ self._http_chunk_splits: Optional[List[int]] = None
120
+ self._buffer: Deque[bytes] = collections.deque()
121
+ self._buffer_offset = 0
122
+ self._eof = False
123
+ self._waiter: Optional[asyncio.Future[None]] = None
124
+ self._eof_waiter: Optional[asyncio.Future[None]] = None
125
+ self._exception: Optional[BaseException] = None
126
+ self._timer = TimerNoop() if timer is None else timer
127
+ self._eof_callbacks: List[Callable[[], None]] = []
128
+
129
+ def __repr__(self) -> str:
130
+ info = [self.__class__.__name__]
131
+ if self._size:
132
+ info.append("%d bytes" % self._size)
133
+ if self._eof:
134
+ info.append("eof")
135
+ if self._low_water != 2**16: # default limit
136
+ info.append("low=%d high=%d" % (self._low_water, self._high_water))
137
+ if self._waiter:
138
+ info.append("w=%r" % self._waiter)
139
+ if self._exception:
140
+ info.append("e=%r" % self._exception)
141
+ return "<%s>" % " ".join(info)
142
+
143
+ def get_read_buffer_limits(self) -> Tuple[int, int]:
144
+ return (self._low_water, self._high_water)
145
+
146
+ def exception(self) -> Optional[BaseException]:
147
+ return self._exception
148
+
149
+ def set_exception(self, exc: BaseException) -> None:
150
+ self._exception = exc
151
+ self._eof_callbacks.clear()
152
+
153
+ waiter = self._waiter
154
+ if waiter is not None:
155
+ self._waiter = None
156
+ set_exception(waiter, exc)
157
+
158
+ waiter = self._eof_waiter
159
+ if waiter is not None:
160
+ self._eof_waiter = None
161
+ set_exception(waiter, exc)
162
+
163
+ def on_eof(self, callback: Callable[[], None]) -> None:
164
+ if self._eof:
165
+ try:
166
+ callback()
167
+ except Exception:
168
+ internal_logger.exception("Exception in eof callback")
169
+ else:
170
+ self._eof_callbacks.append(callback)
171
+
172
+ def feed_eof(self) -> None:
173
+ self._eof = True
174
+
175
+ waiter = self._waiter
176
+ if waiter is not None:
177
+ self._waiter = None
178
+ set_result(waiter, None)
179
+
180
+ waiter = self._eof_waiter
181
+ if waiter is not None:
182
+ self._eof_waiter = None
183
+ set_result(waiter, None)
184
+
185
+ for cb in self._eof_callbacks:
186
+ try:
187
+ cb()
188
+ except Exception:
189
+ internal_logger.exception("Exception in eof callback")
190
+
191
+ self._eof_callbacks.clear()
192
+
193
+ def is_eof(self) -> bool:
194
+ """Return True if 'feed_eof' was called."""
195
+ return self._eof
196
+
197
+ def at_eof(self) -> bool:
198
+ """Return True if the buffer is empty and 'feed_eof' was called."""
199
+ return self._eof and not self._buffer
200
+
201
+ async def wait_eof(self) -> None:
202
+ if self._eof:
203
+ return
204
+
205
+ assert self._eof_waiter is None
206
+ self._eof_waiter = self._loop.create_future()
207
+ try:
208
+ await self._eof_waiter
209
+ finally:
210
+ self._eof_waiter = None
211
+
212
+ def unread_data(self, data: bytes) -> None:
213
+ """rollback reading some data from stream, inserting it to buffer head."""
214
+ warnings.warn(
215
+ "unread_data() is deprecated "
216
+ "and will be removed in future releases (#3260)",
217
+ DeprecationWarning,
218
+ stacklevel=2,
219
+ )
220
+ if not data:
221
+ return
222
+
223
+ if self._buffer_offset:
224
+ self._buffer[0] = self._buffer[0][self._buffer_offset :]
225
+ self._buffer_offset = 0
226
+ self._size += len(data)
227
+ self._cursor -= len(data)
228
+ self._buffer.appendleft(data)
229
+ self._eof_counter = 0
230
+
231
+ # TODO: size is ignored, remove the param later
232
+ def feed_data(self, data: bytes, size: int = 0) -> None:
233
+ assert not self._eof, "feed_data after feed_eof"
234
+
235
+ if not data:
236
+ return
237
+
238
+ self._size += len(data)
239
+ self._buffer.append(data)
240
+ self.total_bytes += len(data)
241
+
242
+ waiter = self._waiter
243
+ if waiter is not None:
244
+ self._waiter = None
245
+ set_result(waiter, None)
246
+
247
+ if self._size > self._high_water and not self._protocol._reading_paused:
248
+ self._protocol.pause_reading()
249
+
250
+ def begin_http_chunk_receiving(self) -> None:
251
+ if self._http_chunk_splits is None:
252
+ if self.total_bytes:
253
+ raise RuntimeError(
254
+ "Called begin_http_chunk_receiving when" "some data was already fed"
255
+ )
256
+ self._http_chunk_splits = []
257
+
258
+ def end_http_chunk_receiving(self) -> None:
259
+ if self._http_chunk_splits is None:
260
+ raise RuntimeError(
261
+ "Called end_chunk_receiving without calling "
262
+ "begin_chunk_receiving first"
263
+ )
264
+
265
+ # self._http_chunk_splits contains logical byte offsets from start of
266
+ # the body transfer. Each offset is the offset of the end of a chunk.
267
+ # "Logical" means bytes, accessible for a user.
268
+ # If no chunks containing logical data were received, current position
269
+ # is difinitely zero.
270
+ pos = self._http_chunk_splits[-1] if self._http_chunk_splits else 0
271
+
272
+ if self.total_bytes == pos:
273
+ # We should not add empty chunks here. So we check for that.
274
+ # Note, when chunked + gzip is used, we can receive a chunk
275
+ # of compressed data, but that data may not be enough for gzip FSM
276
+ # to yield any uncompressed data. That's why current position may
277
+ # not change after receiving a chunk.
278
+ return
279
+
280
+ self._http_chunk_splits.append(self.total_bytes)
281
+
282
+ # wake up readchunk when end of http chunk received
283
+ waiter = self._waiter
284
+ if waiter is not None:
285
+ self._waiter = None
286
+ set_result(waiter, None)
287
+
288
+ async def _wait(self, func_name: str) -> None:
289
+ # StreamReader uses a future to link the protocol feed_data() method
290
+ # to a read coroutine. Running two read coroutines at the same time
291
+ # would have an unexpected behaviour. It would not possible to know
292
+ # which coroutine would get the next data.
293
+ if self._waiter is not None:
294
+ raise RuntimeError(
295
+ "%s() called while another coroutine is "
296
+ "already waiting for incoming data" % func_name
297
+ )
298
+
299
+ waiter = self._waiter = self._loop.create_future()
300
+ try:
301
+ with self._timer:
302
+ await waiter
303
+ finally:
304
+ self._waiter = None
305
+
306
+ async def readline(self) -> bytes:
307
+ return await self.readuntil()
308
+
309
+ async def readuntil(self, separator: bytes = b"\n") -> bytes:
310
+ seplen = len(separator)
311
+ if seplen == 0:
312
+ raise ValueError("Separator should be at least one-byte string")
313
+
314
+ if self._exception is not None:
315
+ raise self._exception
316
+
317
+ chunk = b""
318
+ chunk_size = 0
319
+ not_enough = True
320
+
321
+ while not_enough:
322
+ while self._buffer and not_enough:
323
+ offset = self._buffer_offset
324
+ ichar = self._buffer[0].find(separator, offset) + 1
325
+ # Read from current offset to found separator or to the end.
326
+ data = self._read_nowait_chunk(
327
+ ichar - offset + seplen - 1 if ichar else -1
328
+ )
329
+ chunk += data
330
+ chunk_size += len(data)
331
+ if ichar:
332
+ not_enough = False
333
+
334
+ if chunk_size > self._high_water:
335
+ raise ValueError("Chunk too big")
336
+
337
+ if self._eof:
338
+ break
339
+
340
+ if not_enough:
341
+ await self._wait("readuntil")
342
+
343
+ return chunk
344
+
345
+ async def read(self, n: int = -1) -> bytes:
346
+ if self._exception is not None:
347
+ raise self._exception
348
+
349
+ # migration problem; with DataQueue you have to catch
350
+ # EofStream exception, so common way is to run payload.read() inside
351
+ # infinite loop. what can cause real infinite loop with StreamReader
352
+ # lets keep this code one major release.
353
+ if __debug__:
354
+ if self._eof and not self._buffer:
355
+ self._eof_counter = getattr(self, "_eof_counter", 0) + 1
356
+ if self._eof_counter > 5:
357
+ internal_logger.warning(
358
+ "Multiple access to StreamReader in eof state, "
359
+ "might be infinite loop.",
360
+ stack_info=True,
361
+ )
362
+
363
+ if not n:
364
+ return b""
365
+
366
+ if n < 0:
367
+ # This used to just loop creating a new waiter hoping to
368
+ # collect everything in self._buffer, but that would
369
+ # deadlock if the subprocess sends more than self.limit
370
+ # bytes. So just call self.readany() until EOF.
371
+ blocks = []
372
+ while True:
373
+ block = await self.readany()
374
+ if not block:
375
+ break
376
+ blocks.append(block)
377
+ return b"".join(blocks)
378
+
379
+ # TODO: should be `if` instead of `while`
380
+ # because waiter maybe triggered on chunk end,
381
+ # without feeding any data
382
+ while not self._buffer and not self._eof:
383
+ await self._wait("read")
384
+
385
+ return self._read_nowait(n)
386
+
387
+ async def readany(self) -> bytes:
388
+ if self._exception is not None:
389
+ raise self._exception
390
+
391
+ # TODO: should be `if` instead of `while`
392
+ # because waiter maybe triggered on chunk end,
393
+ # without feeding any data
394
+ while not self._buffer and not self._eof:
395
+ await self._wait("readany")
396
+
397
+ return self._read_nowait(-1)
398
+
399
+ async def readchunk(self) -> Tuple[bytes, bool]:
400
+ """Returns a tuple of (data, end_of_http_chunk).
401
+
402
+ When chunked transfer
403
+ encoding is used, end_of_http_chunk is a boolean indicating if the end
404
+ of the data corresponds to the end of a HTTP chunk , otherwise it is
405
+ always False.
406
+ """
407
+ while True:
408
+ if self._exception is not None:
409
+ raise self._exception
410
+
411
+ while self._http_chunk_splits:
412
+ pos = self._http_chunk_splits.pop(0)
413
+ if pos == self._cursor:
414
+ return (b"", True)
415
+ if pos > self._cursor:
416
+ return (self._read_nowait(pos - self._cursor), True)
417
+ internal_logger.warning(
418
+ "Skipping HTTP chunk end due to data "
419
+ "consumption beyond chunk boundary"
420
+ )
421
+
422
+ if self._buffer:
423
+ return (self._read_nowait_chunk(-1), False)
424
+ # return (self._read_nowait(-1), False)
425
+
426
+ if self._eof:
427
+ # Special case for signifying EOF.
428
+ # (b'', True) is not a final return value actually.
429
+ return (b"", False)
430
+
431
+ await self._wait("readchunk")
432
+
433
+ async def readexactly(self, n: int) -> bytes:
434
+ if self._exception is not None:
435
+ raise self._exception
436
+
437
+ blocks: List[bytes] = []
438
+ while n > 0:
439
+ block = await self.read(n)
440
+ if not block:
441
+ partial = b"".join(blocks)
442
+ raise asyncio.IncompleteReadError(partial, len(partial) + n)
443
+ blocks.append(block)
444
+ n -= len(block)
445
+
446
+ return b"".join(blocks)
447
+
448
+ def read_nowait(self, n: int = -1) -> bytes:
449
+ # default was changed to be consistent with .read(-1)
450
+ #
451
+ # I believe the most users don't know about the method and
452
+ # they are not affected.
453
+ if self._exception is not None:
454
+ raise self._exception
455
+
456
+ if self._waiter and not self._waiter.done():
457
+ raise RuntimeError(
458
+ "Called while some coroutine is waiting for incoming data."
459
+ )
460
+
461
+ return self._read_nowait(n)
462
+
463
+ def _read_nowait_chunk(self, n: int) -> bytes:
464
+ first_buffer = self._buffer[0]
465
+ offset = self._buffer_offset
466
+ if n != -1 and len(first_buffer) - offset > n:
467
+ data = first_buffer[offset : offset + n]
468
+ self._buffer_offset += n
469
+
470
+ elif offset:
471
+ self._buffer.popleft()
472
+ data = first_buffer[offset:]
473
+ self._buffer_offset = 0
474
+
475
+ else:
476
+ data = self._buffer.popleft()
477
+
478
+ self._size -= len(data)
479
+ self._cursor += len(data)
480
+
481
+ chunk_splits = self._http_chunk_splits
482
+ # Prevent memory leak: drop useless chunk splits
483
+ while chunk_splits and chunk_splits[0] < self._cursor:
484
+ chunk_splits.pop(0)
485
+
486
+ if self._size < self._low_water and self._protocol._reading_paused:
487
+ self._protocol.resume_reading()
488
+ return data
489
+
490
+ def _read_nowait(self, n: int) -> bytes:
491
+ """Read not more than n bytes, or whole buffer if n == -1"""
492
+ self._timer.assert_timeout()
493
+
494
+ chunks = []
495
+ while self._buffer:
496
+ chunk = self._read_nowait_chunk(n)
497
+ chunks.append(chunk)
498
+ if n != -1:
499
+ n -= len(chunk)
500
+ if n == 0:
501
+ break
502
+
503
+ return b"".join(chunks) if chunks else b""
504
+
505
+
506
+ class EmptyStreamReader(StreamReader): # lgtm [py/missing-call-to-init]
507
+ def __init__(self) -> None:
508
+ self._read_eof_chunk = False
509
+
510
+ def __repr__(self) -> str:
511
+ return "<%s>" % self.__class__.__name__
512
+
513
+ def exception(self) -> Optional[BaseException]:
514
+ return None
515
+
516
+ def set_exception(self, exc: BaseException) -> None:
517
+ pass
518
+
519
+ def on_eof(self, callback: Callable[[], None]) -> None:
520
+ try:
521
+ callback()
522
+ except Exception:
523
+ internal_logger.exception("Exception in eof callback")
524
+
525
+ def feed_eof(self) -> None:
526
+ pass
527
+
528
+ def is_eof(self) -> bool:
529
+ return True
530
+
531
+ def at_eof(self) -> bool:
532
+ return True
533
+
534
+ async def wait_eof(self) -> None:
535
+ return
536
+
537
+ def feed_data(self, data: bytes, n: int = 0) -> None:
538
+ pass
539
+
540
+ async def readline(self) -> bytes:
541
+ return b""
542
+
543
+ async def read(self, n: int = -1) -> bytes:
544
+ return b""
545
+
546
+ # TODO add async def readuntil
547
+
548
+ async def readany(self) -> bytes:
549
+ return b""
550
+
551
+ async def readchunk(self) -> Tuple[bytes, bool]:
552
+ if not self._read_eof_chunk:
553
+ self._read_eof_chunk = True
554
+ return (b"", False)
555
+
556
+ return (b"", True)
557
+
558
+ async def readexactly(self, n: int) -> bytes:
559
+ raise asyncio.IncompleteReadError(b"", n)
560
+
561
+ def read_nowait(self, n: int = -1) -> bytes:
562
+ return b""
563
+
564
+
565
+ EMPTY_PAYLOAD: Final[StreamReader] = EmptyStreamReader()
566
+
567
+
568
+ class DataQueue(Generic[_T]):
569
+ """DataQueue is a general-purpose blocking queue with one reader."""
570
+
571
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
572
+ self._loop = loop
573
+ self._eof = False
574
+ self._waiter: Optional[asyncio.Future[None]] = None
575
+ self._exception: Optional[BaseException] = None
576
+ self._size = 0
577
+ self._buffer: Deque[Tuple[_T, int]] = collections.deque()
578
+
579
+ def __len__(self) -> int:
580
+ return len(self._buffer)
581
+
582
+ def is_eof(self) -> bool:
583
+ return self._eof
584
+
585
+ def at_eof(self) -> bool:
586
+ return self._eof and not self._buffer
587
+
588
+ def exception(self) -> Optional[BaseException]:
589
+ return self._exception
590
+
591
+ def set_exception(self, exc: BaseException) -> None:
592
+ self._eof = True
593
+ self._exception = exc
594
+
595
+ waiter = self._waiter
596
+ if waiter is not None:
597
+ self._waiter = None
598
+ set_exception(waiter, exc)
599
+
600
+ def feed_data(self, data: _T, size: int = 0) -> None:
601
+ self._size += size
602
+ self._buffer.append((data, size))
603
+
604
+ waiter = self._waiter
605
+ if waiter is not None:
606
+ self._waiter = None
607
+ set_result(waiter, None)
608
+
609
+ def feed_eof(self) -> None:
610
+ self._eof = True
611
+
612
+ waiter = self._waiter
613
+ if waiter is not None:
614
+ self._waiter = None
615
+ set_result(waiter, None)
616
+
617
+ async def read(self) -> _T:
618
+ if not self._buffer and not self._eof:
619
+ assert not self._waiter
620
+ self._waiter = self._loop.create_future()
621
+ try:
622
+ await self._waiter
623
+ except (asyncio.CancelledError, asyncio.TimeoutError):
624
+ self._waiter = None
625
+ raise
626
+
627
+ if self._buffer:
628
+ data, size = self._buffer.popleft()
629
+ self._size -= size
630
+ return data
631
+ else:
632
+ if self._exception is not None:
633
+ raise self._exception
634
+ else:
635
+ raise EofStream
636
+
637
+ def __aiter__(self) -> AsyncStreamIterator[_T]:
638
+ return AsyncStreamIterator(self.read)
639
+
640
+
641
+ class FlowControlDataQueue(DataQueue[_T]):
642
+ """FlowControlDataQueue resumes and pauses an underlying stream.
643
+
644
+ It is a destination for parsed data.
645
+ """
646
+
647
+ def __init__(
648
+ self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop
649
+ ) -> None:
650
+ super().__init__(loop=loop)
651
+
652
+ self._protocol = protocol
653
+ self._limit = limit * 2
654
+
655
+ def feed_data(self, data: _T, size: int = 0) -> None:
656
+ super().feed_data(data, size)
657
+
658
+ if self._size > self._limit and not self._protocol._reading_paused:
659
+ self._protocol.pause_reading()
660
+
661
+ async def read(self) -> _T:
662
+ try:
663
+ return await super().read()
664
+ finally:
665
+ if self._size < self._limit and self._protocol._reading_paused:
666
+ self._protocol.resume_reading()
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/tcp_helpers.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helper methods to tune a TCP connection"""
2
+
3
+ import asyncio
4
+ import socket
5
+ from contextlib import suppress
6
+ from typing import Optional # noqa
7
+
8
+ __all__ = ("tcp_keepalive", "tcp_nodelay")
9
+
10
+
11
+ if hasattr(socket, "SO_KEEPALIVE"):
12
+
13
+ def tcp_keepalive(transport: asyncio.Transport) -> None:
14
+ sock = transport.get_extra_info("socket")
15
+ if sock is not None:
16
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
17
+
18
+ else:
19
+
20
+ def tcp_keepalive(transport: asyncio.Transport) -> None: # pragma: no cover
21
+ pass
22
+
23
+
24
+ def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None:
25
+ sock = transport.get_extra_info("socket")
26
+
27
+ if sock is None:
28
+ return
29
+
30
+ if sock.family not in (socket.AF_INET, socket.AF_INET6):
31
+ return
32
+
33
+ value = bool(value)
34
+
35
+ # socket may be closed already, on windows OSError get raised
36
+ with suppress(OSError):
37
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, value)
platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/test_utils.py ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities shared by tests."""
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import gc
6
+ import inspect
7
+ import ipaddress
8
+ import os
9
+ import socket
10
+ import sys
11
+ import warnings
12
+ from abc import ABC, abstractmethod
13
+ from types import TracebackType
14
+ from typing import (
15
+ TYPE_CHECKING,
16
+ Any,
17
+ Callable,
18
+ Iterator,
19
+ List,
20
+ Optional,
21
+ Type,
22
+ Union,
23
+ cast,
24
+ )
25
+ from unittest import IsolatedAsyncioTestCase, mock
26
+
27
+ from aiosignal import Signal
28
+ from multidict import CIMultiDict, CIMultiDictProxy
29
+ from yarl import URL
30
+
31
+ import aiohttp
32
+ from aiohttp.client import _RequestContextManager, _WSRequestContextManager
33
+
34
+ from . import ClientSession, hdrs
35
+ from .abc import AbstractCookieJar
36
+ from .client_reqrep import ClientResponse
37
+ from .client_ws import ClientWebSocketResponse
38
+ from .helpers import sentinel
39
+ from .http import HttpVersion, RawRequestMessage
40
+ from .typedefs import StrOrURL
41
+ from .web import (
42
+ Application,
43
+ AppRunner,
44
+ BaseRunner,
45
+ Request,
46
+ Server,
47
+ ServerRunner,
48
+ SockSite,
49
+ UrlMappingMatchInfo,
50
+ )
51
+ from .web_protocol import _RequestHandler
52
+
53
+ if TYPE_CHECKING: # pragma: no cover
54
+ from ssl import SSLContext
55
+ else:
56
+ SSLContext = None
57
+
58
+ REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin"
59
+
60
+
61
+ def get_unused_port_socket(
62
+ host: str, family: socket.AddressFamily = socket.AF_INET
63
+ ) -> socket.socket:
64
+ return get_port_socket(host, 0, family)
65
+
66
+
67
+ def get_port_socket(
68
+ host: str, port: int, family: socket.AddressFamily
69
+ ) -> socket.socket:
70
+ s = socket.socket(family, socket.SOCK_STREAM)
71
+ if REUSE_ADDRESS:
72
+ # Windows has different semantics for SO_REUSEADDR,
73
+ # so don't set it. Ref:
74
+ # https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
75
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
76
+ s.bind((host, port))
77
+ return s
78
+
79
+
80
+ def unused_port() -> int:
81
+ """Return a port that is unused on the current host."""
82
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
83
+ s.bind(("127.0.0.1", 0))
84
+ return cast(int, s.getsockname()[1])
85
+
86
+
87
+ class BaseTestServer(ABC):
88
+ __test__ = False
89
+
90
+ def __init__(
91
+ self,
92
+ *,
93
+ scheme: Union[str, object] = sentinel,
94
+ loop: Optional[asyncio.AbstractEventLoop] = None,
95
+ host: str = "127.0.0.1",
96
+ port: Optional[int] = None,
97
+ skip_url_asserts: bool = False,
98
+ socket_factory: Callable[
99
+ [str, int, socket.AddressFamily], socket.socket
100
+ ] = get_port_socket,
101
+ **kwargs: Any,
102
+ ) -> None:
103
+ self._loop = loop
104
+ self.runner: Optional[BaseRunner] = None
105
+ self._root: Optional[URL] = None
106
+ self.host = host
107
+ self.port = port
108
+ self._closed = False
109
+ self.scheme = scheme
110
+ self.skip_url_asserts = skip_url_asserts
111
+ self.socket_factory = socket_factory
112
+
113
+ async def start_server(
114
+ self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any
115
+ ) -> None:
116
+ if self.runner:
117
+ return
118
+ self._loop = loop
119
+ self._ssl = kwargs.pop("ssl", None)
120
+ self.runner = await self._make_runner(handler_cancellation=True, **kwargs)
121
+ await self.runner.setup()
122
+ if not self.port:
123
+ self.port = 0
124
+ try:
125
+ version = ipaddress.ip_address(self.host).version
126
+ except ValueError:
127
+ version = 4
128
+ family = socket.AF_INET6 if version == 6 else socket.AF_INET
129
+ _sock = self.socket_factory(self.host, self.port, family)
130
+ self.host, self.port = _sock.getsockname()[:2]
131
+ site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl)
132
+ await site.start()
133
+ server = site._server
134
+ assert server is not None
135
+ sockets = server.sockets # type: ignore[attr-defined]
136
+ assert sockets is not None
137
+ self.port = sockets[0].getsockname()[1]
138
+ if self.scheme is sentinel:
139
+ if self._ssl:
140
+ scheme = "https"
141
+ else:
142
+ scheme = "http"
143
+ self.scheme = scheme
144
+ self._root = URL(f"{self.scheme}://{self.host}:{self.port}")
145
+
146
+ @abstractmethod # pragma: no cover
147
+ async def _make_runner(self, **kwargs: Any) -> BaseRunner:
148
+ pass
149
+
150
+ def make_url(self, path: StrOrURL) -> URL:
151
+ assert self._root is not None
152
+ url = URL(path)
153
+ if not self.skip_url_asserts:
154
+ assert not url.is_absolute()
155
+ return self._root.join(url)
156
+ else:
157
+ return URL(str(self._root) + str(path))
158
+
159
+ @property
160
+ def started(self) -> bool:
161
+ return self.runner is not None
162
+
163
+ @property
164
+ def closed(self) -> bool:
165
+ return self._closed
166
+
167
+ @property
168
+ def handler(self) -> Server:
169
+ # for backward compatibility
170
+ # web.Server instance
171
+ runner = self.runner
172
+ assert runner is not None
173
+ assert runner.server is not None
174
+ return runner.server
175
+
176
+ async def close(self) -> None:
177
+ """Close all fixtures created by the test client.
178
+
179
+ After that point, the TestClient is no longer usable.
180
+
181
+ This is an idempotent function: running close multiple times
182
+ will not have any additional effects.
183
+
184
+ close is also run when the object is garbage collected, and on
185
+ exit when used as a context manager.
186
+
187
+ """
188
+ if self.started and not self.closed:
189
+ assert self.runner is not None
190
+ await self.runner.cleanup()
191
+ self._root = None
192
+ self.port = None
193
+ self._closed = True
194
+
195
+ def __enter__(self) -> None:
196
+ raise TypeError("Use async with instead")
197
+
198
+ def __exit__(
199
+ self,
200
+ exc_type: Optional[Type[BaseException]],
201
+ exc_value: Optional[BaseException],
202
+ traceback: Optional[TracebackType],
203
+ ) -> None:
204
+ # __exit__ should exist in pair with __enter__ but never executed
205
+ pass # pragma: no cover
206
+
207
+ async def __aenter__(self) -> "BaseTestServer":
208
+ await self.start_server(loop=self._loop)
209
+ return self
210
+
211
+ async def __aexit__(
212
+ self,
213
+ exc_type: Optional[Type[BaseException]],
214
+ exc_value: Optional[BaseException],
215
+ traceback: Optional[TracebackType],
216
+ ) -> None:
217
+ await self.close()
218
+
219
+
220
+ class TestServer(BaseTestServer):
221
+ def __init__(
222
+ self,
223
+ app: Application,
224
+ *,
225
+ scheme: Union[str, object] = sentinel,
226
+ host: str = "127.0.0.1",
227
+ port: Optional[int] = None,
228
+ **kwargs: Any,
229
+ ):
230
+ self.app = app
231
+ super().__init__(scheme=scheme, host=host, port=port, **kwargs)
232
+
233
+ async def _make_runner(self, **kwargs: Any) -> BaseRunner:
234
+ return AppRunner(self.app, **kwargs)
235
+
236
+
237
+ class RawTestServer(BaseTestServer):
238
+ def __init__(
239
+ self,
240
+ handler: _RequestHandler,
241
+ *,
242
+ scheme: Union[str, object] = sentinel,
243
+ host: str = "127.0.0.1",
244
+ port: Optional[int] = None,
245
+ **kwargs: Any,
246
+ ) -> None:
247
+ self._handler = handler
248
+ super().__init__(scheme=scheme, host=host, port=port, **kwargs)
249
+
250
+ async def _make_runner(self, debug: bool = True, **kwargs: Any) -> ServerRunner:
251
+ srv = Server(self._handler, loop=self._loop, debug=debug, **kwargs)
252
+ return ServerRunner(srv, debug=debug, **kwargs)
253
+
254
+
255
+ class TestClient:
256
+ """
257
+ A test client implementation.
258
+
259
+ To write functional tests for aiohttp based servers.
260
+
261
+ """
262
+
263
+ __test__ = False
264
+
265
+ def __init__(
266
+ self,
267
+ server: BaseTestServer,
268
+ *,
269
+ cookie_jar: Optional[AbstractCookieJar] = None,
270
+ loop: Optional[asyncio.AbstractEventLoop] = None,
271
+ **kwargs: Any,
272
+ ) -> None:
273
+ if not isinstance(server, BaseTestServer):
274
+ raise TypeError(
275
+ "server must be TestServer " "instance, found type: %r" % type(server)
276
+ )
277
+ self._server = server
278
+ self._loop = loop
279
+ if cookie_jar is None:
280
+ cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop)
281
+ self._session = ClientSession(loop=loop, cookie_jar=cookie_jar, **kwargs)
282
+ self._closed = False
283
+ self._responses: List[ClientResponse] = []
284
+ self._websockets: List[ClientWebSocketResponse] = []
285
+
286
+ async def start_server(self) -> None:
287
+ await self._server.start_server(loop=self._loop)
288
+
289
+ @property
290
+ def host(self) -> str:
291
+ return self._server.host
292
+
293
+ @property
294
+ def port(self) -> Optional[int]:
295
+ return self._server.port
296
+
297
+ @property
298
+ def server(self) -> BaseTestServer:
299
+ return self._server
300
+
301
+ @property
302
+ def app(self) -> Optional[Application]:
303
+ return cast(Optional[Application], getattr(self._server, "app", None))
304
+
305
+ @property
306
+ def session(self) -> ClientSession:
307
+ """An internal aiohttp.ClientSession.
308
+
309
+ Unlike the methods on the TestClient, client session requests
310
+ do not automatically include the host in the url queried, and
311
+ will require an absolute path to the resource.
312
+
313
+ """
314
+ return self._session
315
+
316
+ def make_url(self, path: StrOrURL) -> URL:
317
+ return self._server.make_url(path)
318
+
319
+ async def _request(
320
+ self, method: str, path: StrOrURL, **kwargs: Any
321
+ ) -> ClientResponse:
322
+ resp = await self._session.request(method, self.make_url(path), **kwargs)
323
+ # save it to close later
324
+ self._responses.append(resp)
325
+ return resp
326
+
327
+ def request(
328
+ self, method: str, path: StrOrURL, **kwargs: Any
329
+ ) -> _RequestContextManager:
330
+ """Routes a request to tested http server.
331
+
332
+ The interface is identical to aiohttp.ClientSession.request,
333
+ except the loop kwarg is overridden by the instance used by the
334
+ test server.
335
+
336
+ """
337
+ return _RequestContextManager(self._request(method, path, **kwargs))
338
+
339
+ def get(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
340
+ """Perform an HTTP GET request."""
341
+ return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs))
342
+
343
+ def post(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
344
+ """Perform an HTTP POST request."""
345
+ return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs))
346
+
347
+ def options(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
348
+ """Perform an HTTP OPTIONS request."""
349
+ return _RequestContextManager(self._request(hdrs.METH_OPTIONS, path, **kwargs))
350
+
351
+ def head(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
352
+ """Perform an HTTP HEAD request."""
353
+ return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs))
354
+
355
+ def put(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
356
+ """Perform an HTTP PUT request."""
357
+ return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs))
358
+
359
+ def patch(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
360
+ """Perform an HTTP PATCH request."""
361
+ return _RequestContextManager(self._request(hdrs.METH_PATCH, path, **kwargs))
362
+
363
+ def delete(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager:
364
+ """Perform an HTTP PATCH request."""
365
+ return _RequestContextManager(self._request(hdrs.METH_DELETE, path, **kwargs))
366
+
367
+ def ws_connect(self, path: StrOrURL, **kwargs: Any) -> _WSRequestContextManager:
368
+ """Initiate websocket connection.
369
+
370
+ The api corresponds to aiohttp.ClientSession.ws_connect.
371
+
372
+ """
373
+ return _WSRequestContextManager(self._ws_connect(path, **kwargs))
374
+
375
+ async def _ws_connect(
376
+ self, path: StrOrURL, **kwargs: Any
377
+ ) -> ClientWebSocketResponse:
378
+ ws = await self._session.ws_connect(self.make_url(path), **kwargs)
379
+ self._websockets.append(ws)
380
+ return ws
381
+
382
+ async def close(self) -> None:
383
+ """Close all fixtures created by the test client.
384
+
385
+ After that point, the TestClient is no longer usable.
386
+
387
+ This is an idempotent function: running close multiple times
388
+ will not have any additional effects.
389
+
390
+ close is also run on exit when used as a(n) (asynchronous)
391
+ context manager.
392
+
393
+ """
394
+ if not self._closed:
395
+ for resp in self._responses:
396
+ resp.close()
397
+ for ws in self._websockets:
398
+ await ws.close()
399
+ await self._session.close()
400
+ await self._server.close()
401
+ self._closed = True
402
+
403
+ def __enter__(self) -> None:
404
+ raise TypeError("Use async with instead")
405
+
406
+ def __exit__(
407
+ self,
408
+ exc_type: Optional[Type[BaseException]],
409
+ exc: Optional[BaseException],
410
+ tb: Optional[TracebackType],
411
+ ) -> None:
412
+ # __exit__ should exist in pair with __enter__ but never executed
413
+ pass # pragma: no cover
414
+
415
+ async def __aenter__(self) -> "TestClient":
416
+ await self.start_server()
417
+ return self
418
+
419
+ async def __aexit__(
420
+ self,
421
+ exc_type: Optional[Type[BaseException]],
422
+ exc: Optional[BaseException],
423
+ tb: Optional[TracebackType],
424
+ ) -> None:
425
+ await self.close()
426
+
427
+
428
+ class AioHTTPTestCase(IsolatedAsyncioTestCase):
429
+ """A base class to allow for unittest web applications using aiohttp.
430
+
431
+ Provides the following:
432
+
433
+ * self.client (aiohttp.test_utils.TestClient): an aiohttp test client.
434
+ * self.loop (asyncio.BaseEventLoop): the event loop in which the
435
+ application and server are running.
436
+ * self.app (aiohttp.web.Application): the application returned by
437
+ self.get_application()
438
+
439
+ Note that the TestClient's methods are asynchronous: you have to
440
+ execute function on the test client using asynchronous methods.
441
+ """
442
+
443
+ async def get_application(self) -> Application:
444
+ """Get application.
445
+
446
+ This method should be overridden
447
+ to return the aiohttp.web.Application
448
+ object to test.
449
+ """
450
+ return self.get_app()
451
+
452
+ def get_app(self) -> Application:
453
+ """Obsolete method used to constructing web application.
454
+
455
+ Use .get_application() coroutine instead.
456
+ """
457
+ raise RuntimeError("Did you forget to define get_application()?")
458
+
459
+ async def asyncSetUp(self) -> None:
460
+ self.loop = asyncio.get_running_loop()
461
+ return await self.setUpAsync()
462
+
463
+ async def setUpAsync(self) -> None:
464
+ self.app = await self.get_application()
465
+ self.server = await self.get_server(self.app)
466
+ self.client = await self.get_client(self.server)
467
+
468
+ await self.client.start_server()
469
+
470
+ async def asyncTearDown(self) -> None:
471
+ return await self.tearDownAsync()
472
+
473
+ async def tearDownAsync(self) -> None:
474
+ await self.client.close()
475
+
476
+ async def get_server(self, app: Application) -> TestServer:
477
+ """Return a TestServer instance."""
478
+ return TestServer(app, loop=self.loop)
479
+
480
+ async def get_client(self, server: TestServer) -> TestClient:
481
+ """Return a TestClient instance."""
482
+ return TestClient(server, loop=self.loop)
483
+
484
+
485
+ def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any:
486
+ """
487
+ A decorator dedicated to use with asynchronous AioHTTPTestCase test methods.
488
+
489
+ In 3.8+, this does nothing.
490
+ """
491
+ warnings.warn(
492
+ "Decorator `@unittest_run_loop` is no longer needed in aiohttp 3.8+",
493
+ DeprecationWarning,
494
+ stacklevel=2,
495
+ )
496
+ return func
497
+
498
+
499
+ _LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop]
500
+
501
+
502
+ @contextlib.contextmanager
503
+ def loop_context(
504
+ loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False
505
+ ) -> Iterator[asyncio.AbstractEventLoop]:
506
+ """A contextmanager that creates an event_loop, for test purposes.
507
+
508
+ Handles the creation and cleanup of a test loop.
509
+ """
510
+ loop = setup_test_loop(loop_factory)
511
+ yield loop
512
+ teardown_test_loop(loop, fast=fast)
513
+
514
+
515
+ def setup_test_loop(
516
+ loop_factory: _LOOP_FACTORY = asyncio.new_event_loop,
517
+ ) -> asyncio.AbstractEventLoop:
518
+ """Create and return an asyncio.BaseEventLoop instance.
519
+
520
+ The caller should also call teardown_test_loop,
521
+ once they are done with the loop.
522
+ """
523
+ loop = loop_factory()
524
+ asyncio.set_event_loop(loop)
525
+ return loop
526
+
527
+
528
+ def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None:
529
+ """Teardown and cleanup an event_loop created by setup_test_loop."""
530
+ closed = loop.is_closed()
531
+ if not closed:
532
+ loop.call_soon(loop.stop)
533
+ loop.run_forever()
534
+ loop.close()
535
+
536
+ if not fast:
537
+ gc.collect()
538
+
539
+ asyncio.set_event_loop(None)
540
+
541
+
542
+ def _create_app_mock() -> mock.MagicMock:
543
+ def get_dict(app: Any, key: str) -> Any:
544
+ return app.__app_dict[key]
545
+
546
+ def set_dict(app: Any, key: str, value: Any) -> None:
547
+ app.__app_dict[key] = value
548
+
549
+ app = mock.MagicMock(spec=Application)
550
+ app.__app_dict = {}
551
+ app.__getitem__ = get_dict
552
+ app.__setitem__ = set_dict
553
+
554
+ app._debug = False
555
+ app.on_response_prepare = Signal(app)
556
+ app.on_response_prepare.freeze()
557
+ return app
558
+
559
+
560
+ def _create_transport(sslcontext: Optional[SSLContext] = None) -> mock.Mock:
561
+ transport = mock.Mock()
562
+
563
+ def get_extra_info(key: str) -> Optional[SSLContext]:
564
+ if key == "sslcontext":
565
+ return sslcontext
566
+ else:
567
+ return None
568
+
569
+ transport.get_extra_info.side_effect = get_extra_info
570
+ return transport
571
+
572
+
573
+ def make_mocked_request(
574
+ method: str,
575
+ path: str,
576
+ headers: Any = None,
577
+ *,
578
+ match_info: Any = sentinel,
579
+ version: HttpVersion = HttpVersion(1, 1),
580
+ closing: bool = False,
581
+ app: Any = None,
582
+ writer: Any = sentinel,
583
+ protocol: Any = sentinel,
584
+ transport: Any = sentinel,
585
+ payload: Any = sentinel,
586
+ sslcontext: Optional[SSLContext] = None,
587
+ client_max_size: int = 1024**2,
588
+ loop: Any = ...,
589
+ ) -> Request:
590
+ """Creates mocked web.Request testing purposes.
591
+
592
+ Useful in unit tests, when spinning full web server is overkill or
593
+ specific conditions and errors are hard to trigger.
594
+ """
595
+ task = mock.Mock()
596
+ if loop is ...:
597
+ loop = mock.Mock()
598
+ loop.create_future.return_value = ()
599
+
600
+ if version < HttpVersion(1, 1):
601
+ closing = True
602
+
603
+ if headers:
604
+ headers = CIMultiDictProxy(CIMultiDict(headers))
605
+ raw_hdrs = tuple(
606
+ (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items()
607
+ )
608
+ else:
609
+ headers = CIMultiDictProxy(CIMultiDict())
610
+ raw_hdrs = ()
611
+
612
+ chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower()
613
+
614
+ message = RawRequestMessage(
615
+ method,
616
+ path,
617
+ version,
618
+ headers,
619
+ raw_hdrs,
620
+ closing,
621
+ None,
622
+ False,
623
+ chunked,
624
+ URL(path),
625
+ )
626
+ if app is None:
627
+ app = _create_app_mock()
628
+
629
+ if transport is sentinel:
630
+ transport = _create_transport(sslcontext)
631
+
632
+ if protocol is sentinel:
633
+ protocol = mock.Mock()
634
+ protocol.transport = transport
635
+
636
+ if writer is sentinel:
637
+ writer = mock.Mock()
638
+ writer.write_headers = make_mocked_coro(None)
639
+ writer.write = make_mocked_coro(None)
640
+ writer.write_eof = make_mocked_coro(None)
641
+ writer.drain = make_mocked_coro(None)
642
+ writer.transport = transport
643
+
644
+ protocol.transport = transport
645
+ protocol.writer = writer
646
+
647
+ if payload is sentinel:
648
+ payload = mock.Mock()
649
+
650
+ req = Request(
651
+ message, payload, protocol, writer, task, loop, client_max_size=client_max_size
652
+ )
653
+
654
+ match_info = UrlMappingMatchInfo(
655
+ {} if match_info is sentinel else match_info, mock.Mock()
656
+ )
657
+ match_info.add_app(app)
658
+ req._match_info = match_info
659
+
660
+ return req
661
+
662
+
663
+ def make_mocked_coro(
664
+ return_value: Any = sentinel, raise_exception: Any = sentinel
665
+ ) -> Any:
666
+ """Creates a coroutine mock."""
667
+
668
+ async def mock_coro(*args: Any, **kwargs: Any) -> Any:
669
+ if raise_exception is not sentinel:
670
+ raise raise_exception
671
+ if not inspect.isawaitable(return_value):
672
+ return return_value
673
+ await return_value
674
+
675
+ return mock.Mock(wraps=mock_coro)