vercel-queue-bundle 0.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. vercel/queue/__init__.py +8 -0
  2. vercel/queue/__main__.py +10 -0
  3. vercel/queue/_internal/__init__.py +1 -0
  4. vercel/queue/_internal/api_async.py +219 -0
  5. vercel/queue/_internal/api_common.py +104 -0
  6. vercel/queue/_internal/api_sync.py +137 -0
  7. vercel/queue/_internal/asgi.py +145 -0
  8. vercel/queue/_internal/asynctools.py +40 -0
  9. vercel/queue/_internal/cli.py +313 -0
  10. vercel/queue/_internal/client.py +1109 -0
  11. vercel/queue/_internal/client_sync.py +432 -0
  12. vercel/queue/_internal/config.py +160 -0
  13. vercel/queue/_internal/constants.py +50 -0
  14. vercel/queue/_internal/devserver.py +205 -0
  15. vercel/queue/_internal/embedded.py +1900 -0
  16. vercel/queue/_internal/errors.py +262 -0
  17. vercel/queue/_internal/http.py +634 -0
  18. vercel/queue/_internal/lease.py +1007 -0
  19. vercel/queue/_internal/log.py +143 -0
  20. vercel/queue/_internal/messages.py +122 -0
  21. vercel/queue/_internal/multipart.py +255 -0
  22. vercel/queue/_internal/names.py +101 -0
  23. vercel/queue/_internal/polling.py +200 -0
  24. vercel/queue/_internal/push.py +246 -0
  25. vercel/queue/_internal/response.py +111 -0
  26. vercel/queue/_internal/retry.py +86 -0
  27. vercel/queue/_internal/streams.py +313 -0
  28. vercel/queue/_internal/subscribers.py +1025 -0
  29. vercel/queue/_internal/transports.py +363 -0
  30. vercel/queue/_internal/types.py +300 -0
  31. vercel/queue/_internal/typeutils.py +203 -0
  32. vercel/queue/_vendor/LICENSE.python-multipart.txt +202 -0
  33. vercel/queue/_vendor/__init__.py +1 -0
  34. vercel/queue/_vendor/multipart/__init__.py +38 -0
  35. vercel/queue/_vendor/multipart/decoders.py +1 -0
  36. vercel/queue/_vendor/multipart/exceptions.py +1 -0
  37. vercel/queue/_vendor/multipart/multipart.py +1 -0
  38. vercel/queue/_vendor/python_multipart/__init__.py +35 -0
  39. vercel/queue/_vendor/python_multipart/decoders.py +185 -0
  40. vercel/queue/_vendor/python_multipart/exceptions.py +34 -0
  41. vercel/queue/_vendor/python_multipart/multipart.py +1925 -0
  42. vercel/queue/devserver.py +24 -0
  43. vercel/queue/embedded.py +50 -0
  44. vercel/queue/py.typed +1 -0
  45. vercel/queue/sync.py +8 -0
  46. vercel/queue/testing/__init__.py +14 -0
  47. vercel/queue/testing/pytest.py +42 -0
  48. vercel/queue/testing/state.py +32 -0
  49. vercel/queue/version.py +3 -0
  50. vercel_queue_bundle-0.7.1.dist-info/METADATA +683 -0
  51. vercel_queue_bundle-0.7.1.dist-info/RECORD +54 -0
  52. vercel_queue_bundle-0.7.1.dist-info/WHEEL +4 -0
  53. vercel_queue_bundle-0.7.1.dist-info/licenses/LICENSE +21 -0
  54. vercel_queue_bundle-0.7.1.dist-info/licenses/vercel/queue/_vendor/LICENSE.python-multipart.txt +202 -0
@@ -0,0 +1,203 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import (
4
+ Annotated,
5
+ Any,
6
+ ClassVar,
7
+ Final,
8
+ ForwardRef,
9
+ Literal,
10
+ TypeVar,
11
+ Union,
12
+ get_args,
13
+ get_origin,
14
+ get_type_hints,
15
+ )
16
+
17
+ import inspect
18
+ import types
19
+ from dataclasses import dataclass
20
+ from types import FrameType
21
+
22
+ _T = TypeVar("_T")
23
+ _TYPE_VAR_TYPE = type(_T)
24
+
25
+
26
+ class TypeAnnotationResolutionError(TypeError):
27
+ """Raised when a runtime annotation cannot be resolved."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ResolvedAnnotation:
32
+ annotation: Any
33
+ localns: dict[str, Any] | None = None
34
+
35
+
36
+ def is_generic_alias(tp: Any) -> bool:
37
+ return get_origin(tp) is not None
38
+
39
+
40
+ def is_annotated(tp: Any) -> bool:
41
+ return get_origin(tp) is Annotated
42
+
43
+
44
+ def strip_annotated(tp: Any) -> Any:
45
+ while is_annotated(tp):
46
+ tp = get_args(tp)[0]
47
+ return tp
48
+
49
+
50
+ def is_type_var(tp: Any) -> bool:
51
+ return isinstance(tp, _TYPE_VAR_TYPE)
52
+
53
+
54
+ def is_classvar(tp: Any) -> bool:
55
+ return get_origin(tp) is ClassVar
56
+
57
+
58
+ def is_final(tp: Any) -> bool:
59
+ return get_origin(tp) is Final
60
+
61
+
62
+ def is_union_type(tp: Any) -> bool:
63
+ return get_origin(tp) in {Union, types.UnionType}
64
+
65
+
66
+ def origin_is(tp: Any, *origins: Any) -> bool:
67
+ return get_origin(tp) in origins
68
+
69
+
70
+ def args(tp: Any) -> tuple[Any, ...]:
71
+ return get_args(tp)
72
+
73
+
74
+ def annotation_needs_resolution(annotation: Any) -> bool:
75
+ if isinstance(annotation, str | ForwardRef):
76
+ return True
77
+ if is_type_var(annotation):
78
+ return False
79
+ if origin_is(annotation, Literal):
80
+ return False
81
+ if origin_is(annotation, Annotated):
82
+ annotation_args = args(annotation)
83
+ return bool(annotation_args) and annotation_needs_resolution(annotation_args[0])
84
+ return any(annotation_needs_resolution(item) for item in args(annotation))
85
+
86
+
87
+ def _normalize_forward_refs(annotation: Any) -> Any:
88
+ if isinstance(annotation, str):
89
+ return ForwardRef(annotation)
90
+ if isinstance(annotation, ForwardRef) or is_type_var(annotation):
91
+ return annotation
92
+
93
+ annotation_args = args(annotation)
94
+ if not annotation_args or origin_is(annotation, Literal):
95
+ return annotation
96
+
97
+ origin = get_origin(annotation)
98
+ if origin is Annotated:
99
+ first_arg = _normalize_forward_refs(annotation_args[0])
100
+ if first_arg is annotation_args[0]:
101
+ return annotation
102
+ return Annotated.__class_getitem__((first_arg, *annotation_args[1:]))
103
+
104
+ normalized_args = tuple(_normalize_forward_refs(item) for item in annotation_args)
105
+ if normalized_args == annotation_args:
106
+ return annotation
107
+
108
+ if isinstance(annotation, types.GenericAlias):
109
+ return origin[normalized_args]
110
+ copy_with = getattr(annotation, "copy_with", None)
111
+ if copy_with is not None:
112
+ return copy_with(normalized_args)
113
+ return annotation
114
+
115
+
116
+ def _resolve_annotation_fully(
117
+ annotation: Any,
118
+ *,
119
+ globalns: dict[str, Any],
120
+ localns: dict[str, Any] | None = None,
121
+ ) -> ResolvedAnnotation:
122
+ resolved = resolve_annotation(annotation, globalns=globalns, localns=localns)
123
+ if not annotation_needs_resolution(resolved):
124
+ return ResolvedAnnotation(resolved, localns)
125
+
126
+ normalized = _normalize_forward_refs(resolved)
127
+ return ResolvedAnnotation(
128
+ resolve_annotation(normalized, globalns=globalns, localns=localns),
129
+ localns,
130
+ )
131
+
132
+
133
+ def _call_stack_localns() -> dict[str, Any]:
134
+ frame: FrameType | None = inspect.currentframe()
135
+ localns: dict[str, Any] = {}
136
+ try:
137
+ frame = frame.f_back if frame is not None else None
138
+ while frame is not None:
139
+ localns = {**frame.f_locals, **localns}
140
+ frame = frame.f_back
141
+ finally:
142
+ del frame
143
+ return localns
144
+
145
+
146
+ def resolve_annotation(
147
+ annotation: Any,
148
+ *,
149
+ globalns: dict[str, Any],
150
+ localns: dict[str, Any] | None = None,
151
+ ) -> Any:
152
+ class AnnotationShim:
153
+ pass
154
+
155
+ AnnotationShim.__annotations__ = {"value": annotation}
156
+ return get_type_hints(
157
+ AnnotationShim,
158
+ globalns=globalns,
159
+ localns=localns,
160
+ include_extras=True,
161
+ )["value"]
162
+
163
+
164
+ def resolve_annotation_from_call_stack(
165
+ annotation: Any,
166
+ *,
167
+ globalns: dict[str, Any],
168
+ ) -> Any:
169
+ return resolve_annotation_with_namespace_from_call_stack(
170
+ annotation,
171
+ globalns=globalns,
172
+ ).annotation
173
+
174
+
175
+ def resolve_annotation_with_namespace_from_call_stack(
176
+ annotation: Any,
177
+ *,
178
+ globalns: dict[str, Any],
179
+ ) -> ResolvedAnnotation:
180
+ if annotation is Any or not annotation_needs_resolution(annotation):
181
+ return ResolvedAnnotation(annotation, _call_stack_localns())
182
+
183
+ resolution_error: BaseException | None = None
184
+ try:
185
+ return _resolve_annotation_fully(annotation, globalns=globalns)
186
+ except (NameError, TypeError, AttributeError) as exc:
187
+ resolution_error = exc
188
+
189
+ localns = _call_stack_localns()
190
+
191
+ try:
192
+ return _resolve_annotation_fully(
193
+ annotation,
194
+ globalns=globalns,
195
+ localns=localns,
196
+ )
197
+ except (NameError, TypeError, AttributeError) as exc:
198
+ resolution_error = exc
199
+
200
+ if not annotation_needs_resolution(annotation):
201
+ return ResolvedAnnotation(annotation)
202
+
203
+ raise TypeAnnotationResolutionError from resolution_error
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ """Generated vendored dependencies for vercel-queue-bundle."""
@@ -0,0 +1,38 @@
1
+ # Copyright 2012, Andrew Dunham
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This only works if using a file system, other loaders not implemented.
16
+
17
+ import importlib.util
18
+ import sys
19
+ import warnings
20
+ from pathlib import Path
21
+
22
+ for p in sys.path:
23
+ file_path = Path(p, "multipart.py")
24
+ try:
25
+ if file_path.is_file():
26
+ spec = importlib.util.spec_from_file_location("multipart", file_path)
27
+ assert spec is not None, f"{file_path} found but not loadable!"
28
+ module = importlib.util.module_from_spec(spec)
29
+ sys.modules["multipart"] = module
30
+ assert spec.loader is not None, f"{file_path} must be loadable!"
31
+ spec.loader.exec_module(module)
32
+ break
33
+ except PermissionError:
34
+ pass
35
+ else:
36
+ warnings.warn("Please use `import python_multipart` instead.", PendingDeprecationWarning, stacklevel=2)
37
+ from vercel.queue._vendor.python_multipart import *
38
+ from vercel.queue._vendor.python_multipart import __all__, __version__
@@ -0,0 +1 @@
1
+ from vercel.queue._vendor.python_multipart.decoders import *
@@ -0,0 +1 @@
1
+ from vercel.queue._vendor.python_multipart.exceptions import *
@@ -0,0 +1 @@
1
+ from vercel.queue._vendor.python_multipart.multipart import *
@@ -0,0 +1,35 @@
1
+ # Copyright 2012, Andrew Dunham
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "0.0.32"
16
+
17
+ from .multipart import (
18
+ BaseParser,
19
+ FormParser,
20
+ MultipartParser,
21
+ OctetStreamParser,
22
+ QuerystringParser,
23
+ create_form_parser,
24
+ parse_form,
25
+ )
26
+
27
+ __all__ = (
28
+ "BaseParser",
29
+ "FormParser",
30
+ "MultipartParser",
31
+ "OctetStreamParser",
32
+ "QuerystringParser",
33
+ "create_form_parser",
34
+ "parse_form",
35
+ )
@@ -0,0 +1,185 @@
1
+ import base64
2
+ import binascii
3
+ from typing import TYPE_CHECKING
4
+
5
+ from .exceptions import DecodeError
6
+
7
+ if TYPE_CHECKING: # pragma: no cover
8
+ from typing import Protocol, TypeVar
9
+
10
+ _T_contra = TypeVar("_T_contra", contravariant=True)
11
+
12
+ class SupportsWrite(Protocol[_T_contra]):
13
+ def write(self, __b: _T_contra) -> object: ...
14
+
15
+ # No way to specify optional methods. See
16
+ # https://github.com/python/typing/issues/601
17
+ # close() [Optional]
18
+ # finalize() [Optional]
19
+
20
+
21
+ class Base64Decoder:
22
+ """This object provides an interface to decode a stream of Base64 data. It
23
+ is instantiated with an "underlying object", and whenever a write()
24
+ operation is performed, it will decode the incoming data as Base64, and
25
+ call write() on the underlying object. This is primarily used for decoding
26
+ form data encoded as Base64, but can be used for other purposes::
27
+
28
+ from vercel.queue._vendor.python_multipart.decoders import Base64Decoder
29
+ fd = open("notb64.txt", "wb")
30
+ decoder = Base64Decoder(fd)
31
+ try:
32
+ decoder.write("Zm9vYmFy") # "foobar" in Base64
33
+ decoder.finalize()
34
+ finally:
35
+ decoder.close()
36
+
37
+ # The contents of "notb64.txt" should be "foobar".
38
+
39
+ This object will also pass all finalize() and close() calls to the
40
+ underlying object, if the underlying object supports them.
41
+
42
+ Note that this class maintains a cache of base64 chunks, so that a write of
43
+ arbitrary size can be performed. You must call :meth:`finalize` on this
44
+ object after all writes are completed to ensure that all data is flushed
45
+ to the underlying object.
46
+
47
+ :param underlying: the underlying object to pass writes to
48
+ """
49
+
50
+ def __init__(self, underlying: "SupportsWrite[bytes]") -> None:
51
+ self.cache = bytearray()
52
+ self.underlying = underlying
53
+
54
+ def write(self, data: bytes) -> int:
55
+ """Takes any input data provided, decodes it as base64, and passes it
56
+ on to the underlying object. If the data provided is invalid base64
57
+ data, then this method will raise
58
+ a :class:`python_multipart.exceptions.DecodeError`
59
+
60
+ :param data: base64 data to decode
61
+ """
62
+
63
+ # Prepend any cache info to our data.
64
+ if len(self.cache) > 0:
65
+ data = bytes(self.cache) + data
66
+
67
+ # Slice off a string that's a multiple of 4.
68
+ decode_len = (len(data) // 4) * 4
69
+ val = data[:decode_len]
70
+
71
+ # Decode and write, if we have any.
72
+ if len(val) > 0:
73
+ try:
74
+ decoded = base64.b64decode(val)
75
+ except binascii.Error:
76
+ raise DecodeError("There was an error raised while decoding base64-encoded data.")
77
+
78
+ self.underlying.write(decoded)
79
+
80
+ # Get the remaining bytes and save in our cache.
81
+ remaining_len = len(data) % 4
82
+ if remaining_len > 0:
83
+ self.cache[:] = data[-remaining_len:]
84
+ else:
85
+ self.cache[:] = b""
86
+
87
+ # Return the length of the data to indicate no error.
88
+ return len(data)
89
+
90
+ def close(self) -> None:
91
+ """Close this decoder. If the underlying object has a `close()`
92
+ method, this function will call it.
93
+ """
94
+ if hasattr(self.underlying, "close"):
95
+ self.underlying.close()
96
+
97
+ def finalize(self) -> None:
98
+ """Finalize this object. This should be called when no more data
99
+ should be written to the stream. This function can raise a
100
+ :class:`python_multipart.exceptions.DecodeError` if there is some remaining
101
+ data in the cache.
102
+
103
+ If the underlying object has a `finalize()` method, this function will
104
+ call it.
105
+ """
106
+ if len(self.cache) > 0:
107
+ raise DecodeError(
108
+ "There are %d bytes remaining in the Base64Decoder cache when finalize() is called" % len(self.cache)
109
+ )
110
+
111
+ if hasattr(self.underlying, "finalize"):
112
+ self.underlying.finalize()
113
+
114
+ def __repr__(self) -> str:
115
+ return f"{self.__class__.__name__}(underlying={self.underlying!r})"
116
+
117
+
118
+ class QuotedPrintableDecoder:
119
+ """This object provides an interface to decode a stream of quoted-printable
120
+ data. It is instantiated with an "underlying object", in the same manner
121
+ as the :class:`python_multipart.decoders.Base64Decoder` class. This class behaves
122
+ in exactly the same way, including maintaining a cache of quoted-printable
123
+ chunks.
124
+
125
+ :param underlying: the underlying object to pass writes to
126
+ """
127
+
128
+ def __init__(self, underlying: "SupportsWrite[bytes]") -> None:
129
+ self.cache = b""
130
+ self.underlying = underlying
131
+
132
+ def write(self, data: bytes) -> int:
133
+ """Takes any input data provided, decodes it as quoted-printable, and
134
+ passes it on to the underlying object.
135
+
136
+ :param data: quoted-printable data to decode
137
+ """
138
+ # Prepend any cache info to our data.
139
+ if len(self.cache) > 0:
140
+ data = self.cache + data
141
+
142
+ # If the last 2 characters have an '=' sign in it, then we won't be
143
+ # able to decode the encoded value and we'll need to save it for the
144
+ # next decoding step.
145
+ if data[-2:].find(b"=") != -1:
146
+ enc, rest = data[:-2], data[-2:]
147
+ else:
148
+ enc = data
149
+ rest = b""
150
+
151
+ # Encode and write, if we have data.
152
+ if len(enc) > 0:
153
+ self.underlying.write(binascii.a2b_qp(enc))
154
+
155
+ # Save remaining in cache.
156
+ self.cache = rest
157
+ return len(data)
158
+
159
+ def close(self) -> None:
160
+ """Close this decoder. If the underlying object has a `close()`
161
+ method, this function will call it.
162
+ """
163
+ if hasattr(self.underlying, "close"):
164
+ self.underlying.close()
165
+
166
+ def finalize(self) -> None:
167
+ """Finalize this object. This should be called when no more data
168
+ should be written to the stream. This function will not raise any
169
+ exceptions, but it may write more data to the underlying object if
170
+ there is data remaining in the cache.
171
+
172
+ If the underlying object has a `finalize()` method, this function will
173
+ call it.
174
+ """
175
+ # If we have a cache, write and then remove it.
176
+ if len(self.cache) > 0: # pragma: no cover
177
+ self.underlying.write(binascii.a2b_qp(self.cache))
178
+ self.cache = b""
179
+
180
+ # Finalize our underlying stream.
181
+ if hasattr(self.underlying, "finalize"):
182
+ self.underlying.finalize()
183
+
184
+ def __repr__(self) -> str:
185
+ return f"{self.__class__.__name__}(underlying={self.underlying!r})"