action0-req 0.1.0__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.
@@ -0,0 +1,27 @@
1
+ from .body import AsyncIterableBody
2
+ from .body import BodyProducer
3
+ from .body import BytesBody
4
+ from .body import FileBody
5
+ from .body import IterableBody
6
+ from .headers import Header
7
+ from .headers import Headers
8
+ from .request import Method
9
+ from .request import Request
10
+ from .response import Response
11
+ from .status import Status
12
+
13
+ __version__: str = "0.1.0"
14
+
15
+ __all__ = [
16
+ "AsyncIterableBody",
17
+ "BodyProducer",
18
+ "BytesBody",
19
+ "FileBody",
20
+ "Header",
21
+ "Headers",
22
+ "IterableBody",
23
+ "Method",
24
+ "Request",
25
+ "Response",
26
+ "Status",
27
+ ]
action0/req/body.py ADDED
@@ -0,0 +1,396 @@
1
+ """Streaming abstractions for request and response bodies."""
2
+
3
+ import asyncio
4
+ import io
5
+ import os
6
+ from typing import IO
7
+ from typing import AsyncIterable
8
+ from typing import AsyncIterator
9
+ from typing import Iterable
10
+ from typing import Iterator
11
+ from typing import Protocol
12
+ from typing import Union
13
+ from typing import runtime_checkable
14
+
15
+ from .headers import Header
16
+ from .headers import Headers
17
+
18
+
19
+ @runtime_checkable
20
+ class BodyProducer(Protocol):
21
+ """
22
+ The interface for streaming the bytes of a request or response body.
23
+
24
+ Implementations produce the body as a sequence of chunks — synchronously
25
+ via :py:meth:`chunks` or asynchronously via :py:meth:`achunks` — and as a
26
+ whole via :py:meth:`as_bytes`. :py:class:`BytesBody` is the simplest
27
+ implementation; file- and iterable-backed producers are planned.
28
+
29
+ The protocol is ``runtime_checkable``, so ``isinstance(obj, BodyProducer)``
30
+ checks that the four methods exist.
31
+ """
32
+
33
+ def content_length(self) -> Union[int, None]:
34
+ """
35
+ :return: the total number of body bytes, or ``None`` if not known in
36
+ advance (such a body would be sent chunked)
37
+ """
38
+ ...
39
+
40
+ def chunks(self) -> Iterator[bytes]:
41
+ """
42
+ :return: the body as an iterator of byte chunks
43
+ """
44
+ ...
45
+
46
+ def achunks(self) -> AsyncIterator[bytes]:
47
+ """
48
+ :return: the body as an asynchronous iterator of byte chunks
49
+ """
50
+ ...
51
+
52
+ def as_bytes(self) -> bytes:
53
+ """
54
+ :return: the whole body as a single bytes object
55
+ """
56
+ ...
57
+
58
+
59
+ class BytesBody:
60
+ """
61
+ The simplest :py:class:`BodyProducer`: an in-memory bytes value,
62
+ produced as a single chunk.
63
+
64
+ Example::
65
+
66
+ >>> body = BytesBody(b"hello")
67
+ >>> body.content_length()
68
+ 5
69
+ >>> list(body.chunks())
70
+ [b'hello']
71
+ >>> body.as_bytes()
72
+ b'hello'
73
+ """
74
+
75
+ def __init__(self, data: bytes) -> None:
76
+ """
77
+ :param data: the body bytes
78
+ """
79
+ self._data = data
80
+
81
+ def content_length(self) -> Union[int, None]:
82
+ """
83
+ :return: the number of body bytes
84
+ """
85
+ return len(self._data)
86
+
87
+ def chunks(self) -> Iterator[bytes]:
88
+ """
89
+ :return: the body as an iterator with a single chunk
90
+ """
91
+ yield self._data
92
+
93
+ async def achunks(self) -> AsyncIterator[bytes]:
94
+ """
95
+ :return: the body as an asynchronous iterator with a single chunk
96
+ """
97
+ yield self._data
98
+
99
+ def as_bytes(self) -> bytes:
100
+ """
101
+ :return: the body bytes
102
+ """
103
+ return self._data
104
+
105
+
106
+ def _open_binary(path: Union[str, "os.PathLike[str]"]) -> IO[bytes]:
107
+ """
108
+ Open a file for binary reading.
109
+
110
+ A typed wrapper: passing the built-in ``open`` through
111
+ :py:func:`asyncio.to_thread` loses the overload selection and with it
112
+ the precise ``IO[bytes]`` return type.
113
+
114
+ :param path: the path of the file to open
115
+ :return: the opened binary file object
116
+ """
117
+ return open(path, "rb")
118
+
119
+
120
+ class FileBody:
121
+ """
122
+ A :py:class:`BodyProducer` streaming a file in chunks.
123
+
124
+ The source can be a path or an already-open binary file object:
125
+
126
+ - A path is opened freshly for every iteration, so the body is
127
+ re-iterable (e.g. for retries) and no file descriptor is held
128
+ between uses.
129
+ - A file object is used as-is and never closed by this class. If it
130
+ is seekable it is rewound to the start for every iteration (making
131
+ it re-iterable too); if not, reading starts at the current position
132
+ and the body is consumable only once.
133
+
134
+ :py:meth:`achunks` performs every blocking file operation in the
135
+ default thread pool via :py:func:`asyncio.to_thread`, so the event
136
+ loop is never stalled — without any extra dependency.
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ source: Union[str, "os.PathLike[str]", IO[bytes]],
142
+ chunk_size: int = 65536,
143
+ ) -> None:
144
+ """
145
+ :param source: the path of the file to stream, or an open binary
146
+ file object
147
+ :param chunk_size: the number of bytes per chunk
148
+ :raises ValueError: if the chunk size is not positive
149
+ """
150
+ if chunk_size <= 0:
151
+ raise ValueError(f"chunk_size must be positive, got {chunk_size}")
152
+ if isinstance(source, (str, os.PathLike)):
153
+ self._path: Union[str, "os.PathLike[str]", None] = source
154
+ self._file: Union[IO[bytes], None] = None
155
+ else:
156
+ self._path = None
157
+ self._file = source
158
+ self._chunk_size = chunk_size
159
+
160
+ def content_length(self) -> Union[int, None]:
161
+ """
162
+ :return: the size of the file; for a non-seekable file object
163
+ ``None`` (unknown)
164
+ """
165
+ if self._path is not None:
166
+ return os.stat(self._path).st_size
167
+ assert self._file is not None
168
+ if not self._file.seekable():
169
+ return None
170
+ # measure the full size, leaving the current position untouched
171
+ position = self._file.tell()
172
+ size = self._file.seek(0, io.SEEK_END)
173
+ self._file.seek(position)
174
+ return size
175
+
176
+ def chunks(self) -> Iterator[bytes]:
177
+ """
178
+ :return: the file contents as an iterator of chunks of (up to)
179
+ the configured chunk size
180
+ """
181
+ if self._path is not None:
182
+ with open(self._path, "rb") as file:
183
+ while chunk := file.read(self._chunk_size):
184
+ yield chunk
185
+ return
186
+ assert self._file is not None
187
+ if self._file.seekable():
188
+ self._file.seek(0)
189
+ while chunk := self._file.read(self._chunk_size):
190
+ yield chunk
191
+
192
+ async def achunks(self) -> AsyncIterator[bytes]:
193
+ """
194
+ :return: the file contents as an asynchronous iterator of chunks;
195
+ all file operations run in the default thread pool
196
+ """
197
+ if self._path is not None:
198
+ opened = await asyncio.to_thread(_open_binary, self._path)
199
+ try:
200
+ while chunk := await asyncio.to_thread(opened.read, self._chunk_size):
201
+ yield chunk
202
+ finally:
203
+ await asyncio.to_thread(opened.close)
204
+ return
205
+ file = self._file
206
+ assert file is not None
207
+ if await asyncio.to_thread(file.seekable):
208
+ await asyncio.to_thread(file.seek, 0)
209
+ while chunk := await asyncio.to_thread(file.read, self._chunk_size):
210
+ yield chunk
211
+
212
+ def as_bytes(self) -> bytes:
213
+ """
214
+ :return: the whole file contents
215
+ """
216
+ return b"".join(self.chunks())
217
+
218
+
219
+ class IterableBody:
220
+ """
221
+ A :py:class:`BodyProducer` wrapping an iterable of byte chunks, e.g.
222
+ a generator. The total length is unknown (:py:meth:`content_length`
223
+ is ``None`` — such a body would be sent chunked).
224
+
225
+ WARNING: if the iterable is a generator (or any other single-use
226
+ iterable), the body can be consumed only once — also by
227
+ :py:meth:`as_bytes`. Pass a list of chunks for a re-iterable body.
228
+ """
229
+
230
+ def __init__(self, iterable: Iterable[bytes]) -> None:
231
+ """
232
+ :param iterable: the byte chunks of the body
233
+ """
234
+ self._iterable = iterable
235
+
236
+ def content_length(self) -> Union[int, None]:
237
+ """
238
+ :return: always ``None``, the length is unknown in advance
239
+ """
240
+ return None
241
+
242
+ def chunks(self) -> Iterator[bytes]:
243
+ """
244
+ :return: the chunks as given by the wrapped iterable
245
+ """
246
+ yield from self._iterable
247
+
248
+ async def achunks(self) -> AsyncIterator[bytes]:
249
+ """
250
+ :return: the chunks as given by the wrapped (synchronous) iterable
251
+ """
252
+ for chunk in self._iterable:
253
+ yield chunk
254
+
255
+ def as_bytes(self) -> bytes:
256
+ """
257
+ :return: all chunks joined (consumes a single-use iterable)
258
+ """
259
+ return b"".join(self._iterable)
260
+
261
+
262
+ class AsyncIterableBody:
263
+ """
264
+ A :py:class:`BodyProducer` wrapping an asynchronous iterable of byte
265
+ chunks, e.g. an async generator proxying another stream. The total
266
+ length is unknown (:py:meth:`content_length` is ``None``).
267
+
268
+ An asynchronous source is async-only: the synchronous accessors
269
+ :py:meth:`chunks` and :py:meth:`as_bytes` raise a
270
+ :py:class:`RuntimeError` — consume the body with :py:meth:`achunks`.
271
+ Like a generator, an async generator source is consumable only once.
272
+ """
273
+
274
+ def __init__(self, aiterable: AsyncIterable[bytes]) -> None:
275
+ """
276
+ :param aiterable: the byte chunks of the body
277
+ """
278
+ self._aiterable = aiterable
279
+
280
+ def content_length(self) -> Union[int, None]:
281
+ """
282
+ :return: always ``None``, the length is unknown in advance
283
+ """
284
+ return None
285
+
286
+ def chunks(self) -> Iterator[bytes]:
287
+ """
288
+ :raises RuntimeError: always — an async body has no synchronous
289
+ chunks; use :py:meth:`achunks`
290
+ """
291
+ raise RuntimeError("an async body cannot be read synchronously; use achunks()")
292
+
293
+ async def achunks(self) -> AsyncIterator[bytes]:
294
+ """
295
+ :return: the chunks as given by the wrapped asynchronous iterable
296
+ """
297
+ async for chunk in self._aiterable:
298
+ yield chunk
299
+
300
+ def as_bytes(self) -> bytes:
301
+ """
302
+ :raises RuntimeError: always — an async body has no synchronous
303
+ bytes view; use :py:meth:`achunks`
304
+ """
305
+ raise RuntimeError("an async body cannot be read synchronously; use achunks()")
306
+
307
+
308
+ BodyTypes = Union[bytes, str, BodyProducer]
309
+ """Everything a request or response accepts as body: raw bytes, text
310
+ (encoded with the Content-Type charset when accessed as bytes), or a
311
+ streaming :py:class:`BodyProducer`."""
312
+
313
+
314
+ # the conversion helpers shared by Request and Response — each class keeps
315
+ # its own thin, documented body_bytes()/body_str()/body_producer() methods
316
+
317
+
318
+ def _charset(headers: Headers) -> str:
319
+ """
320
+ Extract the charset parameter of the Content-Type header.
321
+
322
+ :param headers: the headers of the request or response
323
+ :return: the charset, ``"utf-8"`` if there is none
324
+ """
325
+ content_type = headers.get(Header.CONTENT_TYPE, "")
326
+ for parameter in content_type.split(";")[1:]:
327
+ name, sep, value = parameter.partition("=")
328
+ if sep and name.strip().lower() == "charset":
329
+ return value.strip().strip('"') or "utf-8"
330
+ return "utf-8"
331
+
332
+
333
+ def _body_bytes(body: Union[BodyTypes, None], charset: str) -> Union[bytes, None]:
334
+ """
335
+ Convert a body of any accepted form to bytes.
336
+
337
+ :param body: the body as set
338
+ :param charset: the charset for encoding a str body
339
+ :return: the body bytes, ``None`` if there is no body
340
+ """
341
+ if body is None:
342
+ return None
343
+ if isinstance(body, bytes):
344
+ return body
345
+ if isinstance(body, str):
346
+ return body.encode(charset)
347
+ return body.as_bytes()
348
+
349
+
350
+ def _body_str(body: Union[BodyTypes, None], charset: str) -> Union[str, None]:
351
+ """
352
+ Convert a body of any accepted form to text.
353
+
354
+ :param body: the body as set
355
+ :param charset: the charset for decoding a bytes (or produced) body
356
+ :return: the body text, ``None`` if there is no body
357
+ """
358
+ if body is None:
359
+ return None
360
+ if isinstance(body, str):
361
+ return body
362
+ if isinstance(body, bytes):
363
+ return body.decode(charset)
364
+ return body.as_bytes().decode(charset)
365
+
366
+
367
+ def _body_producer(body: Union[BodyTypes, None], charset: str) -> Union[BodyProducer, None]:
368
+ """
369
+ Convert a body of any accepted form to a streaming producer.
370
+
371
+ :param body: the body as set
372
+ :param charset: the charset for encoding a str body
373
+ :return: the body producer, ``None`` if there is no body
374
+ """
375
+ if body is None:
376
+ return None
377
+ if isinstance(body, bytes):
378
+ return BytesBody(body)
379
+ if isinstance(body, str):
380
+ return BytesBody(body.encode(charset))
381
+ return body
382
+
383
+
384
+ def _rendered_body(body: BodyTypes, charset: str) -> str:
385
+ """
386
+ The body as text for a debug rendering: bytes/str decoded, a producer
387
+ NOT consumed (it may be consumable only once) but shown as a
388
+ placeholder.
389
+
390
+ :param body: the body as set
391
+ :param charset: the charset for decoding a bytes body
392
+ :return: the body text or a ``"<ClassName>"`` placeholder
393
+ """
394
+ if isinstance(body, (bytes, str)):
395
+ return body if isinstance(body, str) else body.decode(charset)
396
+ return f"<{type(body).__name__}>"