Sumitwarrior7 commited on
Commit
a083046
·
verified ·
1 Parent(s): 0f29760

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/INSTALLER +1 -0
  2. .venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/METADATA +199 -0
  3. .venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/RECORD +37 -0
  4. .venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/REQUESTED +0 -0
  5. .venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/WHEEL +4 -0
  6. .venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/licenses/LICENSE +21 -0
  7. .venv/lib/python3.10/site-packages/cachetools/__init__.py +772 -0
  8. .venv/lib/python3.10/site-packages/cachetools/__pycache__/__init__.cpython-310.pyc +0 -0
  9. .venv/lib/python3.10/site-packages/cachetools/__pycache__/keys.cpython-310.pyc +0 -0
  10. .venv/lib/python3.10/site-packages/cachetools/_cached.py +259 -0
  11. .venv/lib/python3.10/site-packages/cachetools/_cachedmethod.py +419 -0
  12. .venv/lib/python3.10/site-packages/cachetools/func.py +105 -0
  13. .venv/lib/python3.10/site-packages/cachetools/keys.py +66 -0
  14. .venv/lib/python3.10/site-packages/caio/__init__.py +104 -0
  15. .venv/lib/python3.10/site-packages/caio/asyncio_base.py +93 -0
  16. .venv/lib/python3.10/site-packages/caio/src/threadpool/README.md +24 -0
  17. .venv/lib/python3.10/site-packages/caio/src/threadpool/threadpool.c +305 -0
  18. .venv/lib/python3.10/site-packages/caio/src/threadpool/threadpool.h +101 -0
  19. .venv/lib/python3.10/site-packages/caio/thread_aio.c +840 -0
  20. .venv/lib/python3.10/site-packages/caio/thread_aio.cpython-310-x86_64-linux-gnu.so +0 -0
  21. .venv/lib/python3.10/site-packages/caio/thread_aio_asyncio.py +8 -0
  22. .venv/lib/python3.10/site-packages/caio/version.py +22 -0
  23. .venv/lib/python3.10/site-packages/cryptography/__about__.py +17 -0
  24. .venv/lib/python3.10/site-packages/cryptography/__init__.py +26 -0
  25. .venv/lib/python3.10/site-packages/cryptography/exceptions.py +52 -0
  26. .venv/lib/python3.10/site-packages/cryptography/fernet.py +224 -0
  27. .venv/lib/python3.10/site-packages/cryptography/hazmat/__init__.py +13 -0
  28. .venv/lib/python3.10/site-packages/cryptography/hazmat/_oid.py +356 -0
  29. .venv/lib/python3.10/site-packages/cryptography/hazmat/asn1/__init__.py +43 -0
  30. .venv/lib/python3.10/site-packages/cryptography/hazmat/asn1/asn1.py +439 -0
  31. .venv/lib/python3.10/site-packages/cryptography/hazmat/backends/__init__.py +13 -0
  32. .venv/lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/__init__.py +9 -0
  33. .venv/lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/backend.py +310 -0
  34. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/__init__.py +3 -0
  35. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi +67 -0
  36. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi +8 -0
  37. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi +7 -0
  38. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi +127 -0
  39. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi +17 -0
  40. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi +117 -0
  41. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi +80 -0
  42. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi +189 -0
  43. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi +38 -0
  44. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi +18 -0
  45. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi +51 -0
  46. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi +41 -0
  47. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi +52 -0
  48. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi +13 -0
  49. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi +13 -0
  50. .venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi +30 -0
.venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/METADATA ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: attrs
3
+ Version: 26.1.0
4
+ Summary: Classes Without Boilerplate
5
+ Project-URL: Documentation, https://www.attrs.org/
6
+ Project-URL: Changelog, https://www.attrs.org/en/stable/changelog.html
7
+ Project-URL: GitHub, https://github.com/python-attrs/attrs
8
+ Project-URL: Funding, https://github.com/sponsors/hynek
9
+ Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-attrs?utm_source=pypi-attrs&utm_medium=pypi
10
+ Author-email: Hynek Schlawack <hs@ox.cx>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: attribute,boilerplate,class
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.9
25
+ Description-Content-Type: text/markdown
26
+
27
+ <p align="center">
28
+ <a href="https://www.attrs.org/">
29
+ <img src="https://raw.githubusercontent.com/python-attrs/attrs/main/docs/_static/attrs_logo.svg" width="35%" alt="attrs" />
30
+ </a>
31
+ </p>
32
+
33
+
34
+ *attrs* is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka [dunder methods](https://www.attrs.org/en/latest/glossary.html#term-dunder-methods)).
35
+ Trusted by NASA for [Mars missions since 2020](https://github.com/readme/featured/nasa-ingenuity-helicopter)!
36
+
37
+ Its main goal is to help you to write **concise** and **correct** software without slowing down your code.
38
+
39
+
40
+ ## Sponsors
41
+
42
+ *attrs* would not be possible without our [amazing sponsors](https://github.com/sponsors/hynek).
43
+ Especially those generously supporting us at the *The Organization* tier and higher:
44
+
45
+ <!-- sponsor-break-begin -->
46
+
47
+ <p align="center">
48
+
49
+ <!-- [[[cog
50
+ import pathlib, tomllib
51
+
52
+ for sponsor in tomllib.loads(pathlib.Path("pyproject.toml").read_text())["tool"]["sponcon"]["sponsors"]:
53
+ print(f'<a href="{sponsor["url"]}"><img title="{sponsor["title"]}" src="https://www.attrs.org/en/26.1.0/_static/sponsors/{sponsor["img"]}" width="190" /></a>')
54
+ ]]] -->
55
+ <a href="https://www.variomedia.de/"><img title="Variomedia AG" src="https://www.attrs.org/en/26.1.0/_static/sponsors/Variomedia.svg" width="190" /></a>
56
+ <a href="https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek"><img title="Tidelift" src="https://www.attrs.org/en/26.1.0/_static/sponsors/Tidelift.svg" width="190" /></a>
57
+ <a href="https://kraken.tech/"><img title="Kraken Tech" src="https://www.attrs.org/en/26.1.0/_static/sponsors/Kraken.svg" width="190" /></a>
58
+ <a href="https://privacy-solutions.org/"><img title="Privacy Solutions" src="https://www.attrs.org/en/26.1.0/_static/sponsors/Privacy-Solutions.svg" width="190" /></a>
59
+ <a href="https://filepreviews.io/"><img title="FilePreviews" src="https://www.attrs.org/en/26.1.0/_static/sponsors/FilePreviews.svg" width="190" /></a>
60
+ <a href="https://www.testmuai.com/?utm_medium=sponsor&utm_source=structlog"><img title="TestMu AI" src="https://www.attrs.org/en/26.1.0/_static/sponsors/TestMu-AI.svg" width="190" /></a>
61
+ <a href="https://polar.sh/"><img title="Polar" src="https://www.attrs.org/en/26.1.0/_static/sponsors/Polar.svg" width="190" /></a>
62
+ <!-- [[[end]]] -->
63
+
64
+ </p>
65
+
66
+ <!-- sponsor-break-end -->
67
+
68
+ <p align="center">
69
+ <strong>Please consider <a href="https://github.com/sponsors/hynek">joining them</a> to help make <em>attrs</em>’s maintenance more sustainable!</strong>
70
+ </p>
71
+
72
+ <!-- teaser-end -->
73
+
74
+ ## Example
75
+
76
+ *attrs* gives you a class decorator and a way to declaratively define the attributes on that class:
77
+
78
+ <!-- code-begin -->
79
+
80
+ ```pycon
81
+ >>> from attrs import asdict, define, make_class, Factory
82
+
83
+ >>> @define
84
+ ... class SomeClass:
85
+ ... a_number: int = 42
86
+ ... list_of_numbers: list[int] = Factory(list)
87
+ ...
88
+ ... def hard_math(self, another_number):
89
+ ... return self.a_number + sum(self.list_of_numbers) * another_number
90
+
91
+
92
+ >>> sc = SomeClass(1, [1, 2, 3])
93
+ >>> sc
94
+ SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
95
+
96
+ >>> sc.hard_math(3)
97
+ 19
98
+ >>> sc == SomeClass(1, [1, 2, 3])
99
+ True
100
+ >>> sc != SomeClass(2, [3, 2, 1])
101
+ True
102
+
103
+ >>> asdict(sc)
104
+ {'a_number': 1, 'list_of_numbers': [1, 2, 3]}
105
+
106
+ >>> SomeClass()
107
+ SomeClass(a_number=42, list_of_numbers=[])
108
+
109
+ >>> C = make_class("C", ["a", "b"])
110
+ >>> C("foo", "bar")
111
+ C(a='foo', b='bar')
112
+ ```
113
+
114
+ After *declaring* your attributes, *attrs* gives you:
115
+
116
+ - a concise and explicit overview of the class's attributes,
117
+ - a nice human-readable `__repr__`,
118
+ - equality-checking methods,
119
+ - an initializer,
120
+ - and much more,
121
+
122
+ *without* writing dull boilerplate code again and again and *without* runtime performance penalties.
123
+
124
+ ---
125
+
126
+ This example uses *attrs*'s modern APIs that have been introduced in version 20.1.0, and the *attrs* package import name that has been added in version 21.3.0.
127
+ The classic APIs (`@attr.s`, `attr.ib`, plus their serious-business aliases) and the `attr` package import name will remain **indefinitely**.
128
+
129
+ Check out [*On The Core API Names*](https://www.attrs.org/en/latest/names.html) for an in-depth explanation!
130
+
131
+
132
+ ### Hate Type Annotations!?
133
+
134
+ No problem!
135
+ Types are entirely **optional** with *attrs*.
136
+ Simply assign `attrs.field()` to the attributes instead of annotating them with types:
137
+
138
+ ```python
139
+ from attrs import define, field
140
+
141
+ @define
142
+ class SomeClass:
143
+ a_number = field(default=42)
144
+ list_of_numbers = field(factory=list)
145
+ ```
146
+
147
+
148
+ ## Data Classes
149
+
150
+ On the tin, *attrs* might remind you of `dataclasses` (and indeed, `dataclasses` [are a descendant](https://hynek.me/articles/import-attrs/) of *attrs*).
151
+ In practice it does a lot more and is more flexible.
152
+ For instance, it allows you to define [special handling of NumPy arrays for equality checks](https://www.attrs.org/en/stable/comparison.html#customization), allows more ways to [plug into the initialization process](https://www.attrs.org/en/stable/init.html#hooking-yourself-into-initialization), has a replacement for `__init_subclass__`, and allows for stepping through the generated methods using a debugger.
153
+
154
+ For more details, please refer to our [comparison page](https://www.attrs.org/en/stable/why.html#data-classes), but generally speaking, we are more likely to commit crimes against nature to make things work that one would expect to work, but that are quite complicated in practice.
155
+
156
+
157
+ ## Project Information
158
+
159
+ - [**Changelog**](https://www.attrs.org/en/stable/changelog.html)
160
+ - [**Documentation**](https://www.attrs.org/)
161
+ - [**PyPI**](https://pypi.org/project/attrs/)
162
+ - [**Source Code**](https://github.com/python-attrs/attrs)
163
+ - [**Contributing**](https://github.com/python-attrs/attrs/blob/main/.github/CONTRIBUTING.md)
164
+ - [**Third-party Extensions**](https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs)
165
+ - **Get Help**: use the `python-attrs` tag on [Stack Overflow](https://stackoverflow.com/questions/tagged/python-attrs)
166
+
167
+
168
+ ### *attrs* for Enterprise
169
+
170
+ Available as part of the [Tidelift Subscription](https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek).
171
+
172
+ The maintainers of *attrs* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications.
173
+ Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use.
174
+
175
+ ## Release Information
176
+
177
+ ### Backwards-incompatible Changes
178
+
179
+ - Field aliases are now resolved *before* calling `field_transformer`, so transformers receive fully populated `Attribute` objects with usable `alias` values instead of `None`.
180
+ The new `Attribute.alias_is_default` flag indicates whether the alias was auto-generated (`True`) or explicitly set by the user (`False`).
181
+ [#1509](https://github.com/python-attrs/attrs/issues/1509)
182
+
183
+
184
+ ### Changes
185
+
186
+ - Fix type annotations for `attrs.validators.optional()`, so it no longer rejects tuples with more than one validator.
187
+ [#1496](https://github.com/python-attrs/attrs/issues/1496)
188
+ - The `attrs.validators.disabled()` contextmanager can now be nested.
189
+ [#1513](https://github.com/python-attrs/attrs/issues/1513)
190
+ - Frozen classes can set `on_setattr=attrs.setters.NO_OP` in addition to `None`.
191
+ [#1515](https://github.com/python-attrs/attrs/issues/1515)
192
+ - It's now possible to pass *attrs* **instances** in addition to *attrs* **classes** to `attrs.fields()`.
193
+ [#1529](https://github.com/python-attrs/attrs/issues/1529)
194
+
195
+
196
+
197
+ ---
198
+
199
+ [Full changelog →](https://www.attrs.org/en/stable/changelog.html)
.venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/RECORD ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ attr/__init__.py,sha256=fOYIvt1eGSqQre4uCS3sJWKZ0mwAuC8UD6qba5OS9_U,2057
2
+ attr/__init__.pyi,sha256=pVGImAUVovq2_TYl_r_HIYnGlyOaoCuEhxo-EvsnnSc,11325
3
+ attr/_cmp.py,sha256=3Nn1TjxllUYiX_nJoVnEkXoDk0hM1DYKj5DE7GZe4i0,4117
4
+ attr/_cmp.pyi,sha256=U-_RU_UZOyPUEQzXE6RMYQQcjkZRY25wTH99sN0s7MM,368
5
+ attr/_compat.py,sha256=x0g7iEUOnBVJC72zyFCgb1eKqyxS-7f2LGnNyZ_r95s,2829
6
+ attr/_config.py,sha256=dGq3xR6fgZEF6UBt_L0T-eUHIB4i43kRmH0P28sJVw8,843
7
+ attr/_funcs.py,sha256=Ix5IETTfz5F01F-12MF_CSFomIn2h8b67EVVz2gCtBE,16479
8
+ attr/_make.py,sha256=H7OH2eWS5CnBzLUjNFE1WymfPrmF1r8fv2RPdt9MuYA,106129
9
+ attr/_next_gen.py,sha256=BQtCUlzwg2gWHTYXBQvrEYBnzBUrDvO57u0Py6UCPhc,26274
10
+ attr/_typing_compat.pyi,sha256=XDP54TUn-ZKhD62TOQebmzrwFyomhUCoGRpclb6alRA,469
11
+ attr/_version_info.py,sha256=w4R-FYC3NK_kMkGUWJlYP4cVAlH9HRaC-um3fcjYkHM,2222
12
+ attr/_version_info.pyi,sha256=x_M3L3WuB7r_ULXAWjx959udKQ4HLB8l-hsc1FDGNvk,209
13
+ attr/converters.py,sha256=GlDeOzPeTFgeBBLbj9G57Ez5lAk68uhSALRYJ_exe84,3861
14
+ attr/converters.pyi,sha256=orU2bff-VjQa2kMDyvnMQV73oJT2WRyQuw4ZR1ym1bE,643
15
+ attr/exceptions.py,sha256=b4vMbnoQ3VpwWZhqrYi_ssXVCK8o2c4HQSS09cSUM9o,1990
16
+ attr/exceptions.pyi,sha256=zZq8bCUnKAy9mDtBEw42ZhPhAUIHoTKedDQInJD883M,539
17
+ attr/filters.py,sha256=ZBiKWLp3R0LfCZsq7X11pn9WX8NslS2wXM4jsnLOGc8,1795
18
+ attr/filters.pyi,sha256=3J5BG-dTxltBk1_-RuNRUHrv2qu1v8v4aDNAQ7_mifA,208
19
+ attr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ attr/setters.py,sha256=5-dcT63GQK35ONEzSgfXCkbB7pPkaR-qv15mm4PVSzQ,1617
21
+ attr/setters.pyi,sha256=NnVkaFU1BB4JB8E4JuXyrzTUgvtMpj8p3wBdJY7uix4,584
22
+ attr/validators.py,sha256=m3QRzZTANr4f2C4eVdUoFg11NgXWak8Wat4qQTGhvcs,21553
23
+ attr/validators.pyi,sha256=gM1ZmHaBckyYWI2EirpRNzqm3B19cw5Iq6B4Kno9YCM,4087
24
+ attrs-26.1.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
25
+ attrs-26.1.0.dist-info/METADATA,sha256=TNQOaQ8jvzfLytNO_WdY4GLfHfB8hoM_fjzpW_H6OMw,8754
26
+ attrs-26.1.0.dist-info/RECORD,,
27
+ attrs-26.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
+ attrs-26.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
29
+ attrs-26.1.0.dist-info/licenses/LICENSE,sha256=iCEVyV38KvHutnFPjsbVy8q_Znyv-HKfQkINpj9xTp8,1109
30
+ attrs/__init__.py,sha256=RxaAZNwYiEh-fcvHLZNpQ_DWKni73M_jxEPEftiq1Zc,1183
31
+ attrs/__init__.pyi,sha256=2gV79g9UxJppGSM48hAZJ6h_MHb70dZoJL31ZNJeZYI,9416
32
+ attrs/converters.py,sha256=8kQljrVwfSTRu8INwEk8SI0eGrzmWftsT7rM0EqyohM,76
33
+ attrs/exceptions.py,sha256=ACCCmg19-vDFaDPY9vFl199SPXCQMN_bENs4DALjzms,76
34
+ attrs/filters.py,sha256=VOUMZug9uEU6dUuA0dF1jInUK0PL3fLgP0VBS5d-CDE,73
35
+ attrs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
+ attrs/setters.py,sha256=eL1YidYQV3T2h9_SYIZSZR1FAcHGb1TuCTy0E0Lv2SU,73
37
+ attrs/validators.py,sha256=xcy6wD5TtTkdCG1f4XWbocPSO0faBjk5IfVJfP6SUj0,76
.venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.10/site-packages/attrs-26.1.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Hynek Schlawack and the attrs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, 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,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
.venv/lib/python3.10/site-packages/cachetools/__init__.py ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extensible memoizing collections and decorators."""
2
+
3
+ __all__ = (
4
+ "Cache",
5
+ "FIFOCache",
6
+ "LFUCache",
7
+ "LRUCache",
8
+ "RRCache",
9
+ "TLRUCache",
10
+ "TTLCache",
11
+ "cached",
12
+ "cachedmethod",
13
+ )
14
+
15
+ __version__ = "7.0.6"
16
+
17
+ import collections
18
+ import collections.abc
19
+ import functools
20
+ import heapq
21
+ import random
22
+ import time
23
+
24
+ from . import keys
25
+
26
+ # Typing stubs for this package are provided by typeshed:
27
+ # https://github.com/python/typeshed/tree/main/stubs/cachetools
28
+
29
+
30
+ class _DefaultSize:
31
+ """A minimal "fake" dict that returns a constant size 1 for any key."""
32
+
33
+ __slots__ = ()
34
+
35
+ def __getitem__(self, _key):
36
+ return 1
37
+
38
+ def __setitem__(self, _key, _value):
39
+ pass
40
+
41
+ def pop(self, _key):
42
+ return 1
43
+
44
+ def clear(self):
45
+ pass
46
+
47
+
48
+ class Cache(collections.abc.MutableMapping):
49
+ """Mutable mapping to serve as a simple cache or cache base class."""
50
+
51
+ __marker = object()
52
+
53
+ __size = _DefaultSize()
54
+
55
+ def __init__(self, maxsize, getsizeof=None):
56
+ if getsizeof:
57
+ self.getsizeof = getsizeof
58
+ if self.getsizeof is not Cache.getsizeof:
59
+ self.__size = dict()
60
+ self.__data = dict()
61
+ self.__currsize = 0
62
+ self.__maxsize = maxsize
63
+
64
+ def __repr__(self):
65
+ return "%s(%s, maxsize=%r, currsize=%r)" % (
66
+ type(self).__name__,
67
+ repr(self.__data),
68
+ self.__maxsize,
69
+ self.__currsize,
70
+ )
71
+
72
+ def __getitem__(self, key):
73
+ try:
74
+ return self.__data[key]
75
+ except KeyError:
76
+ return self.__missing__(key)
77
+
78
+ def __setitem__(self, key, value):
79
+ maxsize = self.__maxsize
80
+ size = self.getsizeof(value)
81
+ if size > maxsize:
82
+ raise ValueError("value too large")
83
+ if key not in self.__data or self.__size[key] < size:
84
+ while self.__currsize + size > maxsize:
85
+ self.popitem()
86
+ if key in self.__data:
87
+ diffsize = size - self.__size[key]
88
+ else:
89
+ diffsize = size
90
+ self.__data[key] = value
91
+ self.__size[key] = size
92
+ self.__currsize += diffsize
93
+
94
+ def __delitem__(self, key):
95
+ size = self.__size.pop(key)
96
+ del self.__data[key]
97
+ self.__currsize -= size
98
+
99
+ def __contains__(self, key):
100
+ return key in self.__data
101
+
102
+ def __missing__(self, key):
103
+ raise KeyError(key)
104
+
105
+ def __iter__(self):
106
+ return iter(self.__data)
107
+
108
+ def __len__(self):
109
+ return len(self.__data)
110
+
111
+ # Note that we cannot simply inherit get(), pop() and setdefault()
112
+ # from MutableMapping, since these rely on __getitem__ throwing a
113
+ # KeyError on cache miss. This is not the case if __missing__ is
114
+ # implemented for a Cache subclass, so we have to roll our own,
115
+ # somewhat less elegant versions.
116
+
117
+ def get(self, key, default=None):
118
+ if key in self:
119
+ return self[key]
120
+ else:
121
+ return default
122
+
123
+ def pop(self, key, default=__marker):
124
+ if key in self:
125
+ value = self[key]
126
+ del self[key]
127
+ elif default is self.__marker:
128
+ raise KeyError(key)
129
+ else:
130
+ value = default
131
+ return value
132
+
133
+ def setdefault(self, key, default=None):
134
+ if key in self:
135
+ value = self[key]
136
+ else:
137
+ self[key] = value = default
138
+ return value
139
+
140
+ # Although the MutableMapping.clear() default implementation works
141
+ # perfectly well, it calls popitem() in a loop until the cache is
142
+ # empty, resulting in O(n) complexity. For large caches, this
143
+ # becomes a significant performance bottleneck, so we provide an
144
+ # optimized version for each Cache subclass.
145
+
146
+ def clear(self):
147
+ self.__data.clear()
148
+ self.__size.clear()
149
+ self.__currsize = 0
150
+
151
+ @property
152
+ def maxsize(self):
153
+ """The maximum size of the cache."""
154
+ return self.__maxsize
155
+
156
+ @property
157
+ def currsize(self):
158
+ """The current size of the cache."""
159
+ return self.__currsize
160
+
161
+ @staticmethod
162
+ def getsizeof(value):
163
+ """Return the size of a cache element's value."""
164
+ return 1
165
+
166
+
167
+ class FIFOCache(Cache):
168
+ """First In First Out (FIFO) cache implementation."""
169
+
170
+ def __init__(self, maxsize, getsizeof=None):
171
+ Cache.__init__(self, maxsize, getsizeof)
172
+ self.__order = collections.OrderedDict()
173
+
174
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
175
+ cache_setitem(self, key, value)
176
+ if key in self.__order:
177
+ self.__order.move_to_end(key)
178
+ else:
179
+ self.__order[key] = None
180
+
181
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
182
+ cache_delitem(self, key)
183
+ del self.__order[key]
184
+
185
+ def popitem(self):
186
+ """Remove and return the `(key, value)` pair first inserted."""
187
+ try:
188
+ key = next(iter(self.__order))
189
+ except StopIteration:
190
+ raise KeyError("%s is empty" % type(self).__name__) from None
191
+ else:
192
+ return (key, self.pop(key))
193
+
194
+ def clear(self):
195
+ Cache.clear(self)
196
+ self.__order.clear()
197
+
198
+
199
+ class LFUCache(Cache):
200
+ """Least Frequently Used (LFU) cache implementation."""
201
+
202
+ class _Link:
203
+ __slots__ = ("count", "keys", "next", "prev")
204
+
205
+ def __init__(self, count):
206
+ self.count = count
207
+ self.keys = set()
208
+
209
+ def unlink(self):
210
+ next = self.next
211
+ prev = self.prev
212
+ prev.next = next
213
+ next.prev = prev
214
+
215
+ def __init__(self, maxsize, getsizeof=None):
216
+ Cache.__init__(self, maxsize, getsizeof)
217
+ self.__root = root = LFUCache._Link(0) # sentinel
218
+ root.prev = root.next = root
219
+ self.__links = {}
220
+
221
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
222
+ value = cache_getitem(self, key)
223
+ if key in self: # __missing__ may not store item
224
+ self.__touch(key)
225
+ return value
226
+
227
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
228
+ cache_setitem(self, key, value)
229
+ if key in self.__links:
230
+ self.__touch(key)
231
+ return
232
+ root = self.__root
233
+ link = root.next
234
+ if link.count != 1:
235
+ link = LFUCache._Link(1)
236
+ link.next = root.next
237
+ root.next = link.next.prev = link
238
+ link.prev = root
239
+ link.keys.add(key)
240
+ self.__links[key] = link
241
+
242
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
243
+ cache_delitem(self, key)
244
+ link = self.__links.pop(key)
245
+ link.keys.remove(key)
246
+ if not link.keys:
247
+ link.unlink()
248
+
249
+ def popitem(self):
250
+ """Remove and return the `(key, value)` pair least frequently used."""
251
+ root = self.__root
252
+ curr = root.next
253
+ if curr is root:
254
+ raise KeyError("%s is empty" % type(self).__name__) from None
255
+ key = next(iter(curr.keys)) # remove an arbitrary element
256
+ return (key, self.pop(key))
257
+
258
+ def clear(self):
259
+ Cache.clear(self)
260
+ root = self.__root
261
+ root.prev = root.next = root
262
+ self.__links.clear()
263
+
264
+ def __touch(self, key):
265
+ """Increment use count"""
266
+ link = self.__links[key]
267
+ curr = link.next
268
+ if curr.count != link.count + 1:
269
+ if len(link.keys) == 1:
270
+ link.count += 1
271
+ return
272
+ curr = LFUCache._Link(link.count + 1)
273
+ curr.next = link.next
274
+ link.next = curr.next.prev = curr
275
+ curr.prev = link
276
+ curr.keys.add(key)
277
+ link.keys.remove(key)
278
+ if not link.keys:
279
+ link.unlink()
280
+ self.__links[key] = curr
281
+
282
+
283
+ class LRUCache(Cache):
284
+ """Least Recently Used (LRU) cache implementation."""
285
+
286
+ def __init__(self, maxsize, getsizeof=None):
287
+ Cache.__init__(self, maxsize, getsizeof)
288
+ self.__order = collections.OrderedDict()
289
+
290
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
291
+ value = cache_getitem(self, key)
292
+ if key in self: # __missing__ may not store item
293
+ self.__touch(key)
294
+ return value
295
+
296
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
297
+ cache_setitem(self, key, value)
298
+ self.__touch(key)
299
+
300
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
301
+ cache_delitem(self, key)
302
+ del self.__order[key]
303
+
304
+ def popitem(self):
305
+ """Remove and return the `(key, value)` pair least recently used."""
306
+ try:
307
+ key = next(iter(self.__order))
308
+ except StopIteration:
309
+ raise KeyError("%s is empty" % type(self).__name__) from None
310
+ else:
311
+ return (key, self.pop(key))
312
+
313
+ def clear(self):
314
+ Cache.clear(self)
315
+ self.__order.clear()
316
+
317
+ def __touch(self, key):
318
+ """Mark as recently used"""
319
+ try:
320
+ self.__order.move_to_end(key)
321
+ except KeyError:
322
+ self.__order[key] = None
323
+
324
+
325
+ class RRCache(Cache):
326
+ """Random Replacement (RR) cache implementation."""
327
+
328
+ def __init__(self, maxsize, choice=random.choice, getsizeof=None):
329
+ Cache.__init__(self, maxsize, getsizeof)
330
+ self.__choice = choice
331
+ self.__index = {}
332
+ self.__keys = []
333
+
334
+ @property
335
+ def choice(self):
336
+ """The `choice` function used by the cache."""
337
+ return self.__choice
338
+
339
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
340
+ cache_setitem(self, key, value)
341
+ if key not in self.__index:
342
+ self.__index[key] = len(self.__keys)
343
+ self.__keys.append(key)
344
+
345
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
346
+ cache_delitem(self, key)
347
+ index = self.__index.pop(key)
348
+ if index != len(self.__keys) - 1:
349
+ last = self.__keys[-1]
350
+ self.__keys[index] = last
351
+ self.__index[last] = index
352
+ self.__keys.pop()
353
+
354
+ def popitem(self):
355
+ """Remove and return a random `(key, value)` pair."""
356
+ try:
357
+ key = self.__choice(self.__keys)
358
+ except IndexError:
359
+ raise KeyError("%s is empty" % type(self).__name__) from None
360
+ else:
361
+ return (key, self.pop(key))
362
+
363
+ def clear(self):
364
+ Cache.clear(self)
365
+ self.__index.clear()
366
+ del self.__keys[:]
367
+
368
+
369
+ class _TimedCache(Cache):
370
+ """Base class for time aware cache implementations."""
371
+
372
+ class _Timer:
373
+ def __init__(self, timer):
374
+ self.__timer = timer
375
+ self.__nesting = 0
376
+
377
+ def __call__(self):
378
+ if self.__nesting == 0:
379
+ return self.__timer()
380
+ else:
381
+ return self.__time
382
+
383
+ def __enter__(self):
384
+ if self.__nesting == 0:
385
+ self.__time = time = self.__timer()
386
+ else:
387
+ time = self.__time
388
+ self.__nesting += 1
389
+ return time
390
+
391
+ def __exit__(self, *exc):
392
+ self.__nesting -= 1
393
+
394
+ def __reduce__(self):
395
+ return _TimedCache._Timer, (self.__timer,)
396
+
397
+ def __getattr__(self, name):
398
+ return getattr(self.__timer, name)
399
+
400
+ def __init__(self, maxsize, timer, getsizeof=None):
401
+ Cache.__init__(self, maxsize, getsizeof)
402
+ self.__timer = _TimedCache._Timer(timer)
403
+
404
+ def __repr__(self, cache_repr=Cache.__repr__):
405
+ with self.__timer as time:
406
+ self.expire(time)
407
+ return cache_repr(self)
408
+
409
+ def __len__(self, cache_len=Cache.__len__):
410
+ with self.__timer as time:
411
+ self.expire(time)
412
+ return cache_len(self)
413
+
414
+ @property
415
+ def currsize(self):
416
+ with self.__timer as time:
417
+ self.expire(time)
418
+ return super().currsize
419
+
420
+ @property
421
+ def timer(self):
422
+ """The timer function used by the cache."""
423
+ return self.__timer
424
+
425
+ def get(self, *args, **kwargs):
426
+ with self.__timer:
427
+ return Cache.get(self, *args, **kwargs)
428
+
429
+ def pop(self, *args, **kwargs):
430
+ with self.__timer:
431
+ return Cache.pop(self, *args, **kwargs)
432
+
433
+ def setdefault(self, *args, **kwargs):
434
+ with self.__timer:
435
+ return Cache.setdefault(self, *args, **kwargs)
436
+
437
+ def clear(self):
438
+ # Subclasses must override to also reset their own time-tracking
439
+ # structures; we do not call expire() here since clear() should
440
+ # be O(1) regardless of cache contents.
441
+ Cache.clear(self)
442
+
443
+
444
+ class TTLCache(_TimedCache):
445
+ """LRU Cache implementation with per-item time-to-live (TTL) value."""
446
+
447
+ class _Link:
448
+ __slots__ = ("key", "expires", "next", "prev")
449
+
450
+ def __init__(self, key=None, expires=None):
451
+ self.key = key
452
+ self.expires = expires
453
+
454
+ def __reduce__(self):
455
+ return TTLCache._Link, (self.key, self.expires)
456
+
457
+ def unlink(self):
458
+ next = self.next
459
+ prev = self.prev
460
+ prev.next = next
461
+ next.prev = prev
462
+
463
+ def __init__(self, maxsize, ttl, timer=time.monotonic, getsizeof=None):
464
+ _TimedCache.__init__(self, maxsize, timer, getsizeof)
465
+ self.__root = root = TTLCache._Link()
466
+ root.prev = root.next = root
467
+ self.__links = collections.OrderedDict()
468
+ self.__ttl = ttl
469
+
470
+ def __contains__(self, key):
471
+ try:
472
+ link = self.__links[key] # no reordering
473
+ except KeyError:
474
+ return False
475
+ else:
476
+ return self.timer() < link.expires
477
+
478
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
479
+ try:
480
+ link = self.__getlink(key)
481
+ except KeyError:
482
+ expired = False
483
+ else:
484
+ expired = not (self.timer() < link.expires)
485
+ if expired:
486
+ return self.__missing__(key)
487
+ else:
488
+ return cache_getitem(self, key)
489
+
490
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
491
+ with self.timer as time:
492
+ self.expire(time)
493
+ cache_setitem(self, key, value)
494
+ try:
495
+ link = self.__getlink(key)
496
+ except KeyError:
497
+ self.__links[key] = link = TTLCache._Link(key)
498
+ else:
499
+ link.unlink()
500
+ link.expires = time + self.__ttl
501
+ link.next = root = self.__root
502
+ link.prev = prev = root.prev
503
+ prev.next = root.prev = link
504
+
505
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
506
+ cache_delitem(self, key)
507
+ link = self.__links.pop(key)
508
+ link.unlink()
509
+ if not (self.timer() < link.expires):
510
+ raise KeyError(key)
511
+
512
+ def __iter__(self):
513
+ root = self.__root
514
+ curr = root.next
515
+ while curr is not root:
516
+ # "freeze" time for iterator access
517
+ with self.timer as time:
518
+ if time < curr.expires:
519
+ yield curr.key
520
+ curr = curr.next
521
+
522
+ def __setstate__(self, state):
523
+ self.__dict__.update(state)
524
+ root = self.__root
525
+ root.prev = root.next = root
526
+ for link in sorted(self.__links.values(), key=lambda obj: obj.expires):
527
+ link.next = root
528
+ link.prev = prev = root.prev
529
+ prev.next = root.prev = link
530
+ self.expire(self.timer())
531
+
532
+ @property
533
+ def ttl(self):
534
+ """The time-to-live value of the cache's items."""
535
+ return self.__ttl
536
+
537
+ def expire(self, time=None):
538
+ """Remove expired items from the cache and return an iterable of the
539
+ expired `(key, value)` pairs.
540
+
541
+ """
542
+ if time is None:
543
+ time = self.timer()
544
+ root = self.__root
545
+ curr = root.next
546
+ links = self.__links
547
+ expired = []
548
+ cache_delitem = Cache.__delitem__
549
+ cache_getitem = Cache.__getitem__
550
+ while curr is not root and not (time < curr.expires):
551
+ expired.append((curr.key, cache_getitem(self, curr.key)))
552
+ cache_delitem(self, curr.key)
553
+ del links[curr.key]
554
+ next = curr.next
555
+ curr.unlink()
556
+ curr = next
557
+ return expired
558
+
559
+ def popitem(self):
560
+ """Remove and return the `(key, value)` pair least recently used that
561
+ has not already expired.
562
+
563
+ """
564
+ with self.timer as time:
565
+ self.expire(time)
566
+ try:
567
+ key = next(iter(self.__links))
568
+ except StopIteration:
569
+ raise KeyError("%s is empty" % type(self).__name__) from None
570
+ else:
571
+ return (key, self.pop(key))
572
+
573
+ def clear(self):
574
+ _TimedCache.clear(self)
575
+ root = self.__root
576
+ root.prev = root.next = root
577
+ self.__links.clear()
578
+
579
+ def __getlink(self, key):
580
+ value = self.__links[key]
581
+ self.__links.move_to_end(key)
582
+ return value
583
+
584
+
585
+ class TLRUCache(_TimedCache):
586
+ """Time aware Least Recently Used (TLRU) cache implementation."""
587
+
588
+ __HEAP_CLEANUP_FACTOR = 2 # clean up the heap if size > N * len(items)
589
+
590
+ @functools.total_ordering
591
+ class _Item:
592
+ __slots__ = ("key", "expires", "removed")
593
+
594
+ def __init__(self, key=None, expires=None):
595
+ self.key = key
596
+ self.expires = expires
597
+ self.removed = False
598
+
599
+ def __lt__(self, other):
600
+ return self.expires < other.expires
601
+
602
+ def __init__(self, maxsize, ttu, timer=time.monotonic, getsizeof=None):
603
+ _TimedCache.__init__(self, maxsize, timer, getsizeof)
604
+ self.__items = collections.OrderedDict()
605
+ self.__order = []
606
+ self.__ttu = ttu
607
+
608
+ def __contains__(self, key):
609
+ try:
610
+ item = self.__items[key] # no reordering
611
+ except KeyError:
612
+ return False
613
+ else:
614
+ return self.timer() < item.expires
615
+
616
+ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
617
+ try:
618
+ item = self.__getitem(key)
619
+ except KeyError:
620
+ expired = False
621
+ else:
622
+ expired = not (self.timer() < item.expires)
623
+ if expired:
624
+ return self.__missing__(key)
625
+ else:
626
+ return cache_getitem(self, key)
627
+
628
+ def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
629
+ with self.timer as time:
630
+ expires = self.__ttu(key, value, time)
631
+ if not (time < expires):
632
+ return # skip expired items
633
+ self.expire(time)
634
+ cache_setitem(self, key, value)
635
+ # removing an existing item would break the heap structure, so
636
+ # only mark it as removed for now
637
+ try:
638
+ self.__getitem(key).removed = True
639
+ except KeyError:
640
+ pass
641
+ self.__items[key] = item = TLRUCache._Item(key, expires)
642
+ heapq.heappush(self.__order, item)
643
+
644
+ def __delitem__(self, key, cache_delitem=Cache.__delitem__):
645
+ with self.timer as time:
646
+ # no self.expire() for performance reasons, e.g. self.clear() [#67]
647
+ cache_delitem(self, key)
648
+ item = self.__items.pop(key)
649
+ item.removed = True
650
+ if not (time < item.expires):
651
+ raise KeyError(key)
652
+
653
+ def __iter__(self):
654
+ for curr in self.__order:
655
+ # "freeze" time for iterator access
656
+ with self.timer as time:
657
+ if time < curr.expires and not curr.removed:
658
+ yield curr.key
659
+
660
+ @property
661
+ def ttu(self):
662
+ """The local time-to-use function used by the cache."""
663
+ return self.__ttu
664
+
665
+ def expire(self, time=None):
666
+ """Remove expired items from the cache and return an iterable of the
667
+ expired `(key, value)` pairs.
668
+
669
+ """
670
+ if time is None:
671
+ time = self.timer()
672
+ items = self.__items
673
+ order = self.__order
674
+ # clean up the heap if too many items are marked as removed
675
+ if len(order) > len(items) * self.__HEAP_CLEANUP_FACTOR:
676
+ self.__order = order = [item for item in order if not item.removed]
677
+ heapq.heapify(order)
678
+ expired = []
679
+ cache_delitem = Cache.__delitem__
680
+ cache_getitem = Cache.__getitem__
681
+ while order and (order[0].removed or not (time < order[0].expires)):
682
+ item = heapq.heappop(order)
683
+ if not item.removed:
684
+ expired.append((item.key, cache_getitem(self, item.key)))
685
+ cache_delitem(self, item.key)
686
+ del items[item.key]
687
+ return expired
688
+
689
+ def popitem(self):
690
+ """Remove and return the `(key, value)` pair least recently used that
691
+ has not already expired.
692
+
693
+ """
694
+ with self.timer as time:
695
+ self.expire(time)
696
+ try:
697
+ key = next(iter(self.__items))
698
+ except StopIteration:
699
+ raise KeyError("%s is empty" % type(self).__name__) from None
700
+ else:
701
+ return (key, self.pop(key))
702
+
703
+ def clear(self):
704
+ _TimedCache.clear(self)
705
+ self.__items.clear()
706
+ del self.__order[:]
707
+
708
+ def __getitem(self, key):
709
+ value = self.__items[key]
710
+ self.__items.move_to_end(key)
711
+ return value
712
+
713
+
714
+ _CacheInfo = collections.namedtuple(
715
+ "CacheInfo", ["hits", "misses", "maxsize", "currsize"]
716
+ )
717
+
718
+
719
+ def cached(cache, key=keys.hashkey, lock=None, condition=None, info=False):
720
+ """Decorator to wrap a function with a memoizing callable that saves
721
+ results in a cache.
722
+
723
+ """
724
+ from ._cached import _wrapper
725
+
726
+ def decorator(func):
727
+ if info:
728
+ if isinstance(cache, Cache):
729
+
730
+ def make_info(hits, misses):
731
+ return _CacheInfo(hits, misses, cache.maxsize, cache.currsize)
732
+
733
+ elif isinstance(cache, collections.abc.Mapping):
734
+
735
+ def make_info(hits, misses):
736
+ return _CacheInfo(hits, misses, None, len(cache))
737
+
738
+ else:
739
+
740
+ def make_info(hits, misses):
741
+ return _CacheInfo(hits, misses, 0, 0)
742
+
743
+ return _wrapper(func, cache, key, lock, condition, info=make_info)
744
+ else:
745
+ return _wrapper(func, cache, key, lock, condition)
746
+
747
+ return decorator
748
+
749
+
750
+ def cachedmethod(cache, key=keys.methodkey, lock=None, condition=None, info=False):
751
+ """Decorator to wrap a method with a memoizing callable that saves
752
+ results in a cache.
753
+
754
+ """
755
+ from ._cachedmethod import _wrapper
756
+
757
+ def decorator(method):
758
+ if info:
759
+
760
+ def make_info(cache, hits, misses):
761
+ if isinstance(cache, Cache):
762
+ return _CacheInfo(hits, misses, cache.maxsize, cache.currsize)
763
+ elif isinstance(cache, collections.abc.Mapping):
764
+ return _CacheInfo(hits, misses, None, len(cache))
765
+ else:
766
+ raise TypeError("cache(self) must return a mutable mapping")
767
+
768
+ return _wrapper(method, cache, key, lock, condition, info=make_info)
769
+ else:
770
+ return _wrapper(method, cache, key, lock, condition)
771
+
772
+ return decorator
.venv/lib/python3.10/site-packages/cachetools/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (23.6 kB). View file
 
.venv/lib/python3.10/site-packages/cachetools/__pycache__/keys.cpython-310.pyc ADDED
Binary file (2.54 kB). View file
 
.venv/lib/python3.10/site-packages/cachetools/_cached.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Function decorator helpers."""
2
+
3
+ __all__ = ()
4
+
5
+ import functools
6
+
7
+ # At least for now, the implementation prefers clarity and performance
8
+ # over ease of maintenance, thus providing separate wrappers for
9
+ # all valid combinations of decorator parameters lock, condition and
10
+ # info.
11
+
12
+
13
+ def _condition_info(func, cache, key, lock, cond, info):
14
+ hits = misses = 0
15
+ pending = set()
16
+
17
+ def wrapper(*args, **kwargs):
18
+ nonlocal hits, misses
19
+ k = key(*args, **kwargs)
20
+ with lock:
21
+ cond.wait_for(lambda: k not in pending)
22
+ try:
23
+ result = cache[k]
24
+ hits += 1
25
+ return result
26
+ except KeyError:
27
+ pending.add(k)
28
+ misses += 1
29
+ try:
30
+ v = func(*args, **kwargs)
31
+ with lock:
32
+ try:
33
+ cache[k] = v
34
+ except ValueError:
35
+ pass # value too large
36
+ return v
37
+ finally:
38
+ with lock:
39
+ pending.remove(k)
40
+ cond.notify_all()
41
+
42
+ def cache_clear():
43
+ nonlocal hits, misses
44
+ with lock:
45
+ cache.clear()
46
+ hits = misses = 0
47
+
48
+ def cache_info():
49
+ with lock:
50
+ return info(hits, misses)
51
+
52
+ wrapper.cache_clear = cache_clear
53
+ wrapper.cache_info = cache_info
54
+ return wrapper
55
+
56
+
57
+ def _locked_info(func, cache, key, lock, info):
58
+ hits = misses = 0
59
+
60
+ def wrapper(*args, **kwargs):
61
+ nonlocal hits, misses
62
+ k = key(*args, **kwargs)
63
+ with lock:
64
+ try:
65
+ result = cache[k]
66
+ hits += 1
67
+ return result
68
+ except KeyError:
69
+ misses += 1
70
+ v = func(*args, **kwargs)
71
+ with lock:
72
+ try:
73
+ # In case of a race condition, i.e. if another thread
74
+ # stored a value for this key while we were calling
75
+ # func(), prefer the cached value.
76
+ return cache.setdefault(k, v)
77
+ except ValueError:
78
+ return v # value too large
79
+
80
+ def cache_clear():
81
+ nonlocal hits, misses
82
+ with lock:
83
+ cache.clear()
84
+ hits = misses = 0
85
+
86
+ def cache_info():
87
+ with lock:
88
+ return info(hits, misses)
89
+
90
+ wrapper.cache_clear = cache_clear
91
+ wrapper.cache_info = cache_info
92
+ return wrapper
93
+
94
+
95
+ def _unlocked_info(func, cache, key, info):
96
+ hits = misses = 0
97
+
98
+ def wrapper(*args, **kwargs):
99
+ nonlocal hits, misses
100
+ k = key(*args, **kwargs)
101
+ try:
102
+ result = cache[k]
103
+ hits += 1
104
+ return result
105
+ except KeyError:
106
+ misses += 1
107
+ v = func(*args, **kwargs)
108
+ try:
109
+ cache[k] = v
110
+ except ValueError:
111
+ pass # value too large
112
+ return v
113
+
114
+ def cache_clear():
115
+ nonlocal hits, misses
116
+ cache.clear()
117
+ hits = misses = 0
118
+
119
+ def cache_info():
120
+ return info(hits, misses)
121
+
122
+ wrapper.cache_clear = cache_clear
123
+ wrapper.cache_info = cache_info
124
+ return wrapper
125
+
126
+
127
+ def _uncached_info(func, info):
128
+ misses = 0
129
+
130
+ def wrapper(*args, **kwargs):
131
+ nonlocal misses
132
+ misses += 1
133
+ return func(*args, **kwargs)
134
+
135
+ def cache_clear():
136
+ nonlocal misses
137
+ misses = 0
138
+
139
+ wrapper.cache_clear = cache_clear
140
+ wrapper.cache_info = lambda: info(0, misses)
141
+ return wrapper
142
+
143
+
144
+ def _condition(func, cache, key, lock, cond):
145
+ pending = set()
146
+
147
+ def wrapper(*args, **kwargs):
148
+ k = key(*args, **kwargs)
149
+ with lock:
150
+ cond.wait_for(lambda: k not in pending)
151
+ try:
152
+ result = cache[k]
153
+ return result
154
+ except KeyError:
155
+ pending.add(k)
156
+ try:
157
+ v = func(*args, **kwargs)
158
+ with lock:
159
+ try:
160
+ cache[k] = v
161
+ except ValueError:
162
+ pass # value too large
163
+ return v
164
+ finally:
165
+ with lock:
166
+ pending.remove(k)
167
+ cond.notify_all()
168
+
169
+ def cache_clear():
170
+ with lock:
171
+ cache.clear()
172
+
173
+ wrapper.cache_clear = cache_clear
174
+ return wrapper
175
+
176
+
177
+ def _locked(func, cache, key, lock):
178
+ def wrapper(*args, **kwargs):
179
+ k = key(*args, **kwargs)
180
+ with lock:
181
+ try:
182
+ return cache[k]
183
+ except KeyError:
184
+ pass # key not found
185
+ v = func(*args, **kwargs)
186
+ with lock:
187
+ try:
188
+ # In case of a race condition, i.e. if another thread
189
+ # stored a value for this key while we were calling
190
+ # func(), prefer the cached value.
191
+ return cache.setdefault(k, v)
192
+ except ValueError:
193
+ return v # value too large
194
+
195
+ def cache_clear():
196
+ with lock:
197
+ cache.clear()
198
+
199
+ wrapper.cache_clear = cache_clear
200
+ return wrapper
201
+
202
+
203
+ def _unlocked(func, cache, key):
204
+ def wrapper(*args, **kwargs):
205
+ k = key(*args, **kwargs)
206
+ try:
207
+ return cache[k]
208
+ except KeyError:
209
+ pass # key not found
210
+ v = func(*args, **kwargs)
211
+ try:
212
+ cache[k] = v
213
+ except ValueError:
214
+ pass # value too large
215
+ return v
216
+
217
+ wrapper.cache_clear = lambda: cache.clear()
218
+ return wrapper
219
+
220
+
221
+ def _uncached(func):
222
+ def wrapper(*args, **kwargs):
223
+ return func(*args, **kwargs)
224
+
225
+ wrapper.cache_clear = lambda: None
226
+ return wrapper
227
+
228
+
229
+ def _wrapper(func, cache, key, lock=None, cond=None, info=None):
230
+ if info is not None:
231
+ if cache is None:
232
+ wrapper = _uncached_info(func, info)
233
+ elif cond is not None and lock is not None:
234
+ wrapper = _condition_info(func, cache, key, lock, cond, info)
235
+ elif cond is not None:
236
+ wrapper = _condition_info(func, cache, key, cond, cond, info)
237
+ elif lock is not None:
238
+ wrapper = _locked_info(func, cache, key, lock, info)
239
+ else:
240
+ wrapper = _unlocked_info(func, cache, key, info)
241
+ else:
242
+ if cache is None:
243
+ wrapper = _uncached(func)
244
+ elif cond is not None and lock is not None:
245
+ wrapper = _condition(func, cache, key, lock, cond)
246
+ elif cond is not None:
247
+ wrapper = _condition(func, cache, key, cond, cond)
248
+ elif lock is not None:
249
+ wrapper = _locked(func, cache, key, lock)
250
+ else:
251
+ wrapper = _unlocked(func, cache, key)
252
+ wrapper.cache_info = None
253
+
254
+ wrapper.cache = cache
255
+ wrapper.cache_key = key
256
+ wrapper.cache_lock = lock if lock is not None else cond
257
+ wrapper.cache_condition = cond
258
+
259
+ return functools.update_wrapper(wrapper, func)
.venv/lib/python3.10/site-packages/cachetools/_cachedmethod.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Method decorator helpers."""
2
+
3
+ __all__ = ()
4
+
5
+ import functools
6
+ import warnings
7
+ import weakref
8
+
9
+
10
+ def _warn_classmethod(stacklevel):
11
+ warnings.warn(
12
+ "decorating class methods with @cachedmethod is deprecated",
13
+ DeprecationWarning,
14
+ stacklevel=stacklevel,
15
+ )
16
+
17
+
18
+ def _warn_instance_dict(msg, stacklevel):
19
+ warnings.warn(
20
+ msg,
21
+ DeprecationWarning,
22
+ stacklevel=stacklevel,
23
+ )
24
+
25
+
26
+ def _none(_):
27
+ return None
28
+
29
+
30
+ class _WrapperBase:
31
+ """Wrapper base class providing default implementations for properties."""
32
+
33
+ def __init__(self, obj, method, cache, key, lock=None, cond=None):
34
+ if isinstance(obj, type):
35
+ _warn_classmethod(stacklevel=5)
36
+ functools.update_wrapper(self, method)
37
+ self._obj = obj # protected
38
+ self.__cache = cache
39
+ self.__key = functools.partial(key, obj)
40
+ self.__lock = lock if lock is not None else _none
41
+ self.__cond = cond if cond is not None else _none
42
+
43
+ def __call__(self, *args, **kwargs):
44
+ raise NotImplementedError() # pragma: no cover
45
+
46
+ def cache_clear(self):
47
+ raise NotImplementedError() # pragma: no cover
48
+
49
+ @property
50
+ def cache(self):
51
+ return self.__cache(self._obj)
52
+
53
+ @property
54
+ def cache_key(self):
55
+ return self.__key # self._obj passed via functools.partial
56
+
57
+ @property
58
+ def cache_lock(self):
59
+ return self.__lock(self._obj)
60
+
61
+ @property
62
+ def cache_condition(self):
63
+ return self.__cond(self._obj)
64
+
65
+
66
+ class _DescriptorBase:
67
+ """Descriptor base class implementing the basic descriptor protocol."""
68
+
69
+ def __init__(self, deprecated=False):
70
+ self.__attrname = None
71
+ self.__deprecated = deprecated
72
+
73
+ def __set_name__(self, owner, name):
74
+ if self.__attrname is None:
75
+ self.__attrname = name
76
+ elif name != self.__attrname:
77
+ raise TypeError(
78
+ "Cannot assign the same @cachedmethod to two different names "
79
+ f"({self.__attrname!r} and {name!r})."
80
+ )
81
+
82
+ def __get__(self, obj, objtype=None):
83
+ wrapper = self.Wrapper(obj)
84
+ if obj is None:
85
+ # Return the wrapper itself without modification when accessed
86
+ # through the class to support class-level introspection, such
87
+ # as for mocking with autospec=True in unittest.mock.
88
+ pass
89
+ elif self.__attrname is not None:
90
+ # replace descriptor instance with wrapper in instance dict
91
+ try:
92
+ # In case of a race condition where another thread already replaced
93
+ # the descriptor, prefer the initial wrapper.
94
+ wrapper = obj.__dict__.setdefault(self.__attrname, wrapper)
95
+ except AttributeError:
96
+ # not all objects have __dict__ (e.g. class defines slots)
97
+ msg = (
98
+ f"No '__dict__' attribute on {type(obj).__name__!r} "
99
+ f"instance to cache {self.__attrname!r} property."
100
+ )
101
+ if self.__deprecated:
102
+ _warn_instance_dict(msg, 3)
103
+ else:
104
+ raise TypeError(msg) from None
105
+ except TypeError:
106
+ msg = (
107
+ f"The '__dict__' attribute on {type(obj).__name__!r} "
108
+ f"instance does not support item assignment for "
109
+ f"caching {self.__attrname!r} property."
110
+ )
111
+ if self.__deprecated:
112
+ _warn_instance_dict(msg, 3)
113
+ else:
114
+ raise TypeError(msg) from None
115
+ elif self.__deprecated:
116
+ pass # deprecated @classmethod, warning already raised elsewhere
117
+ else:
118
+ msg = "Cannot use @cachedmethod instance without calling __set_name__ on it"
119
+ raise TypeError(msg) from None
120
+ return wrapper
121
+
122
+
123
+ class _DeprecatedDescriptorBase(_DescriptorBase):
124
+ """Descriptor base class supporting deprecated @classmethod use."""
125
+
126
+ def __init__(self, wrapper, cache_clear):
127
+ super().__init__(deprecated=True)
128
+ self.__wrapper = wrapper
129
+ self.__cache_clear = cache_clear
130
+
131
+ # called for @classmethod with Python >= 3.13
132
+ def __call__(self, *args, **kwargs):
133
+ _warn_classmethod(stacklevel=3)
134
+ return self.__wrapper(*args, **kwargs)
135
+
136
+ # backward-compatible @classmethod handling with Python >= 3.13
137
+ def cache_clear(self, objtype):
138
+ _warn_classmethod(stacklevel=3)
139
+ return self.__cache_clear(objtype)
140
+
141
+
142
+ # At least for now, the implementation prefers clarity and performance
143
+ # over ease of maintenance, thus providing separate descriptors for
144
+ # all valid combinations of decorator parameters lock, condition and
145
+ # info.
146
+
147
+
148
+ def _condition_info(method, cache, key, lock, cond, info):
149
+ class Descriptor(_DescriptorBase):
150
+ class Wrapper(_WrapperBase):
151
+ def __init__(self, obj):
152
+ super().__init__(obj, method, cache, key, lock, cond)
153
+ self.__hits = self.__misses = 0
154
+ self.__pending = set()
155
+
156
+ def __call__(self, *args, **kwargs):
157
+ cache = self.cache
158
+ lock = self.cache_lock
159
+ cond = self.cache_condition
160
+ key = self.cache_key(*args, **kwargs)
161
+
162
+ with lock:
163
+ cond.wait_for(lambda: key not in self.__pending)
164
+ try:
165
+ result = cache[key]
166
+ self.__hits += 1
167
+ return result
168
+ except KeyError:
169
+ self.__pending.add(key)
170
+ self.__misses += 1
171
+ try:
172
+ val = method(self._obj, *args, **kwargs)
173
+ with lock:
174
+ try:
175
+ cache[key] = val
176
+ except ValueError:
177
+ pass # value too large
178
+ return val
179
+ finally:
180
+ with lock:
181
+ self.__pending.remove(key)
182
+ cond.notify_all()
183
+
184
+ def cache_clear(self):
185
+ with self.cache_lock:
186
+ self.cache.clear()
187
+ self.__hits = self.__misses = 0
188
+
189
+ def cache_info(self):
190
+ with self.cache_lock:
191
+ return info(self.cache, self.__hits, self.__misses)
192
+
193
+ return Descriptor()
194
+
195
+
196
+ def _locked_info(method, cache, key, lock, info):
197
+ class Descriptor(_DescriptorBase):
198
+ class Wrapper(_WrapperBase):
199
+ def __init__(self, obj):
200
+ super().__init__(obj, method, cache, key, lock)
201
+ self.__hits = self.__misses = 0
202
+
203
+ def __call__(self, *args, **kwargs):
204
+ cache = self.cache
205
+ lock = self.cache_lock
206
+ key = self.cache_key(*args, **kwargs)
207
+ with lock:
208
+ try:
209
+ result = cache[key]
210
+ self.__hits += 1
211
+ return result
212
+ except KeyError:
213
+ self.__misses += 1
214
+ val = method(self._obj, *args, **kwargs)
215
+ with lock:
216
+ try:
217
+ # In case of a race condition, i.e. if another thread
218
+ # stored a value for this key while we were calling
219
+ # method(), prefer the cached value.
220
+ return cache.setdefault(key, val)
221
+ except ValueError:
222
+ return val # value too large
223
+
224
+ def cache_clear(self):
225
+ with self.cache_lock:
226
+ self.cache.clear()
227
+ self.__hits = self.__misses = 0
228
+
229
+ def cache_info(self):
230
+ with self.cache_lock:
231
+ return info(self.cache, self.__hits, self.__misses)
232
+
233
+ return Descriptor()
234
+
235
+
236
+ def _unlocked_info(method, cache, key, info):
237
+ class Descriptor(_DescriptorBase):
238
+ class Wrapper(_WrapperBase):
239
+ def __init__(self, obj):
240
+ super().__init__(obj, method, cache, key)
241
+ self.__hits = self.__misses = 0
242
+
243
+ def __call__(self, *args, **kwargs):
244
+ cache = self.cache
245
+ key = self.cache_key(*args, **kwargs)
246
+ try:
247
+ result = cache[key]
248
+ self.__hits += 1
249
+ return result
250
+ except KeyError:
251
+ self.__misses += 1
252
+ val = method(self._obj, *args, **kwargs)
253
+ try:
254
+ cache[key] = val
255
+ except ValueError:
256
+ pass # value too large
257
+ return val
258
+
259
+ def cache_clear(self):
260
+ self.cache.clear()
261
+ self.__hits = self.__misses = 0
262
+
263
+ def cache_info(self):
264
+ return info(self.cache, self.__hits, self.__misses)
265
+
266
+ return Descriptor()
267
+
268
+
269
+ def _condition(method, cache, key, lock, cond):
270
+ # backward-compatible weakref dictionary for Python >= 3.13
271
+ pending = weakref.WeakKeyDictionary()
272
+
273
+ def wrapper(self, pending, *args, **kwargs):
274
+ c = cache(self)
275
+ k = key(self, *args, **kwargs)
276
+ with lock(self):
277
+ cond(self).wait_for(lambda: k not in pending)
278
+ try:
279
+ return c[k]
280
+ except KeyError:
281
+ pending.add(k)
282
+ try:
283
+ v = method(self, *args, **kwargs)
284
+ with lock(self):
285
+ try:
286
+ c[k] = v
287
+ except ValueError:
288
+ pass # value too large
289
+ return v
290
+ finally:
291
+ with lock(self):
292
+ pending.remove(k)
293
+ cond(self).notify_all()
294
+
295
+ def cache_clear(self):
296
+ c = cache(self)
297
+ with lock(self):
298
+ c.clear()
299
+
300
+ def classmethod_wrapper(self, *args, **kwargs):
301
+ p = pending.setdefault(self, set())
302
+ return wrapper(self, p, *args, **kwargs)
303
+
304
+ class Descriptor(_DeprecatedDescriptorBase):
305
+ class Wrapper(_WrapperBase):
306
+ def __init__(self, obj):
307
+ super().__init__(obj, method, cache, key, lock, cond)
308
+ self.__pending = set()
309
+
310
+ def __call__(self, *args, **kwargs):
311
+ return wrapper(self._obj, self.__pending, *args, **kwargs)
312
+
313
+ # objtype: backward-compatible @classmethod handling with Python < 3.13
314
+ def cache_clear(self, _objtype=None):
315
+ return cache_clear(self._obj)
316
+
317
+ return Descriptor(classmethod_wrapper, cache_clear)
318
+
319
+
320
+ def _locked(method, cache, key, lock):
321
+ def wrapper(self, *args, **kwargs):
322
+ c = cache(self)
323
+ k = key(self, *args, **kwargs)
324
+ with lock(self):
325
+ try:
326
+ return c[k]
327
+ except KeyError:
328
+ pass # key not found
329
+ v = method(self, *args, **kwargs)
330
+ with lock(self):
331
+ try:
332
+ # In case of a race condition, i.e. if another thread
333
+ # stored a value for this key while we were calling
334
+ # method(), prefer the cached value.
335
+ return c.setdefault(k, v)
336
+ except ValueError:
337
+ return v # value too large
338
+
339
+ def cache_clear(self):
340
+ c = cache(self)
341
+ with lock(self):
342
+ c.clear()
343
+
344
+ class Descriptor(_DeprecatedDescriptorBase):
345
+ class Wrapper(_WrapperBase):
346
+ def __init__(self, obj):
347
+ super().__init__(obj, method, cache, key, lock)
348
+
349
+ def __call__(self, *args, **kwargs):
350
+ return wrapper(self._obj, *args, **kwargs)
351
+
352
+ # objtype: backward-compatible @classmethod handling with Python < 3.13
353
+ def cache_clear(self, _objtype=None):
354
+ return cache_clear(self._obj)
355
+
356
+ return Descriptor(wrapper, cache_clear)
357
+
358
+
359
+ def _unlocked(method, cache, key):
360
+ def wrapper(self, *args, **kwargs):
361
+ c = cache(self)
362
+ k = key(self, *args, **kwargs)
363
+ try:
364
+ return c[k]
365
+ except KeyError:
366
+ pass # key not found
367
+ v = method(self, *args, **kwargs)
368
+ try:
369
+ c[k] = v
370
+ except ValueError:
371
+ pass # value too large
372
+ return v
373
+
374
+ def cache_clear(self):
375
+ c = cache(self)
376
+ c.clear()
377
+
378
+ class Descriptor(_DeprecatedDescriptorBase):
379
+ class Wrapper(_WrapperBase):
380
+ def __init__(self, obj):
381
+ super().__init__(obj, method, cache, key)
382
+
383
+ def __call__(self, *args, **kwargs):
384
+ return wrapper(self._obj, *args, **kwargs)
385
+
386
+ # objtype: backward-compatible @classmethod handling with Python < 3.13
387
+ def cache_clear(self, _objtype=None):
388
+ return cache_clear(self._obj)
389
+
390
+ return Descriptor(wrapper, cache_clear)
391
+
392
+
393
+ def _wrapper(method, cache, key, lock=None, cond=None, info=None):
394
+ if info is not None:
395
+ if cond is not None and lock is not None:
396
+ wrapper = _condition_info(method, cache, key, lock, cond, info)
397
+ elif cond is not None:
398
+ wrapper = _condition_info(method, cache, key, cond, cond, info)
399
+ elif lock is not None:
400
+ wrapper = _locked_info(method, cache, key, lock, info)
401
+ else:
402
+ wrapper = _unlocked_info(method, cache, key, info)
403
+ else:
404
+ if cond is not None and lock is not None:
405
+ wrapper = _condition(method, cache, key, lock, cond)
406
+ elif cond is not None:
407
+ wrapper = _condition(method, cache, key, cond, cond)
408
+ elif lock is not None:
409
+ wrapper = _locked(method, cache, key, lock)
410
+ else:
411
+ wrapper = _unlocked(method, cache, key)
412
+
413
+ # backward-compatible properties for deprecated @classmethod use
414
+ wrapper.cache = cache
415
+ wrapper.cache_key = key
416
+ wrapper.cache_lock = lock if lock is not None else cond
417
+ wrapper.cache_condition = cond
418
+
419
+ return functools.update_wrapper(wrapper, method)
.venv/lib/python3.10/site-packages/cachetools/func.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """`functools.lru_cache` compatible memoizing function decorators."""
2
+
3
+ __all__ = ("fifo_cache", "lfu_cache", "lru_cache", "rr_cache", "ttl_cache")
4
+
5
+ import functools
6
+ import math
7
+ import random
8
+ import time
9
+ from threading import Condition
10
+
11
+ from . import FIFOCache, LFUCache, LRUCache, RRCache, TTLCache
12
+ from . import cached
13
+ from . import keys
14
+
15
+
16
+ class _UnboundTTLCache(TTLCache):
17
+ def __init__(self, ttl, timer):
18
+ TTLCache.__init__(self, math.inf, ttl, timer)
19
+
20
+ @property
21
+ def maxsize(self):
22
+ return None
23
+
24
+
25
+ def _cache(cache, maxsize, typed):
26
+ def decorator(func):
27
+ # like functools.lru_cache, this has to be thread-safe;
28
+ # additionally, this also prevents cache stampede scenarios
29
+ # using a condition variable
30
+ key = keys.typedkey if typed else keys.hashkey
31
+ wrapper = cached(cache=cache, key=key, condition=Condition(), info=True)(func)
32
+ wrapper.cache_parameters = lambda: {"maxsize": maxsize, "typed": typed}
33
+ return wrapper
34
+
35
+ return decorator
36
+
37
+
38
+ def fifo_cache(maxsize=128, typed=False):
39
+ """Decorator to wrap a function with a memoizing callable that saves
40
+ up to `maxsize` results based on a First In First Out (FIFO)
41
+ algorithm.
42
+
43
+ """
44
+ if maxsize is None:
45
+ return _cache({}, None, typed)
46
+ elif callable(maxsize):
47
+ return _cache(FIFOCache(128), 128, typed)(maxsize)
48
+ else:
49
+ return _cache(FIFOCache(maxsize), maxsize, typed)
50
+
51
+
52
+ def lfu_cache(maxsize=128, typed=False):
53
+ """Decorator to wrap a function with a memoizing callable that saves
54
+ up to `maxsize` results based on a Least Frequently Used (LFU)
55
+ algorithm.
56
+
57
+ """
58
+ if maxsize is None:
59
+ return _cache({}, None, typed)
60
+ elif callable(maxsize):
61
+ return _cache(LFUCache(128), 128, typed)(maxsize)
62
+ else:
63
+ return _cache(LFUCache(maxsize), maxsize, typed)
64
+
65
+
66
+ def lru_cache(maxsize=128, typed=False):
67
+ """Decorator to wrap a function with a memoizing callable that saves
68
+ up to `maxsize` results based on a Least Recently Used (LRU)
69
+ algorithm.
70
+
71
+ """
72
+ if maxsize is None:
73
+ return _cache({}, None, typed)
74
+ elif callable(maxsize):
75
+ return _cache(LRUCache(128), 128, typed)(maxsize)
76
+ else:
77
+ return _cache(LRUCache(maxsize), maxsize, typed)
78
+
79
+
80
+ def rr_cache(maxsize=128, choice=random.choice, typed=False):
81
+ """Decorator to wrap a function with a memoizing callable that saves
82
+ up to `maxsize` results based on a Random Replacement (RR)
83
+ algorithm.
84
+
85
+ """
86
+ if maxsize is None:
87
+ return _cache({}, None, typed)
88
+ elif callable(maxsize):
89
+ return _cache(RRCache(128, choice), 128, typed)(maxsize)
90
+ else:
91
+ return _cache(RRCache(maxsize, choice), maxsize, typed)
92
+
93
+
94
+ def ttl_cache(maxsize=128, ttl=600, timer=time.monotonic, typed=False):
95
+ """Decorator to wrap a function with a memoizing callable that saves
96
+ up to `maxsize` results based on a Least Recently Used (LRU)
97
+ algorithm with a per-item time-to-live (TTL) value.
98
+
99
+ """
100
+ if maxsize is None:
101
+ return _cache(_UnboundTTLCache(ttl, timer), None, typed)
102
+ elif callable(maxsize):
103
+ return _cache(TTLCache(128, ttl, timer), 128, typed)(maxsize)
104
+ else:
105
+ return _cache(TTLCache(maxsize, ttl, timer), maxsize, typed)
.venv/lib/python3.10/site-packages/cachetools/keys.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Key functions for memoizing decorators."""
2
+
3
+ __all__ = ("hashkey", "methodkey", "typedkey", "typedmethodkey")
4
+
5
+
6
+ class _HashedTuple(tuple):
7
+ """A tuple that ensures that hash() will be called no more than once
8
+ per element, since cache decorators will hash the key multiple
9
+ times on a cache miss. See also _HashedSeq in the standard
10
+ library functools implementation.
11
+
12
+ """
13
+
14
+ __hashvalue = None # default value, set in instance on first use
15
+
16
+ def __hash__(self, hash=tuple.__hash__):
17
+ hashvalue = self.__hashvalue
18
+ if hashvalue is None:
19
+ self.__hashvalue = hashvalue = hash(self)
20
+ return hashvalue
21
+
22
+ def __add__(self, other, add=tuple.__add__):
23
+ return _HashedTuple(add(self, other))
24
+
25
+ def __radd__(self, other, add=tuple.__add__):
26
+ return _HashedTuple(add(other, self))
27
+
28
+ def __getstate__(self):
29
+ return {}
30
+
31
+
32
+ # A sentinel for separating args from kwargs. Using the class itself
33
+ # ensures uniqueness and preserves identity when pickling/unpickling.
34
+ _kwmark = (_HashedTuple,)
35
+
36
+
37
+ def hashkey(*args, **kwargs):
38
+ """Return a cache key for the specified hashable arguments."""
39
+
40
+ if kwargs:
41
+ return _HashedTuple(args + _kwmark + tuple(sorted(kwargs.items())))
42
+ else:
43
+ return _HashedTuple(args)
44
+
45
+
46
+ def methodkey(self, *args, **kwargs):
47
+ """Return a cache key for use with cached methods."""
48
+ return hashkey(*args, **kwargs)
49
+
50
+
51
+ def typedkey(*args, **kwargs):
52
+ """Return a typed cache key for the specified hashable arguments."""
53
+
54
+ if kwargs:
55
+ sorted_kwargs = tuple(sorted(kwargs.items()))
56
+ key = _HashedTuple(args + _kwmark + sorted_kwargs)
57
+ key += tuple(type(v) for _, v in sorted_kwargs)
58
+ else:
59
+ key = _HashedTuple(args)
60
+ key += tuple(type(v) for v in args)
61
+ return key
62
+
63
+
64
+ def typedmethodkey(self, *args, **kwargs):
65
+ """Return a typed cache key for use with cached methods."""
66
+ return typedkey(*args, **kwargs)
.venv/lib/python3.10/site-packages/caio/__init__.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+
4
+ from . import python_aio, python_aio_asyncio
5
+ from .abstract import AbstractContext, AbstractOperation
6
+ from .version import __author__, __version__
7
+
8
+
9
+ try:
10
+ from . import linux_aio, linux_aio_asyncio
11
+ except ImportError:
12
+ linux_aio = None # type: ignore
13
+ linux_aio_asyncio = None # type: ignore
14
+
15
+ try:
16
+ from . import thread_aio, thread_aio_asyncio
17
+ except ImportError:
18
+ thread_aio = None # type: ignore
19
+ thread_aio_asyncio = None # type: ignore
20
+
21
+
22
+ variants = tuple(filter(None, [linux_aio, thread_aio, python_aio]))
23
+ variants_asyncio = tuple(
24
+ filter(
25
+ None, [
26
+ linux_aio_asyncio,
27
+ thread_aio_asyncio,
28
+ python_aio_asyncio,
29
+ ],
30
+ ),
31
+ )
32
+
33
+ preferred = variants[0]
34
+ preferred_asyncio = variants_asyncio[0]
35
+
36
+
37
+ def __select_implementation():
38
+ global preferred
39
+ global preferred_asyncio
40
+
41
+ implementations = {
42
+ "linux": (linux_aio, linux_aio_asyncio),
43
+ "thread": (thread_aio, thread_aio_asyncio),
44
+ "python": (python_aio, python_aio_asyncio),
45
+ }
46
+
47
+ implementations = {k: v for k, v in implementations.items() if all(v)}
48
+
49
+ default_implementation = os.path.join(
50
+ os.path.dirname(os.path.abspath(__file__)), "default_implementation",
51
+ )
52
+
53
+ requested = os.getenv("CAIO_IMPL")
54
+
55
+ if not requested and os.path.isfile(default_implementation):
56
+ with open(default_implementation, "r") as fp:
57
+ for line in fp:
58
+ line = line.strip()
59
+ if line.startswith("#") or not line:
60
+ continue
61
+ if line in implementations:
62
+ requested = line
63
+ break
64
+
65
+ elif requested and requested not in implementations:
66
+ warnings.warn(
67
+ "CAIO_IMPL contains unsupported value %r. Use one of %r" % (
68
+ requested, tuple(implementations),
69
+ ),
70
+ RuntimeWarning,
71
+ )
72
+ return
73
+
74
+ preferred, preferred_asyncio = implementations.get(
75
+ requested,
76
+ (preferred, preferred_asyncio),
77
+ )
78
+
79
+
80
+ __select_implementation()
81
+
82
+
83
+ Context = preferred.Context # type: ignore
84
+ Operation = preferred.Operation # type: ignore
85
+ AsyncioContext = preferred_asyncio.AsyncioContext # type: ignore
86
+
87
+
88
+ __all__ = (
89
+ "Context",
90
+ "Operation",
91
+ "AsyncioContext",
92
+ "AbstractContext",
93
+ "AbstractOperation",
94
+ "python_aio",
95
+ "python_aio_asyncio",
96
+ "linux_aio",
97
+ "linux_aio_asyncio",
98
+ "thread_aio",
99
+ "thread_aio_asyncio",
100
+ "__version__",
101
+ "__author__",
102
+ "variants",
103
+ "variants_asyncio",
104
+ )
.venv/lib/python3.10/site-packages/caio/asyncio_base.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import asyncio
3
+ import typing
4
+ from functools import partial
5
+
6
+ from . import abstract
7
+
8
+
9
+ ContextType = typing.Type[abstract.AbstractContext]
10
+ OperationType = typing.Type[abstract.AbstractOperation]
11
+
12
+
13
+ class AsyncioContextBase(abc.ABC):
14
+ MAX_REQUESTS_DEFAULT = 512
15
+ CONTEXT_CLASS = None # type: ContextType
16
+ OPERATION_CLASS = None # type: OperationType
17
+
18
+ def __init__(self, max_requests=None, loop=None, **kwargs):
19
+ max_requests = max_requests or self.MAX_REQUESTS_DEFAULT
20
+ self.loop = loop or asyncio.get_event_loop()
21
+ self.semaphore = asyncio.BoundedSemaphore(max_requests)
22
+ self.context = self._create_context(max_requests, **kwargs)
23
+
24
+ def _create_context(self, max_requests, **kwargs):
25
+ return self.CONTEXT_CLASS(max_requests=max_requests, **kwargs)
26
+
27
+ def _destroy_context(self):
28
+ return
29
+
30
+ async def __aenter__(self):
31
+ return self
32
+
33
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
34
+ self.close()
35
+
36
+ def close(self):
37
+ self._destroy_context()
38
+
39
+ async def submit(self, op):
40
+ if not isinstance(op, self.OPERATION_CLASS):
41
+ raise ValueError("Operation object expected")
42
+
43
+ future = self.loop.create_future()
44
+ op.set_callback(partial(self._on_done, future))
45
+
46
+ async with self.semaphore:
47
+ if self.context.submit(op) != 1:
48
+ raise IOError("Operation was not submitted")
49
+
50
+ try:
51
+ await future
52
+ except asyncio.CancelledError:
53
+ try:
54
+ self.context.cancel(op)
55
+ except ValueError:
56
+ pass
57
+ raise
58
+ return op.get_value()
59
+
60
+ def _on_done(self, future, result):
61
+ """
62
+ In general case impossible predict current thread and the thread
63
+ of event loop. So have to use `call_soon_threadsave` the result setter.
64
+ """
65
+
66
+ if future.done():
67
+ return
68
+
69
+ self.loop.call_soon_threadsafe(
70
+ lambda: future.done() or future.set_result(True),
71
+ )
72
+
73
+ def read(
74
+ self, nbytes: int, fd: int,
75
+ offset: int, priority: int = 0,
76
+ ) -> typing.Awaitable[bytes]:
77
+ return self.submit(
78
+ self.OPERATION_CLASS.read(nbytes, fd, offset, priority),
79
+ )
80
+
81
+ def write(
82
+ self, payload: bytes, fd: int,
83
+ offset: int, priority: int = 0,
84
+ ) -> typing.Awaitable[int]:
85
+ return self.submit(
86
+ self.OPERATION_CLASS.write(payload, fd, offset, priority),
87
+ )
88
+
89
+ def fsync(self, fd: int) -> typing.Awaitable:
90
+ return self.submit(self.OPERATION_CLASS.fsync(fd))
91
+
92
+ def fdsync(self, fd: int) -> typing.Awaitable:
93
+ return self.submit(self.OPERATION_CLASS.fdsync(fd))
.venv/lib/python3.10/site-packages/caio/src/threadpool/README.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![Build Status](https://travis-ci.org/mbrossard/threadpool.svg?branch=master)](https://travis-ci.org/mbrossard/threadpool)
2
+
3
+ A simple C thread pool implementation
4
+ =====================================
5
+
6
+ Currently, the implementation:
7
+ * Works with pthreads only, but API is intentionally opaque to allow
8
+ other implementations (Windows for instance).
9
+ * Starts all threads on creation of the thread pool.
10
+ * Reserves one task for signaling the queue is full.
11
+ * Stops and joins all worker threads on destroy.
12
+
13
+ Possible enhancements
14
+ =====================
15
+
16
+ The API contains addtional unused 'flags' parameters that would allow
17
+ some additional options:
18
+
19
+ * Lazy creation of threads (easy)
20
+ * Reduce number of threads automatically (hard)
21
+ * Unlimited queue size (medium)
22
+ * Kill worker threads on destroy (hard, dangerous)
23
+ * Support Windows API (medium)
24
+ * Reduce locking contention (medium/hard)
.venv/lib/python3.10/site-packages/caio/src/threadpool/threadpool.c ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2016, Mathias Brossard <mathias@brossard.org>.
3
+ * All rights reserved.
4
+ *
5
+ * Redistribution and use in source and binary forms, with or without
6
+ * modification, are permitted provided that the following conditions are
7
+ * met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright
10
+ * notice, this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright
13
+ * notice, this list of conditions and the following disclaimer in the
14
+ * documentation and/or other materials provided with the distribution.
15
+ *
16
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
+ */
28
+
29
+ /**
30
+ * @file threadpool.c
31
+ * @brief Threadpool implementation file
32
+ */
33
+
34
+ #include <stdlib.h>
35
+ #include <pthread.h>
36
+ #include <unistd.h>
37
+
38
+ #include "threadpool.h"
39
+
40
+ typedef enum {
41
+ immediate_shutdown = 1,
42
+ graceful_shutdown = 2
43
+ } threadpool_shutdown_t;
44
+
45
+ /**
46
+ * @struct threadpool_task
47
+ * @brief the work struct
48
+ *
49
+ * @var function Pointer to the function that will perform the task.
50
+ * @var argument Argument to be passed to the function.
51
+ */
52
+
53
+ typedef struct {
54
+ void (*function)(void *);
55
+ void *argument;
56
+ } threadpool_task_t;
57
+
58
+ /**
59
+ * @struct threadpool
60
+ * @brief The threadpool struct
61
+ *
62
+ * @var notify Condition variable to notify worker threads.
63
+ * @var threads Array containing worker threads ID.
64
+ * @var thread_count Number of threads
65
+ * @var queue Array containing the task queue.
66
+ * @var queue_size Size of the task queue.
67
+ * @var head Index of the first element.
68
+ * @var tail Index of the next element.
69
+ * @var count Number of pending tasks
70
+ * @var shutdown Flag indicating if the pool is shutting down
71
+ * @var started Number of started threads
72
+ */
73
+ struct threadpool_t {
74
+ pthread_mutex_t lock;
75
+ pthread_cond_t notify;
76
+ pthread_t *threads;
77
+ threadpool_task_t *queue;
78
+ int thread_count;
79
+ int queue_size;
80
+ int head;
81
+ int tail;
82
+ int count;
83
+ int shutdown;
84
+ int started;
85
+ };
86
+
87
+ /**
88
+ * @function void *threadpool_thread(void *threadpool)
89
+ * @brief the worker thread
90
+ * @param threadpool the pool which own the thread
91
+ */
92
+ static void *threadpool_thread(void *threadpool);
93
+
94
+ int threadpool_free(threadpool_t *pool);
95
+
96
+ threadpool_t *threadpool_create(int thread_count, int queue_size, int flags)
97
+ {
98
+ threadpool_t *pool;
99
+ int i;
100
+ (void) flags;
101
+
102
+ if(thread_count <= 0 || thread_count > MAX_THREADS || queue_size <= 0 || queue_size > MAX_QUEUE) {
103
+ return NULL;
104
+ }
105
+
106
+ if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) {
107
+ goto err;
108
+ }
109
+
110
+ /* Initialize */
111
+ pool->thread_count = 0;
112
+ pool->queue_size = queue_size;
113
+ pool->head = pool->tail = pool->count = 0;
114
+ pool->shutdown = pool->started = 0;
115
+
116
+ /* Allocate thread and task queue */
117
+ pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
118
+ pool->queue = (threadpool_task_t *)malloc
119
+ (sizeof(threadpool_task_t) * queue_size);
120
+
121
+ /* Initialize mutex and conditional variable first */
122
+ if((pthread_mutex_init(&(pool->lock), NULL) != 0) ||
123
+ (pthread_cond_init(&(pool->notify), NULL) != 0) ||
124
+ (pool->threads == NULL) ||
125
+ (pool->queue == NULL)) {
126
+ goto err;
127
+ }
128
+
129
+ /* Start worker threads */
130
+ for(i = 0; i < thread_count; i++) {
131
+ if(pthread_create(&(pool->threads[i]), NULL,
132
+ threadpool_thread, (void*)pool) != 0) {
133
+ threadpool_destroy(pool, 0);
134
+ return NULL;
135
+ }
136
+ pool->thread_count++;
137
+ pool->started++;
138
+ }
139
+
140
+ return pool;
141
+
142
+ err:
143
+ if(pool) {
144
+ threadpool_free(pool);
145
+ }
146
+ return NULL;
147
+ }
148
+
149
+ int threadpool_add(threadpool_t *pool, void (*function)(void *),
150
+ void *argument, int flags)
151
+ {
152
+ int err = 0;
153
+ int next;
154
+ (void) flags;
155
+
156
+ if(pool == NULL || function == NULL) {
157
+ return threadpool_invalid;
158
+ }
159
+
160
+ if(pthread_mutex_lock(&(pool->lock)) != 0) {
161
+ return threadpool_lock_failure;
162
+ }
163
+
164
+ next = (pool->tail + 1) % pool->queue_size;
165
+
166
+ do {
167
+ /* Are we full ? */
168
+ if(pool->count == pool->queue_size) {
169
+ err = threadpool_queue_full;
170
+ break;
171
+ }
172
+
173
+ /* Are we shutting down ? */
174
+ if(pool->shutdown) {
175
+ err = threadpool_shutdown;
176
+ break;
177
+ }
178
+
179
+ /* Add task to queue */
180
+ pool->queue[pool->tail].function = function;
181
+ pool->queue[pool->tail].argument = argument;
182
+ pool->tail = next;
183
+ pool->count += 1;
184
+
185
+ /* pthread_cond_broadcast */
186
+ if(pthread_cond_signal(&(pool->notify)) != 0) {
187
+ err = threadpool_lock_failure;
188
+ break;
189
+ }
190
+ } while(0);
191
+
192
+ if(pthread_mutex_unlock(&pool->lock) != 0) {
193
+ err = threadpool_lock_failure;
194
+ }
195
+
196
+ return err;
197
+ }
198
+
199
+ int threadpool_destroy(threadpool_t *pool, int flags)
200
+ {
201
+ int i, err = 0;
202
+
203
+ if(pool == NULL) {
204
+ return threadpool_invalid;
205
+ }
206
+
207
+ if(pthread_mutex_lock(&(pool->lock)) != 0) {
208
+ return threadpool_lock_failure;
209
+ }
210
+
211
+ do {
212
+ /* Already shutting down */
213
+ if(pool->shutdown) {
214
+ err = threadpool_shutdown;
215
+ break;
216
+ }
217
+
218
+ pool->shutdown = (flags & threadpool_graceful) ?
219
+ graceful_shutdown : immediate_shutdown;
220
+
221
+ /* Wake up all worker threads */
222
+ if((pthread_cond_broadcast(&(pool->notify)) != 0) ||
223
+ (pthread_mutex_unlock(&(pool->lock)) != 0)) {
224
+ err = threadpool_lock_failure;
225
+ break;
226
+ }
227
+
228
+ /* Join all worker thread */
229
+ for(i = 0; i < pool->thread_count; i++) {
230
+ if(pthread_join(pool->threads[i], NULL) != 0) {
231
+ err = threadpool_thread_failure;
232
+ }
233
+ }
234
+ } while(0);
235
+
236
+ /* Only if everything went well do we deallocate the pool */
237
+ if(!err) {
238
+ threadpool_free(pool);
239
+ }
240
+ return err;
241
+ }
242
+
243
+ int threadpool_free(threadpool_t *pool)
244
+ {
245
+ if(pool == NULL || pool->started > 0) {
246
+ return -1;
247
+ }
248
+
249
+ /* Did we manage to allocate ? */
250
+ if(pool->threads) {
251
+ free(pool->threads);
252
+ free(pool->queue);
253
+
254
+ /* Because we allocate pool->threads after initializing the
255
+ mutex and condition variable, we're sure they're
256
+ initialized. Let's lock the mutex just in case. */
257
+ pthread_mutex_lock(&(pool->lock));
258
+ pthread_mutex_destroy(&(pool->lock));
259
+ pthread_cond_destroy(&(pool->notify));
260
+ }
261
+ free(pool);
262
+ return 0;
263
+ }
264
+
265
+
266
+ static void *threadpool_thread(void *threadpool)
267
+ {
268
+ threadpool_t *pool = (threadpool_t *)threadpool;
269
+ threadpool_task_t task;
270
+
271
+ for(;;) {
272
+ /* Lock must be taken to wait on conditional variable */
273
+ pthread_mutex_lock(&(pool->lock));
274
+
275
+ /* Wait on condition variable, check for spurious wakeups.
276
+ When returning from pthread_cond_wait(), we own the lock. */
277
+ while((pool->count == 0) && (!pool->shutdown)) {
278
+ pthread_cond_wait(&(pool->notify), &(pool->lock));
279
+ }
280
+
281
+ if((pool->shutdown == immediate_shutdown) ||
282
+ ((pool->shutdown == graceful_shutdown) &&
283
+ (pool->count == 0))) {
284
+ break;
285
+ }
286
+
287
+ /* Grab our task */
288
+ task.function = pool->queue[pool->head].function;
289
+ task.argument = pool->queue[pool->head].argument;
290
+ pool->head = (pool->head + 1) % pool->queue_size;
291
+ pool->count -= 1;
292
+
293
+ /* Unlock */
294
+ pthread_mutex_unlock(&(pool->lock));
295
+
296
+ /* Get to work */
297
+ (*(task.function))(task.argument);
298
+ }
299
+
300
+ pool->started--;
301
+
302
+ pthread_mutex_unlock(&(pool->lock));
303
+ pthread_exit(NULL);
304
+ return(NULL);
305
+ }
.venv/lib/python3.10/site-packages/caio/src/threadpool/threadpool.h ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) 2016, Mathias Brossard <mathias@brossard.org>.
3
+ * All rights reserved.
4
+ *
5
+ * Redistribution and use in source and binary forms, with or without
6
+ * modification, are permitted provided that the following conditions are
7
+ * met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright
10
+ * notice, this list of conditions and the following disclaimer.
11
+ *
12
+ * 2. Redistributions in binary form must reproduce the above copyright
13
+ * notice, this list of conditions and the following disclaimer in the
14
+ * documentation and/or other materials provided with the distribution.
15
+ *
16
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
+ */
28
+
29
+ #ifndef _THREADPOOL_H_
30
+ #define _THREADPOOL_H_
31
+
32
+ #ifdef __cplusplus
33
+ extern "C" {
34
+ #endif
35
+
36
+ /**
37
+ * @file threadpool.h
38
+ * @brief Threadpool Header File
39
+ */
40
+
41
+ /**
42
+ * Increase this constants at your own risk
43
+ * Large values might slow down your system
44
+ */
45
+ #define MAX_THREADS 128
46
+ #define MAX_QUEUE 65536
47
+
48
+ typedef struct threadpool_t threadpool_t;
49
+
50
+ typedef enum {
51
+ threadpool_invalid = -1,
52
+ threadpool_lock_failure = -2,
53
+ threadpool_queue_full = -3,
54
+ threadpool_shutdown = -4,
55
+ threadpool_thread_failure = -5
56
+ } threadpool_error_t;
57
+
58
+ typedef enum {
59
+ threadpool_graceful = 1
60
+ } threadpool_destroy_flags_t;
61
+
62
+ /**
63
+ * @function threadpool_create
64
+ * @brief Creates a threadpool_t object.
65
+ * @param thread_count Number of worker threads.
66
+ * @param queue_size Size of the queue.
67
+ * @param flags Unused parameter.
68
+ * @return a newly created thread pool or NULL
69
+ */
70
+ threadpool_t *threadpool_create(int thread_count, int queue_size, int flags);
71
+
72
+ /**
73
+ * @function threadpool_add
74
+ * @brief add a new task in the queue of a thread pool
75
+ * @param pool Thread pool to which add the task.
76
+ * @param function Pointer to the function that will perform the task.
77
+ * @param argument Argument to be passed to the function.
78
+ * @param flags Unused parameter.
79
+ * @return 0 if all goes well, negative values in case of error (@see
80
+ * threadpool_error_t for codes).
81
+ */
82
+ int threadpool_add(threadpool_t *pool, void (*routine)(void *),
83
+ void *arg, int flags);
84
+
85
+ /**
86
+ * @function threadpool_destroy
87
+ * @brief Stops and destroys a thread pool.
88
+ * @param pool Thread pool to destroy.
89
+ * @param flags Flags for shutdown
90
+ *
91
+ * Known values for flags are 0 (default) and threadpool_graceful in
92
+ * which case the thread pool doesn't accept any new tasks but
93
+ * processes all pending tasks before shutdown.
94
+ */
95
+ int threadpool_destroy(threadpool_t *pool, int flags);
96
+
97
+ #ifdef __cplusplus
98
+ }
99
+ #endif
100
+
101
+ #endif /* _THREADPOOL_H_ */
.venv/lib/python3.10/site-packages/caio/thread_aio.c ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <unistd.h>
4
+
5
+ #define PY_SSIZE_T_CLEAN
6
+ #include <Python.h>
7
+ #include <structmember.h>
8
+
9
+ #include "src/threadpool/threadpool.h"
10
+
11
+
12
+ static const unsigned CTX_POOL_SIZE_DEFAULT = 8;
13
+ static const unsigned CTX_MAX_REQUESTS_DEFAULT = 512;
14
+
15
+
16
+ static PyTypeObject AIOOperationType;
17
+ static PyTypeObject AIOContextType;
18
+
19
+ typedef struct {
20
+ PyObject_HEAD
21
+ threadpool_t* pool;
22
+ uint16_t max_requests;
23
+ uint8_t pool_size;
24
+ } AIOContext;
25
+
26
+
27
+ typedef struct {
28
+ PyObject_HEAD
29
+ PyObject* py_buffer;
30
+ PyObject* callback;
31
+ int opcode;
32
+ unsigned int fileno;
33
+ off_t offset;
34
+ int result;
35
+ uint8_t error;
36
+ uint8_t in_progress;
37
+ Py_ssize_t buf_size;
38
+ char* buf;
39
+ PyObject* ctx;
40
+ } AIOOperation;
41
+
42
+
43
+ enum THAIO_OP_CODE {
44
+ THAIO_READ,
45
+ THAIO_WRITE,
46
+ THAIO_FSYNC,
47
+ THAIO_FDSYNC,
48
+ THAIO_NOOP,
49
+ };
50
+
51
+
52
+ static void
53
+ AIOContext_dealloc(AIOContext *self) {
54
+ if (self->pool != 0) {
55
+ threadpool_t* pool = self->pool;
56
+ self->pool = 0;
57
+
58
+ threadpool_destroy(pool, 0);
59
+ }
60
+
61
+ Py_TYPE(self)->tp_free((PyObject *) self);
62
+ }
63
+
64
+ /*
65
+ AIOContext.__new__ classmethod definition
66
+ */
67
+ static PyObject *
68
+ AIOContext_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
69
+ AIOContext *self;
70
+
71
+ self = (AIOContext *) type->tp_alloc(type, 0);
72
+ return (PyObject *) self;
73
+ }
74
+
75
+ static int
76
+ AIOContext_init(AIOContext *self, PyObject *args, PyObject *kwds)
77
+ {
78
+ static char *kwlist[] = {"max_requests", "pool_size", NULL};
79
+
80
+ self->pool = NULL;
81
+ self->max_requests = 0;
82
+
83
+ if (!PyArg_ParseTupleAndKeywords(
84
+ args, kwds, "|HH", kwlist,
85
+ &self->max_requests, &self->pool_size
86
+ )) return -1;
87
+
88
+ if (self->max_requests <= 0) {
89
+ self->max_requests = CTX_MAX_REQUESTS_DEFAULT;
90
+ }
91
+
92
+ if (self->pool_size <= 0) {
93
+ self->pool_size = CTX_POOL_SIZE_DEFAULT;
94
+ }
95
+
96
+ if (self->pool_size > MAX_THREADS) {
97
+ PyErr_Format(
98
+ PyExc_ValueError,
99
+ "pool_size too large. Allowed lower then %d",
100
+ MAX_THREADS
101
+ );
102
+ return -1;
103
+ }
104
+
105
+ if (self->max_requests >= (MAX_QUEUE - 1)) {
106
+ PyErr_Format(
107
+ PyExc_ValueError,
108
+ "max_requests too large. Allowed lower then %d",
109
+ MAX_QUEUE - 1
110
+ );
111
+ return -1;
112
+ }
113
+
114
+ self->pool = threadpool_create(self->pool_size, self->max_requests, 0);
115
+
116
+ if (self->pool == NULL) {
117
+ PyErr_Format(
118
+ PyExc_RuntimeError,
119
+ "Pool initialization failed size=%d max_requests=%d",
120
+ self->pool_size, self->max_requests
121
+ );
122
+ return -1;
123
+ }
124
+
125
+ return 0;
126
+ }
127
+
128
+ static PyObject* AIOContext_repr(AIOContext *self) {
129
+ if (self->pool == NULL) {
130
+ PyErr_SetString(PyExc_RuntimeError, "Pool not initialized");
131
+ return NULL;
132
+ }
133
+ return PyUnicode_FromFormat(
134
+ "<%s as %p: max_requests=%i, pool_size=%i, ctx=%lli>",
135
+ Py_TYPE(self)->tp_name, self, self->max_requests,
136
+ self->pool_size, self->pool
137
+ );
138
+ }
139
+
140
+
141
+ void worker(void *arg) {
142
+ PyGILState_STATE state;
143
+
144
+ AIOOperation* op = arg;
145
+ PyObject* ctx = op->ctx;
146
+ op->ctx = NULL;
147
+ op->error = 0;
148
+
149
+ if (op->opcode == THAIO_NOOP) {
150
+ state = PyGILState_Ensure();
151
+ op->ctx = NULL;
152
+ Py_DECREF(ctx);
153
+ Py_DECREF(op);
154
+ PyGILState_Release(state);
155
+ return;
156
+ }
157
+
158
+ int fileno = op->fileno;
159
+ off_t offset = op->offset;
160
+ int buf_size = op->buf_size;
161
+ char* buf = op->buf;
162
+
163
+ int result;
164
+
165
+ switch (op->opcode) {
166
+ case THAIO_WRITE:
167
+ result = pwrite(fileno, (const char*) buf, buf_size, offset);
168
+ break;
169
+ case THAIO_FSYNC:
170
+ result = fsync(fileno);
171
+ break;
172
+ case THAIO_FDSYNC:
173
+ #ifdef HAVE_FDATASYNC
174
+ result = fdatasync(fileno);
175
+ #else
176
+ result = fsync(fileno);
177
+ #endif
178
+ break;
179
+
180
+ case THAIO_READ:
181
+ result = pread(fileno, buf, buf_size, offset);
182
+ break;
183
+ }
184
+
185
+ op->ctx = NULL;
186
+ op->result = result;
187
+
188
+ if (result < 0) op->error = errno;
189
+
190
+ if (op->opcode == THAIO_READ) {
191
+ op->buf_size = result;
192
+ }
193
+ state = PyGILState_Ensure();
194
+ if (op->callback != NULL) {
195
+ PyObject_CallFunction(op->callback, "i", result);
196
+ }
197
+
198
+ if (op->opcode == THAIO_WRITE) {
199
+ Py_DECREF(op->py_buffer);
200
+ op->py_buffer = NULL;
201
+ }
202
+
203
+ Py_DECREF(ctx);
204
+ Py_DECREF(op);
205
+
206
+ PyGILState_Release(state);
207
+ }
208
+
209
+
210
+ inline int process_pool_error(int code) {
211
+ switch (code) {
212
+ case threadpool_invalid:
213
+ PyErr_SetString(
214
+ PyExc_RuntimeError,
215
+ "Thread pool pointer is invalid"
216
+ );
217
+ return code;
218
+ case threadpool_lock_failure:
219
+ PyErr_SetString(
220
+ PyExc_RuntimeError,
221
+ "Failed to lock thread pool"
222
+ );
223
+ return code;
224
+ case threadpool_queue_full:
225
+ PyErr_Format(
226
+ PyExc_RuntimeError,
227
+ "Thread pool queue full"
228
+ );
229
+ return code;
230
+ case threadpool_shutdown:
231
+ PyErr_SetString(
232
+ PyExc_RuntimeError,
233
+ "Thread pool is shutdown"
234
+ );
235
+ return code;
236
+ case threadpool_thread_failure:
237
+ PyErr_SetString(
238
+ PyExc_RuntimeError,
239
+ "Thread failure"
240
+ );
241
+ return code;
242
+ }
243
+
244
+ if (code < 0) PyErr_SetString(PyExc_RuntimeError, "Unknown error");
245
+ return code;
246
+ }
247
+
248
+
249
+
250
+ PyDoc_STRVAR(AIOContext_submit_docstring,
251
+ "Accepts multiple Operations. Returns \n\n"
252
+ " Operation.submit(aio_op1, aio_op2, aio_opN, ...) -> int"
253
+ );
254
+ static PyObject* AIOContext_submit(
255
+ AIOContext *self, PyObject *args
256
+ ) {
257
+ if (self == NULL) {
258
+ PyErr_SetString(PyExc_RuntimeError, "self is NULL");
259
+ return NULL;
260
+ }
261
+
262
+ if (self->pool == NULL) {
263
+ PyErr_SetString(PyExc_RuntimeError, "self->pool is NULL");
264
+ return NULL;
265
+ }
266
+
267
+ if (!PyTuple_Check(args)) {
268
+ PyErr_SetNone(PyExc_ValueError);
269
+ return NULL;
270
+ }
271
+
272
+ unsigned int nr = PyTuple_Size(args);
273
+
274
+ PyObject* obj;
275
+ AIOOperation* ops[nr];
276
+ unsigned int i;
277
+
278
+ for (i=0; i < nr; i++) {
279
+ obj = PyTuple_GetItem(args, i);
280
+ if (PyObject_TypeCheck(obj, &AIOOperationType) == 0) {
281
+ PyErr_Format(
282
+ PyExc_TypeError,
283
+ "Wrong type for argument %d", i
284
+ );
285
+
286
+ return NULL;
287
+ }
288
+
289
+ ops[i] = (AIOOperation*) obj;
290
+ ops[i]->ctx = (void*) self;
291
+ }
292
+
293
+ unsigned int j=0;
294
+ int result = 0;
295
+
296
+ for (i=0; i < nr; i++) {
297
+ if (ops[i]->in_progress) continue;
298
+ ops[i]->in_progress = 1;
299
+ Py_INCREF(ops[i]);
300
+ Py_INCREF(ops[i]->ctx);
301
+ result = threadpool_add(self->pool, worker, (void*) ops[i], 0);
302
+ if (process_pool_error(result) < 0) return NULL;
303
+ j++;
304
+ }
305
+
306
+ return (PyObject*) PyLong_FromSsize_t(j);
307
+ }
308
+
309
+
310
+ PyDoc_STRVAR(AIOContext_cancel_docstring,
311
+ "Cancels multiple Operations. Returns \n\n"
312
+ " Operation.cancel(aio_op1, aio_op2, aio_opN, ...) -> int\n\n"
313
+ "(Always returns zero, this method exists for compatibility reasons)"
314
+ );
315
+ static PyObject* AIOContext_cancel(
316
+ AIOContext *self, PyObject *args
317
+ ) {
318
+ return (PyObject*) PyLong_FromSsize_t(0);
319
+ }
320
+
321
+
322
+ /*
323
+ AIOContext properties
324
+ */
325
+ static PyMemberDef AIOContext_members[] = {
326
+ {
327
+ "pool_size",
328
+ T_INT,
329
+ offsetof(AIOContext, pool_size),
330
+ READONLY,
331
+ "pool_size"
332
+ },
333
+ {
334
+ "max_requests",
335
+ T_USHORT,
336
+ offsetof(AIOContext, max_requests),
337
+ READONLY,
338
+ "max requests"
339
+ },
340
+ {NULL} /* Sentinel */
341
+ };
342
+
343
+ static PyMethodDef AIOContext_methods[] = {
344
+ {
345
+ "submit",
346
+ (PyCFunction) AIOContext_submit, METH_VARARGS,
347
+ AIOContext_submit_docstring
348
+ },
349
+ {
350
+ "cancel",
351
+ (PyCFunction) AIOContext_cancel, METH_VARARGS,
352
+ AIOContext_cancel_docstring
353
+ },
354
+ {NULL} /* Sentinel */
355
+ };
356
+
357
+ static PyTypeObject
358
+ AIOContextType = {
359
+ PyVarObject_HEAD_INIT(NULL, 0)
360
+ .tp_name = "Context",
361
+ .tp_doc = "thread aio context",
362
+ .tp_basicsize = sizeof(AIOContext),
363
+ .tp_itemsize = 0,
364
+ .tp_flags = Py_TPFLAGS_DEFAULT,
365
+ .tp_new = AIOContext_new,
366
+ .tp_init = (initproc) AIOContext_init,
367
+ .tp_dealloc = (destructor) AIOContext_dealloc,
368
+ .tp_members = AIOContext_members,
369
+ .tp_methods = AIOContext_methods,
370
+ .tp_repr = (reprfunc) AIOContext_repr
371
+ };
372
+
373
+
374
+ static void
375
+ AIOOperation_dealloc(AIOOperation *self) {
376
+ Py_CLEAR(self->callback);
377
+
378
+ if ((self->opcode == THAIO_READ) && self->buf != NULL) {
379
+ PyMem_Free(self->buf);
380
+ self->buf = NULL;
381
+ }
382
+
383
+ Py_CLEAR(self->py_buffer);
384
+ Py_TYPE(self)->tp_free((PyObject *) self);
385
+ }
386
+
387
+
388
+ static PyObject* AIOOperation_repr(AIOOperation *self) {
389
+ char* mode;
390
+
391
+ switch (self->opcode) {
392
+ case THAIO_READ:
393
+ mode = "read";
394
+ break;
395
+
396
+ case THAIO_WRITE:
397
+ mode = "write";
398
+ break;
399
+
400
+ case THAIO_FSYNC:
401
+ mode = "fsync";
402
+ break;
403
+
404
+ case THAIO_FDSYNC:
405
+ mode = "fdsync";
406
+ break;
407
+ default:
408
+ mode = "noop";
409
+ break;
410
+ }
411
+
412
+ return PyUnicode_FromFormat(
413
+ "<%s at %p: mode=\"%s\", fd=%i, offset=%i, result=%i, buffer=%p>",
414
+ Py_TYPE(self)->tp_name, self, mode,
415
+ self->fileno, self->offset, self->result, self->buf
416
+ );
417
+ }
418
+
419
+
420
+ /*
421
+ AIOOperation.read classmethod definition
422
+ */
423
+ PyDoc_STRVAR(AIOOperation_read_docstring,
424
+ "Creates a new instance of Operation on read mode.\n\n"
425
+ " Operation.read(\n"
426
+ " nbytes: int,\n"
427
+ " aio_context: Context,\n"
428
+ " fd: int, \n"
429
+ " offset: int,\n"
430
+ " priority=0\n"
431
+ " )"
432
+ );
433
+
434
+ static PyObject* AIOOperation_read(
435
+ PyTypeObject *type, PyObject *args, PyObject *kwds
436
+ ) {
437
+ AIOOperation *self = (AIOOperation *) type->tp_alloc(type, 0);
438
+
439
+ static char *kwlist[] = {"nbytes", "fd", "offset", "priority", NULL};
440
+
441
+ if (self == NULL) {
442
+ PyErr_SetString(PyExc_MemoryError, "can not allocate memory");
443
+ return NULL;
444
+ }
445
+
446
+ self->buf = NULL;
447
+ self->py_buffer = NULL;
448
+ self->in_progress = 0;
449
+
450
+ uint64_t nbytes = 0;
451
+ uint16_t priority;
452
+
453
+ int argIsOk = PyArg_ParseTupleAndKeywords(
454
+ args, kwds, "KI|LH", kwlist,
455
+ &nbytes,
456
+ &(self->fileno),
457
+ &(self->offset),
458
+ &priority
459
+ );
460
+
461
+ if (!argIsOk) return NULL;
462
+
463
+ self->buf = PyMem_Calloc(nbytes, sizeof(char));
464
+ self->buf_size = nbytes;
465
+
466
+ self->py_buffer = PyMemoryView_FromMemory(
467
+ self->buf,
468
+ self->buf_size,
469
+ PyBUF_READ
470
+ );
471
+
472
+ self->opcode = THAIO_READ;
473
+
474
+ return (PyObject*) self;
475
+ }
476
+
477
+ /*
478
+ AIOOperation.write classmethod definition
479
+ */
480
+ PyDoc_STRVAR(AIOOperation_write_docstring,
481
+ "Creates a new instance of Operation on write mode.\n\n"
482
+ " Operation.write(\n"
483
+ " payload_bytes: bytes,\n"
484
+ " fd: int, \n"
485
+ " offset: int,\n"
486
+ " priority=0\n"
487
+ " )"
488
+ );
489
+
490
+ static PyObject* AIOOperation_write(
491
+ PyTypeObject *type, PyObject *args, PyObject *kwds
492
+ ) {
493
+ AIOOperation *self = (AIOOperation *) type->tp_alloc(type, 0);
494
+
495
+ static char *kwlist[] = {"payload_bytes", "fd", "offset", "priority", NULL};
496
+
497
+ if (self == NULL) {
498
+ PyErr_SetString(PyExc_MemoryError, "can not allocate memory");
499
+ return NULL;
500
+ }
501
+
502
+ // unused
503
+ uint16_t priority;
504
+
505
+ self->buf = NULL;
506
+ self->py_buffer = NULL;
507
+ self->in_progress = 0;
508
+
509
+ int argIsOk = PyArg_ParseTupleAndKeywords(
510
+ args, kwds, "OI|LH", kwlist,
511
+ &(self->py_buffer),
512
+ &(self->fileno),
513
+ &(self->offset),
514
+ &priority
515
+ );
516
+
517
+ if (!argIsOk) return NULL;
518
+
519
+ if (!PyBytes_Check(self->py_buffer)) {
520
+ Py_XDECREF(self);
521
+ PyErr_SetString(
522
+ PyExc_ValueError,
523
+ "payload_bytes argument must be bytes"
524
+ );
525
+ return NULL;
526
+ }
527
+
528
+ self->opcode = THAIO_WRITE;
529
+
530
+ if (PyBytes_AsStringAndSize(
531
+ self->py_buffer,
532
+ &self->buf,
533
+ &self->buf_size
534
+ )) {
535
+ Py_XDECREF(self);
536
+ PyErr_SetString(
537
+ PyExc_RuntimeError,
538
+ "Can not convert bytes to c string"
539
+ );
540
+ return NULL;
541
+ }
542
+
543
+ Py_INCREF(self->py_buffer);
544
+
545
+ return (PyObject*) self;
546
+ }
547
+
548
+
549
+ /*
550
+ AIOOperation.fsync classmethod definition
551
+ */
552
+ PyDoc_STRVAR(AIOOperation_fsync_docstring,
553
+ "Creates a new instance of Operation on fsync mode.\n\n"
554
+ " Operation.fsync(\n"
555
+ " aio_context: AIOContext,\n"
556
+ " fd: int, \n"
557
+ " priority=0\n"
558
+ " )"
559
+ );
560
+
561
+ static PyObject* AIOOperation_fsync(
562
+ PyTypeObject *type, PyObject *args, PyObject *kwds
563
+ ) {
564
+ AIOOperation *self = (AIOOperation *) type->tp_alloc(type, 0);
565
+
566
+ static char *kwlist[] = {"fd", "priority", NULL};
567
+
568
+ if (self == NULL) {
569
+ PyErr_SetString(PyExc_MemoryError, "can not allocate memory");
570
+ return NULL;
571
+ }
572
+
573
+ uint16_t priority;
574
+
575
+ self->buf = NULL;
576
+ self->py_buffer = NULL;
577
+ self->in_progress = 0;
578
+
579
+ int argIsOk = PyArg_ParseTupleAndKeywords(
580
+ args, kwds, "I|H", kwlist,
581
+ &(self->fileno),
582
+ &priority
583
+ );
584
+
585
+ if (!argIsOk) return NULL;
586
+
587
+ self->opcode = THAIO_FSYNC;
588
+
589
+ return (PyObject*) self;
590
+ }
591
+
592
+
593
+ /*
594
+ AIOOperation.fdsync classmethod definition
595
+ */
596
+ PyDoc_STRVAR(AIOOperation_fdsync_docstring,
597
+ "Creates a new instance of Operation on fdsync mode.\n\n"
598
+ " Operation.fdsync(\n"
599
+ " aio_context: AIOContext,\n"
600
+ " fd: int, \n"
601
+ " priority=0\n"
602
+ " )"
603
+ );
604
+
605
+ static PyObject* AIOOperation_fdsync(
606
+ PyTypeObject *type, PyObject *args, PyObject *kwds
607
+ ) {
608
+ AIOOperation *self = (AIOOperation *) type->tp_alloc(type, 0);
609
+
610
+ static char *kwlist[] = {"fd", "priority", NULL};
611
+
612
+ if (self == NULL) {
613
+ PyErr_SetString(PyExc_MemoryError, "can not allocate memory");
614
+ return NULL;
615
+ }
616
+
617
+ self->buf = NULL;
618
+ self->py_buffer = NULL;
619
+ self->in_progress = 0;
620
+ uint16_t priority;
621
+
622
+ int argIsOk = PyArg_ParseTupleAndKeywords(
623
+ args, kwds, "I|H", kwlist,
624
+ &(self->fileno),
625
+ &priority
626
+ );
627
+
628
+ if (!argIsOk) return NULL;
629
+
630
+ self->opcode = THAIO_FDSYNC;
631
+
632
+ return (PyObject*) self;
633
+ }
634
+
635
+ /*
636
+ AIOOperation.get_value method definition
637
+ */
638
+ PyDoc_STRVAR(AIOOperation_get_value_docstring,
639
+ "Method returns a bytes value of Operation's result or None.\n\n"
640
+ " Operation.get_value() -> Optional[bytes]"
641
+ );
642
+
643
+ static PyObject* AIOOperation_get_value(
644
+ AIOOperation *self, PyObject *args, PyObject *kwds
645
+ ) {
646
+ if (self->error != 0) {
647
+ PyErr_SetString(
648
+ PyExc_SystemError,
649
+ strerror(self->error)
650
+ );
651
+
652
+ return NULL;
653
+ }
654
+
655
+ switch (self->opcode) {
656
+ case THAIO_READ:
657
+ return PyBytes_FromStringAndSize(
658
+ self->buf, self->buf_size
659
+ );
660
+
661
+ case THAIO_WRITE:
662
+ return PyLong_FromSsize_t(self->result);
663
+ }
664
+
665
+ return Py_None;
666
+ }
667
+
668
+
669
+ /*
670
+ AIOOperation.get_value method definition
671
+ */
672
+ PyDoc_STRVAR(AIOOperation_set_callback_docstring,
673
+ "Set callback which will be called after Operation will be finished.\n\n"
674
+ " Operation.get_value() -> Optional[bytes]"
675
+ );
676
+
677
+ static PyObject* AIOOperation_set_callback(
678
+ AIOOperation *self, PyObject *args, PyObject *kwds
679
+ ) {
680
+ static char *kwlist[] = {"callback", NULL};
681
+
682
+ PyObject* callback;
683
+
684
+ int argIsOk = PyArg_ParseTupleAndKeywords(
685
+ args, kwds, "O", kwlist,
686
+ &callback
687
+ );
688
+
689
+ if (!argIsOk) return NULL;
690
+
691
+ if (!PyCallable_Check(callback)) {
692
+ PyErr_Format(
693
+ PyExc_ValueError,
694
+ "object %r is not callable",
695
+ callback
696
+ );
697
+ return NULL;
698
+ }
699
+
700
+ Py_INCREF(callback);
701
+ self->callback = callback;
702
+
703
+ Py_RETURN_TRUE;
704
+ }
705
+
706
+ /*
707
+ AIOOperation properties
708
+ */
709
+ static PyMemberDef AIOOperation_members[] = {
710
+ {
711
+ "fileno", T_UINT,
712
+ offsetof(AIOOperation, fileno),
713
+ READONLY, "file descriptor"
714
+ },
715
+ {
716
+ "offset", T_ULONGLONG,
717
+ offsetof(AIOOperation, offset),
718
+ READONLY, "offset"
719
+ },
720
+ {
721
+ "payload", T_OBJECT,
722
+ offsetof(AIOOperation, py_buffer),
723
+ READONLY, "payload"
724
+ },
725
+ {
726
+ "nbytes", T_ULONGLONG,
727
+ offsetof(AIOOperation, buf_size),
728
+ READONLY, "nbytes"
729
+ },
730
+ {
731
+ "result", T_INT,
732
+ offsetof(AIOOperation, result),
733
+ READONLY, "result"
734
+ },
735
+ {
736
+ "error", T_INT,
737
+ offsetof(AIOOperation, error),
738
+ READONLY, "error"
739
+ },
740
+ {NULL} /* Sentinel */
741
+ };
742
+
743
+ /*
744
+ AIOOperation methods
745
+ */
746
+ static PyMethodDef AIOOperation_methods[] = {
747
+ {
748
+ "read",
749
+ (PyCFunction) AIOOperation_read,
750
+ METH_CLASS | METH_VARARGS | METH_KEYWORDS,
751
+ AIOOperation_read_docstring
752
+ },
753
+ {
754
+ "write",
755
+ (PyCFunction) AIOOperation_write,
756
+ METH_CLASS | METH_VARARGS | METH_KEYWORDS,
757
+ AIOOperation_write_docstring
758
+ },
759
+ {
760
+ "fsync",
761
+ (PyCFunction) AIOOperation_fsync,
762
+ METH_CLASS | METH_VARARGS | METH_KEYWORDS,
763
+ AIOOperation_fsync_docstring
764
+ },
765
+ {
766
+ "fdsync",
767
+ (PyCFunction) AIOOperation_fdsync,
768
+ METH_CLASS | METH_VARARGS | METH_KEYWORDS,
769
+ AIOOperation_fdsync_docstring
770
+ },
771
+ {
772
+ "get_value",
773
+ (PyCFunction) AIOOperation_get_value, METH_NOARGS,
774
+ AIOOperation_get_value_docstring
775
+ },
776
+ {
777
+ "set_callback",
778
+ (PyCFunction) AIOOperation_set_callback, METH_VARARGS | METH_KEYWORDS,
779
+ AIOOperation_set_callback_docstring
780
+ },
781
+ {NULL} /* Sentinel */
782
+ };
783
+
784
+ /*
785
+ AIOOperation class
786
+ */
787
+ static PyTypeObject
788
+ AIOOperationType = {
789
+ PyVarObject_HEAD_INIT(NULL, 0)
790
+ .tp_name = "aio.AIOOperation",
791
+ .tp_doc = "thread aio operation representation",
792
+ .tp_basicsize = sizeof(AIOOperation),
793
+ .tp_itemsize = 0,
794
+ .tp_flags = Py_TPFLAGS_DEFAULT,
795
+ .tp_dealloc = (destructor) AIOOperation_dealloc,
796
+ .tp_members = AIOOperation_members,
797
+ .tp_methods = AIOOperation_methods,
798
+ .tp_repr = (reprfunc) AIOOperation_repr
799
+ };
800
+
801
+
802
+ static PyModuleDef thread_aio_module = {
803
+ PyModuleDef_HEAD_INIT,
804
+ .m_name = "thread_aio",
805
+ .m_doc = "Thread based AIO.",
806
+ .m_size = -1,
807
+ };
808
+
809
+
810
+ PyMODINIT_FUNC PyInit_thread_aio(void) {
811
+ Py_Initialize();
812
+
813
+ PyObject *m;
814
+
815
+ m = PyModule_Create(&thread_aio_module);
816
+
817
+ if (m == NULL) return NULL;
818
+
819
+ if (PyType_Ready(&AIOContextType) < 0) return NULL;
820
+
821
+ Py_INCREF(&AIOContextType);
822
+
823
+ if (PyModule_AddObject(m, "Context", (PyObject *) &AIOContextType) < 0) {
824
+ Py_XDECREF(&AIOContextType);
825
+ Py_XDECREF(m);
826
+ return NULL;
827
+ }
828
+
829
+ if (PyType_Ready(&AIOOperationType) < 0) return NULL;
830
+
831
+ Py_INCREF(&AIOOperationType);
832
+
833
+ if (PyModule_AddObject(m, "Operation", (PyObject *) &AIOOperationType) < 0) {
834
+ Py_XDECREF(&AIOOperationType);
835
+ Py_XDECREF(m);
836
+ return NULL;
837
+ }
838
+
839
+ return m;
840
+ }
.venv/lib/python3.10/site-packages/caio/thread_aio.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (62.3 kB). View file
 
.venv/lib/python3.10/site-packages/caio/thread_aio_asyncio.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .asyncio_base import AsyncioContextBase
2
+ from .thread_aio import Context, Operation
3
+
4
+
5
+ class AsyncioContext(AsyncioContextBase):
6
+ MAX_REQUESTS_DEFAULT = 512
7
+ OPERATION_CLASS = Operation
8
+ CONTEXT_CLASS = Context
.venv/lib/python3.10/site-packages/caio/version.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ author_info = (("Dmitry Orlov", "me@mosquito.su"),)
2
+
3
+ package_info = "Asynchronous file IO for Linux MacOS or Windows."
4
+ package_license = "Apache Software License"
5
+
6
+ team_email = author_info[0][1]
7
+
8
+ version_info = (0, 9, 25)
9
+
10
+ __author__ = ", ".join("{} <{}>".format(*info) for info in author_info)
11
+ __version__ = ".".join(map(str, version_info))
12
+
13
+
14
+ __all__ = (
15
+ "author_info",
16
+ "package_info",
17
+ "package_license",
18
+ "team_email",
19
+ "version_info",
20
+ "__author__",
21
+ "__version__",
22
+ )
.venv/lib/python3.10/site-packages/cryptography/__about__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ __all__ = [
8
+ "__author__",
9
+ "__copyright__",
10
+ "__version__",
11
+ ]
12
+
13
+ __version__ = "47.0.0"
14
+
15
+
16
+ __author__ = "The Python Cryptographic Authority and individual contributors"
17
+ __copyright__ = f"Copyright 2013-2026 {__author__}"
.venv/lib/python3.10/site-packages/cryptography/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import sys
8
+ import warnings
9
+
10
+ from cryptography import utils
11
+ from cryptography.__about__ import __author__, __copyright__, __version__
12
+
13
+ __all__ = [
14
+ "__author__",
15
+ "__copyright__",
16
+ "__version__",
17
+ ]
18
+
19
+ if sys.version_info[:2] == (3, 8):
20
+ warnings.warn(
21
+ "Python 3.8 is no longer supported by the Python core team "
22
+ "and support for it is deprecated in cryptography. The next "
23
+ "release of cryptography will remove support for Python 3.8.",
24
+ utils.CryptographyDeprecationWarning,
25
+ stacklevel=2,
26
+ )
.venv/lib/python3.10/site-packages/cryptography/exceptions.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions
10
+
11
+ if typing.TYPE_CHECKING:
12
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
13
+
14
+ _Reasons = rust_exceptions._Reasons
15
+
16
+
17
+ class UnsupportedAlgorithm(Exception):
18
+ def __init__(self, message: str, reason: _Reasons | None = None) -> None:
19
+ super().__init__(message)
20
+ self._reason = reason
21
+
22
+
23
+ class AlreadyFinalized(Exception):
24
+ pass
25
+
26
+
27
+ class AlreadyUpdated(Exception):
28
+ pass
29
+
30
+
31
+ class NotYetFinalized(Exception):
32
+ pass
33
+
34
+
35
+ class InvalidTag(Exception):
36
+ pass
37
+
38
+
39
+ class InvalidSignature(Exception):
40
+ pass
41
+
42
+
43
+ class InternalError(Exception):
44
+ def __init__(
45
+ self, msg: str, err_code: list[rust_openssl.OpenSSLError]
46
+ ) -> None:
47
+ super().__init__(msg)
48
+ self.err_code = err_code
49
+
50
+
51
+ class InvalidKey(Exception):
52
+ pass
.venv/lib/python3.10/site-packages/cryptography/fernet.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import binascii
9
+ import os
10
+ import time
11
+ import typing
12
+ from collections.abc import Iterable
13
+
14
+ from cryptography import utils
15
+ from cryptography.exceptions import InvalidSignature
16
+ from cryptography.hazmat.primitives import hashes, padding
17
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
18
+ from cryptography.hazmat.primitives.hmac import HMAC
19
+
20
+
21
+ class InvalidToken(Exception):
22
+ pass
23
+
24
+
25
+ _MAX_CLOCK_SKEW = 60
26
+
27
+
28
+ class Fernet:
29
+ def __init__(
30
+ self,
31
+ key: bytes | str,
32
+ backend: typing.Any = None,
33
+ ) -> None:
34
+ try:
35
+ key = base64.urlsafe_b64decode(key)
36
+ except binascii.Error as exc:
37
+ raise ValueError(
38
+ "Fernet key must be 32 url-safe base64-encoded bytes."
39
+ ) from exc
40
+ if len(key) != 32:
41
+ raise ValueError(
42
+ "Fernet key must be 32 url-safe base64-encoded bytes."
43
+ )
44
+
45
+ self._signing_key = key[:16]
46
+ self._encryption_key = key[16:]
47
+
48
+ @classmethod
49
+ def generate_key(cls) -> bytes:
50
+ return base64.urlsafe_b64encode(os.urandom(32))
51
+
52
+ def encrypt(self, data: bytes) -> bytes:
53
+ return self.encrypt_at_time(data, int(time.time()))
54
+
55
+ def encrypt_at_time(self, data: bytes, current_time: int) -> bytes:
56
+ iv = os.urandom(16)
57
+ return self._encrypt_from_parts(data, current_time, iv)
58
+
59
+ def _encrypt_from_parts(
60
+ self, data: bytes, current_time: int, iv: bytes
61
+ ) -> bytes:
62
+ utils._check_bytes("data", data)
63
+
64
+ padder = padding.PKCS7(algorithms.AES.block_size).padder()
65
+ padded_data = padder.update(data) + padder.finalize()
66
+ encryptor = Cipher(
67
+ algorithms.AES(self._encryption_key),
68
+ modes.CBC(iv),
69
+ ).encryptor()
70
+ ciphertext = encryptor.update(padded_data) + encryptor.finalize()
71
+
72
+ basic_parts = (
73
+ b"\x80"
74
+ + current_time.to_bytes(length=8, byteorder="big")
75
+ + iv
76
+ + ciphertext
77
+ )
78
+
79
+ h = HMAC(self._signing_key, hashes.SHA256())
80
+ h.update(basic_parts)
81
+ hmac = h.finalize()
82
+ return base64.urlsafe_b64encode(basic_parts + hmac)
83
+
84
+ def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:
85
+ timestamp, data = Fernet._get_unverified_token_data(token)
86
+ if ttl is None:
87
+ time_info = None
88
+ else:
89
+ time_info = (ttl, int(time.time()))
90
+ return self._decrypt_data(data, timestamp, time_info)
91
+
92
+ def decrypt_at_time(
93
+ self, token: bytes | str, ttl: int, current_time: int
94
+ ) -> bytes:
95
+ if ttl is None:
96
+ raise ValueError(
97
+ "decrypt_at_time() can only be used with a non-None ttl"
98
+ )
99
+ timestamp, data = Fernet._get_unverified_token_data(token)
100
+ return self._decrypt_data(data, timestamp, (ttl, current_time))
101
+
102
+ def extract_timestamp(self, token: bytes | str) -> int:
103
+ timestamp, data = Fernet._get_unverified_token_data(token)
104
+ # Verify the token was not tampered with.
105
+ self._verify_signature(data)
106
+ return timestamp
107
+
108
+ @staticmethod
109
+ def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]:
110
+ if not isinstance(token, (str, bytes)):
111
+ raise TypeError("token must be bytes or str")
112
+
113
+ try:
114
+ data = base64.urlsafe_b64decode(token)
115
+ except (TypeError, binascii.Error):
116
+ raise InvalidToken
117
+
118
+ if not data or data[0] != 0x80:
119
+ raise InvalidToken
120
+
121
+ if len(data) < 9:
122
+ raise InvalidToken
123
+
124
+ timestamp = int.from_bytes(data[1:9], byteorder="big")
125
+ return timestamp, data
126
+
127
+ def _verify_signature(self, data: bytes) -> None:
128
+ h = HMAC(self._signing_key, hashes.SHA256())
129
+ h.update(data[:-32])
130
+ try:
131
+ h.verify(data[-32:])
132
+ except InvalidSignature:
133
+ raise InvalidToken
134
+
135
+ def _decrypt_data(
136
+ self,
137
+ data: bytes,
138
+ timestamp: int,
139
+ time_info: tuple[int, int] | None,
140
+ ) -> bytes:
141
+ if time_info is not None:
142
+ ttl, current_time = time_info
143
+ if timestamp + ttl < current_time:
144
+ raise InvalidToken
145
+
146
+ if current_time + _MAX_CLOCK_SKEW < timestamp:
147
+ raise InvalidToken
148
+
149
+ self._verify_signature(data)
150
+
151
+ iv = data[9:25]
152
+ ciphertext = data[25:-32]
153
+ decryptor = Cipher(
154
+ algorithms.AES(self._encryption_key), modes.CBC(iv)
155
+ ).decryptor()
156
+ plaintext_padded = decryptor.update(ciphertext)
157
+ try:
158
+ plaintext_padded += decryptor.finalize()
159
+ except ValueError:
160
+ raise InvalidToken
161
+ unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
162
+
163
+ unpadded = unpadder.update(plaintext_padded)
164
+ try:
165
+ unpadded += unpadder.finalize()
166
+ except ValueError:
167
+ raise InvalidToken
168
+ return unpadded
169
+
170
+
171
+ class MultiFernet:
172
+ def __init__(self, fernets: Iterable[Fernet]):
173
+ fernets = list(fernets)
174
+ if not fernets:
175
+ raise ValueError(
176
+ "MultiFernet requires at least one Fernet instance"
177
+ )
178
+ self._fernets = fernets
179
+
180
+ def encrypt(self, msg: bytes) -> bytes:
181
+ return self.encrypt_at_time(msg, int(time.time()))
182
+
183
+ def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes:
184
+ return self._fernets[0].encrypt_at_time(msg, current_time)
185
+
186
+ def rotate(self, msg: bytes | str) -> bytes:
187
+ timestamp, data = Fernet._get_unverified_token_data(msg)
188
+ for f in self._fernets:
189
+ try:
190
+ p = f._decrypt_data(data, timestamp, None)
191
+ break
192
+ except InvalidToken:
193
+ pass
194
+ else:
195
+ raise InvalidToken
196
+
197
+ iv = os.urandom(16)
198
+ return self._fernets[0]._encrypt_from_parts(p, timestamp, iv)
199
+
200
+ def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
201
+ for f in self._fernets:
202
+ try:
203
+ return f.decrypt(msg, ttl)
204
+ except InvalidToken:
205
+ pass
206
+ raise InvalidToken
207
+
208
+ def decrypt_at_time(
209
+ self, msg: bytes | str, ttl: int, current_time: int
210
+ ) -> bytes:
211
+ for f in self._fernets:
212
+ try:
213
+ return f.decrypt_at_time(msg, ttl, current_time)
214
+ except InvalidToken:
215
+ pass
216
+ raise InvalidToken
217
+
218
+ def extract_timestamp(self, msg: bytes | str) -> int:
219
+ for f in self._fernets:
220
+ try:
221
+ return f.extract_timestamp(msg)
222
+ except InvalidToken:
223
+ pass
224
+ raise InvalidToken
.venv/lib/python3.10/site-packages/cryptography/hazmat/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ """
8
+ Hazardous Materials
9
+
10
+ This is a "Hazardous Materials" module. You should ONLY use it if you're
11
+ 100% absolutely sure that you know what you're doing because this module
12
+ is full of land mines, dragons, and dinosaurs with laser guns.
13
+ """
.venv/lib/python3.10/site-packages/cryptography/hazmat/_oid.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import (
8
+ ObjectIdentifier as ObjectIdentifier,
9
+ )
10
+ from cryptography.hazmat.primitives import hashes
11
+
12
+
13
+ class ExtensionOID:
14
+ SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9")
15
+ SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14")
16
+ KEY_USAGE = ObjectIdentifier("2.5.29.15")
17
+ PRIVATE_KEY_USAGE_PERIOD = ObjectIdentifier("2.5.29.16")
18
+ SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17")
19
+ ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18")
20
+ BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19")
21
+ NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30")
22
+ CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31")
23
+ CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32")
24
+ POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33")
25
+ AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35")
26
+ POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36")
27
+ EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37")
28
+ FRESHEST_CRL = ObjectIdentifier("2.5.29.46")
29
+ INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54")
30
+ ISSUING_DISTRIBUTION_POINT = ObjectIdentifier("2.5.29.28")
31
+ AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1")
32
+ SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11")
33
+ OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5")
34
+ TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24")
35
+ CRL_NUMBER = ObjectIdentifier("2.5.29.20")
36
+ DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27")
37
+ PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier(
38
+ "1.3.6.1.4.1.11129.2.4.2"
39
+ )
40
+ PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3")
41
+ SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5")
42
+ MS_CERTIFICATE_TEMPLATE = ObjectIdentifier("1.3.6.1.4.1.311.21.7")
43
+ ADMISSIONS = ObjectIdentifier("1.3.36.8.3.3")
44
+
45
+
46
+ class OCSPExtensionOID:
47
+ NONCE = ObjectIdentifier("1.3.6.1.5.5.7.48.1.2")
48
+ ACCEPTABLE_RESPONSES = ObjectIdentifier("1.3.6.1.5.5.7.48.1.4")
49
+
50
+
51
+ class CRLEntryExtensionOID:
52
+ CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29")
53
+ CRL_REASON = ObjectIdentifier("2.5.29.21")
54
+ INVALIDITY_DATE = ObjectIdentifier("2.5.29.24")
55
+
56
+
57
+ class NameOID:
58
+ COMMON_NAME = ObjectIdentifier("2.5.4.3")
59
+ COUNTRY_NAME = ObjectIdentifier("2.5.4.6")
60
+ LOCALITY_NAME = ObjectIdentifier("2.5.4.7")
61
+ STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8")
62
+ STREET_ADDRESS = ObjectIdentifier("2.5.4.9")
63
+ ORGANIZATION_IDENTIFIER = ObjectIdentifier("2.5.4.97")
64
+ ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10")
65
+ ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11")
66
+ SERIAL_NUMBER = ObjectIdentifier("2.5.4.5")
67
+ SURNAME = ObjectIdentifier("2.5.4.4")
68
+ GIVEN_NAME = ObjectIdentifier("2.5.4.42")
69
+ TITLE = ObjectIdentifier("2.5.4.12")
70
+ INITIALS = ObjectIdentifier("2.5.4.43")
71
+ GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44")
72
+ X500_UNIQUE_IDENTIFIER = ObjectIdentifier("2.5.4.45")
73
+ DN_QUALIFIER = ObjectIdentifier("2.5.4.46")
74
+ PSEUDONYM = ObjectIdentifier("2.5.4.65")
75
+ USER_ID = ObjectIdentifier("0.9.2342.19200300.100.1.1")
76
+ DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25")
77
+ EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1")
78
+ JURISDICTION_COUNTRY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.3")
79
+ JURISDICTION_LOCALITY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.1")
80
+ JURISDICTION_STATE_OR_PROVINCE_NAME = ObjectIdentifier(
81
+ "1.3.6.1.4.1.311.60.2.1.2"
82
+ )
83
+ BUSINESS_CATEGORY = ObjectIdentifier("2.5.4.15")
84
+ POSTAL_ADDRESS = ObjectIdentifier("2.5.4.16")
85
+ POSTAL_CODE = ObjectIdentifier("2.5.4.17")
86
+ INN = ObjectIdentifier("1.2.643.3.131.1.1")
87
+ OGRN = ObjectIdentifier("1.2.643.100.1")
88
+ SNILS = ObjectIdentifier("1.2.643.100.3")
89
+ UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2")
90
+
91
+
92
+ class SignatureAlgorithmOID:
93
+ RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4")
94
+ RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5")
95
+ # This is an alternate OID for RSA with SHA1 that is occasionally seen
96
+ _RSA_WITH_SHA1 = ObjectIdentifier("1.3.14.3.2.29")
97
+ RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14")
98
+ RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11")
99
+ RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12")
100
+ RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13")
101
+ RSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.13")
102
+ RSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.14")
103
+ RSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.15")
104
+ RSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.16")
105
+ RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10")
106
+ ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1")
107
+ ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1")
108
+ ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2")
109
+ ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3")
110
+ ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4")
111
+ ECDSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.9")
112
+ ECDSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.10")
113
+ ECDSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.11")
114
+ ECDSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.12")
115
+ DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3")
116
+ DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1")
117
+ DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2")
118
+ DSA_WITH_SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.3.3")
119
+ DSA_WITH_SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.3.4")
120
+ ED25519 = ObjectIdentifier("1.3.101.112")
121
+ ED448 = ObjectIdentifier("1.3.101.113")
122
+ GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3")
123
+ GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2")
124
+ GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3")
125
+
126
+
127
+ _SIG_OIDS_TO_HASH: dict[ObjectIdentifier, hashes.HashAlgorithm | None] = {
128
+ SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(),
129
+ SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(),
130
+ SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(),
131
+ SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(),
132
+ SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(),
133
+ SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(),
134
+ SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(),
135
+ SignatureAlgorithmOID.RSA_WITH_SHA3_224: hashes.SHA3_224(),
136
+ SignatureAlgorithmOID.RSA_WITH_SHA3_256: hashes.SHA3_256(),
137
+ SignatureAlgorithmOID.RSA_WITH_SHA3_384: hashes.SHA3_384(),
138
+ SignatureAlgorithmOID.RSA_WITH_SHA3_512: hashes.SHA3_512(),
139
+ SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(),
140
+ SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(),
141
+ SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(),
142
+ SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(),
143
+ SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(),
144
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_224: hashes.SHA3_224(),
145
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_256: hashes.SHA3_256(),
146
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_384: hashes.SHA3_384(),
147
+ SignatureAlgorithmOID.ECDSA_WITH_SHA3_512: hashes.SHA3_512(),
148
+ SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(),
149
+ SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(),
150
+ SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256(),
151
+ SignatureAlgorithmOID.ED25519: None,
152
+ SignatureAlgorithmOID.ED448: None,
153
+ SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: None,
154
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: None,
155
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: None,
156
+ }
157
+
158
+
159
+ class HashAlgorithmOID:
160
+ SHA1 = ObjectIdentifier("1.3.14.3.2.26")
161
+ SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.2.4")
162
+ SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.2.1")
163
+ SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.2.2")
164
+ SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.2.3")
165
+ SHA3_224 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.224")
166
+ SHA3_256 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.256")
167
+ SHA3_384 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.384")
168
+ SHA3_512 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.512")
169
+ SHA3_224_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.7")
170
+ SHA3_256_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.8")
171
+ SHA3_384_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.9")
172
+ SHA3_512_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.10")
173
+
174
+
175
+ class PublicKeyAlgorithmOID:
176
+ DSA = ObjectIdentifier("1.2.840.10040.4.1")
177
+ EC_PUBLIC_KEY = ObjectIdentifier("1.2.840.10045.2.1")
178
+ RSAES_PKCS1_v1_5 = ObjectIdentifier("1.2.840.113549.1.1.1")
179
+ RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10")
180
+ X25519 = ObjectIdentifier("1.3.101.110")
181
+ X448 = ObjectIdentifier("1.3.101.111")
182
+ ED25519 = ObjectIdentifier("1.3.101.112")
183
+ ED448 = ObjectIdentifier("1.3.101.113")
184
+
185
+
186
+ class ExtendedKeyUsageOID:
187
+ SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1")
188
+ CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2")
189
+ CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3")
190
+ EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4")
191
+ TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8")
192
+ OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9")
193
+ ANY_EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37.0")
194
+ SMARTCARD_LOGON = ObjectIdentifier("1.3.6.1.4.1.311.20.2.2")
195
+ KERBEROS_PKINIT_KDC = ObjectIdentifier("1.3.6.1.5.2.3.5")
196
+ IPSEC_IKE = ObjectIdentifier("1.3.6.1.5.5.7.3.17")
197
+ BUNDLE_SECURITY = ObjectIdentifier("1.3.6.1.5.5.7.3.35")
198
+ CERTIFICATE_TRANSPARENCY = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.4")
199
+
200
+
201
+ class OtherNameFormOID:
202
+ PERMANENT_IDENTIFIER = ObjectIdentifier("1.3.6.1.5.5.7.8.3")
203
+ HW_MODULE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.4")
204
+ DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7")
205
+ NAI_REALM = ObjectIdentifier("1.3.6.1.5.5.7.8.8")
206
+ SMTP_UTF8_MAILBOX = ObjectIdentifier("1.3.6.1.5.5.7.8.9")
207
+ ACP_NODE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.10")
208
+ BUNDLE_EID = ObjectIdentifier("1.3.6.1.5.5.7.8.11")
209
+
210
+
211
+ class AuthorityInformationAccessOID:
212
+ CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2")
213
+ OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1")
214
+
215
+
216
+ class SubjectInformationAccessOID:
217
+ CA_REPOSITORY = ObjectIdentifier("1.3.6.1.5.5.7.48.5")
218
+
219
+
220
+ class CertificatePoliciesOID:
221
+ CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1")
222
+ CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2")
223
+ ANY_POLICY = ObjectIdentifier("2.5.29.32.0")
224
+
225
+
226
+ class AttributeOID:
227
+ CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7")
228
+ UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2")
229
+
230
+
231
+ _OID_NAMES = {
232
+ NameOID.COMMON_NAME: "commonName",
233
+ NameOID.COUNTRY_NAME: "countryName",
234
+ NameOID.LOCALITY_NAME: "localityName",
235
+ NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName",
236
+ NameOID.STREET_ADDRESS: "streetAddress",
237
+ NameOID.ORGANIZATION_NAME: "organizationName",
238
+ NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName",
239
+ NameOID.SERIAL_NUMBER: "serialNumber",
240
+ NameOID.SURNAME: "surname",
241
+ NameOID.GIVEN_NAME: "givenName",
242
+ NameOID.TITLE: "title",
243
+ NameOID.GENERATION_QUALIFIER: "generationQualifier",
244
+ NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier",
245
+ NameOID.DN_QUALIFIER: "dnQualifier",
246
+ NameOID.PSEUDONYM: "pseudonym",
247
+ NameOID.USER_ID: "userID",
248
+ NameOID.DOMAIN_COMPONENT: "domainComponent",
249
+ NameOID.EMAIL_ADDRESS: "emailAddress",
250
+ NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName",
251
+ NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName",
252
+ NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: (
253
+ "jurisdictionStateOrProvinceName"
254
+ ),
255
+ NameOID.BUSINESS_CATEGORY: "businessCategory",
256
+ NameOID.POSTAL_ADDRESS: "postalAddress",
257
+ NameOID.POSTAL_CODE: "postalCode",
258
+ NameOID.INN: "INN",
259
+ NameOID.OGRN: "OGRN",
260
+ NameOID.SNILS: "SNILS",
261
+ NameOID.UNSTRUCTURED_NAME: "unstructuredName",
262
+ SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption",
263
+ SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption",
264
+ SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption",
265
+ SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption",
266
+ SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption",
267
+ SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption",
268
+ SignatureAlgorithmOID.RSASSA_PSS: "rsassaPss",
269
+ SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1",
270
+ SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224",
271
+ SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256",
272
+ SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384",
273
+ SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512",
274
+ SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1",
275
+ SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224",
276
+ SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256",
277
+ SignatureAlgorithmOID.ED25519: "ed25519",
278
+ SignatureAlgorithmOID.ED448: "ed448",
279
+ SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: (
280
+ "GOST R 34.11-94 with GOST R 34.10-2001"
281
+ ),
282
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: (
283
+ "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)"
284
+ ),
285
+ SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: (
286
+ "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)"
287
+ ),
288
+ HashAlgorithmOID.SHA1: "sha1",
289
+ HashAlgorithmOID.SHA224: "sha224",
290
+ HashAlgorithmOID.SHA256: "sha256",
291
+ HashAlgorithmOID.SHA384: "sha384",
292
+ HashAlgorithmOID.SHA512: "sha512",
293
+ HashAlgorithmOID.SHA3_224: "sha3_224",
294
+ HashAlgorithmOID.SHA3_256: "sha3_256",
295
+ HashAlgorithmOID.SHA3_384: "sha3_384",
296
+ HashAlgorithmOID.SHA3_512: "sha3_512",
297
+ HashAlgorithmOID.SHA3_224_NIST: "sha3_224",
298
+ HashAlgorithmOID.SHA3_256_NIST: "sha3_256",
299
+ HashAlgorithmOID.SHA3_384_NIST: "sha3_384",
300
+ HashAlgorithmOID.SHA3_512_NIST: "sha3_512",
301
+ PublicKeyAlgorithmOID.DSA: "dsaEncryption",
302
+ PublicKeyAlgorithmOID.EC_PUBLIC_KEY: "id-ecPublicKey",
303
+ PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5: "rsaEncryption",
304
+ PublicKeyAlgorithmOID.X25519: "X25519",
305
+ PublicKeyAlgorithmOID.X448: "X448",
306
+ ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth",
307
+ ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth",
308
+ ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning",
309
+ ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection",
310
+ ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping",
311
+ ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning",
312
+ ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin",
313
+ ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC",
314
+ ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes",
315
+ ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier",
316
+ ExtensionOID.KEY_USAGE: "keyUsage",
317
+ ExtensionOID.PRIVATE_KEY_USAGE_PERIOD: "privateKeyUsagePeriod",
318
+ ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName",
319
+ ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName",
320
+ ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints",
321
+ ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: (
322
+ "signedCertificateTimestampList"
323
+ ),
324
+ ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: (
325
+ "signedCertificateTimestampList"
326
+ ),
327
+ ExtensionOID.PRECERT_POISON: "ctPoison",
328
+ ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate",
329
+ ExtensionOID.ADMISSIONS: "Admissions",
330
+ CRLEntryExtensionOID.CRL_REASON: "cRLReason",
331
+ CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate",
332
+ CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer",
333
+ ExtensionOID.NAME_CONSTRAINTS: "nameConstraints",
334
+ ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints",
335
+ ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies",
336
+ ExtensionOID.POLICY_MAPPINGS: "policyMappings",
337
+ ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier",
338
+ ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints",
339
+ ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage",
340
+ ExtensionOID.FRESHEST_CRL: "freshestCRL",
341
+ ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy",
342
+ ExtensionOID.ISSUING_DISTRIBUTION_POINT: "issuingDistributionPoint",
343
+ ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess",
344
+ ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess",
345
+ ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck",
346
+ ExtensionOID.CRL_NUMBER: "cRLNumber",
347
+ ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator",
348
+ ExtensionOID.TLS_FEATURE: "TLSFeature",
349
+ AuthorityInformationAccessOID.OCSP: "OCSP",
350
+ AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers",
351
+ SubjectInformationAccessOID.CA_REPOSITORY: "caRepository",
352
+ CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps",
353
+ CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice",
354
+ OCSPExtensionOID.NONCE: "OCSPNonce",
355
+ AttributeOID.CHALLENGE_PASSWORD: "challengePassword",
356
+ }
.venv/lib/python3.10/site-packages/cryptography/hazmat/asn1/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from cryptography.hazmat.asn1.asn1 import (
6
+ TLV,
7
+ BitString,
8
+ Default,
9
+ Explicit,
10
+ GeneralizedTime,
11
+ IA5String,
12
+ Implicit,
13
+ Null,
14
+ PrintableString,
15
+ SetOf,
16
+ Size,
17
+ UTCTime,
18
+ Variant,
19
+ decode_der,
20
+ encode_der,
21
+ sequence,
22
+ set,
23
+ )
24
+
25
+ __all__ = [
26
+ "TLV",
27
+ "BitString",
28
+ "Default",
29
+ "Explicit",
30
+ "GeneralizedTime",
31
+ "IA5String",
32
+ "Implicit",
33
+ "Null",
34
+ "PrintableString",
35
+ "SetOf",
36
+ "Size",
37
+ "UTCTime",
38
+ "Variant",
39
+ "decode_der",
40
+ "encode_der",
41
+ "sequence",
42
+ "set",
43
+ ]
.venv/lib/python3.10/site-packages/cryptography/hazmat/asn1/asn1.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ import builtins
8
+ import dataclasses
9
+ import sys
10
+ import types
11
+ import typing
12
+
13
+ if sys.version_info < (3, 11):
14
+ import typing_extensions
15
+
16
+ LiteralString = typing_extensions.LiteralString
17
+
18
+ # We use the `include_extras` parameter of `get_type_hints`, which was
19
+ # added in Python 3.9. This can be replaced by the `typing` version
20
+ # once the min version is >= 3.9
21
+ if sys.version_info < (3, 9):
22
+ get_type_hints = typing_extensions.get_type_hints
23
+ get_type_args = typing_extensions.get_args
24
+ get_type_origin = typing_extensions.get_origin
25
+ Annotated = typing_extensions.Annotated
26
+ else:
27
+ get_type_hints = typing.get_type_hints
28
+ get_type_args = typing.get_args
29
+ get_type_origin = typing.get_origin
30
+ Annotated = typing.Annotated
31
+ else:
32
+ get_type_hints = typing.get_type_hints
33
+ get_type_args = typing.get_args
34
+ get_type_origin = typing.get_origin
35
+ Annotated = typing.Annotated
36
+ LiteralString = typing.LiteralString
37
+
38
+ if sys.version_info < (3, 10):
39
+ NoneType = type(None)
40
+ else:
41
+ NoneType = types.NoneType # type: ignore[nonetype-type]
42
+
43
+ from cryptography.hazmat.bindings._rust import declarative_asn1
44
+
45
+ T = typing.TypeVar("T", covariant=True)
46
+ U = typing.TypeVar("U")
47
+ Tag = typing.TypeVar("Tag", bound=LiteralString)
48
+
49
+
50
+ @dataclasses.dataclass(frozen=True)
51
+ class Variant(typing.Generic[U, Tag]):
52
+ """
53
+ A tagged variant for CHOICE fields with the same underlying type.
54
+
55
+ Use this when you have multiple CHOICE alternatives with the same type
56
+ and need to distinguish between them:
57
+
58
+ foo: (
59
+ Annotated[Variant[int, typing.Literal["IntA"]], Implicit(0)]
60
+ | Annotated[Variant[int, typing.Literal["IntB"]], Implicit(1)]
61
+ )
62
+
63
+ Usage:
64
+ example = Example(foo=Variant(5, "IntA"))
65
+ decoded.foo.value # The int value
66
+ decoded.foo.tag # "IntA" or "IntB"
67
+ """
68
+
69
+ value: U
70
+ tag: str
71
+
72
+
73
+ decode_der = declarative_asn1.decode_der
74
+ encode_der = declarative_asn1.encode_der
75
+
76
+
77
+ def _is_union(field_type: type) -> bool:
78
+ # NOTE: types.UnionType for `T | U`, typing.Union for `Union[T, U]`.
79
+ # TODO: Drop the `hasattr()` once the minimum supported Python version
80
+ # is >= 3.10.
81
+ union_types = (
82
+ (types.UnionType, typing.Union)
83
+ if hasattr(types, "UnionType")
84
+ else (typing.Union,)
85
+ )
86
+ return get_type_origin(field_type) in union_types
87
+
88
+
89
+ def _extract_annotation(
90
+ metadata: tuple, field_name: str
91
+ ) -> declarative_asn1.Annotation:
92
+ default = None
93
+ encoding = None
94
+ size = None
95
+ for raw_annotation in metadata:
96
+ if isinstance(raw_annotation, Default):
97
+ if default is not None:
98
+ raise TypeError(
99
+ f"multiple DEFAULT annotations found in field "
100
+ f"'{field_name}'"
101
+ )
102
+ default = raw_annotation.value
103
+ elif isinstance(raw_annotation, declarative_asn1.Encoding):
104
+ if encoding is not None:
105
+ raise TypeError(
106
+ f"multiple IMPLICIT/EXPLICIT annotations found in field "
107
+ f"'{field_name}'"
108
+ )
109
+ encoding = raw_annotation
110
+ elif isinstance(raw_annotation, declarative_asn1.Size):
111
+ if size is not None:
112
+ raise TypeError(
113
+ f"multiple SIZE annotations found in field '{field_name}'"
114
+ )
115
+ size = raw_annotation
116
+ else:
117
+ raise TypeError(f"unsupported annotation: {raw_annotation}")
118
+
119
+ return declarative_asn1.Annotation(
120
+ default=default, encoding=encoding, size=size
121
+ )
122
+
123
+
124
+ def _normalize_field_type(
125
+ field_type: typing.Any, field_name: str
126
+ ) -> declarative_asn1.AnnotatedType:
127
+ # Strip the `Annotated[...]` off, and populate the annotation
128
+ # from it if it exists.
129
+ if get_type_origin(field_type) is Annotated:
130
+ annotation = _extract_annotation(field_type.__metadata__, field_name)
131
+ field_type, *_ = get_type_args(field_type)
132
+ else:
133
+ annotation = declarative_asn1.Annotation()
134
+
135
+ if annotation.size is not None and (
136
+ get_type_origin(field_type) not in (builtins.list, SetOf)
137
+ and field_type
138
+ not in (
139
+ builtins.bytes,
140
+ builtins.str,
141
+ BitString,
142
+ IA5String,
143
+ PrintableString,
144
+ )
145
+ ):
146
+ raise TypeError(
147
+ f"field '{field_name}' has a SIZE annotation, but SIZE "
148
+ "annotations are only supported for fields of types: "
149
+ "[SEQUENCE OF, SET OF, BIT STRING, OCTET STRING, UTF8String, "
150
+ "PrintableString, IA5String]"
151
+ )
152
+
153
+ if field_type is TLV:
154
+ if isinstance(annotation.encoding, Implicit):
155
+ raise TypeError(
156
+ f"field '{field_name}' has an IMPLICIT annotation, but "
157
+ "IMPLICIT annotations are not supported for TLV types."
158
+ )
159
+ elif annotation.default is not None:
160
+ raise TypeError(
161
+ f"field '{field_name}' has a DEFAULT annotation, but "
162
+ "DEFAULT annotations are not supported for TLV types."
163
+ )
164
+
165
+ if hasattr(field_type, "__asn1_root__"):
166
+ root_type = field_type.__asn1_root__
167
+ if not isinstance(
168
+ root_type,
169
+ (declarative_asn1.Type.Sequence, declarative_asn1.Type.Set),
170
+ ):
171
+ raise TypeError(f"unsupported root type: {root_type}")
172
+ return declarative_asn1.AnnotatedType(
173
+ typing.cast(declarative_asn1.Type, root_type), annotation
174
+ )
175
+ elif _is_union(field_type):
176
+ union_args = get_type_args(field_type)
177
+ if len(union_args) == 2 and NoneType in union_args:
178
+ # A Union between a type and None is an OPTIONAL
179
+ optional_type = (
180
+ union_args[0] if union_args[1] is type(None) else union_args[1]
181
+ )
182
+ if optional_type is TLV:
183
+ raise TypeError(
184
+ "optional TLV types (`TLV | None`) are not "
185
+ "currently supported"
186
+ )
187
+ annotated_type = _normalize_field_type(optional_type, field_name)
188
+
189
+ if not annotated_type.annotation.is_empty():
190
+ raise TypeError(
191
+ "optional (`X | None`) types cannot have `X` "
192
+ "annotated: annotations must apply to the union "
193
+ "(i.e: `Annotated[X | None, annotation]`)"
194
+ )
195
+
196
+ if annotation.default is not None:
197
+ raise TypeError(
198
+ "optional (`X | None`) types should not have a DEFAULT "
199
+ "annotation"
200
+ )
201
+
202
+ rust_field_type = declarative_asn1.Type.Option(annotated_type)
203
+
204
+ else:
205
+ # Otherwise, the Union is a CHOICE
206
+ if isinstance(annotation.encoding, Implicit):
207
+ # CHOICEs cannot be IMPLICIT. See X.680 section 31.2.9.
208
+ raise TypeError(
209
+ "CHOICE (`X | Y | ...`) types should not have an IMPLICIT "
210
+ "annotation"
211
+ )
212
+ variants = [
213
+ _type_to_variant(arg, field_name)
214
+ for arg in union_args
215
+ if arg is not type(None)
216
+ ]
217
+
218
+ # Union types should either be all Variants
219
+ # (`Variant[..] | Variant[..] | etc`) or all non Variants
220
+ are_union_types_tagged = variants[0].tag_name is not None
221
+ if any(
222
+ (v.tag_name is not None) != are_union_types_tagged
223
+ for v in variants
224
+ ):
225
+ raise TypeError(
226
+ "When using `asn1.Variant` in a union, all the other "
227
+ "types in the union must also be `asn1.Variant`"
228
+ )
229
+
230
+ if are_union_types_tagged:
231
+ tags = {v.tag_name for v in variants}
232
+ if len(variants) != len(tags):
233
+ raise TypeError(
234
+ "When using `asn1.Variant` in a union, the tags used "
235
+ "must be unique"
236
+ )
237
+
238
+ rust_choice_type = declarative_asn1.Type.Choice(variants)
239
+ # If None is part of the union types, this is an OPTIONAL CHOICE
240
+ rust_field_type = (
241
+ declarative_asn1.Type.Option(
242
+ declarative_asn1.AnnotatedType(
243
+ rust_choice_type, declarative_asn1.Annotation()
244
+ )
245
+ )
246
+ if NoneType in union_args
247
+ else rust_choice_type
248
+ )
249
+
250
+ elif get_type_origin(field_type) is builtins.list:
251
+ inner_type = _normalize_field_type(
252
+ get_type_args(field_type)[0], field_name
253
+ )
254
+ rust_field_type = declarative_asn1.Type.SequenceOf(inner_type)
255
+ elif get_type_origin(field_type) is SetOf:
256
+ inner_type = _normalize_field_type(
257
+ get_type_args(field_type)[0], field_name
258
+ )
259
+ rust_field_type = declarative_asn1.Type.SetOf(inner_type)
260
+ else:
261
+ rust_field_type = declarative_asn1.non_root_python_to_rust(field_type)
262
+
263
+ return declarative_asn1.AnnotatedType(rust_field_type, annotation)
264
+
265
+
266
+ # Convert a type to a Variant. Used with types inside Union
267
+ # annotations (T1, T2, etc in `Union[T1, T2, ...]`).
268
+ def _type_to_variant(
269
+ t: typing.Any, field_name: str
270
+ ) -> declarative_asn1.Variant:
271
+ is_annotated = get_type_origin(t) is Annotated
272
+ inner_type = get_type_args(t)[0] if is_annotated else t
273
+
274
+ # Check if this is a Variant[T, Tag] type
275
+ if get_type_origin(inner_type) is Variant:
276
+ value_type, tag_literal = get_type_args(inner_type)
277
+ if get_type_origin(tag_literal) is not typing.Literal:
278
+ raise TypeError(
279
+ "When using `asn1.Variant` in a type annotation, the second "
280
+ "type parameter must be a `typing.Literal` type. E.g: "
281
+ '`Variant[int, typing.Literal["MyInt"]]`.'
282
+ )
283
+ tag_name = get_type_args(tag_literal)[0]
284
+
285
+ if hasattr(value_type, "__asn1_root__"):
286
+ rust_type = value_type.__asn1_root__
287
+ else:
288
+ rust_type = declarative_asn1.non_root_python_to_rust(value_type)
289
+
290
+ if is_annotated:
291
+ ann_type = declarative_asn1.AnnotatedType(
292
+ rust_type,
293
+ _extract_annotation(t.__metadata__, field_name),
294
+ )
295
+ else:
296
+ ann_type = declarative_asn1.AnnotatedType(
297
+ rust_type,
298
+ declarative_asn1.Annotation(),
299
+ )
300
+
301
+ return declarative_asn1.Variant(Variant, ann_type, tag_name)
302
+ else:
303
+ # Plain type (not a tagged Variant)
304
+ return declarative_asn1.Variant(
305
+ inner_type,
306
+ _normalize_field_type(t, field_name),
307
+ None,
308
+ )
309
+
310
+
311
+ def _annotate_fields(
312
+ raw_fields: dict[str, type],
313
+ ) -> dict[str, declarative_asn1.AnnotatedType]:
314
+ fields = {}
315
+ for field_name, field_type in raw_fields.items():
316
+ # Recursively normalize the field type into something that the
317
+ # Rust code can understand.
318
+ annotated_field_type = _normalize_field_type(field_type, field_name)
319
+ fields[field_name] = annotated_field_type
320
+
321
+ return fields
322
+
323
+
324
+ def _register_asn1_sequence(cls: type[U]) -> None:
325
+ raw_fields = get_type_hints(cls, include_extras=True)
326
+ root = declarative_asn1.Type.Sequence(cls, _annotate_fields(raw_fields))
327
+
328
+ setattr(cls, "__asn1_root__", root)
329
+
330
+
331
+ def _register_asn1_set(cls: type[U]) -> None:
332
+ raw_fields = get_type_hints(cls, include_extras=True)
333
+ root = declarative_asn1.Type.Set(cls, _annotate_fields(raw_fields))
334
+
335
+ setattr(cls, "__asn1_root__", root)
336
+
337
+
338
+ # Due to https://github.com/python/mypy/issues/19731, we can't define an alias
339
+ # for `dataclass_transform` that conditionally points to `typing` or
340
+ # `typing_extensions` depending on the Python version (like we do for
341
+ # `get_type_hints`).
342
+ # We work around it by making the whole decorated class conditional on the
343
+ # Python version.
344
+ if sys.version_info < (3, 11):
345
+
346
+ @typing_extensions.dataclass_transform(kw_only_default=True)
347
+ def sequence(cls: type[U]) -> type[U]:
348
+ # We use `dataclasses.dataclass` to add an __init__ method
349
+ # to the class with keyword-only parameters.
350
+ if sys.version_info >= (3, 10):
351
+ dataclass_cls = dataclasses.dataclass(
352
+ repr=False,
353
+ eq=False,
354
+ # `match_args` was added in Python 3.10 and defaults
355
+ # to True
356
+ match_args=False,
357
+ # `kw_only` was added in Python 3.10 and defaults to
358
+ # False
359
+ kw_only=True,
360
+ )(cls)
361
+ else:
362
+ dataclass_cls = dataclasses.dataclass(
363
+ repr=False,
364
+ eq=False,
365
+ )(cls)
366
+ _register_asn1_sequence(dataclass_cls)
367
+ return dataclass_cls
368
+
369
+ @typing_extensions.dataclass_transform(kw_only_default=True)
370
+ def set(cls: type[U]) -> type[U]:
371
+ # We use `dataclasses.dataclass` to add an __init__ method
372
+ # to the class with keyword-only parameters.
373
+ if sys.version_info >= (3, 10):
374
+ dataclass_cls = dataclasses.dataclass(
375
+ repr=False,
376
+ eq=False,
377
+ # `match_args` was added in Python 3.10 and defaults
378
+ # to True
379
+ match_args=False,
380
+ # `kw_only` was added in Python 3.10 and defaults to
381
+ # False
382
+ kw_only=True,
383
+ )(cls)
384
+ else:
385
+ dataclass_cls = dataclasses.dataclass(
386
+ repr=False,
387
+ eq=False,
388
+ )(cls)
389
+ _register_asn1_set(dataclass_cls)
390
+ return dataclass_cls
391
+
392
+ else:
393
+
394
+ @typing.dataclass_transform(kw_only_default=True)
395
+ def sequence(cls: type[U]) -> type[U]:
396
+ # Only add an __init__ method, with keyword-only
397
+ # parameters.
398
+ dataclass_cls = dataclasses.dataclass(
399
+ repr=False,
400
+ eq=False,
401
+ match_args=False,
402
+ kw_only=True,
403
+ )(cls)
404
+ _register_asn1_sequence(dataclass_cls)
405
+ return dataclass_cls
406
+
407
+ @typing.dataclass_transform(kw_only_default=True)
408
+ def set(cls: type[U]) -> type[U]:
409
+ # Only add an __init__ method, with keyword-only
410
+ # parameters.
411
+ dataclass_cls = dataclasses.dataclass(
412
+ repr=False,
413
+ eq=False,
414
+ match_args=False,
415
+ kw_only=True,
416
+ )(cls)
417
+ _register_asn1_set(dataclass_cls)
418
+ return dataclass_cls
419
+
420
+
421
+ # TODO: replace with `Default[U]` once the min Python version is >= 3.12
422
+ @dataclasses.dataclass(frozen=True)
423
+ class Default(typing.Generic[U]):
424
+ value: U
425
+
426
+
427
+ SetOf = declarative_asn1.SetOf
428
+
429
+ Explicit = declarative_asn1.Encoding.Explicit
430
+ Implicit = declarative_asn1.Encoding.Implicit
431
+ Size = declarative_asn1.Size
432
+
433
+ PrintableString = declarative_asn1.PrintableString
434
+ IA5String = declarative_asn1.IA5String
435
+ UTCTime = declarative_asn1.UTCTime
436
+ GeneralizedTime = declarative_asn1.GeneralizedTime
437
+ BitString = declarative_asn1.BitString
438
+ TLV = declarative_asn1.Tlv
439
+ Null = declarative_asn1.Null
.venv/lib/python3.10/site-packages/cryptography/hazmat/backends/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+
10
+ def default_backend() -> Any:
11
+ from cryptography.hazmat.backends.openssl.backend import backend
12
+
13
+ return backend
.venv/lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.backends.openssl.backend import backend
8
+
9
+ __all__ = ["backend"]
.venv/lib/python3.10/site-packages/cryptography/hazmat/backends/openssl/backend.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from __future__ import annotations
6
+
7
+ from cryptography.hazmat.bindings._rust import openssl as rust_openssl
8
+ from cryptography.hazmat.bindings.openssl import binding
9
+ from cryptography.hazmat.primitives import hashes
10
+ from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding
11
+ from cryptography.hazmat.primitives.asymmetric import ec
12
+ from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
13
+ from cryptography.hazmat.primitives.asymmetric.padding import (
14
+ MGF1,
15
+ OAEP,
16
+ PSS,
17
+ PKCS1v15,
18
+ )
19
+ from cryptography.hazmat.primitives.ciphers import (
20
+ CipherAlgorithm,
21
+ )
22
+ from cryptography.hazmat.primitives.ciphers.algorithms import (
23
+ AES,
24
+ )
25
+ from cryptography.hazmat.primitives.ciphers.modes import (
26
+ CBC,
27
+ Mode,
28
+ )
29
+
30
+
31
+ class Backend:
32
+ """
33
+ OpenSSL API binding interfaces.
34
+ """
35
+
36
+ name = "openssl"
37
+
38
+ # TripleDES encryption is disallowed/deprecated throughout 2023 in
39
+ # FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA).
40
+ _fips_ciphers = (AES,)
41
+ # Sometimes SHA1 is still permissible. That logic is contained
42
+ # within the various *_supported methods.
43
+ _fips_hashes = (
44
+ hashes.SHA224,
45
+ hashes.SHA256,
46
+ hashes.SHA384,
47
+ hashes.SHA512,
48
+ hashes.SHA512_224,
49
+ hashes.SHA512_256,
50
+ hashes.SHA3_224,
51
+ hashes.SHA3_256,
52
+ hashes.SHA3_384,
53
+ hashes.SHA3_512,
54
+ hashes.SHAKE128,
55
+ hashes.SHAKE256,
56
+ )
57
+ _fips_ecdh_curves = (
58
+ ec.SECP224R1,
59
+ ec.SECP256R1,
60
+ ec.SECP384R1,
61
+ ec.SECP521R1,
62
+ )
63
+ _fips_rsa_min_key_size = 2048
64
+ _fips_rsa_min_public_exponent = 65537
65
+ _fips_dsa_min_modulus = 1 << 2048
66
+ _fips_dh_min_key_size = 2048
67
+ _fips_dh_min_modulus = 1 << _fips_dh_min_key_size
68
+
69
+ def __init__(self) -> None:
70
+ self._binding = binding.Binding()
71
+ self._ffi = self._binding.ffi
72
+ self._lib = self._binding.lib
73
+ self._fips_enabled = rust_openssl.is_fips_enabled()
74
+
75
+ def __repr__(self) -> str:
76
+ return (
77
+ f"<OpenSSLBackend(version: {self.openssl_version_text()}, "
78
+ f"FIPS: {self._fips_enabled}, "
79
+ f"Legacy: {rust_openssl._legacy_provider_loaded})>"
80
+ )
81
+
82
+ def openssl_assert(self, ok: bool) -> None:
83
+ return binding._openssl_assert(ok)
84
+
85
+ def _enable_fips(self) -> None:
86
+ # This function enables FIPS mode for OpenSSL 3.0.0 on installs that
87
+ # have the FIPS provider installed properly.
88
+ rust_openssl.enable_fips(rust_openssl._providers)
89
+ assert rust_openssl.is_fips_enabled()
90
+ self._fips_enabled = rust_openssl.is_fips_enabled()
91
+
92
+ def openssl_version_text(self) -> str:
93
+ """
94
+ Friendly string name of the loaded OpenSSL library. This is not
95
+ necessarily the same version as it was compiled against.
96
+
97
+ Example: OpenSSL 3.2.1 30 Jan 2024
98
+ """
99
+ return rust_openssl.openssl_version_text()
100
+
101
+ def openssl_version_number(self) -> int:
102
+ return rust_openssl.openssl_version()
103
+
104
+ def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
105
+ if self._fips_enabled and not isinstance(algorithm, self._fips_hashes):
106
+ return False
107
+
108
+ return rust_openssl.hashes.hash_supported(algorithm)
109
+
110
+ def signature_hash_supported(
111
+ self, algorithm: hashes.HashAlgorithm
112
+ ) -> bool:
113
+ # Dedicated check for hashing algorithm use in message digest for
114
+ # signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption).
115
+ if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
116
+ return False
117
+ return self.hash_supported(algorithm)
118
+
119
+ def scrypt_supported(self) -> bool:
120
+ if self._fips_enabled:
121
+ return False
122
+ else:
123
+ return hasattr(rust_openssl.kdf.Scrypt, "derive")
124
+
125
+ def argon2_supported(self) -> bool:
126
+ if self._fips_enabled:
127
+ return False
128
+ else:
129
+ return hasattr(rust_openssl.kdf.Argon2id, "derive")
130
+
131
+ def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
132
+ # FIPS mode still allows SHA1 for HMAC
133
+ if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
134
+ return True
135
+ if rust_openssl.CRYPTOGRAPHY_IS_AWSLC:
136
+ return isinstance(
137
+ algorithm,
138
+ (
139
+ hashes.MD5,
140
+ hashes.SHA1,
141
+ hashes.SHA224,
142
+ hashes.SHA256,
143
+ hashes.SHA384,
144
+ hashes.SHA512,
145
+ hashes.SHA512_224,
146
+ hashes.SHA512_256,
147
+ ),
148
+ )
149
+ return self.hash_supported(algorithm)
150
+
151
+ def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool:
152
+ if self._fips_enabled:
153
+ # FIPS mode requires AES. TripleDES is disallowed/deprecated in
154
+ # FIPS 140-3.
155
+ if not isinstance(cipher, self._fips_ciphers):
156
+ return False
157
+
158
+ return rust_openssl.ciphers.cipher_supported(cipher, mode)
159
+
160
+ def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
161
+ return self.hmac_supported(algorithm)
162
+
163
+ def _consume_errors(self) -> list[rust_openssl.OpenSSLError]:
164
+ return rust_openssl.capture_error_stack()
165
+
166
+ def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
167
+ if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
168
+ return False
169
+
170
+ return isinstance(
171
+ algorithm,
172
+ (
173
+ hashes.SHA1,
174
+ hashes.SHA224,
175
+ hashes.SHA256,
176
+ hashes.SHA384,
177
+ hashes.SHA512,
178
+ ),
179
+ )
180
+
181
+ def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool:
182
+ if isinstance(padding, PKCS1v15):
183
+ return True
184
+ elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
185
+ # FIPS 186-4 only allows salt length == digest length for PSS
186
+ # It is technically acceptable to set an explicit salt length
187
+ # equal to the digest length and this will incorrectly fail, but
188
+ # since we don't do that in the tests and this method is
189
+ # private, we'll ignore that until we need to do otherwise.
190
+ if (
191
+ self._fips_enabled
192
+ and padding._salt_length != PSS.DIGEST_LENGTH
193
+ ):
194
+ return False
195
+ return self.hash_supported(padding._mgf._algorithm)
196
+ elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
197
+ return self._oaep_hash_supported(
198
+ padding._mgf._algorithm
199
+ ) and self._oaep_hash_supported(padding._algorithm)
200
+ else:
201
+ return False
202
+
203
+ def rsa_encryption_supported(self, padding: AsymmetricPadding) -> bool:
204
+ if self._fips_enabled and isinstance(padding, PKCS1v15):
205
+ return False
206
+ else:
207
+ return self.rsa_padding_supported(padding)
208
+
209
+ def dsa_supported(self) -> bool:
210
+ return (
211
+ not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
212
+ and not self._fips_enabled
213
+ )
214
+
215
+ def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
216
+ if not self.dsa_supported():
217
+ return False
218
+ return self.signature_hash_supported(algorithm)
219
+
220
+ def cmac_algorithm_supported(self, algorithm) -> bool:
221
+ return self.cipher_supported(
222
+ algorithm, CBC(b"\x00" * algorithm.block_size)
223
+ )
224
+
225
+ def elliptic_curve_supported(self, curve: ec.EllipticCurve) -> bool:
226
+ if self._fips_enabled and not isinstance(
227
+ curve, self._fips_ecdh_curves
228
+ ):
229
+ return False
230
+
231
+ return rust_openssl.ec.curve_supported(curve)
232
+
233
+ def elliptic_curve_signature_algorithm_supported(
234
+ self,
235
+ signature_algorithm: ec.EllipticCurveSignatureAlgorithm,
236
+ curve: ec.EllipticCurve,
237
+ ) -> bool:
238
+ # We only support ECDSA right now.
239
+ if not isinstance(signature_algorithm, ec.ECDSA):
240
+ return False
241
+
242
+ return self.elliptic_curve_supported(curve) and (
243
+ isinstance(signature_algorithm.algorithm, asym_utils.Prehashed)
244
+ or self.hash_supported(signature_algorithm.algorithm)
245
+ )
246
+
247
+ def elliptic_curve_exchange_algorithm_supported(
248
+ self, algorithm: ec.ECDH, curve: ec.EllipticCurve
249
+ ) -> bool:
250
+ return self.elliptic_curve_supported(curve) and isinstance(
251
+ algorithm, ec.ECDH
252
+ )
253
+
254
+ def dh_supported(self) -> bool:
255
+ return (
256
+ not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
257
+ and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC
258
+ )
259
+
260
+ def dh_x942_serialization_supported(self) -> bool:
261
+ return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1
262
+
263
+ def x25519_supported(self) -> bool:
264
+ return not self._fips_enabled
265
+
266
+ def x448_supported(self) -> bool:
267
+ if self._fips_enabled:
268
+ return False
269
+ return (
270
+ not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL
271
+ and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
272
+ and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC
273
+ )
274
+
275
+ def mlkem_supported(self) -> bool:
276
+ return (
277
+ rust_openssl.CRYPTOGRAPHY_IS_AWSLC
278
+ or rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
279
+ )
280
+
281
+ def mldsa_supported(self) -> bool:
282
+ return (
283
+ rust_openssl.CRYPTOGRAPHY_IS_AWSLC
284
+ or rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
285
+ )
286
+
287
+ def ed25519_supported(self) -> bool:
288
+ return True
289
+
290
+ def ed448_supported(self) -> bool:
291
+ return (
292
+ not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL
293
+ and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL
294
+ and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC
295
+ )
296
+
297
+ def ecdsa_deterministic_supported(self) -> bool:
298
+ return (
299
+ rust_openssl.CRYPTOGRAPHY_OPENSSL_320_OR_GREATER
300
+ and not self._fips_enabled
301
+ )
302
+
303
+ def poly1305_supported(self) -> bool:
304
+ return not self._fips_enabled
305
+
306
+ def pkcs7_supported(self) -> bool:
307
+ return True
308
+
309
+
310
+ backend = Backend()
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives import padding
8
+ from cryptography.hazmat.primitives._serialization import (
9
+ KeySerializationEncryptionBuilder,
10
+ )
11
+ from cryptography.utils import Buffer
12
+
13
+ class PKCS7PaddingContext(padding.PaddingContext):
14
+ def __init__(self, block_size: int) -> None: ...
15
+ def update(self, data: Buffer) -> bytes: ...
16
+ def finalize(self) -> bytes: ...
17
+
18
+ class ANSIX923PaddingContext(padding.PaddingContext):
19
+ def __init__(self, block_size: int) -> None: ...
20
+ def update(self, data: Buffer) -> bytes: ...
21
+ def finalize(self) -> bytes: ...
22
+
23
+ class PKCS7UnpaddingContext(padding.PaddingContext):
24
+ def __init__(self, block_size: int) -> None: ...
25
+ def update(self, data: Buffer) -> bytes: ...
26
+ def finalize(self) -> bytes: ...
27
+
28
+ class ANSIX923UnpaddingContext(padding.PaddingContext):
29
+ def __init__(self, block_size: int) -> None: ...
30
+ def update(self, data: Buffer) -> bytes: ...
31
+ def finalize(self) -> bytes: ...
32
+
33
+ class Encoding:
34
+ PEM: typing.ClassVar[Encoding]
35
+ DER: typing.ClassVar[Encoding]
36
+ OpenSSH: typing.ClassVar[Encoding]
37
+ Raw: typing.ClassVar[Encoding]
38
+ X962: typing.ClassVar[Encoding]
39
+ SMIME: typing.ClassVar[Encoding]
40
+
41
+ class PrivateFormat:
42
+ PKCS8: typing.ClassVar[PrivateFormat]
43
+ TraditionalOpenSSL: typing.ClassVar[PrivateFormat]
44
+ Raw: typing.ClassVar[PrivateFormat]
45
+ OpenSSH: typing.ClassVar[PrivateFormat]
46
+ PKCS12: typing.ClassVar[PrivateFormat]
47
+ def encryption_builder(self) -> KeySerializationEncryptionBuilder: ...
48
+
49
+ class PublicFormat:
50
+ SubjectPublicKeyInfo: typing.ClassVar[PublicFormat]
51
+ PKCS1: typing.ClassVar[PublicFormat]
52
+ OpenSSH: typing.ClassVar[PublicFormat]
53
+ Raw: typing.ClassVar[PublicFormat]
54
+ CompressedPoint: typing.ClassVar[PublicFormat]
55
+ UncompressedPoint: typing.ClassVar[PublicFormat]
56
+
57
+ class ParameterFormat:
58
+ PKCS3: typing.ClassVar[ParameterFormat]
59
+
60
+ class ObjectIdentifier:
61
+ def __init__(self, value: str) -> None: ...
62
+ @property
63
+ def dotted_string(self) -> str: ...
64
+ @property
65
+ def _name(self) -> str: ...
66
+
67
+ T = typing.TypeVar("T")
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ lib: typing.Any
8
+ ffi: typing.Any
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ def decode_dss_signature(signature: bytes) -> tuple[int, int]: ...
6
+ def encode_dss_signature(r: int, s: int) -> bytes: ...
7
+ def parse_spki_for_data(data: bytes) -> bytes: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import datetime
6
+ import typing
7
+
8
+ def decode_der(cls: type, value: bytes) -> typing.Any: ...
9
+ def encode_der(value: typing.Any) -> bytes: ...
10
+ def non_root_python_to_rust(cls: type) -> Type: ...
11
+
12
+ # Type is a Rust enum with tuple variants. For now, we express the type
13
+ # annotations like this:
14
+ class Type:
15
+ Sequence: typing.ClassVar[type]
16
+ SequenceOf: typing.ClassVar[type]
17
+ Set: typing.ClassVar[type]
18
+ SetOf: typing.ClassVar[type]
19
+ Option: typing.ClassVar[type]
20
+ Choice: typing.ClassVar[type]
21
+ PyBool: typing.ClassVar[type]
22
+ PyInt: typing.ClassVar[type]
23
+ PyBytes: typing.ClassVar[type]
24
+ PyStr: typing.ClassVar[type]
25
+
26
+ class Annotation:
27
+ default: typing.Any | None
28
+ encoding: Encoding | None
29
+ size: Size | None
30
+ def __new__(
31
+ cls,
32
+ default: typing.Any | None = None,
33
+ encoding: Encoding | None = None,
34
+ size: Size | None = None,
35
+ ) -> Annotation: ...
36
+ def is_empty(self) -> bool: ...
37
+
38
+ # Encoding is a Rust enum with tuple variants. For now, we express the type
39
+ # annotations like this:
40
+ class Encoding:
41
+ Implicit: typing.ClassVar[type]
42
+ Explicit: typing.ClassVar[type]
43
+
44
+ class Size:
45
+ min: int
46
+ max: int | None
47
+
48
+ def __new__(cls, min: int, max: int | None) -> Size: ...
49
+ @staticmethod
50
+ def exact(n: int) -> Size: ...
51
+
52
+ class AnnotatedType:
53
+ inner: Type
54
+ annotation: Annotation
55
+
56
+ def __new__(cls, inner: Type, annotation: Annotation) -> AnnotatedType: ...
57
+
58
+ class AnnotatedTypeObject:
59
+ annotated_type: AnnotatedType
60
+ value: typing.Any
61
+
62
+ def __new__(
63
+ cls, annotated_type: AnnotatedType, value: typing.Any
64
+ ) -> AnnotatedTypeObject: ...
65
+
66
+ class Variant:
67
+ python_class: type
68
+ ann_type: AnnotatedType
69
+ tag_name: str | None
70
+
71
+ def __new__(
72
+ cls,
73
+ python_class: type,
74
+ ann_type: AnnotatedType,
75
+ tag_name: str | None,
76
+ ) -> Variant: ...
77
+
78
+ class PrintableString:
79
+ def __new__(cls, inner: str) -> PrintableString: ...
80
+ def __repr__(self) -> str: ...
81
+ def __eq__(self, other: object) -> bool: ...
82
+ def as_str(self) -> str: ...
83
+
84
+ class IA5String:
85
+ def __new__(cls, inner: str) -> IA5String: ...
86
+ def __repr__(self) -> str: ...
87
+ def __eq__(self, other: object) -> bool: ...
88
+ def as_str(self) -> str: ...
89
+
90
+ class UTCTime:
91
+ def __new__(cls, inner: datetime.datetime) -> UTCTime: ...
92
+ def __repr__(self) -> str: ...
93
+ def __eq__(self, other: object) -> bool: ...
94
+ def as_datetime(self) -> datetime.datetime: ...
95
+
96
+ class GeneralizedTime:
97
+ def __new__(cls, inner: datetime.datetime) -> GeneralizedTime: ...
98
+ def __repr__(self) -> str: ...
99
+ def __eq__(self, other: object) -> bool: ...
100
+ def as_datetime(self) -> datetime.datetime: ...
101
+
102
+ class BitString:
103
+ def __new__(cls, data: bytes, padding_bits: int) -> BitString: ...
104
+ def __repr__(self) -> str: ...
105
+ def __eq__(self, other: object) -> bool: ...
106
+ def as_bytes(self) -> bytes: ...
107
+ def padding_bits(self) -> int: ...
108
+
109
+ class Tlv:
110
+ @property
111
+ def tag_bytes(self) -> bytes: ...
112
+ @property
113
+ def data(self) -> memoryview: ...
114
+ def parse(self, cls: type): ...
115
+
116
+ T = typing.TypeVar("T")
117
+
118
+ class SetOf(typing.Generic[T]):
119
+ def __new__(cls, inner: list[T]) -> SetOf[T]: ...
120
+ def as_list(self) -> list[T]: ...
121
+ def __eq__(self, other: object) -> bool: ...
122
+ def __repr__(self) -> str: ...
123
+
124
+ class Null:
125
+ def __new__(cls) -> Null: ...
126
+ def __repr__(self) -> str: ...
127
+ def __eq__(self, other: object) -> bool: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ class _Reasons:
6
+ BACKEND_MISSING_INTERFACE: _Reasons
7
+ UNSUPPORTED_HASH: _Reasons
8
+ UNSUPPORTED_CIPHER: _Reasons
9
+ UNSUPPORTED_PADDING: _Reasons
10
+ UNSUPPORTED_MGF: _Reasons
11
+ UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons
12
+ UNSUPPORTED_ELLIPTIC_CURVE: _Reasons
13
+ UNSUPPORTED_SERIALIZATION: _Reasons
14
+ UNSUPPORTED_X509: _Reasons
15
+ UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons
16
+ UNSUPPORTED_DIFFIE_HELLMAN: _Reasons
17
+ UNSUPPORTED_MAC: _Reasons
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import datetime
6
+ from collections.abc import Iterator
7
+
8
+ from cryptography import x509
9
+ from cryptography.hazmat.primitives import hashes, serialization
10
+ from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
11
+ from cryptography.x509 import ocsp
12
+
13
+ class OCSPRequest:
14
+ @property
15
+ def issuer_key_hash(self) -> bytes: ...
16
+ @property
17
+ def issuer_name_hash(self) -> bytes: ...
18
+ @property
19
+ def hash_algorithm(self) -> hashes.HashAlgorithm: ...
20
+ @property
21
+ def serial_number(self) -> int: ...
22
+ def public_bytes(self, encoding: serialization.Encoding) -> bytes: ...
23
+ @property
24
+ def extensions(self) -> x509.Extensions: ...
25
+
26
+ class OCSPResponse:
27
+ @property
28
+ def responses(self) -> Iterator[OCSPSingleResponse]: ...
29
+ @property
30
+ def response_status(self) -> ocsp.OCSPResponseStatus: ...
31
+ @property
32
+ def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ...
33
+ @property
34
+ def signature_hash_algorithm(
35
+ self,
36
+ ) -> hashes.HashAlgorithm | None: ...
37
+ @property
38
+ def signature(self) -> bytes: ...
39
+ @property
40
+ def tbs_response_bytes(self) -> bytes: ...
41
+ @property
42
+ def certificates(self) -> list[x509.Certificate]: ...
43
+ @property
44
+ def responder_key_hash(self) -> bytes | None: ...
45
+ @property
46
+ def responder_name(self) -> x509.Name | None: ...
47
+ @property
48
+ def produced_at(self) -> datetime.datetime: ...
49
+ @property
50
+ def produced_at_utc(self) -> datetime.datetime: ...
51
+ @property
52
+ def certificate_status(self) -> ocsp.OCSPCertStatus: ...
53
+ @property
54
+ def revocation_time(self) -> datetime.datetime | None: ...
55
+ @property
56
+ def revocation_time_utc(self) -> datetime.datetime | None: ...
57
+ @property
58
+ def revocation_reason(self) -> x509.ReasonFlags | None: ...
59
+ @property
60
+ def this_update(self) -> datetime.datetime: ...
61
+ @property
62
+ def this_update_utc(self) -> datetime.datetime: ...
63
+ @property
64
+ def next_update(self) -> datetime.datetime | None: ...
65
+ @property
66
+ def next_update_utc(self) -> datetime.datetime | None: ...
67
+ @property
68
+ def issuer_key_hash(self) -> bytes: ...
69
+ @property
70
+ def issuer_name_hash(self) -> bytes: ...
71
+ @property
72
+ def hash_algorithm(self) -> hashes.HashAlgorithm: ...
73
+ @property
74
+ def serial_number(self) -> int: ...
75
+ @property
76
+ def extensions(self) -> x509.Extensions: ...
77
+ @property
78
+ def single_extensions(self) -> x509.Extensions: ...
79
+ def public_bytes(self, encoding: serialization.Encoding) -> bytes: ...
80
+
81
+ class OCSPSingleResponse:
82
+ @property
83
+ def certificate_status(self) -> ocsp.OCSPCertStatus: ...
84
+ @property
85
+ def revocation_time(self) -> datetime.datetime | None: ...
86
+ @property
87
+ def revocation_time_utc(self) -> datetime.datetime | None: ...
88
+ @property
89
+ def revocation_reason(self) -> x509.ReasonFlags | None: ...
90
+ @property
91
+ def this_update(self) -> datetime.datetime: ...
92
+ @property
93
+ def this_update_utc(self) -> datetime.datetime: ...
94
+ @property
95
+ def next_update(self) -> datetime.datetime | None: ...
96
+ @property
97
+ def next_update_utc(self) -> datetime.datetime | None: ...
98
+ @property
99
+ def issuer_key_hash(self) -> bytes: ...
100
+ @property
101
+ def issuer_name_hash(self) -> bytes: ...
102
+ @property
103
+ def hash_algorithm(self) -> hashes.HashAlgorithm: ...
104
+ @property
105
+ def serial_number(self) -> int: ...
106
+
107
+ def load_der_ocsp_request(data: bytes) -> ocsp.OCSPRequest: ...
108
+ def load_der_ocsp_response(data: bytes) -> ocsp.OCSPResponse: ...
109
+ def create_ocsp_request(
110
+ builder: ocsp.OCSPRequestBuilder,
111
+ ) -> ocsp.OCSPRequest: ...
112
+ def create_ocsp_response(
113
+ status: ocsp.OCSPResponseStatus,
114
+ builder: ocsp.OCSPResponseBuilder | None,
115
+ private_key: PrivateKeyTypes | None,
116
+ hash_algorithm: hashes.HashAlgorithm | None,
117
+ ) -> ocsp.OCSPResponse: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.bindings._rust.openssl import (
8
+ aead,
9
+ ciphers,
10
+ cmac,
11
+ dh,
12
+ dsa,
13
+ ec,
14
+ ed448,
15
+ ed25519,
16
+ hashes,
17
+ hmac,
18
+ hpke,
19
+ kdf,
20
+ keys,
21
+ mldsa,
22
+ mlkem,
23
+ poly1305,
24
+ rsa,
25
+ x448,
26
+ x25519,
27
+ )
28
+
29
+ __all__ = [
30
+ "aead",
31
+ "ciphers",
32
+ "cmac",
33
+ "dh",
34
+ "dsa",
35
+ "ec",
36
+ "ed448",
37
+ "ed25519",
38
+ "hashes",
39
+ "hmac",
40
+ "hpke",
41
+ "kdf",
42
+ "keys",
43
+ "mldsa",
44
+ "mlkem",
45
+ "openssl_version",
46
+ "openssl_version_text",
47
+ "poly1305",
48
+ "raise_openssl_error",
49
+ "rsa",
50
+ "x448",
51
+ "x25519",
52
+ ]
53
+
54
+ CRYPTOGRAPHY_IS_LIBRESSL: bool
55
+ CRYPTOGRAPHY_IS_BORINGSSL: bool
56
+ CRYPTOGRAPHY_IS_AWSLC: bool
57
+ CRYPTOGRAPHY_OPENSSL_309_OR_GREATER: bool
58
+ CRYPTOGRAPHY_OPENSSL_320_OR_GREATER: bool
59
+ CRYPTOGRAPHY_OPENSSL_330_OR_GREATER: bool
60
+ CRYPTOGRAPHY_OPENSSL_350_OR_GREATER: bool
61
+
62
+ class Providers: ...
63
+
64
+ _legacy_provider_loaded: bool
65
+ _providers: Providers
66
+
67
+ def openssl_version() -> int: ...
68
+ def openssl_version_text() -> str: ...
69
+ def raise_openssl_error() -> typing.NoReturn: ...
70
+ def capture_error_stack() -> list[OpenSSLError]: ...
71
+ def is_fips_enabled() -> bool: ...
72
+ def enable_fips(providers: Providers) -> None: ...
73
+
74
+ class OpenSSLError:
75
+ @property
76
+ def lib(self) -> int: ...
77
+ @property
78
+ def reason(self) -> int: ...
79
+ @property
80
+ def reason_text(self) -> bytes: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from collections.abc import Sequence
6
+
7
+ from cryptography.utils import Buffer
8
+
9
+ class AESGCM:
10
+ def __init__(self, key: Buffer) -> None: ...
11
+ @staticmethod
12
+ def generate_key(bit_length: int) -> bytes: ...
13
+ def encrypt(
14
+ self,
15
+ nonce: Buffer,
16
+ data: Buffer,
17
+ associated_data: Buffer | None,
18
+ ) -> bytes: ...
19
+ def decrypt(
20
+ self,
21
+ nonce: Buffer,
22
+ data: Buffer,
23
+ associated_data: Buffer | None,
24
+ ) -> bytes: ...
25
+ def encrypt_into(
26
+ self,
27
+ nonce: Buffer,
28
+ data: Buffer,
29
+ associated_data: Buffer | None,
30
+ buf: Buffer,
31
+ ) -> int: ...
32
+ def decrypt_into(
33
+ self,
34
+ nonce: Buffer,
35
+ data: Buffer,
36
+ associated_data: Buffer | None,
37
+ buf: Buffer,
38
+ ) -> int: ...
39
+
40
+ class ChaCha20Poly1305:
41
+ def __init__(self, key: Buffer) -> None: ...
42
+ @staticmethod
43
+ def generate_key() -> bytes: ...
44
+ def encrypt(
45
+ self,
46
+ nonce: Buffer,
47
+ data: Buffer,
48
+ associated_data: Buffer | None,
49
+ ) -> bytes: ...
50
+ def encrypt_into(
51
+ self,
52
+ nonce: Buffer,
53
+ data: Buffer,
54
+ associated_data: Buffer | None,
55
+ buf: Buffer,
56
+ ) -> int: ...
57
+ def decrypt(
58
+ self,
59
+ nonce: Buffer,
60
+ data: Buffer,
61
+ associated_data: Buffer | None,
62
+ ) -> bytes: ...
63
+ def decrypt_into(
64
+ self,
65
+ nonce: Buffer,
66
+ data: Buffer,
67
+ associated_data: Buffer | None,
68
+ buf: Buffer,
69
+ ) -> int: ...
70
+
71
+ class AESCCM:
72
+ def __init__(self, key: Buffer, tag_length: int = 16) -> None: ...
73
+ @staticmethod
74
+ def generate_key(bit_length: int) -> bytes: ...
75
+ def encrypt(
76
+ self,
77
+ nonce: Buffer,
78
+ data: Buffer,
79
+ associated_data: Buffer | None,
80
+ ) -> bytes: ...
81
+ def encrypt_into(
82
+ self,
83
+ nonce: Buffer,
84
+ data: Buffer,
85
+ associated_data: Buffer | None,
86
+ buf: Buffer,
87
+ ) -> int: ...
88
+ def decrypt(
89
+ self,
90
+ nonce: Buffer,
91
+ data: Buffer,
92
+ associated_data: Buffer | None,
93
+ ) -> bytes: ...
94
+ def decrypt_into(
95
+ self,
96
+ nonce: Buffer,
97
+ data: Buffer,
98
+ associated_data: Buffer | None,
99
+ buf: Buffer,
100
+ ) -> int: ...
101
+
102
+ class AESSIV:
103
+ def __init__(self, key: Buffer) -> None: ...
104
+ @staticmethod
105
+ def generate_key(bit_length: int) -> bytes: ...
106
+ def encrypt(
107
+ self,
108
+ data: Buffer,
109
+ associated_data: Sequence[Buffer] | None,
110
+ ) -> bytes: ...
111
+ def encrypt_into(
112
+ self,
113
+ data: Buffer,
114
+ associated_data: Sequence[Buffer] | None,
115
+ buf: Buffer,
116
+ ) -> int: ...
117
+ def decrypt(
118
+ self,
119
+ data: Buffer,
120
+ associated_data: Sequence[Buffer] | None,
121
+ ) -> bytes: ...
122
+ def decrypt_into(
123
+ self,
124
+ data: Buffer,
125
+ associated_data: Sequence[Buffer] | None,
126
+ buf: Buffer,
127
+ ) -> int: ...
128
+
129
+ class AESOCB3:
130
+ def __init__(self, key: Buffer) -> None: ...
131
+ @staticmethod
132
+ def generate_key(bit_length: int) -> bytes: ...
133
+ def encrypt(
134
+ self,
135
+ nonce: Buffer,
136
+ data: Buffer,
137
+ associated_data: Buffer | None,
138
+ ) -> bytes: ...
139
+ def encrypt_into(
140
+ self,
141
+ nonce: Buffer,
142
+ data: Buffer,
143
+ associated_data: Buffer | None,
144
+ buf: Buffer,
145
+ ) -> int: ...
146
+ def decrypt(
147
+ self,
148
+ nonce: Buffer,
149
+ data: Buffer,
150
+ associated_data: Buffer | None,
151
+ ) -> bytes: ...
152
+ def decrypt_into(
153
+ self,
154
+ nonce: Buffer,
155
+ data: Buffer,
156
+ associated_data: Buffer | None,
157
+ buf: Buffer,
158
+ ) -> int: ...
159
+
160
+ class AESGCMSIV:
161
+ def __init__(self, key: Buffer) -> None: ...
162
+ @staticmethod
163
+ def generate_key(bit_length: int) -> bytes: ...
164
+ def encrypt(
165
+ self,
166
+ nonce: Buffer,
167
+ data: Buffer,
168
+ associated_data: Buffer | None,
169
+ ) -> bytes: ...
170
+ def encrypt_into(
171
+ self,
172
+ nonce: Buffer,
173
+ data: Buffer,
174
+ associated_data: Buffer | None,
175
+ buf: Buffer,
176
+ ) -> int: ...
177
+ def decrypt(
178
+ self,
179
+ nonce: Buffer,
180
+ data: Buffer,
181
+ associated_data: Buffer | None,
182
+ ) -> bytes: ...
183
+ def decrypt_into(
184
+ self,
185
+ nonce: Buffer,
186
+ data: Buffer,
187
+ associated_data: Buffer | None,
188
+ buf: Buffer,
189
+ ) -> int: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives import ciphers
8
+ from cryptography.hazmat.primitives.ciphers import modes
9
+
10
+ @typing.overload
11
+ def create_encryption_ctx(
12
+ algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag
13
+ ) -> ciphers.AEADEncryptionContext: ...
14
+ @typing.overload
15
+ def create_encryption_ctx(
16
+ algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None
17
+ ) -> ciphers.CipherContext: ...
18
+ @typing.overload
19
+ def create_decryption_ctx(
20
+ algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag
21
+ ) -> ciphers.AEADDecryptionContext: ...
22
+ @typing.overload
23
+ def create_decryption_ctx(
24
+ algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None
25
+ ) -> ciphers.CipherContext: ...
26
+ def cipher_supported(
27
+ algorithm: ciphers.CipherAlgorithm, mode: modes.Mode
28
+ ) -> bool: ...
29
+ def _advance(
30
+ ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int
31
+ ) -> None: ...
32
+ def _advance_aad(
33
+ ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int
34
+ ) -> None: ...
35
+
36
+ class CipherContext: ...
37
+ class AEADEncryptionContext: ...
38
+ class AEADDecryptionContext: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives import ciphers
8
+
9
+ class CMAC:
10
+ def __init__(
11
+ self,
12
+ algorithm: ciphers.BlockCipherAlgorithm,
13
+ backend: typing.Any = None,
14
+ ) -> None: ...
15
+ def update(self, data: bytes) -> None: ...
16
+ def finalize(self) -> bytes: ...
17
+ def verify(self, signature: bytes) -> None: ...
18
+ def copy(self) -> CMAC: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives.asymmetric import dh
8
+
9
+ MIN_MODULUS_SIZE: int
10
+
11
+ class DHPrivateKey: ...
12
+ class DHPublicKey: ...
13
+ class DHParameters: ...
14
+
15
+ class DHPrivateNumbers:
16
+ def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ...
17
+ def private_key(self, backend: typing.Any = None) -> dh.DHPrivateKey: ...
18
+ @property
19
+ def x(self) -> int: ...
20
+ @property
21
+ def public_numbers(self) -> DHPublicNumbers: ...
22
+
23
+ class DHPublicNumbers:
24
+ def __init__(
25
+ self, y: int, parameter_numbers: DHParameterNumbers
26
+ ) -> None: ...
27
+ def public_key(self, backend: typing.Any = None) -> dh.DHPublicKey: ...
28
+ @property
29
+ def y(self) -> int: ...
30
+ @property
31
+ def parameter_numbers(self) -> DHParameterNumbers: ...
32
+
33
+ class DHParameterNumbers:
34
+ def __init__(self, p: int, g: int, q: int | None = None) -> None: ...
35
+ def parameters(self, backend: typing.Any = None) -> dh.DHParameters: ...
36
+ @property
37
+ def p(self) -> int: ...
38
+ @property
39
+ def g(self) -> int: ...
40
+ @property
41
+ def q(self) -> int | None: ...
42
+
43
+ def generate_parameters(
44
+ generator: int, key_size: int, backend: typing.Any = None
45
+ ) -> dh.DHParameters: ...
46
+ def from_pem_parameters(
47
+ data: bytes, backend: typing.Any = None
48
+ ) -> dh.DHParameters: ...
49
+ def from_der_parameters(
50
+ data: bytes, backend: typing.Any = None
51
+ ) -> dh.DHParameters: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives.asymmetric import dsa
8
+
9
+ class DSAPrivateKey: ...
10
+ class DSAPublicKey: ...
11
+ class DSAParameters: ...
12
+
13
+ class DSAPrivateNumbers:
14
+ def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ...
15
+ @property
16
+ def x(self) -> int: ...
17
+ @property
18
+ def public_numbers(self) -> DSAPublicNumbers: ...
19
+ def private_key(self, backend: typing.Any = None) -> dsa.DSAPrivateKey: ...
20
+
21
+ class DSAPublicNumbers:
22
+ def __init__(
23
+ self, y: int, parameter_numbers: DSAParameterNumbers
24
+ ) -> None: ...
25
+ @property
26
+ def y(self) -> int: ...
27
+ @property
28
+ def parameter_numbers(self) -> DSAParameterNumbers: ...
29
+ def public_key(self, backend: typing.Any = None) -> dsa.DSAPublicKey: ...
30
+
31
+ class DSAParameterNumbers:
32
+ def __init__(self, p: int, q: int, g: int) -> None: ...
33
+ @property
34
+ def p(self) -> int: ...
35
+ @property
36
+ def q(self) -> int: ...
37
+ @property
38
+ def g(self) -> int: ...
39
+ def parameters(self, backend: typing.Any = None) -> dsa.DSAParameters: ...
40
+
41
+ def generate_parameters(key_size: int) -> dsa.DSAParameters: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives.asymmetric import ec
8
+
9
+ class ECPrivateKey: ...
10
+ class ECPublicKey: ...
11
+
12
+ class EllipticCurvePrivateNumbers:
13
+ def __init__(
14
+ self, private_value: int, public_numbers: EllipticCurvePublicNumbers
15
+ ) -> None: ...
16
+ def private_key(
17
+ self, backend: typing.Any = None
18
+ ) -> ec.EllipticCurvePrivateKey: ...
19
+ @property
20
+ def private_value(self) -> int: ...
21
+ @property
22
+ def public_numbers(self) -> EllipticCurvePublicNumbers: ...
23
+
24
+ class EllipticCurvePublicNumbers:
25
+ def __init__(self, x: int, y: int, curve: ec.EllipticCurve) -> None: ...
26
+ def public_key(
27
+ self, backend: typing.Any = None
28
+ ) -> ec.EllipticCurvePublicKey: ...
29
+ @property
30
+ def x(self) -> int: ...
31
+ @property
32
+ def y(self) -> int: ...
33
+ @property
34
+ def curve(self) -> ec.EllipticCurve: ...
35
+ def __eq__(self, other: object) -> bool: ...
36
+
37
+ def curve_supported(curve: ec.EllipticCurve) -> bool: ...
38
+ def generate_private_key(
39
+ curve: ec.EllipticCurve, backend: typing.Any = None
40
+ ) -> ec.EllipticCurvePrivateKey: ...
41
+ def from_private_numbers(
42
+ numbers: ec.EllipticCurvePrivateNumbers,
43
+ ) -> ec.EllipticCurvePrivateKey: ...
44
+ def from_public_numbers(
45
+ numbers: ec.EllipticCurvePublicNumbers,
46
+ ) -> ec.EllipticCurvePublicKey: ...
47
+ def from_public_bytes(
48
+ curve: ec.EllipticCurve, data: bytes
49
+ ) -> ec.EllipticCurvePublicKey: ...
50
+ def derive_private_key(
51
+ private_value: int, curve: ec.EllipticCurve
52
+ ) -> ec.EllipticCurvePrivateKey: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from cryptography.hazmat.primitives.asymmetric import ed25519
6
+ from cryptography.utils import Buffer
7
+
8
+ class Ed25519PrivateKey: ...
9
+ class Ed25519PublicKey: ...
10
+
11
+ def generate_key() -> ed25519.Ed25519PrivateKey: ...
12
+ def from_private_bytes(data: Buffer) -> ed25519.Ed25519PrivateKey: ...
13
+ def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ from cryptography.hazmat.primitives.asymmetric import ed448
6
+ from cryptography.utils import Buffer
7
+
8
+ class Ed448PrivateKey: ...
9
+ class Ed448PublicKey: ...
10
+
11
+ def generate_key() -> ed448.Ed448PrivateKey: ...
12
+ def from_private_bytes(data: Buffer) -> ed448.Ed448PrivateKey: ...
13
+ def from_public_bytes(data: bytes) -> ed448.Ed448PublicKey: ...
.venv/lib/python3.10/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ import typing
6
+
7
+ from cryptography.hazmat.primitives import hashes
8
+ from cryptography.utils import Buffer
9
+
10
+ class Hash(hashes.HashContext):
11
+ def __init__(
12
+ self, algorithm: hashes.HashAlgorithm, backend: typing.Any = None
13
+ ) -> None: ...
14
+ @property
15
+ def algorithm(self) -> hashes.HashAlgorithm: ...
16
+ def update(self, data: Buffer) -> None: ...
17
+ def finalize(self) -> bytes: ...
18
+ def copy(self) -> Hash: ...
19
+ @staticmethod
20
+ def hash(algorithm: hashes.HashAlgorithm, data: Buffer) -> bytes: ...
21
+
22
+ def hash_supported(algorithm: hashes.HashAlgorithm) -> bool: ...
23
+
24
+ class XOFHash:
25
+ def __init__(self, algorithm: hashes.ExtendableOutputFunction) -> None: ...
26
+ @property
27
+ def algorithm(self) -> hashes.ExtendableOutputFunction: ...
28
+ def update(self, data: Buffer) -> None: ...
29
+ def squeeze(self, length: int) -> bytes: ...
30
+ def copy(self) -> XOFHash: ...