FaustDerLegende commited on
Commit
f09ed9c
·
verified ·
1 Parent(s): b9c46f7

Upload folder using huggingface_hub (part 3)

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 +36 -0
  2. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/INSTALLER +1 -0
  3. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/METADATA +108 -0
  4. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/RECORD +100 -0
  5. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/WHEEL +5 -0
  6. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/entry_points.txt +2 -0
  7. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/licenses/LICENSE +20 -0
  8. .venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/top_level.txt +1 -0
  9. .venv/lib/python3.12/site-packages/anyio/abc/_resources.py +39 -0
  10. .venv/lib/python3.12/site-packages/anyio/abc/_sockets.py +401 -0
  11. .venv/lib/python3.12/site-packages/anyio/abc/_streams.py +237 -0
  12. .venv/lib/python3.12/site-packages/anyio/abc/_subprocesses.py +82 -0
  13. .venv/lib/python3.12/site-packages/anyio/abc/_tasks.py +223 -0
  14. .venv/lib/python3.12/site-packages/anyio/abc/_testing.py +79 -0
  15. .venv/lib/python3.12/site-packages/anyio/from_thread.py +588 -0
  16. .venv/lib/python3.12/site-packages/anyio/functools.py +400 -0
  17. .venv/lib/python3.12/site-packages/anyio/itertools.py +629 -0
  18. .venv/lib/python3.12/site-packages/anyio/lowlevel.py +228 -0
  19. .venv/lib/python3.12/site-packages/anyio/py.typed +0 -0
  20. .venv/lib/python3.12/site-packages/anyio/pytest_plugin.py +404 -0
  21. .venv/lib/python3.12/site-packages/anyio/streams/__init__.py +0 -0
  22. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312-pytest-9.1.1.pyc +0 -0
  23. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc +0 -0
  24. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/buffered.cpython-312.pyc +0 -0
  25. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/file.cpython-312.pyc +0 -0
  26. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312-pytest-9.1.1.pyc +0 -0
  27. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc +0 -0
  28. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312-pytest-9.1.1.pyc +0 -0
  29. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc +0 -0
  30. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/text.cpython-312.pyc +0 -0
  31. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312-pytest-9.1.1.pyc +0 -0
  32. .venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc +0 -0
  33. .venv/lib/python3.12/site-packages/anyio/streams/buffered.py +201 -0
  34. .venv/lib/python3.12/site-packages/anyio/streams/file.py +157 -0
  35. .venv/lib/python3.12/site-packages/anyio/streams/memory.py +326 -0
  36. .venv/lib/python3.12/site-packages/anyio/streams/stapled.py +160 -0
  37. .venv/lib/python3.12/site-packages/anyio/streams/text.py +176 -0
  38. .venv/lib/python3.12/site-packages/anyio/streams/tls.py +436 -0
  39. .venv/lib/python3.12/site-packages/anyio/to_interpreter.py +246 -0
  40. .venv/lib/python3.12/site-packages/anyio/to_process.py +269 -0
  41. .venv/lib/python3.12/site-packages/anyio/to_thread.py +80 -0
  42. .venv/lib/python3.12/site-packages/av/__init__.pxd +0 -0
  43. .venv/lib/python3.12/site-packages/av/__init__.py +73 -0
  44. .venv/lib/python3.12/site-packages/av/__main__.py +54 -0
  45. .venv/lib/python3.12/site-packages/av/__pycache__/__init__.cpython-312.pyc +0 -0
  46. .venv/lib/python3.12/site-packages/av/__pycache__/__main__.cpython-312.pyc +0 -0
  47. .venv/lib/python3.12/site-packages/av/__pycache__/_core.cpython-312.pyc +0 -0
  48. .venv/lib/python3.12/site-packages/av/__pycache__/about.cpython-312.pyc +0 -0
  49. .venv/lib/python3.12/site-packages/av/__pycache__/bitstream.cpython-312.pyc +0 -0
  50. .venv/lib/python3.12/site-packages/av/__pycache__/buffer.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -73,3 +73,39 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
73
  .venv/lib/python3.12/site-packages/_polars_runtime_32/_polars_runtime.abi3.so filter=lfs diff=lfs merge=lfs -text
74
  .venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312-pytest-9.1.1.pyc filter=lfs diff=lfs merge=lfs -text
75
  .venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  .venv/lib/python3.12/site-packages/_polars_runtime_32/_polars_runtime.abi3.so filter=lfs diff=lfs merge=lfs -text
74
  .venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312-pytest-9.1.1.pyc filter=lfs diff=lfs merge=lfs -text
75
  .venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
76
+ .venv/lib/python3.12/site-packages/av/_core.abi3.so filter=lfs diff=lfs merge=lfs -text
77
+ .venv/lib/python3.12/site-packages/av/audio/codeccontext.abi3.so filter=lfs diff=lfs merge=lfs -text
78
+ .venv/lib/python3.12/site-packages/av/audio/fifo.abi3.so filter=lfs diff=lfs merge=lfs -text
79
+ .venv/lib/python3.12/site-packages/av/audio/format.abi3.so filter=lfs diff=lfs merge=lfs -text
80
+ .venv/lib/python3.12/site-packages/av/audio/frame.abi3.so filter=lfs diff=lfs merge=lfs -text
81
+ .venv/lib/python3.12/site-packages/av/audio/layout.abi3.so filter=lfs diff=lfs merge=lfs -text
82
+ .venv/lib/python3.12/site-packages/av/audio/plane.abi3.so filter=lfs diff=lfs merge=lfs -text
83
+ .venv/lib/python3.12/site-packages/av/audio/resampler.abi3.so filter=lfs diff=lfs merge=lfs -text
84
+ .venv/lib/python3.12/site-packages/av/audio/stream.abi3.so filter=lfs diff=lfs merge=lfs -text
85
+ .venv/lib/python3.12/site-packages/av/bitstream.abi3.so filter=lfs diff=lfs merge=lfs -text
86
+ .venv/lib/python3.12/site-packages/av/buffer.abi3.so filter=lfs diff=lfs merge=lfs -text
87
+ .venv/lib/python3.12/site-packages/av/codec/codec.abi3.so filter=lfs diff=lfs merge=lfs -text
88
+ .venv/lib/python3.12/site-packages/av/codec/context.abi3.so filter=lfs diff=lfs merge=lfs -text
89
+ .venv/lib/python3.12/site-packages/av/codec/hwaccel.abi3.so filter=lfs diff=lfs merge=lfs -text
90
+ .venv/lib/python3.12/site-packages/av/container/core.abi3.so filter=lfs diff=lfs merge=lfs -text
91
+ .venv/lib/python3.12/site-packages/av/container/input.abi3.so filter=lfs diff=lfs merge=lfs -text
92
+ .venv/lib/python3.12/site-packages/av/container/output.abi3.so filter=lfs diff=lfs merge=lfs -text
93
+ .venv/lib/python3.12/site-packages/av/container/pyio.abi3.so filter=lfs diff=lfs merge=lfs -text
94
+ .venv/lib/python3.12/site-packages/av/container/streams.abi3.so filter=lfs diff=lfs merge=lfs -text
95
+ .venv/lib/python3.12/site-packages/av/device.abi3.so filter=lfs diff=lfs merge=lfs -text
96
+ .venv/lib/python3.12/site-packages/av/dictionary.abi3.so filter=lfs diff=lfs merge=lfs -text
97
+ .venv/lib/python3.12/site-packages/av/error.abi3.so filter=lfs diff=lfs merge=lfs -text
98
+ .venv/lib/python3.12/site-packages/av/filter/context.abi3.so filter=lfs diff=lfs merge=lfs -text
99
+ .venv/lib/python3.12/site-packages/av/filter/filter.abi3.so filter=lfs diff=lfs merge=lfs -text
100
+ .venv/lib/python3.12/site-packages/av/filter/graph.abi3.so filter=lfs diff=lfs merge=lfs -text
101
+ .venv/lib/python3.12/site-packages/av/filter/link.abi3.so filter=lfs diff=lfs merge=lfs -text
102
+ .venv/lib/python3.12/site-packages/av/filter/loudnorm.abi3.so filter=lfs diff=lfs merge=lfs -text
103
+ .venv/lib/python3.12/site-packages/av/format.abi3.so filter=lfs diff=lfs merge=lfs -text
104
+ .venv/lib/python3.12/site-packages/av/frame.abi3.so filter=lfs diff=lfs merge=lfs -text
105
+ .venv/lib/python3.12/site-packages/av/index.abi3.so filter=lfs diff=lfs merge=lfs -text
106
+ .venv/lib/python3.12/site-packages/av/logging.abi3.so filter=lfs diff=lfs merge=lfs -text
107
+ .venv/lib/python3.12/site-packages/av/opaque.abi3.so filter=lfs diff=lfs merge=lfs -text
108
+ .venv/lib/python3.12/site-packages/av/packet.abi3.so filter=lfs diff=lfs merge=lfs -text
109
+ .venv/lib/python3.12/site-packages/av/plane.abi3.so filter=lfs diff=lfs merge=lfs -text
110
+ .venv/lib/python3.12/site-packages/av/rational.abi3.so filter=lfs diff=lfs merge=lfs -text
111
+ .venv/lib/python3.12/site-packages/av/sidedata/encparams.abi3.so filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/METADATA ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: anyio
3
+ Version: 4.15.1
4
+ Summary: High-level concurrency and networking framework on top of asyncio or Trio
5
+ Author-email: Alex Grönholm <alex.gronholm@nextday.fi>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/
8
+ Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html
9
+ Project-URL: Source code, https://github.com/agronholm/anyio
10
+ Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Framework :: AnyIO
14
+ Classifier: Typing :: Typed
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/x-rst
26
+ License-File: LICENSE
27
+ Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11"
28
+ Requires-Dist: idna>=2.8
29
+ Requires-Dist: typing_extensions>=4.16.0; python_version < "3.15"
30
+ Provides-Extra: trio
31
+ Requires-Dist: trio>=0.32.0; extra == "trio"
32
+ Dynamic: license-file
33
+
34
+ .. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg
35
+ :target: https://github.com/agronholm/anyio/actions/workflows/test.yml
36
+ :alt: Build Status
37
+ .. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master
38
+ :target: https://coveralls.io/github/agronholm/anyio?branch=master
39
+ :alt: Code Coverage
40
+ .. image:: https://readthedocs.org/projects/anyio/badge/?version=latest
41
+ :target: https://anyio.readthedocs.io/en/latest/?badge=latest
42
+ :alt: Documentation
43
+ .. image:: https://badges.gitter.im/gitterHQ/gitter.svg
44
+ :target: https://gitter.im/python-trio/AnyIO
45
+ :alt: Gitter chat
46
+ .. image:: https://tidelift.com/badges/package/pypi/anyio
47
+ :target: https://tidelift.com/subscription/pkg/pypi-anyio
48
+ :alt: Tidelift
49
+
50
+ AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or
51
+ Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony
52
+ with the native SC of Trio itself.
53
+
54
+ Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or
55
+ Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full
56
+ refactoring necessary. It will blend in with the native libraries of your chosen backend.
57
+
58
+ To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it
59
+ `here <https://anyio.readthedocs.io/en/stable/why.html>`_.
60
+
61
+ Documentation
62
+ -------------
63
+
64
+ View full documentation at: https://anyio.readthedocs.io/
65
+
66
+ Features
67
+ --------
68
+
69
+ AnyIO offers the following functionality:
70
+
71
+ * Task groups (nurseries_ in trio terminology)
72
+ * High-level networking (TCP, UDP and UNIX sockets)
73
+
74
+ * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python
75
+ 3.8)
76
+ * async/await style UDP sockets (unlike asyncio where you still have to use Transports and
77
+ Protocols)
78
+
79
+ * A versatile API for byte streams and object streams
80
+ * Inter-task synchronization and communication (locks, conditions, events, semaphores, object
81
+ streams and futures)
82
+ * Worker threads
83
+ * Subprocesses
84
+ * Subinterpreter support for code parallelization (on Python 3.13 and later)
85
+ * Asynchronous file I/O (using worker threads)
86
+ * Signal handling
87
+ * Asynchronous versions of the functools_ and itertools_ modules
88
+
89
+ AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures.
90
+ It even works with the popular Hypothesis_ library.
91
+
92
+ .. _asyncio: https://docs.python.org/3/library/asyncio.html
93
+ .. _Trio: https://github.com/python-trio/trio
94
+ .. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency
95
+ .. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning
96
+ .. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs
97
+ .. _pytest: https://docs.pytest.org/en/latest/
98
+ .. _functools: https://docs.python.org/3/library/functools.html
99
+ .. _itertools: https://docs.python.org/3/library/itertools.html
100
+ .. _Hypothesis: https://hypothesis.works/
101
+
102
+ Security contact information
103
+ ----------------------------
104
+
105
+ To report a security vulnerability, please use the `Tidelift security contact`_.
106
+ Tidelift will coordinate the fix and disclosure.
107
+
108
+ .. _Tidelift security contact: https://tidelift.com/security
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/RECORD ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ anyio-4.15.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ anyio-4.15.1.dist-info/METADATA,sha256=BDrstXGvcYnopsUo9djjJUXxss36r3YdUebVtn6jyoE,4733
3
+ anyio-4.15.1.dist-info/RECORD,,
4
+ anyio-4.15.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ anyio-4.15.1.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39
6
+ anyio-4.15.1.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081
7
+ anyio-4.15.1.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6
8
+ anyio/__init__.py,sha256=OfroYRjIUw_JFj0Zwh1JAaajMQg4VqtoAt0XoOHDRwE,7602
9
+ anyio/__pycache__/__init__.cpython-312.pyc,,
10
+ anyio/__pycache__/_lazyimport.cpython-312.pyc,,
11
+ anyio/__pycache__/from_thread.cpython-312.pyc,,
12
+ anyio/__pycache__/functools.cpython-312.pyc,,
13
+ anyio/__pycache__/itertools.cpython-312.pyc,,
14
+ anyio/__pycache__/lowlevel.cpython-312.pyc,,
15
+ anyio/__pycache__/pytest_plugin.cpython-312.pyc,,
16
+ anyio/__pycache__/to_interpreter.cpython-312.pyc,,
17
+ anyio/__pycache__/to_process.cpython-312.pyc,,
18
+ anyio/__pycache__/to_thread.cpython-312.pyc,,
19
+ anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ anyio/_backends/__pycache__/__init__.cpython-312.pyc,,
21
+ anyio/_backends/__pycache__/_asyncio.cpython-312.pyc,,
22
+ anyio/_backends/__pycache__/_trio.cpython-312.pyc,,
23
+ anyio/_backends/_asyncio.py,sha256=Vqy7O1ymmEpxTiPzehSuBCVTziGALNV-BbsIRaKXsg4,107767
24
+ anyio/_backends/_trio.py,sha256=Gs8XzX0IeBvje8IEZtJmpNylKCUAChKv7I_YZi3wlmg,45715
25
+ anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ anyio/_core/__pycache__/__init__.cpython-312.pyc,,
27
+ anyio/_core/__pycache__/_asyncio_selector_thread.cpython-312.pyc,,
28
+ anyio/_core/__pycache__/_concurrency_utils.cpython-312.pyc,,
29
+ anyio/_core/__pycache__/_contextmanagers.cpython-312.pyc,,
30
+ anyio/_core/__pycache__/_eventloop.cpython-312.pyc,,
31
+ anyio/_core/__pycache__/_exceptions.cpython-312.pyc,,
32
+ anyio/_core/__pycache__/_fileio.cpython-312.pyc,,
33
+ anyio/_core/__pycache__/_futures.cpython-312.pyc,,
34
+ anyio/_core/__pycache__/_resources.cpython-312.pyc,,
35
+ anyio/_core/__pycache__/_signals.cpython-312.pyc,,
36
+ anyio/_core/__pycache__/_sockets.cpython-312.pyc,,
37
+ anyio/_core/__pycache__/_streams.cpython-312.pyc,,
38
+ anyio/_core/__pycache__/_subprocesses.cpython-312.pyc,,
39
+ anyio/_core/__pycache__/_synchronization.cpython-312.pyc,,
40
+ anyio/_core/__pycache__/_tasks.cpython-312.pyc,,
41
+ anyio/_core/__pycache__/_tempfile.cpython-312.pyc,,
42
+ anyio/_core/__pycache__/_testing.cpython-312.pyc,,
43
+ anyio/_core/__pycache__/_typedattr.cpython-312.pyc,,
44
+ anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626
45
+ anyio/_core/_concurrency_utils.py,sha256=kvRXMrnDqgQTBkZc-f279-lBnZM4YbSToXqhnAUCfSc,4522
46
+ anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215
47
+ anyio/_core/_eventloop.py,sha256=ByZUeJD9alMfcyTseRo5IzTO0IltEul_Gyq9iqSjqDk,6658
48
+ anyio/_core/_exceptions.py,sha256=B4ZhLkBQT4tI6vShv4-GJui492IJsoIDTw1FQJEkmAI,5618
49
+ anyio/_core/_fileio.py,sha256=q--ft9h5Y_FRLzhAnoYrXf3tOuZ8ZyIN2A9mCfMbZRc,34163
50
+ anyio/_core/_futures.py,sha256=YQq5uhnCnKQMQD62tOLfzEm7dUXY3GQorJdH6ghfgIQ,6177
51
+ anyio/_core/_resources.py,sha256=Ld5duCe9NwgPfI7EIOh3CMIBYQ7rq6ZQEa7CFS0u9Ec,450
52
+ anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016
53
+ anyio/_core/_sockets.py,sha256=C8b-3w5H9n0Fo4g7X8WJvk0m6CGh6NVAAFtieBGHK3g,35289
54
+ anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806
55
+ anyio/_core/_subprocesses.py,sha256=TMBuGNILz-47w5t9vayJ1GpCpDT6LxsMohJDFCewIRc,7938
56
+ anyio/_core/_synchronization.py,sha256=ggsd74QPd846faA2HQeT07ONQ5HQ1S78gy8mvB3qCrw,21658
57
+ anyio/_core/_tasks.py,sha256=J2dhM_Jq3Grsfg_enNWpRz2SxfM15uLt-pEfvoQq3uA,15391
58
+ anyio/_core/_tempfile.py,sha256=IgoBCFaPhrFvsF9KHcCcrnCRn-UqMfw0WRdSDWgxAiI,19726
59
+ anyio/_core/_testing.py,sha256=ZRucLh5kqhiFWAJMMbd8yZ6uIvz0rq3WwL72ldosxAU,2340
60
+ anyio/_core/_typedattr.py,sha256=gt9Dzn-IL0QW14aHPDD8PAtq95FYKNNupHyf37xZGPQ,2607
61
+ anyio/_lazyimport.py,sha256=LCjnYanIfYE9G-Dv_EsqNLDuVRppNicWZjCTfS9-sJU,6082
62
+ anyio/abc/__init__.py,sha256=XIVvCI2c6oyaOcqXe94k2rzU5_s7-ZNnlxGTk34H4T0,3050
63
+ anyio/abc/__pycache__/__init__.cpython-312.pyc,,
64
+ anyio/abc/__pycache__/_eventloop.cpython-312.pyc,,
65
+ anyio/abc/__pycache__/_resources.cpython-312.pyc,,
66
+ anyio/abc/__pycache__/_sockets.cpython-312.pyc,,
67
+ anyio/abc/__pycache__/_streams.cpython-312.pyc,,
68
+ anyio/abc/__pycache__/_subprocesses.cpython-312.pyc,,
69
+ anyio/abc/__pycache__/_tasks.cpython-312.pyc,,
70
+ anyio/abc/__pycache__/_testing.cpython-312.pyc,,
71
+ anyio/abc/_eventloop.py,sha256=0-UwgB351rkocCt8m3fjTmcNx2Fxn52nUoujG5DzMvU,11127
72
+ anyio/abc/_resources.py,sha256=hrb0LXUgHSp3i8G6W8JJchdzKXgg1m0T-L7udXmv2y0,900
73
+ anyio/abc/_sockets.py,sha256=jQWnPX7iDIDyvyvVkbuFhjezw4oI2WggzbW6Vl2-eqs,13162
74
+ anyio/abc/_streams.py,sha256=IMeOPPutFXRbyeAutxV1HJe7FUQZYp2qKrJJpP1DCv0,7620
75
+ anyio/abc/_subprocesses.py,sha256=CDqU1p0HuBS0pXUzBW_hbfhihTJRM67n__7qZmoPU84,2123
76
+ anyio/abc/_tasks.py,sha256=HBPpT72aOy0bwMAxBCKmnXsR328wCYRjYm3iaVw2fQo,7070
77
+ anyio/abc/_testing.py,sha256=A9Y8RAClIPn1A0aNHBN8YoaRy_MKOpbFGEbTHAXgB6U,2145
78
+ anyio/from_thread.py,sha256=iZZbfcNySi4wAcx1_cxAQE4J0YZC88qRMIYqQ6SF9sc,19415
79
+ anyio/functools.py,sha256=T4JS8IXq-x1S0Lbo2owF8l9fza2KypO147QLeyz4cjs,11797
80
+ anyio/itertools.py,sha256=TS7_UCa2Y3cggtaLlWHbjOyf6QhPfQUdPduNW-ddXTE,16255
81
+ anyio/lowlevel.py,sha256=QyWkvfetbCH0mHkqv1yxGwOaiZ7fyxhpZkHWOXPV5JU,6280
82
+ anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
83
+ anyio/pytest_plugin.py,sha256=oLXyOstvRZW3VVbqIODhZsPt4jSz2UGh44YeG2nJXx0,14516
84
+ anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
85
+ anyio/streams/__pycache__/__init__.cpython-312.pyc,,
86
+ anyio/streams/__pycache__/buffered.cpython-312.pyc,,
87
+ anyio/streams/__pycache__/file.cpython-312.pyc,,
88
+ anyio/streams/__pycache__/memory.cpython-312.pyc,,
89
+ anyio/streams/__pycache__/stapled.cpython-312.pyc,,
90
+ anyio/streams/__pycache__/text.cpython-312.pyc,,
91
+ anyio/streams/__pycache__/tls.cpython-312.pyc,,
92
+ anyio/streams/buffered.py,sha256=u7hCD8SNrYHcutG6K5wEiy1F88-pizgjvEFM22Kq2Cw,6746
93
+ anyio/streams/file.py,sha256=6jujI2m-QJITqqKFamrupX_DNsU7y2Fz3omLZxOLuY0,4524
94
+ anyio/streams/memory.py,sha256=rpxNzDMag9PCOynBqN64KyuAfAPB41vFyRP-Npo-lE0,10793
95
+ anyio/streams/stapled.py,sha256=UJ2Rgt0NUmM1VovRNOoZoic960lcbDjb3vhfZg3b_Z0,4845
96
+ anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765
97
+ anyio/streams/tls.py,sha256=fqLmxvULFO9rvxGyJ33VPrOIN7E3eiU1q90BkmKigQ8,15818
98
+ anyio/to_interpreter.py,sha256=ATnoT6kei9wDmQZtXTA3SsY4CK7XKr8Ta4_x5i6pbTw,7100
99
+ anyio/to_process.py,sha256=p6n8j0nreJUl1DEkR_9PL6KRoKtNqFxORTn8qZBvn94,9850
100
+ anyio/to_thread.py,sha256=8MPVrrQq8ttGvV21cSd68rMto5bhxJ0-i9CupXag5Gs,2750
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest11]
2
+ anyio = anyio.pytest_plugin
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Alex Grönholm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.venv/lib/python3.12/site-packages/anyio-4.15.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ anyio
.venv/lib/python3.12/site-packages/anyio/abc/_resources.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from abc import ABCMeta, abstractmethod
5
+ from types import TracebackType
6
+ from typing import TypeVar
7
+
8
+ if sys.version_info >= (3, 11):
9
+ from typing import Self
10
+ else:
11
+ from typing_extensions import Self
12
+
13
+ T = TypeVar("T")
14
+
15
+
16
+ class AsyncResource(metaclass=ABCMeta):
17
+ """
18
+ Abstract base class for all closeable asynchronous resources.
19
+
20
+ Works as an asynchronous context manager which returns the instance itself on enter,
21
+ and calls :meth:`aclose` on exit.
22
+ """
23
+
24
+ __slots__ = ()
25
+
26
+ async def __aenter__(self) -> Self:
27
+ return self
28
+
29
+ async def __aexit__(
30
+ self,
31
+ exc_type: type[BaseException] | None,
32
+ exc_val: BaseException | None,
33
+ exc_tb: TracebackType | None,
34
+ ) -> None:
35
+ await self.aclose()
36
+
37
+ @abstractmethod
38
+ async def aclose(self) -> None:
39
+ """Close the resource."""
.venv/lib/python3.12/site-packages/anyio/abc/_sockets.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import errno
4
+ import socket
5
+ from abc import abstractmethod
6
+ from collections.abc import Callable, Collection, Mapping
7
+ from contextlib import AsyncExitStack
8
+ from io import IOBase
9
+ from ipaddress import IPv4Address, IPv6Address
10
+ from socket import AddressFamily
11
+ from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar
12
+
13
+ from .._core._eventloop import get_async_backend
14
+ from .._core._typedattr import (
15
+ TypedAttributeProvider,
16
+ TypedAttributeSet,
17
+ typed_attribute,
18
+ )
19
+ from ._streams import ByteStream, Listener, UnreliableObjectStream
20
+
21
+ if TYPE_CHECKING:
22
+ from ._tasks import TaskGroup
23
+
24
+ IPAddressType: TypeAlias = str | IPv4Address | IPv6Address
25
+ IPSockAddrType: TypeAlias = tuple[str, int]
26
+ SockAddrType: TypeAlias = IPSockAddrType | str
27
+ UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType]
28
+ UNIXDatagramPacketType: TypeAlias = tuple[bytes, str]
29
+ T_Retval = TypeVar("T_Retval")
30
+
31
+
32
+ def _validate_socket(
33
+ sock_or_fd: socket.socket | int,
34
+ sock_type: socket.SocketKind,
35
+ addr_family: socket.AddressFamily = socket.AF_UNSPEC,
36
+ *,
37
+ require_connected: bool = False,
38
+ require_bound: bool = False,
39
+ ) -> socket.socket:
40
+ if isinstance(sock_or_fd, int):
41
+ try:
42
+ sock = socket.socket(fileno=sock_or_fd)
43
+ except OSError as exc:
44
+ if exc.errno == errno.ENOTSOCK:
45
+ raise ValueError(
46
+ "the file descriptor does not refer to a socket"
47
+ ) from exc
48
+ elif require_connected:
49
+ raise ValueError("the socket must be connected") from exc
50
+ elif require_bound:
51
+ raise ValueError("the socket must be bound to a local address") from exc
52
+ else:
53
+ raise
54
+ elif isinstance(sock_or_fd, socket.socket):
55
+ sock = sock_or_fd
56
+ else:
57
+ raise TypeError(
58
+ f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead"
59
+ )
60
+
61
+ try:
62
+ if require_connected:
63
+ try:
64
+ sock.getpeername()
65
+ except OSError as exc:
66
+ raise ValueError("the socket must be connected") from exc
67
+
68
+ if require_bound:
69
+ try:
70
+ if sock.family in (socket.AF_INET, socket.AF_INET6):
71
+ bound_addr = sock.getsockname()[1]
72
+ else:
73
+ bound_addr = sock.getsockname()
74
+ except OSError:
75
+ bound_addr = None
76
+
77
+ if not bound_addr:
78
+ raise ValueError("the socket must be bound to a local address")
79
+
80
+ if addr_family != socket.AF_UNSPEC and sock.family != addr_family:
81
+ raise ValueError(
82
+ f"address family mismatch: expected {addr_family.name}, got "
83
+ f"{sock.family.name}"
84
+ )
85
+
86
+ if sock.type != sock_type:
87
+ raise ValueError(
88
+ f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}"
89
+ )
90
+ except BaseException:
91
+ # Avoid ResourceWarning from the locally constructed socket object
92
+ if isinstance(sock_or_fd, int):
93
+ sock.detach()
94
+
95
+ raise
96
+
97
+ sock.setblocking(False)
98
+ return sock
99
+
100
+
101
+ class SocketAttribute(TypedAttributeSet):
102
+ """
103
+ .. attribute:: family
104
+ :type: socket.AddressFamily
105
+
106
+ the address family of the underlying socket
107
+
108
+ .. attribute:: local_address
109
+ :type: tuple[str, int] | str
110
+
111
+ the local address the underlying socket is connected to
112
+
113
+ .. attribute:: local_port
114
+ :type: int
115
+
116
+ for IP based sockets, the local port the underlying socket is bound to
117
+
118
+ .. attribute:: raw_socket
119
+ :type: socket.socket
120
+
121
+ the underlying stdlib socket object
122
+
123
+ .. attribute:: remote_address
124
+ :type: tuple[str, int] | str
125
+
126
+ the remote address the underlying socket is connected to
127
+
128
+ .. attribute:: remote_port
129
+ :type: int
130
+
131
+ for IP based sockets, the remote port the underlying socket is connected to
132
+ """
133
+
134
+ family: AddressFamily = typed_attribute()
135
+ local_address: SockAddrType = typed_attribute()
136
+ local_port: int = typed_attribute()
137
+ raw_socket: socket.socket = typed_attribute()
138
+ remote_address: SockAddrType = typed_attribute()
139
+ remote_port: int = typed_attribute()
140
+
141
+
142
+ class _SocketProvider(TypedAttributeProvider):
143
+ @property
144
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
145
+ from .._core._sockets import convert_ipv6_sockaddr as convert
146
+
147
+ attributes: dict[Any, Callable[[], Any]] = {
148
+ SocketAttribute.family: lambda: self._raw_socket.family,
149
+ SocketAttribute.local_address: lambda: convert(
150
+ self._raw_socket.getsockname()
151
+ ),
152
+ SocketAttribute.raw_socket: lambda: self._raw_socket,
153
+ }
154
+ try:
155
+ peername: tuple[str, int] | None = convert(self._raw_socket.getpeername())
156
+ except OSError:
157
+ peername = None
158
+
159
+ # Provide the remote address for connected sockets
160
+ if peername is not None:
161
+ attributes[SocketAttribute.remote_address] = lambda: peername
162
+
163
+ # Provide local and remote ports for IP based sockets
164
+ if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6):
165
+ attributes[SocketAttribute.local_port] = lambda: (
166
+ self._raw_socket.getsockname()[1]
167
+ )
168
+ if peername is not None:
169
+ remote_port = peername[1]
170
+ attributes[SocketAttribute.remote_port] = lambda: remote_port
171
+
172
+ return attributes
173
+
174
+ @property
175
+ @abstractmethod
176
+ def _raw_socket(self) -> socket.socket:
177
+ pass
178
+
179
+
180
+ class SocketStream(ByteStream, _SocketProvider):
181
+ """
182
+ Transports bytes over a socket.
183
+
184
+ Supports all relevant extra attributes from :class:`~SocketAttribute`.
185
+ """
186
+
187
+ @classmethod
188
+ async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream:
189
+ """
190
+ Wrap an existing socket object or file descriptor as a socket stream.
191
+
192
+ The newly created socket wrapper takes ownership of the socket being passed in.
193
+ The existing socket must already be connected.
194
+
195
+ :param sock_or_fd: a socket object or file descriptor
196
+ :return: a socket stream
197
+
198
+ """
199
+ sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True)
200
+ return await get_async_backend().wrap_stream_socket(sock)
201
+
202
+
203
+ class UNIXSocketStream(SocketStream):
204
+ @classmethod
205
+ async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream:
206
+ """
207
+ Wrap an existing socket object or file descriptor as a UNIX socket stream.
208
+
209
+ The newly created socket wrapper takes ownership of the socket being passed in.
210
+ The existing socket must already be connected.
211
+
212
+ :param sock_or_fd: a socket object or file descriptor
213
+ :return: a UNIX socket stream
214
+
215
+ """
216
+ sock = _validate_socket(
217
+ sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True
218
+ )
219
+ return await get_async_backend().wrap_unix_stream_socket(sock)
220
+
221
+ @abstractmethod
222
+ async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
223
+ """
224
+ Send file descriptors along with a message to the peer.
225
+
226
+ :param message: a non-empty bytestring
227
+ :param fds: a collection of files (either numeric file descriptors or open file
228
+ or socket objects)
229
+ """
230
+
231
+ @abstractmethod
232
+ async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
233
+ """
234
+ Receive file descriptors along with a message from the peer.
235
+
236
+ :param msglen: length of the message to expect from the peer
237
+ :param maxfds: maximum number of file descriptors to expect from the peer
238
+ :return: a tuple of (message, file descriptors)
239
+ """
240
+
241
+
242
+ class SocketListener(Listener[SocketStream], _SocketProvider):
243
+ """
244
+ Listens to incoming socket connections.
245
+
246
+ Supports all relevant extra attributes from :class:`~SocketAttribute`.
247
+ """
248
+
249
+ @classmethod
250
+ async def from_socket(
251
+ cls,
252
+ sock_or_fd: socket.socket | int,
253
+ ) -> SocketListener:
254
+ """
255
+ Wrap an existing socket object or file descriptor as a socket listener.
256
+
257
+ The newly created listener takes ownership of the socket being passed in.
258
+
259
+ :param sock_or_fd: a socket object or file descriptor
260
+ :return: a socket listener
261
+
262
+ """
263
+ sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True)
264
+ return await get_async_backend().wrap_listener_socket(sock)
265
+
266
+ @abstractmethod
267
+ async def accept(self) -> SocketStream:
268
+ """Accept an incoming connection."""
269
+
270
+ async def serve(
271
+ self,
272
+ handler: Callable[[SocketStream], Any],
273
+ task_group: TaskGroup | None = None,
274
+ ) -> None:
275
+ from .. import create_task_group
276
+
277
+ async with AsyncExitStack() as stack:
278
+ if task_group is None:
279
+ task_group = await stack.enter_async_context(create_task_group())
280
+
281
+ while True:
282
+ stream = await self.accept()
283
+ task_group.start_soon(handler, stream)
284
+
285
+
286
+ class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider):
287
+ """
288
+ Represents an unconnected UDP socket.
289
+
290
+ Supports all relevant extra attributes from :class:`~SocketAttribute`.
291
+ """
292
+
293
+ @classmethod
294
+ async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket:
295
+ """
296
+ Wrap an existing socket object or file descriptor as a UDP socket.
297
+
298
+ The newly created socket wrapper takes ownership of the socket being passed in.
299
+ The existing socket must be bound to a local address.
300
+
301
+ :param sock_or_fd: a socket object or file descriptor
302
+ :return: a UDP socket
303
+
304
+ """
305
+ sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True)
306
+ return await get_async_backend().wrap_udp_socket(sock)
307
+
308
+ async def sendto(self, data: bytes, host: str, port: int) -> None:
309
+ """
310
+ Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))).
311
+
312
+ """
313
+ return await self.send((data, (host, port)))
314
+
315
+
316
+ class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider):
317
+ """
318
+ Represents an connected UDP socket.
319
+
320
+ Supports all relevant extra attributes from :class:`~SocketAttribute`.
321
+ """
322
+
323
+ @classmethod
324
+ async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket:
325
+ """
326
+ Wrap an existing socket object or file descriptor as a connected UDP socket.
327
+
328
+ The newly created socket wrapper takes ownership of the socket being passed in.
329
+ The existing socket must already be connected.
330
+
331
+ :param sock_or_fd: a socket object or file descriptor
332
+ :return: a connected UDP socket
333
+
334
+ """
335
+ sock = _validate_socket(
336
+ sock_or_fd,
337
+ socket.SOCK_DGRAM,
338
+ require_connected=True,
339
+ )
340
+ return await get_async_backend().wrap_connected_udp_socket(sock)
341
+
342
+
343
+ class UNIXDatagramSocket(
344
+ UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider
345
+ ):
346
+ """
347
+ Represents an unconnected Unix datagram socket.
348
+
349
+ Supports all relevant extra attributes from :class:`~SocketAttribute`.
350
+ """
351
+
352
+ @classmethod
353
+ async def from_socket(
354
+ cls,
355
+ sock_or_fd: socket.socket | int,
356
+ ) -> UNIXDatagramSocket:
357
+ """
358
+ Wrap an existing socket object or file descriptor as a UNIX datagram
359
+ socket.
360
+
361
+ The newly created socket wrapper takes ownership of the socket being passed in.
362
+
363
+ :param sock_or_fd: a socket object or file descriptor
364
+ :return: a UNIX datagram socket
365
+
366
+ """
367
+ sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX)
368
+ return await get_async_backend().wrap_unix_datagram_socket(sock)
369
+
370
+ async def sendto(self, data: bytes, path: str) -> None:
371
+ """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path))."""
372
+ return await self.send((data, path))
373
+
374
+
375
+ class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider):
376
+ """
377
+ Represents a connected Unix datagram socket.
378
+
379
+ Supports all relevant extra attributes from :class:`~SocketAttribute`.
380
+ """
381
+
382
+ @classmethod
383
+ async def from_socket(
384
+ cls,
385
+ sock_or_fd: socket.socket | int,
386
+ ) -> ConnectedUNIXDatagramSocket:
387
+ """
388
+ Wrap an existing socket object or file descriptor as a connected UNIX datagram
389
+ socket.
390
+
391
+ The newly created socket wrapper takes ownership of the socket being passed in.
392
+ The existing socket must already be connected.
393
+
394
+ :param sock_or_fd: a socket object or file descriptor
395
+ :return: a connected UNIX datagram socket
396
+
397
+ """
398
+ sock = _validate_socket(
399
+ sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True
400
+ )
401
+ return await get_async_backend().wrap_connected_unix_datagram_socket(sock)
.venv/lib/python3.12/site-packages/anyio/abc/_streams.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABCMeta, abstractmethod
4
+ from collections.abc import Callable
5
+ from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeVar
6
+
7
+ from .._core._exceptions import EndOfStream
8
+ from .._core._typedattr import TypedAttributeProvider
9
+ from ._resources import AsyncResource
10
+
11
+ if TYPE_CHECKING:
12
+ from ._tasks import TaskGroup
13
+
14
+ T_Item = TypeVar("T_Item")
15
+ T_co = TypeVar("T_co", covariant=True)
16
+ T_contra = TypeVar("T_contra", contravariant=True)
17
+
18
+
19
+ class UnreliableObjectReceiveStream(
20
+ AsyncResource, TypedAttributeProvider, Generic[T_co]
21
+ ):
22
+ """
23
+ An interface for receiving objects.
24
+
25
+ This interface makes no guarantees that the received messages arrive in the order in
26
+ which they were sent, or that no messages are missed.
27
+
28
+ Asynchronously iterating over objects of this type will yield objects matching the
29
+ given type parameter.
30
+ """
31
+
32
+ def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]:
33
+ return self
34
+
35
+ async def __anext__(self) -> T_co:
36
+ try:
37
+ return await self.receive()
38
+ except EndOfStream:
39
+ raise StopAsyncIteration from None
40
+
41
+ @abstractmethod
42
+ async def receive(self) -> T_co:
43
+ """
44
+ Receive the next item.
45
+
46
+ :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly
47
+ closed
48
+ :raises ~anyio.EndOfStream: if this stream has been closed from the other end
49
+ :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable
50
+ due to external causes
51
+ """
52
+
53
+
54
+ class UnreliableObjectSendStream(
55
+ AsyncResource, TypedAttributeProvider, Generic[T_contra]
56
+ ):
57
+ """
58
+ An interface for sending objects.
59
+
60
+ This interface makes no guarantees that the messages sent will reach the
61
+ recipient(s) in the same order in which they were sent, or at all.
62
+ """
63
+
64
+ @abstractmethod
65
+ async def send(self, item: T_contra) -> None:
66
+ """
67
+ Send an item to the peer(s).
68
+
69
+ :param item: the item to send
70
+ :raises ~anyio.ClosedResourceError: if the send stream has been explicitly
71
+ closed
72
+ :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable
73
+ due to external causes
74
+ """
75
+
76
+
77
+ class UnreliableObjectStream(
78
+ UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item]
79
+ ):
80
+ """
81
+ A bidirectional message stream which does not guarantee the order or reliability of
82
+ message delivery.
83
+ """
84
+
85
+
86
+ class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]):
87
+ """
88
+ A receive message stream which guarantees that messages are received in the same
89
+ order in which they were sent, and that no messages are missed.
90
+ """
91
+
92
+
93
+ class ObjectSendStream(UnreliableObjectSendStream[T_contra]):
94
+ """
95
+ A send message stream which guarantees that messages are delivered in the same order
96
+ in which they were sent, without missing any messages in the middle.
97
+ """
98
+
99
+
100
+ class ObjectStream(
101
+ ObjectReceiveStream[T_Item],
102
+ ObjectSendStream[T_Item],
103
+ UnreliableObjectStream[T_Item],
104
+ ):
105
+ """
106
+ A bidirectional message stream which guarantees the order and reliability of message
107
+ delivery.
108
+ """
109
+
110
+ @abstractmethod
111
+ async def send_eof(self) -> None:
112
+ """
113
+ Send an end-of-file indication to the peer.
114
+
115
+ You should not try to send any further data to this stream after calling this
116
+ method. This method is idempotent (does nothing on successive calls).
117
+ """
118
+
119
+
120
+ class ByteReceiveStream(AsyncResource, TypedAttributeProvider):
121
+ """
122
+ An interface for receiving bytes from a single peer.
123
+
124
+ Iterating this byte stream will yield a byte string of arbitrary length, but no more
125
+ than 65536 bytes.
126
+ """
127
+
128
+ def __aiter__(self) -> ByteReceiveStream:
129
+ return self
130
+
131
+ async def __anext__(self) -> bytes:
132
+ try:
133
+ return await self.receive()
134
+ except EndOfStream:
135
+ raise StopAsyncIteration from None
136
+
137
+ @abstractmethod
138
+ async def receive(self, max_bytes: int = 65536) -> bytes:
139
+ """
140
+ Receive at most ``max_bytes`` bytes from the peer.
141
+
142
+ .. note:: Implementers of this interface should not return an empty
143
+ :class:`bytes` object, and users should ignore them.
144
+
145
+ :param max_bytes: maximum number of bytes to receive (must be a positive
146
+ integer)
147
+ :return: the received bytes
148
+ :raises ValueError: if ``max_bytes`` is less than 1
149
+ :raises ~anyio.EndOfStream: if this stream has been closed from the other end
150
+ """
151
+
152
+
153
+ class ByteSendStream(AsyncResource, TypedAttributeProvider):
154
+ """An interface for sending bytes to a single peer."""
155
+
156
+ @abstractmethod
157
+ async def send(self, item: bytes) -> None:
158
+ """
159
+ Send the given bytes to the peer.
160
+
161
+ :param item: the bytes to send
162
+ """
163
+
164
+
165
+ class ByteStream(ByteReceiveStream, ByteSendStream):
166
+ """A bidirectional byte stream."""
167
+
168
+ @abstractmethod
169
+ async def send_eof(self) -> None:
170
+ """
171
+ Send an end-of-file indication to the peer.
172
+
173
+ You should not try to send any further data to this stream after calling this
174
+ method. This method is idempotent (does nothing on successive calls).
175
+ """
176
+
177
+
178
+ #: Type alias for all unreliable bytes-oriented receive streams.
179
+ AnyUnreliableByteReceiveStream: TypeAlias = (
180
+ UnreliableObjectReceiveStream[bytes] | ByteReceiveStream
181
+ )
182
+ #: Type alias for all unreliable bytes-oriented send streams.
183
+ AnyUnreliableByteSendStream: TypeAlias = (
184
+ UnreliableObjectSendStream[bytes] | ByteSendStream
185
+ )
186
+ #: Type alias for all unreliable bytes-oriented streams.
187
+ AnyUnreliableByteStream: TypeAlias = UnreliableObjectStream[bytes] | ByteStream
188
+ #: Type alias for all bytes-oriented receive streams.
189
+ AnyByteReceiveStream: TypeAlias = ObjectReceiveStream[bytes] | ByteReceiveStream
190
+ #: Type alias for all bytes-oriented send streams.
191
+ AnyByteSendStream: TypeAlias = ObjectSendStream[bytes] | ByteSendStream
192
+ #: Type alias for all bytes-oriented streams.
193
+ AnyByteStream: TypeAlias = ObjectStream[bytes] | ByteStream
194
+
195
+
196
+ class Listener(AsyncResource, TypedAttributeProvider, Generic[T_co]):
197
+ """An interface for objects that let you accept incoming connections."""
198
+
199
+ @abstractmethod
200
+ async def serve(
201
+ self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None
202
+ ) -> None:
203
+ """
204
+ Accept incoming connections as they come in and start tasks to handle them.
205
+
206
+ :param handler: a callable that will be used to handle each accepted connection
207
+ :param task_group: the task group that will be used to start tasks for handling
208
+ each accepted connection (if omitted, an ad-hoc task group will be created)
209
+ """
210
+
211
+
212
+ class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta):
213
+ @abstractmethod
214
+ async def connect(self) -> ObjectStream[T_co]:
215
+ """
216
+ Connect to the remote endpoint.
217
+
218
+ :return: an object stream connected to the remote end
219
+ :raises ConnectionFailed: if the connection fails
220
+ """
221
+
222
+
223
+ class ByteStreamConnectable(metaclass=ABCMeta):
224
+ @abstractmethod
225
+ async def connect(self) -> ByteStream:
226
+ """
227
+ Connect to the remote endpoint.
228
+
229
+ :return: a bytestream connected to the remote end
230
+ :raises ConnectionFailed: if the connection fails
231
+ """
232
+
233
+
234
+ #: Type alias for all connectables returning bytestreams or bytes-oriented object streams
235
+ AnyByteStreamConnectable: TypeAlias = (
236
+ ObjectStreamConnectable[bytes] | ByteStreamConnectable
237
+ )
.venv/lib/python3.12/site-packages/anyio/abc/_subprocesses.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import abstractmethod
4
+ from signal import Signals
5
+ from typing import TYPE_CHECKING
6
+
7
+ from ._resources import AsyncResource
8
+
9
+ if TYPE_CHECKING:
10
+ from ._streams import ByteReceiveStream, ByteSendStream
11
+
12
+
13
+ class Process(AsyncResource):
14
+ """An asynchronous version of :class:`subprocess.Popen`."""
15
+
16
+ @abstractmethod
17
+ async def wait(self) -> int:
18
+ """
19
+ Wait until the process exits.
20
+
21
+ :return: the exit code of the process
22
+ """
23
+
24
+ @abstractmethod
25
+ def terminate(self) -> None:
26
+ """
27
+ Terminates the process, gracefully if possible.
28
+
29
+ On Windows, this calls ``TerminateProcess()``.
30
+ On POSIX systems, this sends ``SIGTERM`` to the process.
31
+
32
+ .. seealso:: :meth:`subprocess.Popen.terminate`
33
+ """
34
+
35
+ @abstractmethod
36
+ def kill(self) -> None:
37
+ """
38
+ Kills the process.
39
+
40
+ On Windows, this calls ``TerminateProcess()``.
41
+ On POSIX systems, this sends ``SIGKILL`` to the process.
42
+
43
+ .. seealso:: :meth:`subprocess.Popen.kill`
44
+ """
45
+
46
+ @abstractmethod
47
+ def send_signal(self, signal: Signals) -> None:
48
+ """
49
+ Send a signal to the subprocess.
50
+
51
+ .. seealso:: :meth:`subprocess.Popen.send_signal`
52
+
53
+ :param signal: the signal number (e.g. :data:`signal.SIGHUP`)
54
+ """
55
+
56
+ @property
57
+ @abstractmethod
58
+ def pid(self) -> int:
59
+ """The process ID of the process."""
60
+
61
+ @property
62
+ @abstractmethod
63
+ def returncode(self) -> int | None:
64
+ """
65
+ The return code of the process. If the process has not yet terminated, this will
66
+ be ``None``.
67
+ """
68
+
69
+ @property
70
+ @abstractmethod
71
+ def stdin(self) -> ByteSendStream | None:
72
+ """The stream for the standard input of the process."""
73
+
74
+ @property
75
+ @abstractmethod
76
+ def stdout(self) -> ByteReceiveStream | None:
77
+ """The stream for the standard output of the process."""
78
+
79
+ @property
80
+ @abstractmethod
81
+ def stderr(self) -> ByteReceiveStream | None:
82
+ """The stream for the standard error output of the process."""
.venv/lib/python3.12/site-packages/anyio/abc/_tasks.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from abc import ABCMeta, abstractmethod
5
+ from collections.abc import Callable, Coroutine
6
+ from contextvars import Context
7
+ from types import TracebackType
8
+ from typing import TYPE_CHECKING, Any, Literal, Protocol, final, overload
9
+
10
+ if sys.version_info >= (3, 13):
11
+ from typing import TypeVar
12
+ else:
13
+ from typing_extensions import TypeVar
14
+
15
+ if sys.version_info >= (3, 11):
16
+ from typing import TypeVarTuple, Unpack
17
+ else:
18
+ from typing_extensions import TypeVarTuple, Unpack
19
+
20
+ if TYPE_CHECKING:
21
+ from .._core._tasks import CancelScope, TaskHandle
22
+
23
+ T_co = TypeVar("T_co", covariant=True)
24
+ T_contra = TypeVar("T_contra", contravariant=True, default=None)
25
+ PosArgsT = TypeVarTuple("PosArgsT")
26
+
27
+
28
+ def get_coro_name(coro: Coroutine[Any, Any, object], override: object = None) -> str:
29
+ if override is not None:
30
+ return str(override)
31
+
32
+ try:
33
+ cr_frame = coro.cr_frame # type: ignore[attr-defined]
34
+ module = cr_frame.f_globals["__name__"]
35
+ except (AttributeError, KeyError):
36
+ module = None
37
+
38
+ qualname = getattr(coro, "__qualname__", None)
39
+ return ".".join([x for x in (module, qualname) if x])
40
+
41
+
42
+ def get_callable_name(func: Callable, override: object = None) -> str:
43
+ if override is not None:
44
+ return str(override)
45
+
46
+ module = getattr(func, "__module__", None)
47
+ qualname = getattr(func, "__qualname__", None)
48
+ return ".".join([x for x in (module, qualname) if x])
49
+
50
+
51
+ def call_for_coroutine(
52
+ func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]],
53
+ args: tuple[Unpack[PosArgsT]],
54
+ **kwargs: Any,
55
+ ) -> Coroutine[Any, Any, T_co]:
56
+ """
57
+ Call the given function with the given positional and keyword arguments.
58
+
59
+ :return: the resulting coroutine
60
+ :raises TypeError: if the return value was not a coroutine object
61
+
62
+ """
63
+ coro = func(*args, **kwargs)
64
+ if not isinstance(coro, Coroutine):
65
+ prefix = f"{func.__module__}." if hasattr(func, "__module__") else ""
66
+ raise TypeError(
67
+ f"Expected {prefix}{func.__qualname__}() to return a coroutine, but "
68
+ f"the return value ({coro!r}) is not a coroutine object"
69
+ )
70
+
71
+ return coro
72
+
73
+
74
+ class TaskStatus(Protocol[T_contra]):
75
+ @overload
76
+ def started(self: TaskStatus[None]) -> None: ...
77
+
78
+ @overload
79
+ def started(self, value: T_contra) -> None: ...
80
+
81
+ def started(self, value: T_contra | None = None) -> None:
82
+ """
83
+ Signal that the task has started.
84
+
85
+ :param value: object passed back to the starter of the task
86
+ """
87
+
88
+
89
+ class TaskGroup(metaclass=ABCMeta):
90
+ """
91
+ Groups several asynchronous tasks together.
92
+
93
+ :ivar cancel_scope: the cancel scope inherited by all child tasks
94
+ :vartype cancel_scope: CancelScope
95
+
96
+ .. note:: On asyncio, support for eager task factories is considered to be
97
+ **experimental**. In particular, they don't follow the usual semantics of new
98
+ tasks being scheduled on the next iteration of the event loop, and may thus
99
+ cause unexpected behavior in code that wasn't written with such semantics in
100
+ mind.
101
+ """
102
+
103
+ cancel_scope: CancelScope
104
+
105
+ def cancel(self, reason: str | None = None) -> None:
106
+ """
107
+ Cancel this task group's cancel scope immediately.
108
+
109
+ This is a shortcut for calling ``.cancel_scope.cancel()`` on the task group.
110
+
111
+ :param reason: a message describing the reason for the cancellation
112
+
113
+ .. versionadded:: 4.14.0
114
+
115
+ """
116
+ self.cancel_scope.cancel(reason)
117
+
118
+ @abstractmethod
119
+ def create_task(
120
+ self,
121
+ coro: Coroutine[Any, Any, T_co],
122
+ *,
123
+ name: object = None,
124
+ context: Context | None = None,
125
+ ) -> TaskHandle[T_co]:
126
+ """
127
+ Create a new task from a coroutine object and schedule it to run.
128
+
129
+ :param coro: a coroutine object
130
+ :param name: optional name to give the task
131
+ :param context: optional context to run the task in
132
+ :return: a task handle
133
+
134
+ .. versionadded:: 4.14.0
135
+ """
136
+
137
+ @final
138
+ def start_soon(
139
+ self,
140
+ func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]],
141
+ *args: Unpack[PosArgsT],
142
+ name: object = None,
143
+ ) -> TaskHandle[T_co]:
144
+ """
145
+ Start a new task in this task group.
146
+
147
+ :param func: a coroutine function
148
+ :param args: positional arguments to call the function with
149
+ :param name: name of the task, for the purposes of introspection and debugging
150
+ :return: a task handle
151
+
152
+ .. versionadded:: 3.0
153
+ .. versionchanged:: 4.14.0
154
+ This method now returns a task handle.
155
+
156
+ """
157
+ final_name = get_callable_name(func, name)
158
+ return self.create_task(call_for_coroutine(func, args), name=final_name)
159
+
160
+ @overload
161
+ async def start(
162
+ self,
163
+ func: Callable[..., Coroutine[Any, Any, T_co]],
164
+ *args: object,
165
+ name: object = None,
166
+ return_handle: Literal[False] = ...,
167
+ ) -> Any: ...
168
+
169
+ @overload
170
+ async def start(
171
+ self,
172
+ func: Callable[..., Coroutine[Any, Any, T_co]],
173
+ *args: object,
174
+ name: object = None,
175
+ return_handle: Literal[True],
176
+ ) -> TaskHandle[T_co, Any]: ...
177
+
178
+ @abstractmethod
179
+ async def start(
180
+ self,
181
+ func: Callable[..., Coroutine[Any, Any, T_co]],
182
+ *args: object,
183
+ name: object = None,
184
+ return_handle: Literal[False, True] = False,
185
+ ) -> Any:
186
+ """
187
+ Start a new task and wait until it signals for readiness.
188
+
189
+ The target callable must accept a keyword argument ``task_status`` (of type
190
+ :class:`TaskStatus`). Awaiting on this method will return whatever was passed to
191
+ ``task_status.started()`` (``None`` by default).
192
+
193
+ .. note:: The :class:`TaskStatus` class is generic, and the type argument should
194
+ indicate the type of the value that will be passed to
195
+ ``task_status.started()``.
196
+
197
+ :param func: a coroutine function that accepts the ``task_status`` keyword
198
+ argument
199
+ :param args: positional arguments to call the function with
200
+ :param name: an optional name for the task, for introspection and debugging
201
+ :param return_handle: if ``True``, return a :class:`TaskHandle` which also
202
+ contains the start value in ``start_value``
203
+ :return: the value passed to ``task_status.started()``
204
+ :raises RuntimeError: if the task finishes without calling
205
+ ``task_status.started()``
206
+
207
+ .. seealso:: :ref:`start_initialize`
208
+
209
+ .. versionadded:: 3.0
210
+ """
211
+
212
+ @abstractmethod
213
+ async def __aenter__(self) -> TaskGroup:
214
+ """Enter the task group context and allow starting new tasks."""
215
+
216
+ @abstractmethod
217
+ async def __aexit__(
218
+ self,
219
+ exc_type: type[BaseException] | None,
220
+ exc_val: BaseException | None,
221
+ exc_tb: TracebackType | None,
222
+ ) -> bool:
223
+ """Exit the task group context waiting for all tasks to finish."""
.venv/lib/python3.12/site-packages/anyio/abc/_testing.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import types
5
+ from abc import ABCMeta, abstractmethod
6
+ from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable
7
+ from typing import Any, TypeVar
8
+
9
+ if sys.version_info >= (3, 11):
10
+ from typing import Self
11
+ else:
12
+ from typing_extensions import Self
13
+
14
+ _T = TypeVar("_T")
15
+
16
+
17
+ class TestRunner(metaclass=ABCMeta):
18
+ """
19
+ Encapsulates a running event loop. Every call made through this object will use the
20
+ same event loop.
21
+ """
22
+
23
+ def __enter__(self) -> Self:
24
+ return self
25
+
26
+ @abstractmethod
27
+ def __exit__(
28
+ self,
29
+ exc_type: type[BaseException] | None,
30
+ exc_val: BaseException | None,
31
+ exc_tb: types.TracebackType | None,
32
+ ) -> bool | None: ...
33
+
34
+ @abstractmethod
35
+ def run_asyncgen_fixture(
36
+ self,
37
+ fixture_func: Callable[..., AsyncGenerator[_T, Any]],
38
+ kwargs: dict[str, Any],
39
+ ) -> Iterable[_T]:
40
+ """
41
+ Run an async generator fixture.
42
+
43
+ :param fixture_func: the fixture function
44
+ :param kwargs: keyword arguments to call the fixture function with
45
+ :return: an iterator yielding the value yielded from the async generator
46
+ """
47
+
48
+ @abstractmethod
49
+ def run_fixture(
50
+ self,
51
+ fixture_func: Callable[..., Coroutine[Any, Any, _T]],
52
+ kwargs: dict[str, Any],
53
+ ) -> _T:
54
+ """
55
+ Run an async fixture.
56
+
57
+ :param fixture_func: the fixture function
58
+ :param kwargs: keyword arguments to call the fixture function with
59
+ :return: the return value of the fixture function
60
+ """
61
+
62
+ @abstractmethod
63
+ def run_test(
64
+ self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
65
+ ) -> None:
66
+ """
67
+ Run an async test function.
68
+
69
+ :param test_func: the test function
70
+ :param kwargs: keyword arguments to call the test function with
71
+ """
72
+
73
+ @abstractmethod
74
+ def is_running(self) -> bool:
75
+ """
76
+ Check if the test runner is running.
77
+
78
+ :return: ``True`` if the coroutine is currently being run, ``False`` otherwise.
79
+ """
.venv/lib/python3.12/site-packages/anyio/from_thread.py ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "BlockingPortal",
5
+ "BlockingPortalProvider",
6
+ "check_cancelled",
7
+ "run",
8
+ "run_sync",
9
+ "start_blocking_portal",
10
+ )
11
+
12
+ import sys
13
+ from collections.abc import Awaitable, Callable, Coroutine, Generator
14
+ from concurrent.futures import Future
15
+ from contextlib import (
16
+ AbstractAsyncContextManager,
17
+ AbstractContextManager,
18
+ contextmanager,
19
+ )
20
+ from contextvars import Context
21
+ from dataclasses import dataclass, field
22
+ from functools import partial
23
+ from inspect import isawaitable
24
+ from threading import Lock, Thread, current_thread, get_ident
25
+ from types import TracebackType
26
+ from typing import (
27
+ Any,
28
+ Generic,
29
+ TypeVar,
30
+ cast,
31
+ overload,
32
+ )
33
+
34
+ from ._core._eventloop import (
35
+ get_cancelled_exc_class,
36
+ threadlocals,
37
+ )
38
+ from ._core._eventloop import run as run_eventloop
39
+ from ._core._exceptions import NoEventLoopError
40
+ from ._core._synchronization import Event
41
+ from ._core._tasks import CancelScope, create_task_group
42
+ from .abc._tasks import TaskStatus
43
+ from .lowlevel import EventLoopToken, current_token
44
+
45
+ if sys.version_info >= (3, 11):
46
+ from typing import Self, TypeVarTuple, Unpack
47
+ else:
48
+ from typing_extensions import Self, TypeVarTuple, Unpack
49
+
50
+ T_Retval = TypeVar("T_Retval")
51
+ T_co = TypeVar("T_co", covariant=True)
52
+ PosArgsT = TypeVarTuple("PosArgsT")
53
+
54
+
55
+ def _token_or_error(token: EventLoopToken | None) -> EventLoopToken:
56
+ if token is not None:
57
+ return token
58
+
59
+ try:
60
+ return threadlocals.current_token
61
+ except AttributeError:
62
+ raise NoEventLoopError(
63
+ "Not running inside an AnyIO worker thread, and no event loop token was "
64
+ "provided"
65
+ ) from None
66
+
67
+
68
+ def run(
69
+ func: Callable[[Unpack[PosArgsT]], Coroutine[Any, Any, T_co]],
70
+ *args: Unpack[PosArgsT],
71
+ token: EventLoopToken | None = None,
72
+ ) -> T_co:
73
+ """
74
+ Call a coroutine function from a worker thread.
75
+
76
+ :param func: a coroutine function
77
+ :param args: positional arguments for the callable
78
+ :param token: an event loop token to use to get back to the event loop thread
79
+ (required if calling this function from outside an AnyIO worker thread)
80
+ :return: the return value of the coroutine function
81
+ :raises MissingTokenError: if no token was provided and called from outside an
82
+ AnyIO worker thread
83
+ :raises RunFinishedError: if the event loop tied to ``token`` is no longer running
84
+
85
+ .. versionchanged:: 4.11.0
86
+ Added the ``token`` parameter.
87
+
88
+ """
89
+ explicit_token = token is not None
90
+ token = _token_or_error(token)
91
+ return token.backend_class.run_async_from_thread(
92
+ func, args, token=token.native_token if explicit_token else None
93
+ )
94
+
95
+
96
+ def run_sync(
97
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
98
+ *args: Unpack[PosArgsT],
99
+ token: EventLoopToken | None = None,
100
+ ) -> T_Retval:
101
+ """
102
+ Call a function in the event loop thread from a worker thread.
103
+
104
+ :param func: a callable
105
+ :param args: positional arguments for the callable
106
+ :param token: an event loop token to use to get back to the event loop thread
107
+ (required if calling this function from outside an AnyIO worker thread)
108
+ :return: the return value of the callable
109
+ :raises MissingTokenError: if no token was provided and called from outside an
110
+ AnyIO worker thread
111
+ :raises RunFinishedError: if the event loop tied to ``token`` is no longer running
112
+
113
+ .. versionchanged:: 4.11.0
114
+ Added the ``token`` parameter.
115
+
116
+ """
117
+ explicit_token = token is not None
118
+ token = _token_or_error(token)
119
+ return token.backend_class.run_sync_from_thread(
120
+ func, args, token=token.native_token if explicit_token else None
121
+ )
122
+
123
+
124
+ class _BlockingAsyncContextManager(AbstractContextManager, Generic[T_co]):
125
+ _enter_future: Future[T_co]
126
+ _exit_future: Future[bool | None]
127
+ _exit_event: Event
128
+ _exit_exc_info: tuple[
129
+ type[BaseException] | None, BaseException | None, TracebackType | None
130
+ ] = (None, None, None)
131
+
132
+ def __init__(
133
+ self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal
134
+ ):
135
+ self._async_cm = async_cm
136
+ self._portal = portal
137
+
138
+ async def run_async_cm(self) -> bool | None:
139
+ try:
140
+ self._exit_event = Event()
141
+ value = await self._async_cm.__aenter__()
142
+ except BaseException as exc:
143
+ self._enter_future.set_exception(exc)
144
+ raise
145
+ else:
146
+ self._enter_future.set_result(value)
147
+
148
+ try:
149
+ # Wait for the sync context manager to exit.
150
+ # This next statement can raise `get_cancelled_exc_class()` if
151
+ # something went wrong in a task group in this async context
152
+ # manager.
153
+ await self._exit_event.wait()
154
+ finally:
155
+ # In case of cancellation, it could be that we end up here before
156
+ # `_BlockingAsyncContextManager.__exit__` is called, and an
157
+ # `_exit_exc_info` has been set.
158
+ result = await self._async_cm.__aexit__(*self._exit_exc_info)
159
+
160
+ return result
161
+
162
+ def __enter__(self) -> T_co:
163
+ self._enter_future = Future()
164
+ self._exit_future = self._portal.start_task_soon(self.run_async_cm)
165
+ return self._enter_future.result()
166
+
167
+ def __exit__(
168
+ self,
169
+ exc_type: type[BaseException] | None,
170
+ exc_value: BaseException | None,
171
+ traceback: TracebackType | None,
172
+ /,
173
+ ) -> bool | None:
174
+ self._exit_exc_info = exc_type, exc_value, traceback
175
+ self._portal.call(self._exit_event.set)
176
+ return self._exit_future.result()
177
+
178
+
179
+ class _BlockingPortalTaskStatus(TaskStatus):
180
+ def __init__(self, future: Future):
181
+ self._future = future
182
+
183
+ def started(self, value: object = None) -> None:
184
+ self._future.set_result(value)
185
+
186
+
187
+ class BlockingPortal:
188
+ """
189
+ An object that lets external threads run code in an asynchronous event loop.
190
+
191
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
192
+ current thread
193
+ """
194
+
195
+ def __init__(self) -> None:
196
+ self._token = current_token()
197
+ self._event_loop_thread_id: int | None = get_ident()
198
+ self._stop_event = Event()
199
+ self._task_group = create_task_group()
200
+
201
+ async def __aenter__(self) -> Self:
202
+ await self._task_group.__aenter__()
203
+ return self
204
+
205
+ async def __aexit__(
206
+ self,
207
+ exc_type: type[BaseException] | None,
208
+ exc_val: BaseException | None,
209
+ exc_tb: TracebackType | None,
210
+ ) -> bool:
211
+ await self.stop()
212
+ return await self._task_group.__aexit__(exc_type, exc_val, exc_tb)
213
+
214
+ def _check_running(self) -> None:
215
+ if self._event_loop_thread_id is None:
216
+ raise RuntimeError("This portal is not running")
217
+ if self._event_loop_thread_id == get_ident():
218
+ raise RuntimeError(
219
+ "This method cannot be called from the event loop thread"
220
+ )
221
+
222
+ async def sleep_until_stopped(self) -> None:
223
+ """Sleep until :meth:`stop` is called."""
224
+ await self._stop_event.wait()
225
+
226
+ async def stop(self, cancel_remaining: bool = False) -> None:
227
+ """
228
+ Signal the portal to shut down.
229
+
230
+ This marks the portal as no longer accepting new calls and exits from
231
+ :meth:`sleep_until_stopped`.
232
+
233
+ :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False``
234
+ to let them finish before returning
235
+
236
+ """
237
+ self._event_loop_thread_id = None
238
+ self._stop_event.set()
239
+ if cancel_remaining:
240
+ self._task_group.cancel_scope.cancel("the blocking portal is shutting down")
241
+
242
+ async def _call_func(
243
+ self,
244
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
245
+ args: tuple[Unpack[PosArgsT]],
246
+ kwargs: dict[str, Any],
247
+ future: Future[T_Retval],
248
+ ) -> None:
249
+ event_loop_thread_id = self._event_loop_thread_id
250
+
251
+ def callback(f: Future[T_Retval]) -> None:
252
+ if f.cancelled():
253
+ if event_loop_thread_id == get_ident():
254
+ scope.cancel("the future was cancelled")
255
+ elif event_loop_thread_id is not None:
256
+ run_sync(
257
+ scope.cancel, "the future was cancelled", token=self._token
258
+ )
259
+
260
+ try:
261
+ retval_or_awaitable = func(*args, **kwargs)
262
+ if isawaitable(retval_or_awaitable):
263
+ with CancelScope() as scope:
264
+ future.add_done_callback(callback)
265
+ retval = await retval_or_awaitable
266
+ else:
267
+ retval = retval_or_awaitable
268
+ except get_cancelled_exc_class():
269
+ future.cancel()
270
+ future.set_running_or_notify_cancel()
271
+ except BaseException as exc:
272
+ if not future.cancelled():
273
+ future.set_exception(exc)
274
+
275
+ # Let base exceptions fall through
276
+ if not isinstance(exc, Exception):
277
+ raise
278
+ else:
279
+ if not future.cancelled():
280
+ future.set_result(retval)
281
+ finally:
282
+ scope = None # type: ignore[assignment]
283
+
284
+ def _spawn_task_from_thread(
285
+ self,
286
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
287
+ args: tuple[Unpack[PosArgsT]],
288
+ kwargs: dict[str, Any],
289
+ name: object,
290
+ future: Future[T_Retval],
291
+ ) -> None:
292
+ """
293
+ Spawn a new task using the given callable.
294
+
295
+ :param func: a callable
296
+ :param args: positional arguments to be passed to the callable
297
+ :param kwargs: keyword arguments to be passed to the callable
298
+ :param name: name of the task (will be coerced to a string if not ``None``)
299
+ :param future: a future that will resolve to the return value of the callable,
300
+ or the exception raised during its execution
301
+
302
+ """
303
+ run_sync(
304
+ partial(self._task_group.start_soon, name=name),
305
+ self._call_func,
306
+ func,
307
+ args,
308
+ kwargs,
309
+ future,
310
+ token=self._token,
311
+ )
312
+
313
+ @overload
314
+ def call(
315
+ self,
316
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
317
+ *args: Unpack[PosArgsT],
318
+ ) -> T_Retval: ...
319
+
320
+ @overload
321
+ def call(
322
+ self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT]
323
+ ) -> T_Retval: ...
324
+
325
+ def call(
326
+ self,
327
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
328
+ *args: Unpack[PosArgsT],
329
+ ) -> T_Retval:
330
+ """
331
+ Call the given function in the event loop thread.
332
+
333
+ If the callable returns a coroutine object, it is awaited on.
334
+
335
+ :param func: any callable
336
+ :raises RuntimeError: if the portal is not running or if this method is called
337
+ from within the event loop thread
338
+
339
+ """
340
+ return cast(T_Retval, self.start_task_soon(func, *args).result())
341
+
342
+ @overload
343
+ def start_task_soon(
344
+ self,
345
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
346
+ *args: Unpack[PosArgsT],
347
+ name: object = None,
348
+ ) -> Future[T_Retval]: ...
349
+
350
+ @overload
351
+ def start_task_soon(
352
+ self,
353
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
354
+ *args: Unpack[PosArgsT],
355
+ name: object = None,
356
+ ) -> Future[T_Retval]: ...
357
+
358
+ def start_task_soon(
359
+ self,
360
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
361
+ *args: Unpack[PosArgsT],
362
+ name: object = None,
363
+ ) -> Future[T_Retval]:
364
+ """
365
+ Start a task in the portal's task group.
366
+
367
+ The task will be run inside a cancel scope which can be cancelled by cancelling
368
+ the returned future.
369
+
370
+ :param func: the target function
371
+ :param args: positional arguments passed to ``func``
372
+ :param name: name of the task (will be coerced to a string if not ``None``)
373
+ :return: a future that resolves with the return value of the callable if the
374
+ task completes successfully, or with the exception raised in the task
375
+ :raises RuntimeError: if the portal is not running or if this method is called
376
+ from within the event loop thread
377
+ :rtype: concurrent.futures.Future[T_Retval]
378
+
379
+ .. versionadded:: 3.0
380
+
381
+ """
382
+ self._check_running()
383
+ f: Future[T_Retval] = Future()
384
+ self._spawn_task_from_thread(func, args, {}, name, f)
385
+ return f
386
+
387
+ def start_task(
388
+ self,
389
+ func: Callable[..., Awaitable[T_Retval]],
390
+ *args: object,
391
+ name: object = None,
392
+ ) -> tuple[Future[T_Retval], Any]:
393
+ """
394
+ Start a task in the portal's task group and wait until it signals for readiness.
395
+
396
+ This method works the same way as :meth:`.abc.TaskGroup.start`.
397
+
398
+ :param func: the target function
399
+ :param args: positional arguments passed to ``func``
400
+ :param name: name of the task (will be coerced to a string if not ``None``)
401
+ :return: a tuple of (future, task_status_value) where the ``task_status_value``
402
+ is the value passed to ``task_status.started()`` from within the target
403
+ function
404
+ :rtype: tuple[concurrent.futures.Future[T_Retval], Any]
405
+
406
+ .. versionadded:: 3.0
407
+
408
+ """
409
+
410
+ def task_done(future: Future[T_Retval]) -> None:
411
+ if not task_status_future.done():
412
+ if future.cancelled():
413
+ task_status_future.cancel()
414
+ elif future.exception():
415
+ task_status_future.set_exception(future.exception())
416
+ else:
417
+ exc = RuntimeError(
418
+ "Task exited without calling task_status.started()"
419
+ )
420
+ task_status_future.set_exception(exc)
421
+
422
+ self._check_running()
423
+ task_status_future: Future = Future()
424
+ task_status = _BlockingPortalTaskStatus(task_status_future)
425
+ f: Future = Future()
426
+ f.add_done_callback(task_done)
427
+ self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f)
428
+ return f, task_status_future.result()
429
+
430
+ def wrap_async_context_manager(
431
+ self, cm: AbstractAsyncContextManager[T_co]
432
+ ) -> AbstractContextManager[T_co]:
433
+ """
434
+ Wrap an async context manager as a synchronous context manager via this portal.
435
+
436
+ Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping
437
+ in the middle until the synchronous context manager exits.
438
+
439
+ :param cm: an asynchronous context manager
440
+ :return: a synchronous context manager
441
+
442
+ .. versionadded:: 2.1
443
+
444
+ """
445
+ return _BlockingAsyncContextManager(cm, self)
446
+
447
+
448
+ @dataclass
449
+ class BlockingPortalProvider:
450
+ """
451
+ A manager for a blocking portal. Used as a context manager. The first thread to
452
+ enter this context manager causes a blocking portal to be started with the specific
453
+ parameters, and the last thread to exit causes the portal to be shut down. Thus,
454
+ there will be exactly one blocking portal running in this context as long as at
455
+ least one thread has entered this context manager.
456
+
457
+ The parameters are the same as for :func:`~anyio.run`.
458
+
459
+ :param backend: name of the backend
460
+ :param backend_options: backend options
461
+
462
+ .. versionadded:: 4.4
463
+ """
464
+
465
+ backend: str = "asyncio"
466
+ backend_options: dict[str, Any] | None = None
467
+ _lock: Lock = field(init=False, default_factory=Lock)
468
+ _leases: int = field(init=False, default=0)
469
+ _portal: BlockingPortal = field(init=False)
470
+ _portal_cm: AbstractContextManager[BlockingPortal] | None = field(
471
+ init=False, default=None
472
+ )
473
+
474
+ def __enter__(self) -> BlockingPortal:
475
+ with self._lock:
476
+ if self._portal_cm is None:
477
+ self._portal_cm = start_blocking_portal(
478
+ self.backend, self.backend_options
479
+ )
480
+ self._portal = self._portal_cm.__enter__()
481
+
482
+ self._leases += 1
483
+ return self._portal
484
+
485
+ def __exit__(
486
+ self,
487
+ exc_type: type[BaseException] | None,
488
+ exc_val: BaseException | None,
489
+ exc_tb: TracebackType | None,
490
+ ) -> None:
491
+ portal_cm: AbstractContextManager[BlockingPortal] | None = None
492
+ with self._lock:
493
+ assert self._portal_cm
494
+ assert self._leases > 0
495
+ self._leases -= 1
496
+ if not self._leases:
497
+ portal_cm = self._portal_cm
498
+ self._portal_cm = None
499
+ del self._portal
500
+
501
+ if portal_cm:
502
+ portal_cm.__exit__(None, None, None)
503
+
504
+
505
+ @contextmanager
506
+ def start_blocking_portal(
507
+ backend: str = "asyncio",
508
+ backend_options: dict[str, Any] | None = None,
509
+ *,
510
+ name: str | None = None,
511
+ ) -> Generator[BlockingPortal, Any, None]:
512
+ """
513
+ Start a new event loop in a new thread and run a blocking portal in its main task.
514
+
515
+ The parameters are the same as for :func:`~anyio.run`.
516
+
517
+ :param backend: name of the backend
518
+ :param backend_options: backend options
519
+ :param name: name of the thread
520
+ :return: a context manager that yields a blocking portal
521
+
522
+ .. versionchanged:: 3.0
523
+ Usage as a context manager is now required.
524
+
525
+ """
526
+
527
+ async def run_portal() -> None:
528
+ async with BlockingPortal() as portal_:
529
+ if name is None:
530
+ current_thread().name = f"{backend}-portal-{id(portal_):x}"
531
+
532
+ future.set_result(portal_)
533
+ await portal_.sleep_until_stopped()
534
+
535
+ def run_blocking_portal() -> None:
536
+ if future.set_running_or_notify_cancel():
537
+ try:
538
+ run_eventloop(
539
+ run_portal, backend=backend, backend_options=backend_options
540
+ )
541
+ except BaseException as exc:
542
+ if not future.done():
543
+ future.set_exception(exc)
544
+
545
+ future: Future[BlockingPortal] = Future()
546
+ kwargs: dict[str, Any] = {}
547
+ if sys.version_info >= (3, 14):
548
+ kwargs["context"] = Context()
549
+
550
+ thread = Thread(target=run_blocking_portal, daemon=True, name=name, **kwargs)
551
+ thread.start()
552
+ try:
553
+ cancel_remaining_tasks = False
554
+ portal = future.result()
555
+ try:
556
+ yield portal
557
+ except BaseException:
558
+ cancel_remaining_tasks = True
559
+ raise
560
+ finally:
561
+ try:
562
+ portal.call(portal.stop, cancel_remaining_tasks)
563
+ except RuntimeError:
564
+ pass
565
+ finally:
566
+ thread.join()
567
+
568
+
569
+ def check_cancelled() -> None:
570
+ """
571
+ Check if the cancel scope of the host task's running the current worker thread has
572
+ been cancelled.
573
+
574
+ If the host task's current cancel scope has indeed been cancelled, the
575
+ backend-specific cancellation exception will be raised.
576
+
577
+ :raises RuntimeError: if the current thread was not spawned by
578
+ :func:`.to_thread.run_sync`
579
+
580
+ """
581
+ try:
582
+ token: EventLoopToken = threadlocals.current_token
583
+ except AttributeError:
584
+ raise NoEventLoopError(
585
+ "This function can only be called inside an AnyIO worker thread"
586
+ ) from None
587
+
588
+ token.backend_class.check_cancelled()
.venv/lib/python3.12/site-packages/anyio/functools.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "AsyncCacheInfo",
5
+ "AsyncCacheParameters",
6
+ "AsyncLRUCacheWrapper",
7
+ "cache",
8
+ "lru_cache",
9
+ "reduce",
10
+ )
11
+
12
+ import functools
13
+ from collections import OrderedDict
14
+ from collections.abc import (
15
+ AsyncIterable,
16
+ Awaitable,
17
+ Callable,
18
+ Coroutine,
19
+ Hashable,
20
+ Iterable,
21
+ )
22
+ from functools import update_wrapper
23
+ from inspect import iscoroutinefunction
24
+ from typing import (
25
+ Any,
26
+ Generic,
27
+ NamedTuple,
28
+ ParamSpec,
29
+ TypedDict,
30
+ TypeVar,
31
+ cast,
32
+ final,
33
+ overload,
34
+ )
35
+ from weakref import WeakKeyDictionary
36
+
37
+ from ._core._eventloop import current_time
38
+ from ._core._synchronization import Lock
39
+ from .lowlevel import RunVar, checkpoint
40
+
41
+ T = TypeVar("T")
42
+ S = TypeVar("S")
43
+ P = ParamSpec("P")
44
+ lru_cache_items: RunVar[
45
+ WeakKeyDictionary[
46
+ AsyncLRUCacheWrapper[Any, Any],
47
+ OrderedDict[
48
+ Hashable,
49
+ tuple[_InitialMissingType, Lock, float | None]
50
+ | tuple[Any, None, float | None],
51
+ ],
52
+ ]
53
+ ] = RunVar("lru_cache_items")
54
+
55
+
56
+ class _InitialMissingType:
57
+ pass
58
+
59
+
60
+ initial_missing: _InitialMissingType = _InitialMissingType()
61
+
62
+
63
+ class AsyncCacheInfo(NamedTuple):
64
+ hits: int
65
+ misses: int
66
+ maxsize: int | None
67
+ currsize: int
68
+ ttl: int | None
69
+
70
+
71
+ class AsyncCacheParameters(TypedDict):
72
+ maxsize: int | None
73
+ typed: bool
74
+ always_checkpoint: bool
75
+ ttl: int | None
76
+
77
+
78
+ class _LRUMethodWrapper(Generic[T]):
79
+ def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object):
80
+ self.__wrapper = wrapper
81
+ self.__instance = instance
82
+
83
+ def cache_info(self) -> AsyncCacheInfo:
84
+ return self.__wrapper.cache_info()
85
+
86
+ def cache_parameters(self) -> AsyncCacheParameters:
87
+ return self.__wrapper.cache_parameters()
88
+
89
+ def cache_clear(self) -> None:
90
+ self.__wrapper.cache_clear()
91
+
92
+ async def __call__(self, *args: Any, **kwargs: Any) -> T:
93
+ if self.__instance is None:
94
+ return await self.__wrapper(*args, **kwargs)
95
+
96
+ return await self.__wrapper(self.__instance, *args, **kwargs)
97
+
98
+
99
+ @final
100
+ class AsyncLRUCacheWrapper(Generic[P, T]):
101
+ def __init__(
102
+ self,
103
+ func: Callable[P, Awaitable[T]],
104
+ maxsize: int | None,
105
+ typed: bool,
106
+ always_checkpoint: bool,
107
+ ttl: int | None,
108
+ ):
109
+ self.__wrapped__ = func
110
+ self._hits: int = 0
111
+ self._misses: int = 0
112
+ self._maxsize = max(maxsize, 0) if maxsize is not None else None
113
+ self._currsize: int = 0
114
+ self._typed = typed
115
+ self._always_checkpoint = always_checkpoint
116
+ self._ttl = ttl
117
+ update_wrapper(self, func)
118
+
119
+ def cache_info(self) -> AsyncCacheInfo:
120
+ return AsyncCacheInfo(
121
+ self._hits, self._misses, self._maxsize, self._currsize, self._ttl
122
+ )
123
+
124
+ def cache_parameters(self) -> AsyncCacheParameters:
125
+ return {
126
+ "maxsize": self._maxsize,
127
+ "typed": self._typed,
128
+ "always_checkpoint": self._always_checkpoint,
129
+ "ttl": self._ttl,
130
+ }
131
+
132
+ def cache_clear(self) -> None:
133
+ if cache := lru_cache_items.get(None):
134
+ cache.pop(self, None)
135
+ self._hits = self._misses = self._currsize = 0
136
+
137
+ async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
138
+ # Easy case first: if maxsize == 0, no caching is done
139
+ if self._maxsize == 0:
140
+ value = await self.__wrapped__(*args, **kwargs)
141
+ self._misses += 1
142
+ return value
143
+
144
+ # The key is constructed as a flat tuple to avoid memory overhead
145
+ key: tuple[Any, ...] = args
146
+ if kwargs:
147
+ # initial_missing is used as a separator
148
+ key += (initial_missing,) + sum(kwargs.items(), ())
149
+
150
+ if self._typed:
151
+ key += tuple(type(arg) for arg in args)
152
+ if kwargs:
153
+ key += (initial_missing,) + tuple(type(val) for val in kwargs.values())
154
+
155
+ try:
156
+ cache = lru_cache_items.get()
157
+ except LookupError:
158
+ cache = WeakKeyDictionary()
159
+ lru_cache_items.set(cache)
160
+
161
+ try:
162
+ cache_entry = cache[self]
163
+ except KeyError:
164
+ cache_entry = cache[self] = OrderedDict()
165
+
166
+ cached_value: T | _InitialMissingType
167
+ try:
168
+ cached_value, lock, expires_at = cache_entry[key]
169
+ except KeyError:
170
+ # We're the first task to call this function
171
+ cached_value, lock, expires_at = (
172
+ initial_missing,
173
+ Lock(fast_acquire=not self._always_checkpoint),
174
+ None,
175
+ )
176
+ cache_entry[key] = cached_value, lock, expires_at
177
+
178
+ if lock is None:
179
+ if expires_at is not None and current_time() >= expires_at:
180
+ self._currsize -= 1
181
+ cached_value, lock, expires_at = (
182
+ initial_missing,
183
+ Lock(fast_acquire=not self._always_checkpoint),
184
+ None,
185
+ )
186
+ cache_entry[key] = cached_value, lock, expires_at
187
+ else:
188
+ # The value was already cached
189
+ self._hits += 1
190
+ cache_entry.move_to_end(key)
191
+ if self._always_checkpoint:
192
+ await checkpoint()
193
+
194
+ return cast(T, cached_value)
195
+
196
+ async with lock:
197
+ # Check if another task filled the cache while we acquired the lock
198
+ if (cached_value := cache_entry[key][0]) is initial_missing:
199
+ self._misses += 1
200
+ if self._maxsize is not None and self._currsize >= self._maxsize:
201
+ cache_entry.popitem(last=False)
202
+ else:
203
+ self._currsize += 1
204
+
205
+ value = await self.__wrapped__(*args, **kwargs)
206
+ expires_at = (
207
+ current_time() + self._ttl if self._ttl is not None else None
208
+ )
209
+ cache_entry[key] = value, None, expires_at
210
+ else:
211
+ # Another task filled the cache while we were waiting for the lock
212
+ self._hits += 1
213
+ cache_entry.move_to_end(key)
214
+ value = cast(T, cached_value)
215
+
216
+ return value
217
+
218
+ def __get__(
219
+ self, instance: object, owner: type | None = None
220
+ ) -> _LRUMethodWrapper[T]:
221
+ wrapper = _LRUMethodWrapper(self, instance)
222
+ update_wrapper(wrapper, self.__wrapped__)
223
+ return wrapper
224
+
225
+
226
+ class _LRUCacheWrapper:
227
+ def __init__(
228
+ self, maxsize: int | None, typed: bool, always_checkpoint: bool, ttl: int | None
229
+ ):
230
+ self._maxsize = maxsize
231
+ self._typed = typed
232
+ self._always_checkpoint = always_checkpoint
233
+ self._ttl = ttl
234
+
235
+ @overload
236
+ def __call__( # type: ignore[overload-overlap]
237
+ self, func: Callable[P, Coroutine[Any, Any, T]], /
238
+ ) -> AsyncLRUCacheWrapper[P, T]: ...
239
+
240
+ @overload
241
+ def __call__(
242
+ self, func: Callable[..., T], /
243
+ ) -> functools._lru_cache_wrapper[T]: ...
244
+
245
+ def __call__(
246
+ self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], /
247
+ ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]:
248
+ if iscoroutinefunction(f):
249
+ return AsyncLRUCacheWrapper(
250
+ f, self._maxsize, self._typed, self._always_checkpoint, self._ttl
251
+ )
252
+
253
+ return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type]
254
+
255
+
256
+ @overload
257
+ def cache( # type: ignore[overload-overlap]
258
+ func: Callable[P, Coroutine[Any, Any, T]], /
259
+ ) -> AsyncLRUCacheWrapper[P, T]: ...
260
+
261
+
262
+ @overload
263
+ def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ...
264
+
265
+
266
+ def cache(func: Callable[..., Any] | Callable[P, Coroutine[Any, Any, Any]], /) -> Any:
267
+ """
268
+ A convenient shortcut for :func:`lru_cache` with ``maxsize=None``.
269
+
270
+ This is the asynchronous equivalent to :func:`functools.cache`.
271
+
272
+ """
273
+ return lru_cache(maxsize=None)(func)
274
+
275
+
276
+ @overload
277
+ def lru_cache(
278
+ *,
279
+ maxsize: int | None = ...,
280
+ typed: bool = ...,
281
+ always_checkpoint: bool = ...,
282
+ ttl: int | None = ...,
283
+ ) -> _LRUCacheWrapper: ...
284
+
285
+
286
+ @overload
287
+ def lru_cache( # type: ignore[overload-overlap]
288
+ func: Callable[P, Coroutine[Any, Any, T]], /
289
+ ) -> AsyncLRUCacheWrapper[P, T]: ...
290
+
291
+
292
+ @overload
293
+ def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ...
294
+
295
+
296
+ def lru_cache(
297
+ func: Callable[..., Coroutine[Any, Any, Any]] | Callable[..., Any] | None = None,
298
+ /,
299
+ *,
300
+ maxsize: int | None = 128,
301
+ typed: bool = False,
302
+ always_checkpoint: bool = False,
303
+ ttl: int | None = None,
304
+ ) -> Any:
305
+ """
306
+ An asynchronous version of :func:`functools.lru_cache`.
307
+
308
+ If a synchronous function is passed, the standard library
309
+ :func:`functools.lru_cache` is applied instead.
310
+
311
+ :param always_checkpoint: if ``True``, every call to the cached function will be
312
+ guaranteed to yield control to the event loop at least once
313
+ :param ttl: time in seconds after which to invalidate cache entries
314
+
315
+ .. note:: Caches and locks are managed on a per-event loop basis.
316
+
317
+ """
318
+ if func is None:
319
+ return _LRUCacheWrapper(maxsize, typed, always_checkpoint, ttl)
320
+
321
+ if not callable(func):
322
+ raise TypeError("the first argument must be callable")
323
+
324
+ return _LRUCacheWrapper(maxsize, typed, always_checkpoint, ttl)(func)
325
+
326
+
327
+ @overload
328
+ async def reduce(
329
+ function: Callable[[T, S], Awaitable[T]],
330
+ iterable: Iterable[S] | AsyncIterable[S],
331
+ /,
332
+ initial: T,
333
+ ) -> T: ...
334
+
335
+
336
+ @overload
337
+ async def reduce(
338
+ function: Callable[[T, T], Awaitable[T]],
339
+ iterable: Iterable[T] | AsyncIterable[T],
340
+ /,
341
+ ) -> T: ...
342
+
343
+
344
+ async def reduce( # type: ignore[misc]
345
+ function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]],
346
+ iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S],
347
+ /,
348
+ initial: T | _InitialMissingType = initial_missing,
349
+ ) -> T:
350
+ """
351
+ Asynchronous version of :func:`functools.reduce`.
352
+
353
+ :param function: a coroutine function that takes two arguments: the accumulated
354
+ value and the next element from the iterable
355
+ :param iterable: an iterable or async iterable
356
+ :param initial: the initial value (if missing, the first element of the iterable is
357
+ used as the initial value)
358
+
359
+ """
360
+ element: Any
361
+ function_called = False
362
+ if isinstance(iterable, AsyncIterable):
363
+ async_it = iterable.__aiter__()
364
+ if initial is initial_missing:
365
+ try:
366
+ value = cast(T, await async_it.__anext__())
367
+ except StopAsyncIteration:
368
+ raise TypeError(
369
+ "reduce() of empty sequence with no initial value"
370
+ ) from None
371
+ else:
372
+ value = cast(T, initial)
373
+
374
+ async for element in async_it:
375
+ value = await function(value, element)
376
+ function_called = True
377
+ elif isinstance(iterable, Iterable):
378
+ it = iter(iterable)
379
+ if initial is initial_missing:
380
+ try:
381
+ value = cast(T, next(it))
382
+ except StopIteration:
383
+ raise TypeError(
384
+ "reduce() of empty sequence with no initial value"
385
+ ) from None
386
+ else:
387
+ value = cast(T, initial)
388
+
389
+ for element in it:
390
+ value = await function(value, element)
391
+ function_called = True
392
+ else:
393
+ raise TypeError("reduce() argument 2 must be an iterable or async iterable")
394
+
395
+ # Make sure there is at least one checkpoint, even if an empty iterable and an
396
+ # initial value were given
397
+ if not function_called:
398
+ await checkpoint()
399
+
400
+ return value
.venv/lib/python3.12/site-packages/anyio/itertools.py ADDED
@@ -0,0 +1,629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "Chain",
5
+ "accumulate",
6
+ "batched",
7
+ "combinations",
8
+ "combinations_with_replacement",
9
+ "compress",
10
+ "count",
11
+ "cycle",
12
+ "dropwhile",
13
+ "filterfalse",
14
+ "groupby",
15
+ "islice",
16
+ "pairwise",
17
+ "permutations",
18
+ "product",
19
+ "repeat",
20
+ "starmap",
21
+ "takewhile",
22
+ "tee",
23
+ "zip_longest",
24
+ )
25
+
26
+ import itertools
27
+ import operator
28
+ import sys
29
+ from collections.abc import (
30
+ AsyncGenerator,
31
+ AsyncIterable,
32
+ AsyncIterator,
33
+ Awaitable,
34
+ Callable,
35
+ Iterable,
36
+ Iterator,
37
+ )
38
+ from dataclasses import dataclass, field
39
+ from typing import Any, Generic, TypeVar, cast, overload
40
+
41
+ from ._core._synchronization import Lock
42
+ from ._core._tasks import CancelScope
43
+ from .lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled
44
+
45
+ if sys.version_info < (3, 15):
46
+ from typing_extensions import sentinel
47
+
48
+ T = TypeVar("T")
49
+ R = TypeVar("R")
50
+ _tee_end = sentinel("_tee_end")
51
+
52
+
53
+ @dataclass(eq=False)
54
+ class _IterableAsyncIterator(AsyncIterator[T]):
55
+ iterator: Iterator[T]
56
+
57
+ async def __anext__(self) -> T:
58
+ await checkpoint_if_cancelled()
59
+ try:
60
+ result = next(self.iterator)
61
+ except StopIteration:
62
+ await cancel_shielded_checkpoint()
63
+ raise StopAsyncIteration from None
64
+
65
+ await cancel_shielded_checkpoint()
66
+ return result
67
+
68
+
69
+ def _iterate(iterable: Iterable[T] | AsyncIterable[T]) -> AsyncIterator[T]:
70
+ if isinstance(iterable, AsyncIterator):
71
+ return iterable
72
+
73
+ if isinstance(iterable, AsyncIterable):
74
+ return iterable.__aiter__()
75
+
76
+ return _IterableAsyncIterator(iter(iterable))
77
+
78
+
79
+ @dataclass(eq=False)
80
+ class _TeeLink(Generic[T]):
81
+ value: object | None = None
82
+ next: _TeeLink[T] | None = None
83
+ filled: bool = False
84
+
85
+
86
+ @dataclass(eq=False)
87
+ class _TeeState(Generic[T]):
88
+ iterator: AsyncIterator[T]
89
+ lock: Lock = field(default_factory=Lock)
90
+
91
+ async def fill(self, link: _TeeLink[T]) -> bool:
92
+ if link.filled:
93
+ return False
94
+
95
+ async with self.lock:
96
+ if link.filled:
97
+ return True
98
+
99
+ link.value = await anext(self.iterator, _tee_end)
100
+ if link.value is not _tee_end:
101
+ link.next = _TeeLink()
102
+
103
+ link.filled = True
104
+ return True
105
+
106
+
107
+ class _TeeAsyncIterator(AsyncIterator[T]):
108
+ _state: _TeeState[T]
109
+ _link: _TeeLink[T]
110
+ _element_yielded: bool
111
+
112
+ def __init__(
113
+ self, iterable: Iterable[T] | AsyncIterable[T] | _TeeAsyncIterator[T]
114
+ ) -> None:
115
+ if isinstance(iterable, _TeeAsyncIterator):
116
+ self._state = iterable._state
117
+ self._link = iterable._link
118
+ else:
119
+ self._state = _TeeState(_iterate(iterable))
120
+ self._link = _TeeLink()
121
+
122
+ self._element_yielded = False
123
+
124
+ async def __anext__(self) -> T:
125
+ had_yieldpoint = await self._state.fill(self._link)
126
+ if self._link.value is _tee_end:
127
+ if not self._element_yielded:
128
+ await checkpoint()
129
+
130
+ raise StopAsyncIteration
131
+
132
+ if not had_yieldpoint:
133
+ await checkpoint_if_cancelled()
134
+
135
+ self._element_yielded = True
136
+ value = cast(T, self._link.value)
137
+ next_link = self._link.next
138
+ assert next_link is not None
139
+ self._link = next_link
140
+ if not had_yieldpoint:
141
+ await cancel_shielded_checkpoint()
142
+
143
+ return value
144
+
145
+
146
+ async def _operator_add(x: T, y: T) -> T:
147
+ return operator.add(x, y)
148
+
149
+
150
+ async def accumulate(
151
+ iterable: Iterable[T] | AsyncIterable[T],
152
+ function: Callable[[T, T], Awaitable[T]] = _operator_add,
153
+ *,
154
+ initial: T | None = None,
155
+ ) -> AsyncGenerator[T, None]:
156
+ iterator = _iterate(iterable)
157
+ if initial is None:
158
+ try:
159
+ total = await anext(iterator)
160
+ except StopAsyncIteration:
161
+ await checkpoint()
162
+ return
163
+ else:
164
+ await checkpoint_if_cancelled()
165
+ total = initial
166
+ await cancel_shielded_checkpoint()
167
+
168
+ yield total
169
+
170
+ async for element in iterator:
171
+ total = await function(total, element)
172
+ yield total
173
+
174
+
175
+ async def batched(
176
+ iterable: Iterable[T] | AsyncIterable[T], n: int, *, strict: bool = False
177
+ ) -> AsyncGenerator[tuple[T, ...], None]:
178
+ if n < 1:
179
+ raise ValueError("n must be at least one")
180
+
181
+ iterator = _iterate(iterable)
182
+
183
+ while True:
184
+ batch: list[T] = []
185
+ for _ in range(n):
186
+ try:
187
+ batch.append(await anext(iterator))
188
+ except StopAsyncIteration:
189
+ if not batch:
190
+ await checkpoint()
191
+ return
192
+ if strict:
193
+ raise ValueError("batched(): incomplete batch") from None
194
+
195
+ yield tuple(batch)
196
+ return
197
+
198
+ yield tuple(batch)
199
+
200
+
201
+ class Chain:
202
+ def __call__(
203
+ self, *iterables: Iterable[T] | AsyncIterable[T]
204
+ ) -> AsyncGenerator[T, None]:
205
+ return self.from_iterable(iterables)
206
+
207
+ async def from_iterable(
208
+ self,
209
+ iterables: (
210
+ Iterable[Iterable[T] | AsyncIterable[T]]
211
+ | AsyncIterable[Iterable[T] | AsyncIterable[T]]
212
+ ),
213
+ ) -> AsyncGenerator[T, None]:
214
+ element_yielded = False
215
+ outer_iter = _iterate(iterables)
216
+
217
+ try:
218
+ async for iterable in outer_iter:
219
+ async for element in _iterate(iterable):
220
+ element_yielded = True
221
+ yield element
222
+ finally:
223
+ aclose = getattr(outer_iter, "aclose", None)
224
+ if aclose is not None:
225
+ with CancelScope(shield=True):
226
+ await aclose()
227
+
228
+ if not element_yielded:
229
+ await checkpoint()
230
+
231
+
232
+ chain: Chain = Chain()
233
+
234
+
235
+ async def combinations(
236
+ iterable: Iterable[T] | AsyncIterable[T], r: int
237
+ ) -> AsyncGenerator[tuple[T, ...], None]:
238
+ pool: list[T] = [element async for element in _iterate(iterable)]
239
+ async for combination in _iterate(itertools.combinations(pool, r)):
240
+ yield combination
241
+
242
+
243
+ async def combinations_with_replacement(
244
+ iterable: Iterable[T] | AsyncIterable[T], r: int
245
+ ) -> AsyncGenerator[tuple[T, ...], None]:
246
+ pool: list[T] = [element async for element in _iterate(iterable)]
247
+ async for combination in _iterate(itertools.combinations_with_replacement(pool, r)):
248
+ yield combination
249
+
250
+
251
+ async def compress(
252
+ data: Iterable[T] | AsyncIterable[T],
253
+ selectors: Iterable[object] | AsyncIterable[object],
254
+ ) -> AsyncGenerator[T, None]:
255
+ data_iterator = _iterate(data)
256
+ selector_iterator = _iterate(selectors)
257
+ element_yielded = False
258
+
259
+ while True:
260
+ try:
261
+ datum = await anext(data_iterator)
262
+ selector = await anext(selector_iterator)
263
+ except StopAsyncIteration:
264
+ if not element_yielded:
265
+ await checkpoint()
266
+
267
+ return
268
+
269
+ if selector:
270
+ element_yielded = True
271
+ yield datum
272
+
273
+
274
+ async def count(start: int = 0, step: int = 1) -> AsyncGenerator[int, None]:
275
+ n = start
276
+ while True:
277
+ await checkpoint_if_cancelled()
278
+ value = n
279
+ n += step
280
+ await cancel_shielded_checkpoint()
281
+ yield value
282
+
283
+
284
+ async def cycle(
285
+ iterable: Iterable[T] | AsyncIterable[T],
286
+ ) -> AsyncGenerator[T, None]:
287
+ saved: list[T] = []
288
+ async for element in _iterate(iterable):
289
+ saved.append(element)
290
+ yield element
291
+
292
+ if not saved:
293
+ await checkpoint()
294
+ return
295
+
296
+ while True:
297
+ for element in saved:
298
+ await checkpoint()
299
+ yield element
300
+
301
+
302
+ async def dropwhile(
303
+ predicate: Callable[[T], Awaitable[object]],
304
+ iterable: Iterable[T] | AsyncIterable[T],
305
+ ) -> AsyncGenerator[T, None]:
306
+ element_yielded = False
307
+ dropping = True
308
+
309
+ async for element in _iterate(iterable):
310
+ if dropping and await predicate(element):
311
+ continue
312
+
313
+ dropping = False
314
+ element_yielded = True
315
+ yield element
316
+
317
+ if not element_yielded:
318
+ await checkpoint()
319
+
320
+
321
+ async def filterfalse(
322
+ predicate: Callable[[T], Awaitable[object]],
323
+ iterable: Iterable[T] | AsyncIterable[T],
324
+ ) -> AsyncGenerator[T, None]:
325
+ element_yielded = False
326
+
327
+ async for element in _iterate(iterable):
328
+ if not await predicate(element):
329
+ element_yielded = True
330
+ yield element
331
+
332
+ if not element_yielded:
333
+ await checkpoint()
334
+
335
+
336
+ @overload
337
+ def groupby(
338
+ iterable: Iterable[T] | AsyncIterable[T],
339
+ ) -> AsyncGenerator[tuple[T, list[T]], None]: ...
340
+
341
+
342
+ @overload
343
+ def groupby(
344
+ iterable: Iterable[T] | AsyncIterable[T],
345
+ key: Callable[[T], Awaitable[R]],
346
+ ) -> AsyncGenerator[tuple[R, list[T]], None]: ...
347
+
348
+
349
+ async def groupby(
350
+ iterable: Iterable[T] | AsyncIterable[T],
351
+ key: Callable[[T], Awaitable[object]] | None = None,
352
+ ) -> AsyncGenerator[tuple[object, list[T]], None]:
353
+ iterator = _iterate(iterable)
354
+ try:
355
+ element = await anext(iterator)
356
+ except StopAsyncIteration:
357
+ await checkpoint()
358
+ return
359
+
360
+ group_key = element if key is None else await key(element)
361
+ values = [element]
362
+
363
+ async for element in iterator:
364
+ next_key = element if key is None else await key(element)
365
+ if next_key != group_key:
366
+ completed_group = group_key, values
367
+ group_key = next_key
368
+ values = [element]
369
+ yield completed_group
370
+ else:
371
+ values.append(element)
372
+
373
+ yield group_key, values
374
+
375
+
376
+ @overload
377
+ def islice(
378
+ iterable: Iterable[T] | AsyncIterable[T],
379
+ stop: int | None,
380
+ /,
381
+ ) -> AsyncGenerator[T, None]: ...
382
+
383
+
384
+ @overload
385
+ def islice(
386
+ iterable: Iterable[T] | AsyncIterable[T],
387
+ start: int | None,
388
+ stop: int | None,
389
+ step: int | None = 1,
390
+ /,
391
+ ) -> AsyncGenerator[T, None]: ...
392
+
393
+
394
+ async def islice(
395
+ iterable: Iterable[T] | AsyncIterable[T],
396
+ *args: int | None,
397
+ ) -> AsyncGenerator[T, None]:
398
+ if not args:
399
+ raise TypeError("islice expected at least 2 arguments, got 1")
400
+ if len(args) > 3:
401
+ raise TypeError(f"islice expected at most 4 arguments, got {len(args) + 1}")
402
+
403
+ slice_args = slice(*args)
404
+
405
+ start_message = (
406
+ "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."
407
+ )
408
+ stop_message = (
409
+ "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."
410
+ )
411
+ step_message = "Step for islice() must be a positive integer or None."
412
+
413
+ def normalize_index(value: object, message: str) -> int:
414
+ try:
415
+ index = operator.index(cast(Any, value))
416
+ except TypeError:
417
+ raise ValueError(message) from None
418
+
419
+ if index < 0 or index > sys.maxsize:
420
+ raise ValueError(message)
421
+
422
+ return index
423
+
424
+ start = (
425
+ 0
426
+ if slice_args.start is None
427
+ else normalize_index(slice_args.start, start_message)
428
+ )
429
+ stop = (
430
+ None
431
+ if slice_args.stop is None
432
+ else normalize_index(slice_args.stop, stop_message)
433
+ )
434
+ step = (
435
+ 1 if slice_args.step is None else normalize_index(slice_args.step, step_message)
436
+ )
437
+
438
+ if step <= 0:
439
+ raise ValueError(step_message)
440
+
441
+ if stop == 0 or start == stop:
442
+ await checkpoint()
443
+ return
444
+
445
+ iterator = _iterate(iterable)
446
+ index = 0
447
+ element_yielded = False
448
+
449
+ while stop is None or index < stop:
450
+ try:
451
+ element = await anext(iterator)
452
+ except StopAsyncIteration:
453
+ if not element_yielded:
454
+ await checkpoint()
455
+
456
+ return
457
+
458
+ if index >= start and (index - start) % step == 0:
459
+ index += 1
460
+ element_yielded = True
461
+ yield element
462
+ else:
463
+ index += 1
464
+
465
+ if not element_yielded:
466
+ await checkpoint()
467
+
468
+
469
+ async def pairwise(
470
+ iterable: Iterable[T] | AsyncIterable[T],
471
+ ) -> AsyncGenerator[tuple[T, T], None]:
472
+ iterator = _iterate(iterable)
473
+ try:
474
+ previous = await anext(iterator)
475
+ except StopAsyncIteration:
476
+ await checkpoint()
477
+ return
478
+
479
+ element_yielded = False
480
+ async for element in iterator:
481
+ element_yielded = True
482
+ pair = (previous, element)
483
+ previous = element
484
+ yield pair
485
+
486
+ if not element_yielded:
487
+ await checkpoint()
488
+
489
+
490
+ async def permutations(
491
+ iterable: Iterable[T] | AsyncIterable[T], r: int | None = None
492
+ ) -> AsyncGenerator[tuple[T, ...], None]:
493
+ pool: list[T] = [element async for element in _iterate(iterable)]
494
+ n = len(pool)
495
+ if r is None:
496
+ r = n
497
+ elif not isinstance(r, int):
498
+ raise TypeError("Expected int as r")
499
+ elif r < 0:
500
+ raise ValueError("r must be non-negative")
501
+
502
+ async for permutation in _iterate(itertools.permutations(pool, r)):
503
+ yield permutation
504
+
505
+
506
+ async def product(
507
+ *iterables: Iterable[T] | AsyncIterable[T], repeat: int = 1
508
+ ) -> AsyncGenerator[tuple[T, ...], None]:
509
+ repeat = operator.index(repeat)
510
+ if repeat < 0:
511
+ raise ValueError("repeat argument cannot be negative")
512
+
513
+ pools: list[tuple[T, ...]] = []
514
+ for iterable in iterables:
515
+ pool: list[T] = [element async for element in _iterate(iterable)]
516
+ pools.append(tuple(pool))
517
+
518
+ async for value in _iterate(itertools.product(*pools, repeat=repeat)):
519
+ yield value
520
+
521
+
522
+ async def repeat(element: T, times: int | None = None) -> AsyncGenerator[T, None]:
523
+ if times is None:
524
+ while True:
525
+ await checkpoint()
526
+ yield element
527
+
528
+ remaining = operator.index(cast(Any, times))
529
+ if remaining <= 0:
530
+ await checkpoint()
531
+ return
532
+
533
+ while remaining > 0:
534
+ await checkpoint_if_cancelled()
535
+ remaining -= 1
536
+ await cancel_shielded_checkpoint()
537
+ yield element
538
+
539
+
540
+ async def starmap(
541
+ function: Callable[..., Awaitable[R]],
542
+ iterable: (
543
+ Iterable[Iterable[object] | AsyncIterable[object]]
544
+ | AsyncIterable[Iterable[object] | AsyncIterable[object]]
545
+ ),
546
+ ) -> AsyncGenerator[R, None]:
547
+ result_yielded = False
548
+
549
+ async for args_iterable in _iterate(iterable):
550
+ args = [element async for element in _iterate(args_iterable)]
551
+ result_yielded = True
552
+ yield await function(*args)
553
+
554
+ if not result_yielded:
555
+ await checkpoint()
556
+
557
+
558
+ def tee(
559
+ iterable: Iterable[T] | AsyncIterable[T], n: int = 2
560
+ ) -> tuple[AsyncIterator[T], ...]:
561
+ n = operator.index(cast(Any, n))
562
+ if n < 0:
563
+ raise ValueError("n must be >= 0")
564
+ if n == 0:
565
+ return ()
566
+
567
+ iterator = _TeeAsyncIterator(iterable)
568
+ iterators: list[AsyncIterator[T]] = [iterator]
569
+ iterators.extend(_TeeAsyncIterator(iterator) for _ in range(n - 1))
570
+ return tuple(iterators)
571
+
572
+
573
+ async def takewhile(
574
+ predicate: Callable[[T], Awaitable[object]],
575
+ iterable: Iterable[T] | AsyncIterable[T],
576
+ ) -> AsyncGenerator[T, None]:
577
+ element_yielded = False
578
+
579
+ async for element in _iterate(iterable):
580
+ if not await predicate(element):
581
+ if not element_yielded:
582
+ await checkpoint()
583
+
584
+ return
585
+
586
+ element_yielded = True
587
+ yield element
588
+
589
+ if not element_yielded:
590
+ await checkpoint()
591
+
592
+
593
+ async def zip_longest(
594
+ *iterables: Iterable[object] | AsyncIterable[object],
595
+ fillvalue: object = None,
596
+ ) -> AsyncGenerator[tuple[object, ...], None]:
597
+ iterators = [_iterate(iterable) for iterable in iterables]
598
+ num_active = len(iterators)
599
+ if not num_active:
600
+ await checkpoint()
601
+ return
602
+
603
+ active = [True] * num_active
604
+ tuple_yielded = False
605
+
606
+ while True:
607
+ values: list[object] = []
608
+ for index, iterator in enumerate(iterators):
609
+ if not active[index]:
610
+ values.append(fillvalue)
611
+ continue
612
+
613
+ try:
614
+ value = await anext(iterator)
615
+ except StopAsyncIteration:
616
+ active[index] = False
617
+ num_active -= 1
618
+ if not num_active:
619
+ if not tuple_yielded:
620
+ await checkpoint()
621
+
622
+ return
623
+
624
+ value = fillvalue
625
+
626
+ values.append(value)
627
+
628
+ tuple_yielded = True
629
+ yield tuple(values)
.venv/lib/python3.12/site-packages/anyio/lowlevel.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "EventLoopToken",
5
+ "RunVar",
6
+ "RunvarToken",
7
+ "cancel_shielded_checkpoint",
8
+ "checkpoint",
9
+ "checkpoint_if_cancelled",
10
+ "current_token",
11
+ )
12
+
13
+ import enum
14
+ from dataclasses import dataclass
15
+ from types import TracebackType
16
+ from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, final, overload
17
+ from weakref import WeakKeyDictionary
18
+
19
+ from ._core._eventloop import get_async_backend
20
+
21
+ if TYPE_CHECKING:
22
+ from .abc import AsyncBackend
23
+
24
+ T = TypeVar("T")
25
+ D = TypeVar("D")
26
+
27
+
28
+ async def checkpoint() -> None:
29
+ """
30
+ Check for cancellation and allow the scheduler to switch to another task.
31
+
32
+ Equivalent to (but more efficient than)::
33
+
34
+ await checkpoint_if_cancelled()
35
+ await cancel_shielded_checkpoint()
36
+
37
+ .. versionadded:: 3.0
38
+
39
+ """
40
+ await get_async_backend().checkpoint()
41
+
42
+
43
+ async def checkpoint_if_cancelled() -> None:
44
+ """
45
+ Enter a checkpoint if the enclosing cancel scope has been cancelled.
46
+
47
+ This does not allow the scheduler to switch to a different task.
48
+
49
+ .. versionadded:: 3.0
50
+
51
+ """
52
+ await get_async_backend().checkpoint_if_cancelled()
53
+
54
+
55
+ async def cancel_shielded_checkpoint() -> None:
56
+ """
57
+ Allow the scheduler to switch to another task but without checking for cancellation.
58
+
59
+ Equivalent to (but potentially more efficient than)::
60
+
61
+ with CancelScope(shield=True):
62
+ await checkpoint()
63
+
64
+ .. versionadded:: 3.0
65
+
66
+ """
67
+ await get_async_backend().cancel_shielded_checkpoint()
68
+
69
+
70
+ @final
71
+ @dataclass(frozen=True, repr=False)
72
+ class EventLoopToken:
73
+ """
74
+ An opaque object that holds a reference to an event loop.
75
+
76
+ .. versionadded:: 4.11.0
77
+ """
78
+
79
+ backend_class: type[AsyncBackend]
80
+ native_token: object
81
+
82
+
83
+ def current_token() -> EventLoopToken:
84
+ """
85
+ Return a token object that can be used to call code in the current event loop from
86
+ another thread.
87
+
88
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
89
+ current thread
90
+
91
+ .. versionadded:: 4.11.0
92
+
93
+ """
94
+ backend_class = get_async_backend()
95
+ raw_token = backend_class.current_token()
96
+ return EventLoopToken(backend_class, raw_token)
97
+
98
+
99
+ _run_vars: WeakKeyDictionary[object, dict[RunVar[Any], Any]] = WeakKeyDictionary()
100
+
101
+
102
+ class _NoValueSet(enum.Enum):
103
+ NO_VALUE_SET = enum.auto()
104
+
105
+
106
+ class RunvarToken(Generic[T]):
107
+ """
108
+ A token that can be used to restore a :class:`RunVar` to its previous value.
109
+
110
+ Returned by :meth:`RunVar.set`. Can be used as a context manager to automatically
111
+ reset the variable on exit, or passed directly to :meth:`RunVar.reset`.
112
+ """
113
+
114
+ __slots__ = "_redeemed", "_value", "_var"
115
+
116
+ def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]):
117
+ self._var = var
118
+ self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value
119
+ self._redeemed = False
120
+
121
+ def __enter__(self) -> RunvarToken[T]:
122
+ return self
123
+
124
+ def __exit__(
125
+ self,
126
+ exc_type: type[BaseException] | None,
127
+ exc_val: BaseException | None,
128
+ exc_tb: TracebackType | None,
129
+ ) -> None:
130
+ self._var.reset(self)
131
+
132
+
133
+ class RunVar(Generic[T]):
134
+ """
135
+ Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop.
136
+
137
+ Can be used as a context manager, Just like :class:`~contextvars.ContextVar`, that
138
+ will reset the variable to its previous value when the context block is exited.
139
+ """
140
+
141
+ __slots__ = "_default", "_name"
142
+
143
+ NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET
144
+
145
+ def __init__(
146
+ self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET
147
+ ):
148
+ self._name = name
149
+ self._default = default
150
+
151
+ @property
152
+ def _current_vars(self) -> dict[RunVar[T], T]:
153
+ native_token = current_token().native_token
154
+ try:
155
+ return _run_vars[native_token]
156
+ except KeyError:
157
+ run_vars = _run_vars[native_token] = {}
158
+ return run_vars
159
+
160
+ @overload
161
+ def get(self, default: D) -> T | D: ...
162
+
163
+ @overload
164
+ def get(self) -> T: ...
165
+
166
+ def get(
167
+ self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET
168
+ ) -> T | D:
169
+ """
170
+ Return the current value of this run variable.
171
+
172
+ :param default: a fallback value to return if no value has been set
173
+ :return: the current value, the provided default, or the variable's own default
174
+ :raises LookupError: if no value is set and no default is available
175
+
176
+ """
177
+ try:
178
+ return self._current_vars[self]
179
+ except KeyError:
180
+ if default is not RunVar.NO_VALUE_SET:
181
+ return default
182
+ elif self._default is not RunVar.NO_VALUE_SET:
183
+ return self._default
184
+
185
+ raise LookupError(
186
+ f'Run variable "{self._name}" has no value and no default set'
187
+ )
188
+
189
+ def set(self, value: T) -> RunvarToken[T]:
190
+ """
191
+ Set the value of this run variable for the current event loop.
192
+
193
+ :param value: the new value
194
+ :return: a token that can be used to restore the previous value
195
+
196
+ """
197
+ current_vars = self._current_vars
198
+ token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET))
199
+ current_vars[self] = value
200
+ return token
201
+
202
+ def reset(self, token: RunvarToken[T]) -> None:
203
+ """
204
+ Restore this run variable to the value it held before the matching :meth:`set`.
205
+
206
+ :param token: the token returned by :meth:`set`
207
+ :raises ValueError: if the token belongs to a different :class:`RunVar` or the token
208
+ has already been used
209
+
210
+ """
211
+ if token._var is not self:
212
+ raise ValueError("This token does not belong to this RunVar")
213
+
214
+ if token._redeemed:
215
+ raise ValueError("This token has already been used")
216
+
217
+ if token._value is _NoValueSet.NO_VALUE_SET:
218
+ try:
219
+ del self._current_vars[self]
220
+ except KeyError:
221
+ pass
222
+ else:
223
+ self._current_vars[self] = token._value
224
+
225
+ token._redeemed = True
226
+
227
+ def __repr__(self) -> str:
228
+ return f"<RunVar name={self._name!r}>"
.venv/lib/python3.12/site-packages/anyio/py.typed ADDED
File without changes
.venv/lib/python3.12/site-packages/anyio/pytest_plugin.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import socket
5
+ import sys
6
+ from collections.abc import Callable, Generator, Iterator
7
+ from contextlib import ExitStack, contextmanager
8
+ from inspect import isasyncgenfunction, iscoroutinefunction, ismethod
9
+ from typing import TYPE_CHECKING, Any, cast
10
+
11
+ import pytest
12
+ from _pytest.fixtures import FuncFixtureInfo, SubRequest
13
+ from _pytest.outcomes import Exit
14
+ from _pytest.scope import Scope
15
+
16
+ from . import get_available_backends
17
+ from ._core._eventloop import (
18
+ current_async_library,
19
+ get_async_backend,
20
+ reset_current_async_library,
21
+ set_current_async_library,
22
+ )
23
+ from ._core._exceptions import iterate_exceptions
24
+
25
+ if TYPE_CHECKING:
26
+ from .abc import TestRunner
27
+
28
+ if sys.version_info < (3, 11):
29
+ from exceptiongroup import ExceptionGroup
30
+
31
+ if TYPE_CHECKING:
32
+ # pytest >= 9.2 keeps CallSpec2 as a TYPE_CHECKING-only alias of CallSpec
33
+ from _pytest.python import CallSpec2 as CallSpec
34
+ else:
35
+ try:
36
+ # c.f. https://github.com/pytest-dev/pytest/pull/14742
37
+ # pytest >= 9.2
38
+ from _pytest.python import CallSpec
39
+ except ImportError:
40
+ from _pytest.python import CallSpec2 as CallSpec
41
+
42
+ _current_runner: TestRunner | None = None
43
+ _runner_stack: ExitStack | None = None
44
+ _runner_leases = 0
45
+
46
+
47
+ def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]:
48
+ if isinstance(backend, str):
49
+ return backend, {}
50
+ elif isinstance(backend, tuple) and len(backend) == 2:
51
+ if isinstance(backend[0], str) and isinstance(backend[1], dict):
52
+ return cast(tuple[str, dict[str, Any]], backend)
53
+
54
+ raise TypeError("anyio_backend must be either a string or tuple of (string, dict)")
55
+
56
+
57
+ @contextmanager
58
+ def get_runner(
59
+ backend_name: str, backend_options: dict[str, Any]
60
+ ) -> Iterator[TestRunner]:
61
+ global _current_runner, _runner_leases, _runner_stack
62
+ if _current_runner is None:
63
+ asynclib = get_async_backend(backend_name)
64
+ _runner_stack = ExitStack()
65
+ if current_async_library() is None:
66
+ # Since we're in control of the event loop, we can cache the name of the
67
+ # async library
68
+ token = set_current_async_library(backend_name)
69
+ _runner_stack.callback(reset_current_async_library, token)
70
+
71
+ backend_options = backend_options or {}
72
+ _current_runner = _runner_stack.enter_context(
73
+ asynclib.create_test_runner(backend_options)
74
+ )
75
+
76
+ _runner_leases += 1
77
+ try:
78
+ yield _current_runner
79
+ finally:
80
+ _runner_leases -= 1
81
+ if not _runner_leases:
82
+ assert _runner_stack is not None
83
+ _runner_stack.close()
84
+ _runner_stack = _current_runner = None
85
+
86
+
87
+ def pytest_addoption(parser: pytest.Parser) -> None:
88
+ group = parser.getgroup("anyio")
89
+ parser.addini(
90
+ "anyio_mode",
91
+ default="strict",
92
+ help='AnyIO plugin mode (either "strict" or "auto")',
93
+ )
94
+ group.addoption(
95
+ "--anyio-mode",
96
+ default=None,
97
+ dest="anyio_mode",
98
+ help="""
99
+ 'auto' - All async test functions will be handled by AnyIO pytest plugin
100
+ 'strict' - Disabling autoprocessing(useful when anyio tests
101
+ need to coexist with other async test plugins)
102
+ """,
103
+ )
104
+
105
+
106
+ def _is_auto_mode(config: pytest.Config, mode: str) -> bool:
107
+ return (
108
+ config.getoption(mode, default=None) == "auto" or config.getini(mode) == "auto"
109
+ )
110
+
111
+
112
+ def pytest_configure(config: pytest.Config) -> None:
113
+ config.addinivalue_line(
114
+ "markers",
115
+ "anyio: mark the (coroutine function) test to be run asynchronously via anyio.",
116
+ )
117
+ if (
118
+ _is_auto_mode(config, "anyio_mode")
119
+ and config.pluginmanager.has_plugin("asyncio")
120
+ and _is_auto_mode(config, "asyncio_mode")
121
+ ):
122
+ config.issue_config_time_warning(
123
+ pytest.PytestConfigWarning(
124
+ "AnyIO auto mode has been enabled together with pytest-asyncio auto "
125
+ "mode. This may cause unexpected behavior."
126
+ ),
127
+ 1,
128
+ )
129
+
130
+
131
+ @pytest.hookimpl(hookwrapper=True)
132
+ def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]:
133
+ def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any:
134
+ # Rebind any fixture methods to the request instance
135
+ if (
136
+ request.instance
137
+ and ismethod(func)
138
+ and type(func.__self__) is type(request.instance)
139
+ ):
140
+ local_func = func.__func__.__get__(request.instance)
141
+ else:
142
+ local_func = func
143
+
144
+ backend_name, backend_options = extract_backend_and_options(anyio_backend)
145
+ if has_backend_arg:
146
+ kwargs["anyio_backend"] = anyio_backend
147
+
148
+ if has_request_arg:
149
+ kwargs["request"] = request
150
+
151
+ with get_runner(backend_name, backend_options) as runner:
152
+ # re-entrant call into the test runner detected. this happens when an async fixture
153
+ # is dynamically requested via request.getfixturevalue() from inside a running async
154
+ # test or fixture. on asyncio this raises RuntimeError: This event loop is already
155
+ # running, on trio the runner deadlocks - the host loop blocks waiting for the
156
+ # coroutine to return, but the coroutine is waiting for the host loop. raising here
157
+ # prevents the hang and gives a consistent error across backends.
158
+ if runner.is_running():
159
+ raise RuntimeError(
160
+ "Cannot schedule a coroutine in the test runner while another is already running; "
161
+ "likely caused by request.getfixturevalue() on an async fixture."
162
+ )
163
+
164
+ if isasyncgenfunction(local_func):
165
+ yield from runner.run_asyncgen_fixture(local_func, kwargs)
166
+ else:
167
+ yield runner.run_fixture(local_func, kwargs)
168
+
169
+ # Only apply this to coroutine functions and async generator functions in requests
170
+ # that involve the anyio_backend fixture
171
+ func = fixturedef.func
172
+ if isasyncgenfunction(func) or iscoroutinefunction(func):
173
+ if "anyio_backend" in request.fixturenames:
174
+ fixturedef.func = wrapper
175
+ original_argname = fixturedef.argnames
176
+
177
+ if not (has_backend_arg := "anyio_backend" in fixturedef.argnames):
178
+ fixturedef.argnames += ("anyio_backend",)
179
+
180
+ if not (has_request_arg := "request" in fixturedef.argnames):
181
+ fixturedef.argnames += ("request",)
182
+
183
+ try:
184
+ return (yield)
185
+ finally:
186
+ fixturedef.func = func
187
+ fixturedef.argnames = original_argname
188
+
189
+ return (yield)
190
+
191
+
192
+ @pytest.hookimpl(tryfirst=True)
193
+ def pytest_pycollect_makeitem(
194
+ collector: pytest.Module | pytest.Class, name: str, obj: object
195
+ ) -> None:
196
+ if collector.istestfunction(obj, name):
197
+ inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj
198
+ if iscoroutinefunction(inner_func):
199
+ anyio_auto_mode = _is_auto_mode(collector.config, "anyio_mode")
200
+ marker = collector.get_closest_marker("anyio")
201
+ own_markers = getattr(obj, "pytestmark", ())
202
+ if (
203
+ anyio_auto_mode
204
+ or marker
205
+ or any(marker.name == "anyio" for marker in own_markers)
206
+ ):
207
+ pytest.mark.usefixtures("anyio_backend")(obj)
208
+
209
+
210
+ def pytest_collection_finish(session: pytest.Session) -> None:
211
+ for i, item in reversed(list(enumerate(session.items))):
212
+ if (
213
+ isinstance(item, pytest.Function)
214
+ and iscoroutinefunction(item.function)
215
+ and item.get_closest_marker("anyio") is not None
216
+ and "anyio_backend" not in item.fixturenames
217
+ ):
218
+ new_items = []
219
+ try:
220
+ cs_fields = {f.name for f in dataclasses.fields(CallSpec)}
221
+ except TypeError:
222
+ cs_fields = set()
223
+
224
+ for param_index, backend in enumerate(get_available_backends()):
225
+ if "_arg2scope" in cs_fields: # pytest >= 8
226
+ callspec = CallSpec(
227
+ params={"anyio_backend": backend},
228
+ indices={"anyio_backend": param_index},
229
+ _arg2scope={"anyio_backend": Scope.Module},
230
+ _idlist=[backend],
231
+ marks=[],
232
+ )
233
+ else: # pytest 7.x
234
+ callspec = CallSpec( # type: ignore[call-arg]
235
+ funcargs={},
236
+ params={"anyio_backend": backend},
237
+ indices={"anyio_backend": param_index},
238
+ arg2scope={"anyio_backend": Scope.Module},
239
+ idlist=[backend],
240
+ marks=[],
241
+ )
242
+
243
+ fi = item._fixtureinfo
244
+ new_names_closure = list(fi.names_closure)
245
+ if "anyio_backend" not in new_names_closure:
246
+ new_names_closure.append("anyio_backend")
247
+
248
+ new_fixtureinfo = FuncFixtureInfo(
249
+ argnames=fi.argnames,
250
+ initialnames=fi.initialnames,
251
+ names_closure=new_names_closure,
252
+ name2fixturedefs=fi.name2fixturedefs,
253
+ )
254
+ new_item = pytest.Function.from_parent(
255
+ item.parent,
256
+ name=f"{item.originalname}[{backend}]",
257
+ callspec=callspec,
258
+ callobj=item.obj,
259
+ fixtureinfo=new_fixtureinfo,
260
+ keywords=item.keywords,
261
+ originalname=item.originalname,
262
+ )
263
+ new_items.append(new_item)
264
+
265
+ session.items[i : i + 1] = new_items
266
+
267
+
268
+ @pytest.hookimpl(tryfirst=True)
269
+ def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None:
270
+ def run_with_hypothesis(**kwargs: Any) -> None:
271
+ with get_runner(backend_name, backend_options) as runner:
272
+ runner.run_test(original_func, kwargs)
273
+
274
+ backend = pyfuncitem.funcargs.get("anyio_backend")
275
+ if backend:
276
+ backend_name, backend_options = extract_backend_and_options(backend)
277
+
278
+ if hasattr(pyfuncitem.obj, "hypothesis"):
279
+ # Wrap the inner test function unless it's already wrapped
280
+ original_func = pyfuncitem.obj.hypothesis.inner_test
281
+ if original_func.__qualname__ != run_with_hypothesis.__qualname__:
282
+ if iscoroutinefunction(original_func):
283
+ pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis
284
+
285
+ return None
286
+
287
+ if iscoroutinefunction(pyfuncitem.obj):
288
+ funcargs = pyfuncitem.funcargs
289
+ testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
290
+ with get_runner(backend_name, backend_options) as runner:
291
+ try:
292
+ runner.run_test(pyfuncitem.obj, testargs)
293
+ except ExceptionGroup as excgrp:
294
+ for exc in iterate_exceptions(excgrp):
295
+ if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)):
296
+ raise exc from excgrp
297
+
298
+ raise
299
+
300
+ return True
301
+
302
+ return None
303
+
304
+
305
+ @pytest.fixture(scope="module", params=get_available_backends())
306
+ def anyio_backend(request: Any) -> Any:
307
+ return request.param
308
+
309
+
310
+ @pytest.fixture
311
+ def anyio_backend_name(anyio_backend: Any) -> str:
312
+ if isinstance(anyio_backend, str):
313
+ return anyio_backend
314
+ else:
315
+ return anyio_backend[0]
316
+
317
+
318
+ @pytest.fixture
319
+ def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]:
320
+ if isinstance(anyio_backend, str):
321
+ return {}
322
+ else:
323
+ return anyio_backend[1]
324
+
325
+
326
+ class FreePortFactory:
327
+ """
328
+ Manages port generation based on specified socket kind, ensuring no duplicate
329
+ ports are generated.
330
+
331
+ This class provides functionality for generating available free ports on the
332
+ system. It is initialized with a specific socket kind and can generate ports
333
+ for given address families while avoiding reuse of previously generated ports.
334
+
335
+ Users should not instantiate this class directly, but use the
336
+ ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple
337
+ uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead.
338
+ """
339
+
340
+ def __init__(self, kind: socket.SocketKind) -> None:
341
+ self._kind = kind
342
+ self._generated = set[int]()
343
+
344
+ @property
345
+ def kind(self) -> socket.SocketKind:
346
+ """
347
+ The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or
348
+ :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability
349
+
350
+ """
351
+ return self._kind
352
+
353
+ def __call__(self, family: socket.AddressFamily | None = None) -> int:
354
+ """
355
+ Return an unbound port for the given address family.
356
+
357
+ :param family: if omitted, both IPv4 and IPv6 addresses will be tried
358
+ :return: a port number
359
+
360
+ """
361
+ if family is not None:
362
+ families = [family]
363
+ else:
364
+ families = [socket.AF_INET]
365
+ if socket.has_ipv6:
366
+ families.append(socket.AF_INET6)
367
+
368
+ while True:
369
+ port = 0
370
+ with ExitStack() as stack:
371
+ for fam in families:
372
+ sock = stack.enter_context(socket.socket(fam, self._kind))
373
+ addr = "::1" if fam == socket.AF_INET6 else "127.0.0.1"
374
+ try:
375
+ sock.bind((addr, port))
376
+ except OSError:
377
+ break
378
+
379
+ if not port:
380
+ port = sock.getsockname()[1]
381
+ else:
382
+ if port not in self._generated:
383
+ self._generated.add(port)
384
+ return port
385
+
386
+
387
+ @pytest.fixture(scope="session")
388
+ def free_tcp_port_factory() -> FreePortFactory:
389
+ return FreePortFactory(socket.SOCK_STREAM)
390
+
391
+
392
+ @pytest.fixture(scope="session")
393
+ def free_udp_port_factory() -> FreePortFactory:
394
+ return FreePortFactory(socket.SOCK_DGRAM)
395
+
396
+
397
+ @pytest.fixture
398
+ def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int:
399
+ return free_tcp_port_factory()
400
+
401
+
402
+ @pytest.fixture
403
+ def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int:
404
+ return free_udp_port_factory()
.venv/lib/python3.12/site-packages/anyio/streams/__init__.py ADDED
File without changes
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312-pytest-9.1.1.pyc ADDED
Binary file (188 Bytes). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (188 Bytes). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/buffered.cpython-312.pyc ADDED
Binary file (9.57 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/file.cpython-312.pyc ADDED
Binary file (7.56 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312-pytest-9.1.1.pyc ADDED
Binary file (15.2 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/memory.cpython-312.pyc ADDED
Binary file (15.1 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312-pytest-9.1.1.pyc ADDED
Binary file (8.38 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/stapled.cpython-312.pyc ADDED
Binary file (8.27 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/text.cpython-312.pyc ADDED
Binary file (9.33 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312-pytest-9.1.1.pyc ADDED
Binary file (20.5 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/__pycache__/tls.cpython-312.pyc ADDED
Binary file (20.4 kB). View file
 
.venv/lib/python3.12/site-packages/anyio/streams/buffered.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "BufferedByteReceiveStream",
5
+ "BufferedByteStream",
6
+ "BufferedConnectable",
7
+ )
8
+
9
+ import sys
10
+ from collections.abc import Callable, Iterable, Mapping
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, SupportsIndex
13
+
14
+ from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead
15
+ from ..abc import (
16
+ AnyByteReceiveStream,
17
+ AnyByteStream,
18
+ AnyByteStreamConnectable,
19
+ ByteReceiveStream,
20
+ ByteStream,
21
+ ByteStreamConnectable,
22
+ )
23
+
24
+ if sys.version_info >= (3, 12):
25
+ from typing import override
26
+ else:
27
+ from typing_extensions import override
28
+
29
+
30
+ @dataclass(eq=False)
31
+ class BufferedByteReceiveStream(ByteReceiveStream):
32
+ """
33
+ Wraps any bytes-based receive stream and uses a buffer to provide sophisticated
34
+ receiving capabilities in the form of a byte stream.
35
+ """
36
+
37
+ receive_stream: AnyByteReceiveStream
38
+ _buffer: bytearray = field(init=False, default_factory=bytearray)
39
+ _closed: bool = field(init=False, default=False)
40
+
41
+ async def aclose(self) -> None:
42
+ await self.receive_stream.aclose()
43
+ self._closed = True
44
+
45
+ @property
46
+ def buffer(self) -> bytes:
47
+ """The bytes currently in the buffer."""
48
+ return bytes(self._buffer)
49
+
50
+ @property
51
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
52
+ return self.receive_stream.extra_attributes
53
+
54
+ def feed_data(self, data: Iterable[SupportsIndex], /) -> None:
55
+ """
56
+ Append data directly into the buffer.
57
+
58
+ Any data in the buffer will be consumed by receive operations before receiving
59
+ anything from the wrapped stream.
60
+
61
+ :param data: the data to append to the buffer (can be bytes or anything else
62
+ that supports ``__index__()``)
63
+
64
+ """
65
+ self._buffer.extend(data)
66
+
67
+ async def receive(self, max_bytes: int = 65536) -> bytes:
68
+ if max_bytes < 1:
69
+ raise ValueError("max_bytes must be a positive integer")
70
+
71
+ if self._closed:
72
+ raise ClosedResourceError
73
+
74
+ if self._buffer:
75
+ chunk = bytes(self._buffer[:max_bytes])
76
+ del self._buffer[:max_bytes]
77
+ return chunk
78
+ elif isinstance(self.receive_stream, ByteReceiveStream):
79
+ return await self.receive_stream.receive(max_bytes)
80
+ else:
81
+ # With a bytes-oriented object stream, we need to handle any surplus bytes
82
+ # we get from the receive() call
83
+ chunk = await self.receive_stream.receive()
84
+ if len(chunk) > max_bytes:
85
+ # Save the surplus bytes in the buffer
86
+ self._buffer.extend(chunk[max_bytes:])
87
+ return chunk[:max_bytes]
88
+ else:
89
+ return chunk
90
+
91
+ async def receive_exactly(self, nbytes: int) -> bytes:
92
+ """
93
+ Read exactly the given amount of bytes from the stream.
94
+
95
+ :param nbytes: the number of bytes to read
96
+ :return: the bytes read
97
+ :raises ~anyio.IncompleteRead: if the stream was closed before the requested
98
+ amount of bytes could be read from the stream
99
+
100
+ """
101
+ while True:
102
+ remaining = nbytes - len(self._buffer)
103
+ if remaining <= 0:
104
+ retval = self._buffer[:nbytes]
105
+ del self._buffer[:nbytes]
106
+ return bytes(retval)
107
+
108
+ try:
109
+ if isinstance(self.receive_stream, ByteReceiveStream):
110
+ chunk = await self.receive_stream.receive(remaining)
111
+ else:
112
+ chunk = await self.receive_stream.receive()
113
+ except EndOfStream as exc:
114
+ raise IncompleteRead from exc
115
+
116
+ self._buffer.extend(chunk)
117
+
118
+ async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes:
119
+ """
120
+ Read from the stream until the delimiter is found or max_bytes have been read.
121
+
122
+ :param delimiter: the marker to look for in the stream
123
+ :param max_bytes: maximum number of bytes that will be read before raising
124
+ :exc:`~anyio.DelimiterNotFound`
125
+ :return: the bytes read (not including the delimiter)
126
+ :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter
127
+ was found
128
+ :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the
129
+ bytes read up to the maximum allowed
130
+
131
+ """
132
+ delimiter_size = len(delimiter)
133
+ offset = 0
134
+ while True:
135
+ # Check if the delimiter can be found in the current buffer
136
+ index = self._buffer.find(delimiter, offset)
137
+ if index >= 0:
138
+ found = self._buffer[:index]
139
+ del self._buffer[: index + len(delimiter) :]
140
+ return bytes(found)
141
+
142
+ # Check if the buffer is already at or over the limit
143
+ if len(self._buffer) >= max_bytes:
144
+ raise DelimiterNotFound(max_bytes)
145
+
146
+ # Read more data into the buffer from the socket
147
+ try:
148
+ data = await self.receive_stream.receive()
149
+ except EndOfStream as exc:
150
+ raise IncompleteRead from exc
151
+
152
+ # Move the offset forward and add the new data to the buffer
153
+ offset = max(len(self._buffer) - delimiter_size + 1, 0)
154
+ self._buffer.extend(data)
155
+
156
+
157
+ class BufferedByteStream(BufferedByteReceiveStream, ByteStream):
158
+ """
159
+ A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed
160
+ through to the wrapped stream as-is.
161
+ """
162
+
163
+ def __init__(self, stream: AnyByteStream):
164
+ """
165
+ :param stream: the stream to be wrapped
166
+
167
+ """
168
+ super().__init__(stream)
169
+ self._stream = stream
170
+
171
+ @override
172
+ async def send_eof(self) -> None:
173
+ await self._stream.send_eof()
174
+
175
+ @override
176
+ async def send(self, item: bytes) -> None:
177
+ await self._stream.send(item)
178
+
179
+
180
+ class BufferedConnectable(ByteStreamConnectable):
181
+ """
182
+ Wraps a byte stream connectable to produce :class:`BufferedByteStream` connections.
183
+
184
+ Use this when you want the streams returned by :meth:`connect` to have the buffered
185
+ receive API (e.g. :meth:`~BufferedByteReceiveStream.receive_exactly` and
186
+ :meth:`~BufferedByteReceiveStream.receive_until`).
187
+
188
+ :param connectable: the byte stream connectable to wrap
189
+ """
190
+
191
+ def __init__(self, connectable: AnyByteStreamConnectable):
192
+ """
193
+ :param connectable: the connectable to wrap
194
+
195
+ """
196
+ self.connectable = connectable
197
+
198
+ @override
199
+ async def connect(self) -> BufferedByteStream:
200
+ stream = await self.connectable.connect()
201
+ return BufferedByteStream(stream)
.venv/lib/python3.12/site-packages/anyio/streams/file.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "FileReadStream",
5
+ "FileStreamAttribute",
6
+ "FileWriteStream",
7
+ )
8
+
9
+ from collections.abc import Callable, Mapping
10
+ from io import SEEK_SET, UnsupportedOperation
11
+ from os import PathLike
12
+ from pathlib import Path
13
+ from typing import IO, Any
14
+
15
+ from .. import (
16
+ BrokenResourceError,
17
+ ClosedResourceError,
18
+ EndOfStream,
19
+ TypedAttributeSet,
20
+ to_thread,
21
+ typed_attribute,
22
+ )
23
+ from ..abc import ByteReceiveStream, ByteSendStream
24
+
25
+
26
+ class FileStreamAttribute(TypedAttributeSet):
27
+ #: the open file descriptor
28
+ file: IO[bytes] = typed_attribute()
29
+ #: the path of the file on the file system, if available (file must be a real file)
30
+ path: Path = typed_attribute()
31
+ #: the file number, if available (file must be a real file or a TTY)
32
+ fileno: int = typed_attribute()
33
+
34
+
35
+ class _BaseFileStream:
36
+ def __init__(self, file: IO[bytes]):
37
+ self._file = file
38
+
39
+ async def aclose(self) -> None:
40
+ await to_thread.run_sync(self._file.close)
41
+
42
+ @property
43
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
44
+ attributes: dict[Any, Callable[[], Any]] = {
45
+ FileStreamAttribute.file: lambda: self._file,
46
+ }
47
+
48
+ if hasattr(self._file, "name"):
49
+ attributes[FileStreamAttribute.path] = lambda: Path(self._file.name)
50
+
51
+ try:
52
+ self._file.fileno()
53
+ except UnsupportedOperation:
54
+ pass
55
+ else:
56
+ attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno()
57
+
58
+ return attributes
59
+
60
+
61
+ class FileReadStream(_BaseFileStream, ByteReceiveStream):
62
+ """
63
+ A byte stream that reads from a file in the file system.
64
+
65
+ :param file: a file that has been opened for reading in binary mode
66
+
67
+ .. versionadded:: 3.0
68
+ """
69
+
70
+ @classmethod
71
+ async def from_path(cls, path: str | PathLike[str]) -> FileReadStream:
72
+ """
73
+ Create a file read stream by opening the given file.
74
+
75
+ :param path: path of the file to read from
76
+
77
+ """
78
+ file = await to_thread.run_sync(Path(path).open, "rb")
79
+ return cls(file)
80
+
81
+ async def receive(self, max_bytes: int = 65536) -> bytes:
82
+ if max_bytes < 1:
83
+ raise ValueError("max_bytes must be a positive integer")
84
+
85
+ try:
86
+ data = await to_thread.run_sync(self._file.read, max_bytes)
87
+ except ValueError:
88
+ raise ClosedResourceError from None
89
+ except OSError as exc:
90
+ raise BrokenResourceError from exc
91
+
92
+ if data:
93
+ return data
94
+ else:
95
+ raise EndOfStream
96
+
97
+ async def seek(self, position: int, whence: int = SEEK_SET) -> int:
98
+ """
99
+ Seek the file to the given position.
100
+
101
+ .. seealso:: :meth:`io.IOBase.seek`
102
+
103
+ .. note:: Not all file descriptors are seekable.
104
+
105
+ :param position: position to seek the file to
106
+ :param whence: controls how ``position`` is interpreted
107
+ :return: the new absolute position
108
+ :raises OSError: if the file is not seekable
109
+
110
+ """
111
+ return await to_thread.run_sync(self._file.seek, position, whence)
112
+
113
+ async def tell(self) -> int:
114
+ """
115
+ Return the current stream position.
116
+
117
+ .. note:: Not all file descriptors are seekable.
118
+
119
+ :return: the current absolute position
120
+ :raises OSError: if the file is not seekable
121
+
122
+ """
123
+ return await to_thread.run_sync(self._file.tell)
124
+
125
+
126
+ class FileWriteStream(_BaseFileStream, ByteSendStream):
127
+ """
128
+ A byte stream that writes to a file in the file system.
129
+
130
+ :param file: a file that has been opened for writing in binary mode
131
+
132
+ .. versionadded:: 3.0
133
+ """
134
+
135
+ @classmethod
136
+ async def from_path(
137
+ cls, path: str | PathLike[str], append: bool = False
138
+ ) -> FileWriteStream:
139
+ """
140
+ Create a file write stream by opening the given file for writing.
141
+
142
+ :param path: path of the file to write to
143
+ :param append: if ``True``, open the file for appending; if ``False``, any
144
+ existing file at the given path will be truncated
145
+
146
+ """
147
+ mode = "ab" if append else "wb"
148
+ file = await to_thread.run_sync(Path(path).open, mode)
149
+ return cls(file)
150
+
151
+ async def send(self, item: bytes) -> None:
152
+ try:
153
+ await to_thread.run_sync(self._file.write, item)
154
+ except ValueError:
155
+ raise ClosedResourceError from None
156
+ except OSError as exc:
157
+ raise BrokenResourceError from exc
.venv/lib/python3.12/site-packages/anyio/streams/memory.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "MemoryObjectReceiveStream",
5
+ "MemoryObjectSendStream",
6
+ "MemoryObjectStreamStatistics",
7
+ )
8
+
9
+ import warnings
10
+ from collections import OrderedDict, deque
11
+ from dataclasses import dataclass, field
12
+ from types import TracebackType
13
+ from typing import Generic, NamedTuple, TypeVar
14
+
15
+ from .._core._exceptions import (
16
+ BrokenResourceError,
17
+ ClosedResourceError,
18
+ EndOfStream,
19
+ WouldBlock,
20
+ )
21
+ from .._core._synchronization import Event
22
+ from .._core._testing import TaskInfo, get_current_task
23
+ from ..abc import ObjectReceiveStream, ObjectSendStream
24
+ from ..lowlevel import checkpoint
25
+
26
+ T_Item = TypeVar("T_Item")
27
+ T_co = TypeVar("T_co", covariant=True)
28
+ T_contra = TypeVar("T_contra", contravariant=True)
29
+
30
+
31
+ class MemoryObjectStreamStatistics(NamedTuple):
32
+ current_buffer_used: int #: number of items stored in the buffer
33
+ #: maximum number of items that can be stored on this stream (or :data:`math.inf`)
34
+ max_buffer_size: float
35
+ open_send_streams: int #: number of unclosed clones of the send stream
36
+ open_receive_streams: int #: number of unclosed clones of the receive stream
37
+ #: number of tasks blocked on :meth:`MemoryObjectSendStream.send`
38
+ tasks_waiting_send: int
39
+ #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive`
40
+ tasks_waiting_receive: int
41
+
42
+
43
+ @dataclass(eq=False)
44
+ class _MemoryObjectItemReceiver(Generic[T_Item]):
45
+ task_info: TaskInfo = field(init=False, default_factory=get_current_task)
46
+ item: T_Item = field(init=False)
47
+
48
+ def __repr__(self) -> str:
49
+ # When item is not defined, we get following error with default __repr__:
50
+ # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item'
51
+ item = getattr(self, "item", None)
52
+ return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})"
53
+
54
+
55
+ @dataclass(eq=False)
56
+ class _MemoryObjectStreamState(Generic[T_Item]):
57
+ max_buffer_size: float = field()
58
+ buffer: deque[T_Item] = field(init=False, default_factory=deque)
59
+ open_send_channels: int = field(init=False, default=0)
60
+ open_receive_channels: int = field(init=False, default=0)
61
+ waiting_receivers: OrderedDict[Event, _MemoryObjectItemReceiver[T_Item]] = field(
62
+ init=False, default_factory=OrderedDict
63
+ )
64
+ waiting_senders: OrderedDict[Event, T_Item] = field(
65
+ init=False, default_factory=OrderedDict
66
+ )
67
+
68
+ def statistics(self) -> MemoryObjectStreamStatistics:
69
+ return MemoryObjectStreamStatistics(
70
+ len(self.buffer),
71
+ self.max_buffer_size,
72
+ self.open_send_channels,
73
+ self.open_receive_channels,
74
+ len(self.waiting_senders),
75
+ len(self.waiting_receivers),
76
+ )
77
+
78
+
79
+ @dataclass(eq=False)
80
+ class MemoryObjectReceiveStream(ObjectReceiveStream[T_co], Generic[T_co]):
81
+ _state: _MemoryObjectStreamState[T_co]
82
+ _closed: bool = field(init=False, default=False)
83
+
84
+ def __post_init__(self) -> None:
85
+ self._state.open_receive_channels += 1
86
+
87
+ def receive_nowait(self) -> T_co:
88
+ """
89
+ Receive the next item if it can be done without waiting.
90
+
91
+ :return: the received item
92
+ :raises ~anyio.ClosedResourceError: if this send stream has been closed
93
+ :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been
94
+ closed from the sending end
95
+ :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks
96
+ waiting to send
97
+
98
+ """
99
+ if self._closed:
100
+ raise ClosedResourceError
101
+
102
+ if self._state.waiting_senders:
103
+ # Get the item from the next sender
104
+ send_event, item = self._state.waiting_senders.popitem(last=False)
105
+ self._state.buffer.append(item)
106
+ send_event.set()
107
+
108
+ if self._state.buffer:
109
+ return self._state.buffer.popleft()
110
+ elif not self._state.open_send_channels:
111
+ raise EndOfStream
112
+
113
+ raise WouldBlock
114
+
115
+ async def receive(self) -> T_co:
116
+ await checkpoint()
117
+ try:
118
+ return self.receive_nowait()
119
+ except WouldBlock:
120
+ # Add ourselves in the queue
121
+ receive_event = Event()
122
+ receiver = _MemoryObjectItemReceiver[T_co]()
123
+ self._state.waiting_receivers[receive_event] = receiver
124
+
125
+ try:
126
+ await receive_event.wait()
127
+ finally:
128
+ self._state.waiting_receivers.pop(receive_event, None)
129
+
130
+ try:
131
+ return receiver.item
132
+ except AttributeError:
133
+ raise EndOfStream from None
134
+
135
+ def clone(self) -> MemoryObjectReceiveStream[T_co]:
136
+ """
137
+ Create a clone of this receive stream.
138
+
139
+ Each clone can be closed separately. Only when all clones have been closed will
140
+ the receiving end of the memory stream be considered closed by the sending ends.
141
+
142
+ :return: the cloned stream
143
+
144
+ """
145
+ if self._closed:
146
+ raise ClosedResourceError
147
+
148
+ return MemoryObjectReceiveStream(_state=self._state)
149
+
150
+ def close(self) -> None:
151
+ """
152
+ Close the stream.
153
+
154
+ This works the exact same way as :meth:`aclose`, but is provided as a special
155
+ case for the benefit of synchronous callbacks.
156
+
157
+ """
158
+ if not self._closed:
159
+ self._closed = True
160
+ self._state.open_receive_channels -= 1
161
+ if self._state.open_receive_channels == 0:
162
+ send_events = list(self._state.waiting_senders.keys())
163
+ for event in send_events:
164
+ event.set()
165
+
166
+ async def aclose(self) -> None:
167
+ self.close()
168
+
169
+ def statistics(self) -> MemoryObjectStreamStatistics:
170
+ """
171
+ Return statistics about the current state of this stream.
172
+
173
+ .. versionadded:: 3.0
174
+ """
175
+ return self._state.statistics()
176
+
177
+ def __enter__(self) -> MemoryObjectReceiveStream[T_co]:
178
+ return self
179
+
180
+ def __exit__(
181
+ self,
182
+ exc_type: type[BaseException] | None,
183
+ exc_val: BaseException | None,
184
+ exc_tb: TracebackType | None,
185
+ ) -> None:
186
+ self.close()
187
+
188
+ def __del__(self) -> None:
189
+ if not self._closed:
190
+ warnings.warn(
191
+ f"Unclosed <{self.__class__.__name__} at {id(self):x}>",
192
+ ResourceWarning,
193
+ stacklevel=1,
194
+ source=self,
195
+ )
196
+
197
+
198
+ @dataclass(eq=False)
199
+ class MemoryObjectSendStream(ObjectSendStream[T_contra], Generic[T_contra]):
200
+ _state: _MemoryObjectStreamState[T_contra]
201
+ _closed: bool = field(init=False, default=False)
202
+
203
+ def __post_init__(self) -> None:
204
+ self._state.open_send_channels += 1
205
+
206
+ def send_nowait(self, item: T_contra) -> None:
207
+ """
208
+ Send an item immediately if it can be done without waiting.
209
+
210
+ :param item: the item to send
211
+ :raises ~anyio.ClosedResourceError: if this send stream has been closed
212
+ :raises ~anyio.BrokenResourceError: if the stream has been closed from the
213
+ receiving end
214
+ :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting
215
+ to receive
216
+
217
+ """
218
+ if self._closed:
219
+ raise ClosedResourceError
220
+ if not self._state.open_receive_channels:
221
+ raise BrokenResourceError
222
+
223
+ while self._state.waiting_receivers:
224
+ receive_event, receiver = self._state.waiting_receivers.popitem(last=False)
225
+ if not receiver.task_info.has_pending_cancellation():
226
+ receiver.item = item
227
+ receive_event.set()
228
+ return
229
+
230
+ if len(self._state.buffer) < self._state.max_buffer_size:
231
+ self._state.buffer.append(item)
232
+ else:
233
+ raise WouldBlock
234
+
235
+ async def send(self, item: T_contra) -> None:
236
+ """
237
+ Send an item to the stream.
238
+
239
+ If the buffer is full, this method blocks until there is again room in the
240
+ buffer or the item can be sent directly to a receiver.
241
+
242
+ :param item: the item to send
243
+ :raises ~anyio.ClosedResourceError: if this send stream has been closed
244
+ :raises ~anyio.BrokenResourceError: if the stream has been closed from the
245
+ receiving end
246
+
247
+ """
248
+ await checkpoint()
249
+ try:
250
+ self.send_nowait(item)
251
+ except WouldBlock:
252
+ # Wait until there's someone on the receiving end
253
+ send_event = Event()
254
+ self._state.waiting_senders[send_event] = item
255
+ try:
256
+ await send_event.wait()
257
+ except BaseException:
258
+ self._state.waiting_senders.pop(send_event, None)
259
+ raise
260
+
261
+ if send_event in self._state.waiting_senders:
262
+ del self._state.waiting_senders[send_event]
263
+ raise BrokenResourceError from None
264
+
265
+ def clone(self) -> MemoryObjectSendStream[T_contra]:
266
+ """
267
+ Create a clone of this send stream.
268
+
269
+ Each clone can be closed separately. Only when all clones have been closed will
270
+ the sending end of the memory stream be considered closed by the receiving ends.
271
+
272
+ :return: the cloned stream
273
+
274
+ """
275
+ if self._closed:
276
+ raise ClosedResourceError
277
+
278
+ return MemoryObjectSendStream(_state=self._state)
279
+
280
+ def close(self) -> None:
281
+ """
282
+ Close the stream.
283
+
284
+ This works the exact same way as :meth:`aclose`, but is provided as a special
285
+ case for the benefit of synchronous callbacks.
286
+
287
+ """
288
+ if not self._closed:
289
+ self._closed = True
290
+ self._state.open_send_channels -= 1
291
+ if self._state.open_send_channels == 0:
292
+ receive_events = list(self._state.waiting_receivers.keys())
293
+ self._state.waiting_receivers.clear()
294
+ for event in receive_events:
295
+ event.set()
296
+
297
+ async def aclose(self) -> None:
298
+ self.close()
299
+
300
+ def statistics(self) -> MemoryObjectStreamStatistics:
301
+ """
302
+ Return statistics about the current state of this stream.
303
+
304
+ .. versionadded:: 3.0
305
+ """
306
+ return self._state.statistics()
307
+
308
+ def __enter__(self) -> MemoryObjectSendStream[T_contra]:
309
+ return self
310
+
311
+ def __exit__(
312
+ self,
313
+ exc_type: type[BaseException] | None,
314
+ exc_val: BaseException | None,
315
+ exc_tb: TracebackType | None,
316
+ ) -> None:
317
+ self.close()
318
+
319
+ def __del__(self) -> None:
320
+ if not self._closed:
321
+ warnings.warn(
322
+ f"Unclosed <{self.__class__.__name__} at {id(self):x}>",
323
+ ResourceWarning,
324
+ stacklevel=1,
325
+ source=self,
326
+ )
.venv/lib/python3.12/site-packages/anyio/streams/stapled.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "MultiListener",
5
+ "StapledByteStream",
6
+ "StapledObjectStream",
7
+ )
8
+
9
+ from collections.abc import Callable, Mapping, Sequence
10
+ from dataclasses import dataclass
11
+ from typing import Any, Generic, TypeVar
12
+
13
+ from ..abc import (
14
+ ByteReceiveStream,
15
+ ByteSendStream,
16
+ ByteStream,
17
+ Listener,
18
+ ObjectReceiveStream,
19
+ ObjectSendStream,
20
+ ObjectStream,
21
+ TaskGroup,
22
+ )
23
+
24
+ T_Item = TypeVar("T_Item")
25
+ T_Stream = TypeVar("T_Stream")
26
+
27
+
28
+ @dataclass(eq=False)
29
+ class StapledByteStream(ByteStream):
30
+ """
31
+ Combines two byte streams into a single, bidirectional byte stream.
32
+
33
+ Extra attributes will be provided from both streams, with the receive stream
34
+ providing the values in case of a conflict.
35
+
36
+ :param ByteSendStream send_stream: the sending byte stream
37
+ :param ByteReceiveStream receive_stream: the receiving byte stream
38
+ """
39
+
40
+ send_stream: ByteSendStream
41
+ receive_stream: ByteReceiveStream
42
+
43
+ async def receive(self, max_bytes: int = 65536) -> bytes:
44
+ if max_bytes < 1:
45
+ raise ValueError("max_bytes must be a positive integer")
46
+
47
+ return await self.receive_stream.receive(max_bytes)
48
+
49
+ async def send(self, item: bytes) -> None:
50
+ await self.send_stream.send(item)
51
+
52
+ async def send_eof(self) -> None:
53
+ await self.send_stream.aclose()
54
+
55
+ async def aclose(self) -> None:
56
+ await self.send_stream.aclose()
57
+ await self.receive_stream.aclose()
58
+
59
+ @property
60
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
61
+ return {
62
+ **self.send_stream.extra_attributes,
63
+ **self.receive_stream.extra_attributes,
64
+ }
65
+
66
+
67
+ @dataclass(eq=False)
68
+ class StapledObjectStream(ObjectStream[T_Item], Generic[T_Item]):
69
+ """
70
+ Combines two object streams into a single, bidirectional object stream.
71
+
72
+ Extra attributes will be provided from both streams, with the receive stream
73
+ providing the values in case of a conflict.
74
+
75
+ :param ObjectSendStream send_stream: the sending object stream
76
+ :param ObjectReceiveStream receive_stream: the receiving object stream
77
+ """
78
+
79
+ send_stream: ObjectSendStream[T_Item]
80
+ receive_stream: ObjectReceiveStream[T_Item]
81
+
82
+ async def receive(self) -> T_Item:
83
+ return await self.receive_stream.receive()
84
+
85
+ async def send(self, item: T_Item) -> None:
86
+ await self.send_stream.send(item)
87
+
88
+ def send_nowait(self, item: T_Item) -> None:
89
+ try:
90
+ send_nowait = self.send_stream.send_nowait # type: ignore[attr-defined]
91
+ except AttributeError as exc:
92
+ raise NotImplementedError(
93
+ f"'send_nowait' method not implemented in {type(self.send_stream)}"
94
+ ) from exc
95
+
96
+ send_nowait(item)
97
+
98
+ async def send_eof(self) -> None:
99
+ await self.send_stream.aclose()
100
+
101
+ async def aclose(self) -> None:
102
+ await self.send_stream.aclose()
103
+ await self.receive_stream.aclose()
104
+
105
+ @property
106
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
107
+ return {
108
+ **self.send_stream.extra_attributes,
109
+ **self.receive_stream.extra_attributes,
110
+ }
111
+
112
+
113
+ @dataclass(eq=False)
114
+ class MultiListener(Listener[T_Stream], Generic[T_Stream]):
115
+ """
116
+ Combines multiple listeners into one, serving connections from all of them at once.
117
+
118
+ Any MultiListeners in the given collection of listeners will have their listeners
119
+ moved into this one.
120
+
121
+ Extra attributes are provided from each listener, with each successive listener
122
+ overriding any conflicting attributes from the previous one.
123
+
124
+ :param listeners: listeners to serve
125
+ :type listeners: Sequence[Listener[T_Stream]]
126
+ """
127
+
128
+ listeners: Sequence[Listener[T_Stream]]
129
+
130
+ def __post_init__(self) -> None:
131
+ listeners: list[Listener[T_Stream]] = []
132
+ for listener in self.listeners:
133
+ if isinstance(listener, MultiListener):
134
+ listeners.extend(listener.listeners)
135
+ del listener.listeners[:] # type: ignore[attr-defined]
136
+ else:
137
+ listeners.append(listener)
138
+
139
+ self.listeners = listeners
140
+
141
+ async def serve(
142
+ self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None
143
+ ) -> None:
144
+ from .. import create_task_group
145
+
146
+ async with create_task_group() as tg:
147
+ for listener in self.listeners:
148
+ tg.start_soon(listener.serve, handler, task_group)
149
+
150
+ async def aclose(self) -> None:
151
+ for listener in self.listeners:
152
+ await listener.aclose()
153
+
154
+ @property
155
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
156
+ attributes: dict = {}
157
+ for listener in self.listeners:
158
+ attributes.update(listener.extra_attributes)
159
+
160
+ return attributes
.venv/lib/python3.12/site-packages/anyio/streams/text.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "TextConnectable",
5
+ "TextReceiveStream",
6
+ "TextSendStream",
7
+ "TextStream",
8
+ )
9
+
10
+ import codecs
11
+ import sys
12
+ from collections.abc import Callable, Mapping
13
+ from dataclasses import InitVar, dataclass, field
14
+ from typing import Any
15
+
16
+ from ..abc import (
17
+ AnyByteReceiveStream,
18
+ AnyByteSendStream,
19
+ AnyByteStream,
20
+ AnyByteStreamConnectable,
21
+ ObjectReceiveStream,
22
+ ObjectSendStream,
23
+ ObjectStream,
24
+ ObjectStreamConnectable,
25
+ )
26
+
27
+ if sys.version_info >= (3, 12):
28
+ from typing import override
29
+ else:
30
+ from typing_extensions import override
31
+
32
+
33
+ @dataclass(eq=False)
34
+ class TextReceiveStream(ObjectReceiveStream[str]):
35
+ """
36
+ Stream wrapper that decodes bytes to strings using the given encoding.
37
+
38
+ Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any
39
+ completely received unicode characters as soon as they come in.
40
+
41
+ :param transport_stream: any bytes-based receive stream
42
+ :param encoding: character encoding to use for decoding bytes to strings (defaults
43
+ to ``utf-8``)
44
+ :param errors: handling scheme for decoding errors (defaults to ``strict``; see the
45
+ `codecs module documentation`_ for a comprehensive list of options)
46
+
47
+ .. _codecs module documentation:
48
+ https://docs.python.org/3/library/codecs.html#codec-objects
49
+ """
50
+
51
+ transport_stream: AnyByteReceiveStream
52
+ encoding: InitVar[str] = "utf-8"
53
+ errors: InitVar[str] = "strict"
54
+ _decoder: codecs.IncrementalDecoder = field(init=False)
55
+
56
+ def __post_init__(self, encoding: str, errors: str) -> None:
57
+ decoder_class = codecs.getincrementaldecoder(encoding)
58
+ self._decoder = decoder_class(errors=errors)
59
+
60
+ async def receive(self) -> str:
61
+ while True:
62
+ chunk = await self.transport_stream.receive()
63
+ decoded = self._decoder.decode(chunk)
64
+ if decoded:
65
+ return decoded
66
+
67
+ async def aclose(self) -> None:
68
+ await self.transport_stream.aclose()
69
+ self._decoder.reset()
70
+
71
+ @property
72
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
73
+ return self.transport_stream.extra_attributes
74
+
75
+
76
+ @dataclass(eq=False)
77
+ class TextSendStream(ObjectSendStream[str]):
78
+ """
79
+ Sends strings to the wrapped stream as bytes using the given encoding.
80
+
81
+ :param AnyByteSendStream transport_stream: any bytes-based send stream
82
+ :param str encoding: character encoding to use for encoding strings to bytes
83
+ (defaults to ``utf-8``)
84
+ :param str errors: handling scheme for encoding errors (defaults to ``strict``; see
85
+ the `codecs module documentation`_ for a comprehensive list of options)
86
+
87
+ .. _codecs module documentation:
88
+ https://docs.python.org/3/library/codecs.html#codec-objects
89
+ """
90
+
91
+ transport_stream: AnyByteSendStream
92
+ encoding: InitVar[str] = "utf-8"
93
+ errors: str = "strict"
94
+ _encoder: Callable[..., tuple[bytes, int]] = field(init=False)
95
+
96
+ def __post_init__(self, encoding: str) -> None:
97
+ self._encoder = codecs.getencoder(encoding)
98
+
99
+ async def send(self, item: str) -> None:
100
+ encoded = self._encoder(item, self.errors)[0]
101
+ await self.transport_stream.send(encoded)
102
+
103
+ async def aclose(self) -> None:
104
+ await self.transport_stream.aclose()
105
+
106
+ @property
107
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
108
+ return self.transport_stream.extra_attributes
109
+
110
+
111
+ @dataclass(eq=False)
112
+ class TextStream(ObjectStream[str]):
113
+ """
114
+ A bidirectional stream that decodes bytes to strings on receive and encodes strings
115
+ to bytes on send.
116
+
117
+ Extra attributes will be provided from both streams, with the receive stream
118
+ providing the values in case of a conflict.
119
+
120
+ :param AnyByteStream transport_stream: any bytes-based stream
121
+ :param str encoding: character encoding to use for encoding/decoding strings to/from
122
+ bytes (defaults to ``utf-8``)
123
+ :param str errors: handling scheme for encoding errors (defaults to ``strict``; see
124
+ the `codecs module documentation`_ for a comprehensive list of options)
125
+
126
+ .. _codecs module documentation:
127
+ https://docs.python.org/3/library/codecs.html#codec-objects
128
+ """
129
+
130
+ transport_stream: AnyByteStream
131
+ encoding: InitVar[str] = "utf-8"
132
+ errors: InitVar[str] = "strict"
133
+ _receive_stream: TextReceiveStream = field(init=False)
134
+ _send_stream: TextSendStream = field(init=False)
135
+
136
+ def __post_init__(self, encoding: str, errors: str) -> None:
137
+ self._receive_stream = TextReceiveStream(
138
+ self.transport_stream, encoding=encoding, errors=errors
139
+ )
140
+ self._send_stream = TextSendStream(
141
+ self.transport_stream, encoding=encoding, errors=errors
142
+ )
143
+
144
+ async def receive(self) -> str:
145
+ return await self._receive_stream.receive()
146
+
147
+ async def send(self, item: str) -> None:
148
+ await self._send_stream.send(item)
149
+
150
+ async def send_eof(self) -> None:
151
+ await self.transport_stream.send_eof()
152
+
153
+ async def aclose(self) -> None:
154
+ await self._send_stream.aclose()
155
+ await self._receive_stream.aclose()
156
+
157
+ @property
158
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
159
+ return {
160
+ **self._send_stream.extra_attributes,
161
+ **self._receive_stream.extra_attributes,
162
+ }
163
+
164
+
165
+ class TextConnectable(ObjectStreamConnectable[str]):
166
+ def __init__(self, connectable: AnyByteStreamConnectable):
167
+ """
168
+ :param connectable: the bytestream endpoint to wrap
169
+
170
+ """
171
+ self.connectable = connectable
172
+
173
+ @override
174
+ async def connect(self) -> TextStream:
175
+ stream = await self.connectable.connect()
176
+ return TextStream(stream)
.venv/lib/python3.12/site-packages/anyio/streams/tls.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "TLSAttribute",
5
+ "TLSConnectable",
6
+ "TLSListener",
7
+ "TLSStream",
8
+ )
9
+
10
+ import logging
11
+ import re
12
+ import ssl
13
+ import sys
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass
16
+ from functools import wraps
17
+ from ssl import SSLContext
18
+ from typing import Any, TypeAlias, TypeVar
19
+
20
+ from .. import (
21
+ BrokenResourceError,
22
+ EndOfStream,
23
+ aclose_forcefully,
24
+ get_cancelled_exc_class,
25
+ to_thread,
26
+ )
27
+ from .._core._typedattr import TypedAttributeSet, typed_attribute
28
+ from ..abc import (
29
+ AnyByteStream,
30
+ AnyByteStreamConnectable,
31
+ ByteStream,
32
+ ByteStreamConnectable,
33
+ Listener,
34
+ TaskGroup,
35
+ )
36
+
37
+ if sys.version_info >= (3, 11):
38
+ from typing import TypeVarTuple, Unpack
39
+ else:
40
+ from typing_extensions import TypeVarTuple, Unpack
41
+
42
+ if sys.version_info >= (3, 12):
43
+ from typing import override
44
+ else:
45
+ from typing_extensions import override
46
+
47
+ T_Retval = TypeVar("T_Retval")
48
+ PosArgsT = TypeVarTuple("PosArgsT")
49
+ _PCTRTT: TypeAlias = tuple[tuple[str, str], ...]
50
+ _PCTRTTT: TypeAlias = tuple[_PCTRTT, ...]
51
+
52
+
53
+ class TLSAttribute(TypedAttributeSet):
54
+ """Contains Transport Layer Security related attributes."""
55
+
56
+ #: the selected ALPN protocol
57
+ alpn_protocol: str | None = typed_attribute()
58
+ #: the channel binding for type ``tls-unique``
59
+ channel_binding_tls_unique: bytes = typed_attribute()
60
+ #: the selected cipher
61
+ cipher: tuple[str, str, int] = typed_attribute()
62
+ #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert`
63
+ # for more information)
64
+ peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute()
65
+ #: the peer certificate in binary form
66
+ peer_certificate_binary: bytes | None = typed_attribute()
67
+ #: ``True`` if this is the server side of the connection
68
+ server_side: bool = typed_attribute()
69
+ #: ciphers shared by the client during the TLS handshake (``None`` if this is the
70
+ #: client side)
71
+ shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute()
72
+ #: the :class:`~ssl.SSLObject` used for encryption
73
+ ssl_object: ssl.SSLObject = typed_attribute()
74
+ #: ``True`` if this stream does (and expects) a closing TLS handshake when the
75
+ #: stream is being closed
76
+ standard_compatible: bool = typed_attribute()
77
+ #: the TLS protocol version (e.g. ``TLSv1.2``)
78
+ tls_version: str = typed_attribute()
79
+
80
+
81
+ @dataclass(eq=False)
82
+ class TLSStream(ByteStream):
83
+ """
84
+ A stream wrapper that encrypts all sent data and decrypts received data.
85
+
86
+ This class has no public initializer; use :meth:`wrap` instead.
87
+ All extra attributes from :class:`~TLSAttribute` are supported.
88
+
89
+ :var AnyByteStream transport_stream: the wrapped stream
90
+
91
+ """
92
+
93
+ transport_stream: AnyByteStream
94
+ standard_compatible: bool
95
+ _ssl_object: ssl.SSLObject
96
+ _read_bio: ssl.MemoryBIO
97
+ _write_bio: ssl.MemoryBIO
98
+
99
+ @classmethod
100
+ async def wrap(
101
+ cls,
102
+ transport_stream: AnyByteStream,
103
+ *,
104
+ server_side: bool | None = None,
105
+ hostname: str | None = None,
106
+ ssl_context: ssl.SSLContext | None = None,
107
+ standard_compatible: bool = True,
108
+ ) -> TLSStream:
109
+ """
110
+ Wrap an existing stream with Transport Layer Security.
111
+
112
+ This performs a TLS handshake with the peer.
113
+
114
+ :param transport_stream: a bytes-transporting stream to wrap
115
+ :param server_side: ``True`` if this is the server side of the connection,
116
+ ``False`` if this is the client side (if omitted, will be set to ``False``
117
+ if ``hostname`` has been provided, ``False`` otherwise). Used only to create
118
+ a default context when an explicit context has not been provided.
119
+ :param hostname: host name of the peer (if host name checking is desired)
120
+ :param ssl_context: the SSLContext object to use (if not provided, a secure
121
+ default will be created)
122
+ :param standard_compatible: if ``False``, skip the closing handshake when
123
+ closing the connection, and don't raise an exception if the peer does the
124
+ same
125
+ :raises ~ssl.SSLError: if the TLS handshake fails
126
+
127
+ """
128
+ if server_side is None:
129
+ server_side = not hostname
130
+
131
+ if not ssl_context:
132
+ purpose = (
133
+ ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH
134
+ )
135
+ ssl_context = ssl.create_default_context(purpose)
136
+
137
+ # Re-enable detection of unexpected EOFs if it was disabled by Python
138
+ if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
139
+ ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
140
+
141
+ bio_in = ssl.MemoryBIO()
142
+ bio_out = ssl.MemoryBIO()
143
+
144
+ # Resolve international host names using IDNA 2008.
145
+ # Otherwise wrap_bio() would resolve them with IDNA 2003.
146
+ if hostname is not None:
147
+ from .._core._sockets import idna2008_resolve
148
+
149
+ server_hostname: bytes | None = idna2008_resolve(hostname)
150
+ else:
151
+ server_hostname = None
152
+
153
+ # External SSLContext implementations may do blocking I/O in wrap_bio(),
154
+ # but the standard library implementation won't
155
+ if type(ssl_context) is ssl.SSLContext:
156
+ ssl_object = ssl_context.wrap_bio(
157
+ bio_in,
158
+ bio_out,
159
+ server_side=server_side,
160
+ server_hostname=server_hostname,
161
+ )
162
+ else:
163
+ ssl_object = await to_thread.run_sync(
164
+ ssl_context.wrap_bio,
165
+ bio_in,
166
+ bio_out,
167
+ server_side,
168
+ server_hostname,
169
+ None,
170
+ )
171
+
172
+ wrapper = cls(
173
+ transport_stream=transport_stream,
174
+ standard_compatible=standard_compatible,
175
+ _ssl_object=ssl_object,
176
+ _read_bio=bio_in,
177
+ _write_bio=bio_out,
178
+ )
179
+ await wrapper._call_sslobject_method(ssl_object.do_handshake)
180
+ return wrapper
181
+
182
+ async def _call_sslobject_method(
183
+ self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT]
184
+ ) -> T_Retval:
185
+ while True:
186
+ try:
187
+ result = func(*args)
188
+ except ssl.SSLWantReadError:
189
+ try:
190
+ # Flush any pending writes first
191
+ if self._write_bio.pending:
192
+ await self.transport_stream.send(self._write_bio.read())
193
+
194
+ data = await self.transport_stream.receive()
195
+ except EndOfStream:
196
+ self._read_bio.write_eof()
197
+ except OSError as exc:
198
+ self._read_bio.write_eof()
199
+ self._write_bio.write_eof()
200
+ raise BrokenResourceError from exc
201
+ else:
202
+ self._read_bio.write(data)
203
+ except ssl.SSLWantWriteError:
204
+ await self.transport_stream.send(self._write_bio.read())
205
+ except ssl.SSLSyscallError as exc:
206
+ self._read_bio.write_eof()
207
+ self._write_bio.write_eof()
208
+ raise BrokenResourceError from exc
209
+ except ssl.SSLError as exc:
210
+ self._read_bio.write_eof()
211
+ self._write_bio.write_eof()
212
+ if isinstance(exc, ssl.SSLEOFError) or (
213
+ exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror
214
+ ):
215
+ if self.standard_compatible:
216
+ raise BrokenResourceError from exc
217
+ else:
218
+ raise EndOfStream from None
219
+
220
+ raise
221
+ else:
222
+ # Flush any pending writes first
223
+ if self._write_bio.pending:
224
+ await self.transport_stream.send(self._write_bio.read())
225
+
226
+ return result
227
+
228
+ async def unwrap(self) -> tuple[AnyByteStream, bytes]:
229
+ """
230
+ Does the TLS closing handshake.
231
+
232
+ :return: a tuple of (wrapped byte stream, bytes left in the read buffer)
233
+
234
+ """
235
+ await self._call_sslobject_method(self._ssl_object.unwrap)
236
+ self._read_bio.write_eof()
237
+ self._write_bio.write_eof()
238
+ return self.transport_stream, self._read_bio.read()
239
+
240
+ async def aclose(self) -> None:
241
+ if self.standard_compatible:
242
+ try:
243
+ await self.unwrap()
244
+ except BaseException:
245
+ await aclose_forcefully(self.transport_stream)
246
+ raise
247
+
248
+ await self.transport_stream.aclose()
249
+
250
+ async def receive(self, max_bytes: int = 65536) -> bytes:
251
+ if max_bytes < 1:
252
+ raise ValueError("max_bytes must be a positive integer")
253
+
254
+ data = await self._call_sslobject_method(self._ssl_object.read, max_bytes)
255
+ if not data:
256
+ raise EndOfStream
257
+
258
+ return data
259
+
260
+ async def send(self, item: bytes) -> None:
261
+ await self._call_sslobject_method(self._ssl_object.write, item)
262
+
263
+ async def send_eof(self) -> None:
264
+ tls_version = self.extra(TLSAttribute.tls_version)
265
+ match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version)
266
+ if match:
267
+ major, minor = int(match.group(1)), int(match.group(2) or 0)
268
+ if (major, minor) < (1, 3):
269
+ raise NotImplementedError(
270
+ f"send_eof() requires at least TLSv1.3; current "
271
+ f"session uses {tls_version}"
272
+ )
273
+
274
+ raise NotImplementedError(
275
+ "send_eof() has not yet been implemented for TLS streams"
276
+ )
277
+
278
+ @property
279
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
280
+ return {
281
+ **self.transport_stream.extra_attributes,
282
+ TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol,
283
+ TLSAttribute.channel_binding_tls_unique: (
284
+ self._ssl_object.get_channel_binding
285
+ ),
286
+ TLSAttribute.cipher: self._ssl_object.cipher,
287
+ TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False),
288
+ TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert(
289
+ True
290
+ ),
291
+ TLSAttribute.server_side: lambda: self._ssl_object.server_side,
292
+ TLSAttribute.shared_ciphers: lambda: (
293
+ self._ssl_object.shared_ciphers()
294
+ if self._ssl_object.server_side
295
+ else None
296
+ ),
297
+ TLSAttribute.standard_compatible: lambda: self.standard_compatible,
298
+ TLSAttribute.ssl_object: lambda: self._ssl_object,
299
+ TLSAttribute.tls_version: self._ssl_object.version,
300
+ }
301
+
302
+
303
+ @dataclass(eq=False)
304
+ class TLSListener(Listener[TLSStream]):
305
+ """
306
+ A convenience listener that wraps another listener and auto-negotiates a TLS session
307
+ on every accepted connection.
308
+
309
+ If the TLS handshake times out or raises an exception,
310
+ :meth:`handle_handshake_error` is called to do whatever post-mortem processing is
311
+ deemed necessary.
312
+
313
+ Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute.
314
+
315
+ :param Listener listener: the listener to wrap
316
+ :param ssl_context: the SSL context object
317
+ :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap`
318
+ :param handshake_timeout: time limit for the TLS handshake
319
+ (passed to :func:`~anyio.fail_after`)
320
+ """
321
+
322
+ listener: Listener[Any]
323
+ ssl_context: ssl.SSLContext
324
+ standard_compatible: bool = True
325
+ handshake_timeout: float = 30
326
+
327
+ @staticmethod
328
+ async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None:
329
+ """
330
+ Handle an exception raised during the TLS handshake.
331
+
332
+ This method does 3 things:
333
+
334
+ #. Forcefully closes the original stream
335
+ #. Logs the exception (unless it was a cancellation exception) using the
336
+ ``anyio.streams.tls`` logger
337
+ #. Reraises the exception if it was a base exception or a cancellation exception
338
+
339
+ :param exc: the exception
340
+ :param stream: the original stream
341
+
342
+ """
343
+ await aclose_forcefully(stream)
344
+
345
+ # Log all except cancellation exceptions
346
+ if not isinstance(exc, get_cancelled_exc_class()):
347
+ # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using
348
+ # any asyncio implementation, so we explicitly pass the exception to log
349
+ # (https://github.com/python/cpython/issues/108668). Trio does not have this
350
+ # issue because it works around the CPython bug.
351
+ logging.getLogger(__name__).exception(
352
+ "Error during TLS handshake", exc_info=exc
353
+ )
354
+
355
+ # Only reraise base exceptions and cancellation exceptions
356
+ if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()):
357
+ raise # noqa: PLE0704
358
+
359
+ async def serve(
360
+ self,
361
+ handler: Callable[[TLSStream], Any],
362
+ task_group: TaskGroup | None = None,
363
+ ) -> None:
364
+ @wraps(handler)
365
+ async def handler_wrapper(stream: AnyByteStream) -> None:
366
+ from .. import fail_after
367
+
368
+ try:
369
+ with fail_after(self.handshake_timeout):
370
+ wrapped_stream = await TLSStream.wrap(
371
+ stream,
372
+ ssl_context=self.ssl_context,
373
+ standard_compatible=self.standard_compatible,
374
+ )
375
+ except BaseException as exc:
376
+ await self.handle_handshake_error(exc, stream)
377
+ else:
378
+ await handler(wrapped_stream)
379
+
380
+ await self.listener.serve(handler_wrapper, task_group)
381
+
382
+ async def aclose(self) -> None:
383
+ await self.listener.aclose()
384
+
385
+ @property
386
+ def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
387
+ return {
388
+ TLSAttribute.standard_compatible: lambda: self.standard_compatible,
389
+ }
390
+
391
+
392
+ class TLSConnectable(ByteStreamConnectable):
393
+ """
394
+ Wraps another connectable and does TLS negotiation after a successful connection.
395
+
396
+ :param connectable: the connectable to wrap
397
+ :param hostname: host name of the server (if host name checking is desired)
398
+ :param ssl_context: the SSLContext object to use (if not provided, a secure default
399
+ will be created)
400
+ :param standard_compatible: if ``False``, skip the closing handshake when closing
401
+ the connection, and don't raise an exception if the server does the same
402
+ """
403
+
404
+ def __init__(
405
+ self,
406
+ connectable: AnyByteStreamConnectable,
407
+ *,
408
+ hostname: str | None = None,
409
+ ssl_context: ssl.SSLContext | None = None,
410
+ standard_compatible: bool = True,
411
+ ) -> None:
412
+ self.connectable = connectable
413
+ self.ssl_context: SSLContext = ssl_context or ssl.create_default_context(
414
+ ssl.Purpose.SERVER_AUTH
415
+ )
416
+ if not isinstance(self.ssl_context, ssl.SSLContext):
417
+ raise TypeError(
418
+ "ssl_context must be an instance of ssl.SSLContext, not "
419
+ f"{type(self.ssl_context).__name__}"
420
+ )
421
+ self.hostname = hostname
422
+ self.standard_compatible = standard_compatible
423
+
424
+ @override
425
+ async def connect(self) -> TLSStream:
426
+ stream = await self.connectable.connect()
427
+ try:
428
+ return await TLSStream.wrap(
429
+ stream,
430
+ hostname=self.hostname,
431
+ ssl_context=self.ssl_context,
432
+ standard_compatible=self.standard_compatible,
433
+ )
434
+ except BaseException:
435
+ await aclose_forcefully(stream)
436
+ raise
.venv/lib/python3.12/site-packages/anyio/to_interpreter.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "current_default_interpreter_limiter",
5
+ "run_sync",
6
+ )
7
+
8
+ import atexit
9
+ import os
10
+ import sys
11
+ from collections import deque
12
+ from collections.abc import Callable
13
+ from typing import Any, Final, TypeVar
14
+
15
+ from . import current_time, to_thread
16
+ from ._core._exceptions import BrokenWorkerInterpreter
17
+ from ._core._synchronization import CapacityLimiter
18
+ from .lowlevel import RunVar
19
+
20
+ if sys.version_info >= (3, 11):
21
+ from typing import TypeVarTuple, Unpack
22
+ else:
23
+ from typing_extensions import TypeVarTuple, Unpack
24
+
25
+ if sys.version_info >= (3, 14):
26
+ from concurrent.interpreters import ExecutionFailed, create
27
+
28
+ def _interp_call(
29
+ func: Callable[..., Any], args: tuple[Any, ...]
30
+ ) -> tuple[Any, bool]:
31
+ try:
32
+ retval = func(*args)
33
+ except BaseException as exc:
34
+ return exc, True
35
+ else:
36
+ return retval, False
37
+
38
+ class _Worker:
39
+ last_used: float = 0
40
+
41
+ def __init__(self) -> None:
42
+ self._interpreter = create()
43
+
44
+ def destroy(self) -> None:
45
+ self._interpreter.close()
46
+
47
+ def call(
48
+ self,
49
+ func: Callable[..., T_Retval],
50
+ args: tuple[Any, ...],
51
+ ) -> T_Retval:
52
+ try:
53
+ res, is_exception = self._interpreter.call(_interp_call, func, args)
54
+ except ExecutionFailed as exc:
55
+ raise BrokenWorkerInterpreter(exc.excinfo) from exc
56
+
57
+ if is_exception:
58
+ raise res
59
+
60
+ return res
61
+ elif sys.version_info >= (3, 13):
62
+ import _interpqueues
63
+ import _interpreters
64
+
65
+ UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib
66
+ FMT_UNPICKLED: Final = 0
67
+ FMT_PICKLED: Final = 1
68
+ QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND)
69
+ QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND)
70
+
71
+ _run_func = compile(
72
+ """
73
+ import _interpqueues
74
+ from _interpreters import NotShareableError
75
+ from pickle import loads, dumps, HIGHEST_PROTOCOL
76
+
77
+ QUEUE_PICKLE_ARGS = (1, 2)
78
+ QUEUE_UNPICKLE_ARGS = (0, 2)
79
+
80
+ item = _interpqueues.get(queue_id)[0]
81
+ try:
82
+ func, args = loads(item)
83
+ retval = func(*args)
84
+ except BaseException as exc:
85
+ is_exception = True
86
+ retval = exc
87
+ else:
88
+ is_exception = False
89
+
90
+ try:
91
+ _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS)
92
+ except NotShareableError:
93
+ retval = dumps(retval, HIGHEST_PROTOCOL)
94
+ _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS)
95
+ """,
96
+ "<string>",
97
+ "exec",
98
+ )
99
+
100
+ class _Worker:
101
+ last_used: float = 0
102
+
103
+ def __init__(self) -> None:
104
+ self._interpreter_id = _interpreters.create()
105
+ self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS)
106
+ _interpreters.set___main___attrs(
107
+ self._interpreter_id, {"queue_id": self._queue_id}
108
+ )
109
+
110
+ def destroy(self) -> None:
111
+ _interpqueues.destroy(self._queue_id)
112
+ _interpreters.destroy(self._interpreter_id)
113
+
114
+ def call(
115
+ self,
116
+ func: Callable[..., T_Retval],
117
+ args: tuple[Any, ...],
118
+ ) -> T_Retval:
119
+ import pickle
120
+
121
+ item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL)
122
+ _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS)
123
+ exc_info = _interpreters.exec(self._interpreter_id, _run_func)
124
+ if exc_info:
125
+ raise BrokenWorkerInterpreter(exc_info)
126
+
127
+ res = _interpqueues.get(self._queue_id)
128
+ (res, is_exception), fmt = res[:2]
129
+ if fmt == FMT_PICKLED:
130
+ res = pickle.loads(res)
131
+
132
+ if is_exception:
133
+ raise res
134
+
135
+ return res
136
+ else:
137
+
138
+ class _Worker:
139
+ last_used: float = 0
140
+
141
+ def __init__(self) -> None:
142
+ raise RuntimeError("subinterpreters require at least Python 3.13")
143
+
144
+ def call(
145
+ self,
146
+ func: Callable[..., T_Retval],
147
+ args: tuple[Any, ...],
148
+ ) -> T_Retval:
149
+ raise NotImplementedError
150
+
151
+ def destroy(self) -> None:
152
+ pass
153
+
154
+
155
+ DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value
156
+ MAX_WORKER_IDLE_TIME = (
157
+ 30 # seconds a subinterpreter can be idle before becoming eligible for pruning
158
+ )
159
+
160
+ T_Retval = TypeVar("T_Retval")
161
+ PosArgsT = TypeVarTuple("PosArgsT")
162
+
163
+ _idle_workers = RunVar[deque[_Worker]]("_available_workers")
164
+ _default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter")
165
+
166
+
167
+ def _stop_workers(workers: deque[_Worker]) -> None:
168
+ for worker in workers:
169
+ worker.destroy()
170
+
171
+ workers.clear()
172
+
173
+
174
+ async def run_sync(
175
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
176
+ *args: Unpack[PosArgsT],
177
+ limiter: CapacityLimiter | None = None,
178
+ ) -> T_Retval:
179
+ """
180
+ Call the given function with the given arguments in a subinterpreter.
181
+
182
+ .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet
183
+ available, so the code path for that Python version relies on an undocumented,
184
+ private API. As such, it is recommended to not rely on this function for anything
185
+ mission-critical on Python 3.13.
186
+
187
+ :param func: a callable
188
+ :param args: the positional arguments for the callable
189
+ :param limiter: capacity limiter to use to limit the total number of subinterpreters
190
+ running (if omitted, the default limiter is used)
191
+ :return: the result of the call
192
+ :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter
193
+
194
+ """
195
+ if limiter is None:
196
+ limiter = current_default_interpreter_limiter()
197
+
198
+ try:
199
+ idle_workers = _idle_workers.get()
200
+ except LookupError:
201
+ idle_workers = deque()
202
+ _idle_workers.set(idle_workers)
203
+ atexit.register(_stop_workers, idle_workers)
204
+
205
+ async with limiter:
206
+ try:
207
+ worker = idle_workers.pop()
208
+ except IndexError:
209
+ worker = _Worker()
210
+
211
+ try:
212
+ return await to_thread.run_sync(
213
+ worker.call,
214
+ func,
215
+ args,
216
+ limiter=limiter,
217
+ )
218
+ finally:
219
+ # Prune workers that have been idle for too long
220
+ now = current_time()
221
+ while idle_workers:
222
+ if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME:
223
+ break
224
+
225
+ await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter)
226
+
227
+ worker.last_used = current_time()
228
+ idle_workers.append(worker)
229
+
230
+
231
+ def current_default_interpreter_limiter() -> CapacityLimiter:
232
+ """
233
+ Return the capacity limiter used by default to limit the number of concurrently
234
+ running subinterpreters.
235
+
236
+ Defaults to the number of CPU cores.
237
+
238
+ :return: a capacity limiter object
239
+
240
+ """
241
+ try:
242
+ return _default_interpreter_limiter.get()
243
+ except LookupError:
244
+ limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT)
245
+ _default_interpreter_limiter.set(limiter)
246
+ return limiter
.venv/lib/python3.12/site-packages/anyio/to_process.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "current_default_process_limiter",
5
+ "process_worker",
6
+ "run_sync",
7
+ )
8
+
9
+ import os
10
+ import pickle
11
+ import runpy
12
+ import subprocess
13
+ import sys
14
+ from collections import deque
15
+ from collections.abc import Callable
16
+ from types import ModuleType
17
+ from typing import TypeVar, cast
18
+
19
+ from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class
20
+ from ._core._exceptions import BrokenWorkerProcess
21
+ from ._core._subprocesses import open_process
22
+ from ._core._synchronization import CapacityLimiter
23
+ from ._core._tasks import CancelScope, fail_after
24
+ from .abc import ByteReceiveStream, ByteSendStream, Process
25
+ from .lowlevel import RunVar, checkpoint_if_cancelled
26
+ from .streams.buffered import BufferedByteReceiveStream
27
+
28
+ if sys.version_info >= (3, 11):
29
+ from typing import TypeVarTuple, Unpack
30
+ else:
31
+ from typing_extensions import TypeVarTuple, Unpack
32
+
33
+ WORKER_MAX_IDLE_TIME = 300 # 5 minutes
34
+
35
+ T_Retval = TypeVar("T_Retval")
36
+ PosArgsT = TypeVarTuple("PosArgsT")
37
+
38
+ _process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers")
39
+ _process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar(
40
+ "_process_pool_idle_workers"
41
+ )
42
+ _default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter")
43
+
44
+
45
+ async def run_sync( # type: ignore[return]
46
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
47
+ *args: Unpack[PosArgsT],
48
+ cancellable: bool = False,
49
+ limiter: CapacityLimiter | None = None,
50
+ ) -> T_Retval:
51
+ """
52
+ Call the given function with the given arguments in a worker process.
53
+
54
+ If the ``cancellable`` option is enabled and the task waiting for its completion is
55
+ cancelled, the worker process running it will be abruptly terminated using SIGKILL
56
+ (or ``terminateProcess()`` on Windows).
57
+
58
+ :param func: a callable
59
+ :param args: positional arguments for the callable
60
+ :param cancellable: ``True`` to allow cancellation of the operation while it's
61
+ running
62
+ :param limiter: capacity limiter to use to limit the total amount of processes
63
+ running (if omitted, the default limiter is used)
64
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
65
+ current thread
66
+ :return: an awaitable that yields the return value of the function.
67
+
68
+ """
69
+
70
+ async def send_raw_command(pickled_cmd: bytes) -> object:
71
+ try:
72
+ await stdin.send(pickled_cmd)
73
+ response = await buffered.receive_until(b"\n", 50)
74
+ status, length = response.split(b" ")
75
+ if status not in (b"RETURN", b"EXCEPTION"):
76
+ raise RuntimeError(
77
+ f"Worker process returned unexpected response: {response!r}"
78
+ )
79
+
80
+ pickled_response = await buffered.receive_exactly(int(length))
81
+ except BaseException as exc:
82
+ workers.discard(process)
83
+ try:
84
+ process.kill()
85
+ with CancelScope(shield=True):
86
+ await process.aclose()
87
+ except ProcessLookupError:
88
+ pass
89
+
90
+ if isinstance(exc, get_cancelled_exc_class()):
91
+ raise
92
+ else:
93
+ raise BrokenWorkerProcess from exc
94
+
95
+ retval = pickle.loads(pickled_response)
96
+ if status == b"EXCEPTION":
97
+ assert isinstance(retval, BaseException)
98
+ raise retval
99
+ else:
100
+ return retval
101
+
102
+ # First pickle the request before trying to reserve a worker process
103
+ await checkpoint_if_cancelled()
104
+ request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL)
105
+
106
+ # If this is the first run in this event loop thread, set up the necessary variables
107
+ try:
108
+ workers = _process_pool_workers.get()
109
+ idle_workers = _process_pool_idle_workers.get()
110
+ except LookupError:
111
+ workers = set()
112
+ idle_workers = deque()
113
+ _process_pool_workers.set(workers)
114
+ _process_pool_idle_workers.set(idle_workers)
115
+ get_async_backend().setup_process_pool_exit_at_shutdown(workers)
116
+
117
+ async with limiter or current_default_process_limiter():
118
+ # Pop processes from the pool (starting from the most recently used) until we
119
+ # find one that hasn't exited yet
120
+ process: Process
121
+ while idle_workers:
122
+ process, _idle_since = idle_workers.pop()
123
+ if process.returncode is None:
124
+ stdin = cast(ByteSendStream, process.stdin)
125
+ buffered = BufferedByteReceiveStream(
126
+ cast(ByteReceiveStream, process.stdout)
127
+ )
128
+
129
+ # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME
130
+ # seconds or longer
131
+ now = current_time()
132
+ killed_processes: list[Process] = []
133
+ while idle_workers:
134
+ if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME:
135
+ break
136
+
137
+ process_to_kill, _idle_since = idle_workers.popleft()
138
+ process_to_kill.kill()
139
+ workers.remove(process_to_kill)
140
+ killed_processes.append(process_to_kill)
141
+
142
+ with CancelScope(shield=True):
143
+ for killed_process in killed_processes:
144
+ await killed_process.aclose()
145
+
146
+ break
147
+
148
+ workers.remove(process)
149
+ else:
150
+ command = [sys.executable, "-u", "-m", __name__]
151
+ process = await open_process(
152
+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE
153
+ )
154
+ try:
155
+ stdin = cast(ByteSendStream, process.stdin)
156
+ buffered = BufferedByteReceiveStream(
157
+ cast(ByteReceiveStream, process.stdout)
158
+ )
159
+ with fail_after(20):
160
+ message = await buffered.receive(6)
161
+
162
+ if message != b"READY\n":
163
+ raise BrokenWorkerProcess(
164
+ f"Worker process returned unexpected response: {message!r}"
165
+ )
166
+
167
+ main_module_path = getattr(sys.modules["__main__"], "__file__", None)
168
+ pickled = pickle.dumps(
169
+ ("init", sys.path, main_module_path),
170
+ protocol=pickle.HIGHEST_PROTOCOL,
171
+ )
172
+ await send_raw_command(pickled)
173
+ except (BrokenWorkerProcess, get_cancelled_exc_class()):
174
+ raise
175
+ except BaseException as exc:
176
+ process.kill()
177
+ raise BrokenWorkerProcess(
178
+ "Error during worker process initialization"
179
+ ) from exc
180
+
181
+ workers.add(process)
182
+
183
+ with CancelScope(shield=not cancellable):
184
+ try:
185
+ return cast(T_Retval, await send_raw_command(request))
186
+ finally:
187
+ if process in workers:
188
+ idle_workers.append((process, current_time()))
189
+
190
+
191
+ def current_default_process_limiter() -> CapacityLimiter:
192
+ """
193
+ Return the capacity limiter that is used by default to limit the number of worker
194
+ processes.
195
+
196
+ :return: a capacity limiter object
197
+
198
+ """
199
+ try:
200
+ return _default_process_limiter.get()
201
+ except LookupError:
202
+ limiter = CapacityLimiter(os.cpu_count() or 2)
203
+ _default_process_limiter.set(limiter)
204
+ return limiter
205
+
206
+
207
+ def process_worker() -> None:
208
+ # Redirect standard streams to os.devnull so that user code won't interfere with the
209
+ # parent-worker communication
210
+ stdin = sys.stdin
211
+ stdout = sys.stdout
212
+ sys.stdin = open(os.devnull)
213
+ sys.stdout = open(os.devnull, "w")
214
+ sys.stderr = open(os.devnull, "w")
215
+
216
+ stdout.buffer.write(b"READY\n")
217
+ while True:
218
+ retval = exception = None
219
+ try:
220
+ command, *args = pickle.load(stdin.buffer)
221
+ except EOFError:
222
+ return
223
+ except BaseException as exc:
224
+ exception = exc
225
+ else:
226
+ if command == "run":
227
+ func, args = args
228
+ try:
229
+ retval = func(*args)
230
+ except BaseException as exc:
231
+ exception = exc
232
+ elif command == "init":
233
+ main_module_path: str | None
234
+ sys.path, main_module_path = args
235
+ del sys.modules["__main__"]
236
+ if main_module_path and os.path.isfile(main_module_path):
237
+ # Load the parent's main module but as __mp_main__ instead of
238
+ # __main__ (like multiprocessing does) to avoid infinite recursion
239
+ try:
240
+ main = ModuleType("__mp_main__")
241
+ main_content = runpy.run_path(
242
+ main_module_path, run_name="__mp_main__"
243
+ )
244
+ main.__dict__.update(main_content)
245
+ sys.modules["__main__"] = sys.modules["__mp_main__"] = main
246
+ except BaseException as exc:
247
+ exception = exc
248
+ try:
249
+ if exception is not None:
250
+ status = b"EXCEPTION"
251
+ pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL)
252
+ else:
253
+ status = b"RETURN"
254
+ pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL)
255
+ except BaseException as exc:
256
+ exception = exc
257
+ status = b"EXCEPTION"
258
+ pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL)
259
+
260
+ stdout.buffer.write(b"%s %d\n" % (status, len(pickled)))
261
+ stdout.buffer.write(pickled)
262
+
263
+ # Respect SIGTERM
264
+ if isinstance(exception, SystemExit):
265
+ raise exception
266
+
267
+
268
+ if __name__ == "__main__":
269
+ process_worker()
.venv/lib/python3.12/site-packages/anyio/to_thread.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "current_default_thread_limiter",
5
+ "run_sync",
6
+ )
7
+
8
+ import sys
9
+ from collections.abc import Callable
10
+ from typing import TYPE_CHECKING, TypeVar
11
+ from warnings import warn
12
+
13
+ from ._core._eventloop import get_async_backend
14
+
15
+ if TYPE_CHECKING:
16
+ from ._core._synchronization import CapacityLimiter
17
+
18
+ if sys.version_info >= (3, 11):
19
+ from typing import TypeVarTuple, Unpack
20
+ else:
21
+ from typing_extensions import TypeVarTuple, Unpack
22
+
23
+ T_Retval = TypeVar("T_Retval")
24
+ PosArgsT = TypeVarTuple("PosArgsT")
25
+
26
+
27
+ async def run_sync(
28
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
29
+ *args: Unpack[PosArgsT],
30
+ abandon_on_cancel: bool = False,
31
+ cancellable: bool | None = None,
32
+ limiter: CapacityLimiter | None = None,
33
+ ) -> T_Retval:
34
+ """
35
+ Call the given function with the given arguments in a worker thread.
36
+
37
+ If the ``abandon_on_cancel`` option is enabled and the task waiting for its
38
+ completion is cancelled, the thread will still run its course but its
39
+ return value (or any raised exception) will be ignored.
40
+
41
+ :param func: a callable
42
+ :param args: positional arguments for the callable
43
+ :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run
44
+ unchecked on own) if the host task is cancelled, ``False`` to ignore
45
+ cancellations in the host task until the operation has completed in the worker
46
+ thread
47
+ :param cancellable: deprecated alias of ``abandon_on_cancel``; will override
48
+ ``abandon_on_cancel`` if both parameters are passed
49
+ :param limiter: capacity limiter to use to limit the total amount of threads running
50
+ (if omitted, the default limiter is used)
51
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
52
+ current thread
53
+ :return: an awaitable that yields the return value of the function.
54
+
55
+ """
56
+ if cancellable is not None:
57
+ abandon_on_cancel = cancellable
58
+ warn(
59
+ "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is "
60
+ "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead",
61
+ DeprecationWarning,
62
+ stacklevel=2,
63
+ )
64
+
65
+ return await get_async_backend().run_sync_in_worker_thread(
66
+ func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter
67
+ )
68
+
69
+
70
+ def current_default_thread_limiter() -> CapacityLimiter:
71
+ """
72
+ Return the capacity limiter that is used by default to limit the number of
73
+ concurrent threads.
74
+
75
+ :return: a capacity limiter object
76
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
77
+ current thread
78
+
79
+ """
80
+ return get_async_backend().current_default_thread_limiter()
.venv/lib/python3.12/site-packages/av/__init__.pxd ADDED
File without changes
.venv/lib/python3.12/site-packages/av/__init__.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MUST import the core before anything else in order to initialize the underlying
2
+ # library that is being wrapped.
3
+ from av._core import time_base, library_versions, ffmpeg_version_info
4
+
5
+ # Capture logging (by importing it).
6
+ from av import logging
7
+
8
+ # For convenience, import all common attributes.
9
+ from av.about import __version__
10
+ from av.audio.codeccontext import AudioCodecContext
11
+ from av.audio.fifo import AudioFifo
12
+ from av.audio.format import AudioFormat
13
+ from av.audio.frame import AudioFrame
14
+ from av.audio.layout import AudioLayout
15
+ from av.audio.resampler import AudioResampler
16
+ from av.audio.stream import AudioStream
17
+ from av.bitstream import BitStreamFilterContext, bitstream_filters_available
18
+ from av.codec.codec import Codec, codecs_available
19
+ from av.codec.context import CodecContext
20
+ from av.container import open
21
+ from av.device import DeviceInfo, enumerate_input_devices, enumerate_output_devices
22
+ from av.format import ContainerFormat, formats_available
23
+ from av.packet import Packet
24
+ from av.rational import AVRational
25
+ from av.error import * # noqa: F403; This is limited to exception types.
26
+ from av.video.codeccontext import VideoCodecContext
27
+ from av.video.format import VideoFormat
28
+ from av.video.frame import VideoFrame
29
+ from av.video.stream import VideoStream
30
+
31
+ __all__ = (
32
+ "__version__",
33
+ "time_base",
34
+ "ffmpeg_version_info",
35
+ "library_versions",
36
+ "AudioCodecContext",
37
+ "AudioFifo",
38
+ "AudioFormat",
39
+ "AudioFrame",
40
+ "AudioLayout",
41
+ "AudioResampler",
42
+ "AudioStream",
43
+ "BitStreamFilterContext",
44
+ "bitstream_filters_available",
45
+ "Codec",
46
+ "codecs_available",
47
+ "CodecContext",
48
+ "open",
49
+ "DeviceInfo",
50
+ "enumerate_input_devices",
51
+ "enumerate_output_devices",
52
+ "ContainerFormat",
53
+ "formats_available",
54
+ "Packet",
55
+ "VideoCodecContext",
56
+ "VideoFormat",
57
+ "VideoFrame",
58
+ "VideoStream",
59
+ )
60
+
61
+
62
+ def get_include() -> str:
63
+ """
64
+ Returns the path to the `include` folder to be used when building extensions to av.
65
+ """
66
+ import os
67
+
68
+ # Installed package
69
+ include_path = os.path.join(os.path.dirname(__file__), "include")
70
+ if os.path.exists(include_path):
71
+ return include_path
72
+ # Running from source directory
73
+ return os.path.join(os.path.dirname(__file__), os.pardir, "include")
.venv/lib/python3.12/site-packages/av/__main__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+
5
+
6
+ def main() -> None:
7
+ parser = argparse.ArgumentParser()
8
+ parser.add_argument("--codecs", action="store_true")
9
+ parser.add_argument("--hwdevices", action="store_true")
10
+ parser.add_argument("--hwconfigs", action="store_true")
11
+ parser.add_argument("--version", action="store_true")
12
+ args = parser.parse_args()
13
+
14
+ if args.version:
15
+ import av
16
+ import av._core
17
+
18
+ print(f"PyAV v{av.__version__}")
19
+
20
+ by_config: dict = {}
21
+ for libname, config in sorted(av._core.library_meta.items()):
22
+ version = config["version"]
23
+ if version[0] >= 0:
24
+ by_config.setdefault(
25
+ (config["configuration"], config["license"]), []
26
+ ).append((libname, config))
27
+
28
+ for (config, license), libs in sorted(by_config.items()):
29
+ print("library configuration:", config)
30
+ print("library license:", license)
31
+ for libname, config in libs:
32
+ version = config["version"]
33
+ print(f"{libname:<13} {version[0]:3d}.{version[1]:3d}.{version[2]:3d}")
34
+
35
+ if args.hwdevices:
36
+ from av.codec.hwaccel import hwdevices_available
37
+
38
+ print("Hardware device types:")
39
+ for x in hwdevices_available():
40
+ print(" ", x)
41
+
42
+ if args.hwconfigs:
43
+ from av.codec.codec import dump_hwconfigs
44
+
45
+ dump_hwconfigs()
46
+
47
+ if args.codecs:
48
+ from av.codec.codec import dump_codecs
49
+
50
+ dump_codecs()
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
.venv/lib/python3.12/site-packages/av/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.42 kB). View file
 
.venv/lib/python3.12/site-packages/av/__pycache__/__main__.cpython-312.pyc ADDED
Binary file (2.46 kB). View file
 
.venv/lib/python3.12/site-packages/av/__pycache__/_core.cpython-312.pyc ADDED
Binary file (2.68 kB). View file
 
.venv/lib/python3.12/site-packages/av/__pycache__/about.cpython-312.pyc ADDED
Binary file (201 Bytes). View file
 
.venv/lib/python3.12/site-packages/av/__pycache__/bitstream.cpython-312.pyc ADDED
Binary file (6.53 kB). View file
 
.venv/lib/python3.12/site-packages/av/__pycache__/buffer.cpython-312.pyc ADDED
Binary file (5.2 kB). View file