| 1 |
import asyncio |
| 2 |
import enum |
| 3 |
import io |
| 4 |
import json |
| 5 |
import mimetypes |
| 6 |
import os |
| 7 |
import warnings |
| 8 |
from abc import ABC, abstractmethod |
| 9 |
from itertools import chain |
| 10 |
from typing import ( |
| 11 |
IO, |
| 12 |
TYPE_CHECKING, |
| 13 |
Any, |
| 14 |
Dict, |
| 15 |
Final, |
| 16 |
Iterable, |
| 17 |
Optional, |
| 18 |
TextIO, |
| 19 |
Tuple, |
| 20 |
Type, |
| 21 |
Union, |
| 22 |
) |
| 23 |
|
| 24 |
from multidict import CIMultiDict |
| 25 |
|
| 26 |
from . import hdrs |
| 27 |
from .abc import AbstractStreamWriter |
| 28 |
from .helpers import ( |
| 29 |
_SENTINEL, |
| 30 |
content_disposition_header, |
| 31 |
guess_filename, |
| 32 |
parse_mimetype, |
| 33 |
sentinel, |
| 34 |
) |
| 35 |
from .streams import StreamReader |
| 36 |
from .typedefs import JSONEncoder, _CIMultiDict |
| 37 |
|
| 38 |
__all__ = ( |
| 39 |
"PAYLOAD_REGISTRY", |
| 40 |
"get_payload", |
| 41 |
"payload_type", |
| 42 |
"Payload", |
| 43 |
"BytesPayload", |
| 44 |
"StringPayload", |
| 45 |
"IOBasePayload", |
| 46 |
"BytesIOPayload", |
| 47 |
"BufferedReaderPayload", |
| 48 |
"TextIOPayload", |
| 49 |
"StringIOPayload", |
| 50 |
"JsonPayload", |
| 51 |
"AsyncIterablePayload", |
| 52 |
) |
| 53 |
|
| 54 |
TOO_LARGE_BYTES_BODY: Final[int] = 2**20 # 1 MB |
| 55 |
|
| 56 |
if TYPE_CHECKING: |
| 57 |
from typing import List |
| 58 |
|
| 59 |
|
| 60 |
class LookupError(Exception): |
| 61 |
pass |
| 62 |
|
| 63 |
|
| 64 |
class Order(str, enum.Enum): |
| 65 |
normal = "normal" |
| 66 |
try_first = "try_first" |
| 67 |
try_last = "try_last" |
| 68 |
|
| 69 |
|
| 70 |
def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload": |
| 71 |
return PAYLOAD_REGISTRY.get(data, *args, **kwargs) |
| 72 |
|
| 73 |
|
| 74 |
def register_payload( |
| 75 |
factory: Type["Payload"], type: Any, *, order: Order = Order.normal |
| 76 |
) -> None: |
| 77 |
PAYLOAD_REGISTRY.register(factory, type, order=order) |
| 78 |
|
| 79 |
|
| 80 |
class payload_type: |
| 81 |
def __init__(self, type: Any, *, order: Order = Order.normal) -> None: |
| 82 |
self.type = type |
| 83 |
self.order = order |
| 84 |
|
| 85 |
def __call__(self, factory: Type["Payload"]) -> Type["Payload"]: |
| 86 |
register_payload(factory, self.type, order=self.order) |
| 87 |
return factory |
| 88 |
|
| 89 |
|
| 90 |
PayloadType = Type["Payload"] |
| 91 |
_PayloadRegistryItem = Tuple[PayloadType, Any] |
| 92 |
|
| 93 |
|
| 94 |
class PayloadRegistry: |
| 95 |
"""Payload registry. |
| 96 |
|
| 97 |
note: we need zope.interface for more efficient adapter search |
| 98 |
""" |
| 99 |
|
| 100 |
def __init__(self) -> None: |
| 101 |
self._first: List[_PayloadRegistryItem] = [] |
| 102 |
self._normal: List[_PayloadRegistryItem] = [] |
| 103 |
self._last: List[_PayloadRegistryItem] = [] |
| 104 |
self._normal_lookup: Dict[Any, PayloadType] = {} |
| 105 |
|
| 106 |
def get( |
| 107 |
self, |
| 108 |
data: Any, |
| 109 |
*args: Any, |
| 110 |
_CHAIN: "Type[chain[_PayloadRegistryItem]]" = chain, |
| 111 |
**kwargs: Any, |
| 112 |
) -> "Payload": |
| 113 |
if self._first: |
| 114 |
for factory, type_ in self._first: |
| 115 |
if isinstance(data, type_): |
| 116 |
return factory(data, *args, **kwargs) |
| 117 |
# Try the fast lookup first |
| 118 |
if lookup_factory := self._normal_lookup.get(type(data)): |
| 119 |
return lookup_factory(data, *args, **kwargs) |
| 120 |
# Bail early if its already a Payload |
| 121 |
if isinstance(data, Payload): |
| 122 |
return data |
| 123 |
# Fallback to the slower linear search |
| 124 |
for factory, type_ in _CHAIN(self._normal, self._last): |
| 125 |
if isinstance(data, type_): |
| 126 |
return factory(data, *args, **kwargs) |
| 127 |
raise LookupError() |
| 128 |
|
| 129 |
def register( |
| 130 |
self, factory: PayloadType, type: Any, *, order: Order = Order.normal |
| 131 |
) -> None: |
| 132 |
if order is Order.try_first: |
| 133 |
self._first.append((factory, type)) |
| 134 |
elif order is Order.normal: |
| 135 |
self._normal.append((factory, type)) |
| 136 |
if isinstance(type, Iterable): |
| 137 |
for t in type: |
| 138 |
self._normal_lookup[t] = factory |
| 139 |
else: |
| 140 |
self._normal_lookup[type] = factory |
| 141 |
elif order is Order.try_last: |
| 142 |
self._last.append((factory, type)) |
| 143 |
else: |
| 144 |
raise ValueError(f"Unsupported order {order!r}") |
| 145 |
|
| 146 |
|
| 147 |
class Payload(ABC): |
| 148 |
|
| 149 |
_default_content_type: str = "application/octet-stream" |
| 150 |
_size: Optional[int] = None |
| 151 |
|
| 152 |
def __init__( |
| 153 |
self, |
| 154 |
value: Any, |
| 155 |
headers: Optional[ |
| 156 |
Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]] |
| 157 |
] = None, |
| 158 |
content_type: Union[str, None, _SENTINEL] = sentinel, |
| 159 |
filename: Optional[str] = None, |
| 160 |
encoding: Optional[str] = None, |
| 161 |
**kwargs: Any, |
| 162 |
) -> None: |
| 163 |
self._encoding = encoding |
| 164 |
self._filename = filename |
| 165 |
self._headers: _CIMultiDict = CIMultiDict() |
| 166 |
self._value = value |
| 167 |
if content_type is not sentinel and content_type is not None: |
| 168 |
self._headers[hdrs.CONTENT_TYPE] = content_type |
| 169 |
elif self._filename is not None: |
| 170 |
content_type = mimetypes.guess_type(self._filename)[0] |
| 171 |
if content_type is None: |
| 172 |
content_type = self._default_content_type |
| 173 |
self._headers[hdrs.CONTENT_TYPE] = content_type |
| 174 |
else: |
| 175 |
self._headers[hdrs.CONTENT_TYPE] = self._default_content_type |
| 176 |
if headers: |
| 177 |
self._headers.update(headers) |
| 178 |
|
| 179 |
@property |
| 180 |
def size(self) -> Optional[int]: |
| 181 |
"""Size of the payload.""" |
| 182 |
return self._size |
| 183 |
|
| 184 |
@property |
| 185 |
def filename(self) -> Optional[str]: |
| 186 |
"""Filename of the payload.""" |
| 187 |
return self._filename |
| 188 |
|
| 189 |
@property |
| 190 |
def headers(self) -> _CIMultiDict: |
| 191 |
"""Custom item headers""" |
| 192 |
return self._headers |
| 193 |
|
| 194 |
@property |
| 195 |
def _binary_headers(self) -> bytes: |
| 196 |
return ( |
| 197 |
"".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode( |
| 198 |
"utf-8" |
| 199 |
) |
| 200 |
+ b"\r\n" |
| 201 |
) |
| 202 |
|
| 203 |
@property |
| 204 |
def encoding(self) -> Optional[str]: |
| 205 |
"""Payload encoding""" |
| 206 |
return self._encoding |
| 207 |
|
| 208 |
@property |
| 209 |
def content_type(self) -> str: |
| 210 |
"""Content type""" |
| 211 |
return self._headers[hdrs.CONTENT_TYPE] |
| 212 |
|
| 213 |
def set_content_disposition( |
| 214 |
self, |
| 215 |
disptype: str, |
| 216 |
quote_fields: bool = True, |
| 217 |
_charset: str = "utf-8", |
| 218 |
**params: Any, |
| 219 |
) -> None: |
| 220 |
"""Sets ``Content-Disposition`` header.""" |
| 221 |
self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_header( |
| 222 |
disptype, quote_fields=quote_fields, _charset=_charset, **params |
| 223 |
) |
| 224 |
|
| 225 |
@abstractmethod |
| 226 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 227 |
"""Return string representation of the value. |
| 228 |
|
| 229 |
This is named decode() to allow compatibility with bytes objects. |
| 230 |
""" |
| 231 |
|
| 232 |
@abstractmethod |
| 233 |
async def write(self, writer: AbstractStreamWriter) -> None: |
| 234 |
"""Write payload. |
| 235 |
|
| 236 |
writer is an AbstractStreamWriter instance: |
| 237 |
""" |
| 238 |
|
| 239 |
|
| 240 |
class BytesPayload(Payload): |
| 241 |
_value: bytes |
| 242 |
|
| 243 |
def __init__( |
| 244 |
self, value: Union[bytes, bytearray, memoryview], *args: Any, **kwargs: Any |
| 245 |
) -> None: |
| 246 |
if "content_type" not in kwargs: |
| 247 |
kwargs["content_type"] = "application/octet-stream" |
| 248 |
|
| 249 |
super().__init__(value, *args, **kwargs) |
| 250 |
|
| 251 |
if isinstance(value, memoryview): |
| 252 |
self._size = value.nbytes |
| 253 |
elif isinstance(value, (bytes, bytearray)): |
| 254 |
self._size = len(value) |
| 255 |
else: |
| 256 |
raise TypeError(f"value argument must be byte-ish, not {type(value)!r}") |
| 257 |
|
| 258 |
if self._size > TOO_LARGE_BYTES_BODY: |
| 259 |
kwargs = {"source": self} |
| 260 |
warnings.warn( |
| 261 |
"Sending a large body directly with raw bytes might" |
| 262 |
" lock the event loop. You should probably pass an " |
| 263 |
"io.BytesIO object instead", |
| 264 |
ResourceWarning, |
| 265 |
**kwargs, |
| 266 |
) |
| 267 |
|
| 268 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 269 |
return self._value.decode(encoding, errors) |
| 270 |
|
| 271 |
async def write(self, writer: AbstractStreamWriter) -> None: |
| 272 |
await writer.write(self._value) |
| 273 |
|
| 274 |
|
| 275 |
class StringPayload(BytesPayload): |
| 276 |
def __init__( |
| 277 |
self, |
| 278 |
value: str, |
| 279 |
*args: Any, |
| 280 |
encoding: Optional[str] = None, |
| 281 |
content_type: Optional[str] = None, |
| 282 |
**kwargs: Any, |
| 283 |
) -> None: |
| 284 |
|
| 285 |
if encoding is None: |
| 286 |
if content_type is None: |
| 287 |
real_encoding = "utf-8" |
| 288 |
content_type = "text/plain; charset=utf-8" |
| 289 |
else: |
| 290 |
mimetype = parse_mimetype(content_type) |
| 291 |
real_encoding = mimetype.parameters.get("charset", "utf-8") |
| 292 |
else: |
| 293 |
if content_type is None: |
| 294 |
content_type = "text/plain; charset=%s" % encoding |
| 295 |
real_encoding = encoding |
| 296 |
|
| 297 |
super().__init__( |
| 298 |
value.encode(real_encoding), |
| 299 |
encoding=real_encoding, |
| 300 |
content_type=content_type, |
| 301 |
*args, |
| 302 |
**kwargs, |
| 303 |
) |
| 304 |
|
| 305 |
|
| 306 |
class StringIOPayload(StringPayload): |
| 307 |
def __init__(self, value: IO[str], *args: Any, **kwargs: Any) -> None: |
| 308 |
super().__init__(value.read(), *args, **kwargs) |
| 309 |
|
| 310 |
|
| 311 |
class IOBasePayload(Payload): |
| 312 |
_value: io.IOBase |
| 313 |
|
| 314 |
def __init__( |
| 315 |
self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any |
| 316 |
) -> None: |
| 317 |
if "filename" not in kwargs: |
| 318 |
kwargs["filename"] = guess_filename(value) |
| 319 |
|
| 320 |
super().__init__(value, *args, **kwargs) |
| 321 |
|
| 322 |
if self._filename is not None and disposition is not None: |
| 323 |
if hdrs.CONTENT_DISPOSITION not in self.headers: |
| 324 |
self.set_content_disposition(disposition, filename=self._filename) |
| 325 |
|
| 326 |
async def write(self, writer: AbstractStreamWriter) -> None: |
| 327 |
loop = asyncio.get_event_loop() |
| 328 |
try: |
| 329 |
chunk = await loop.run_in_executor(None, self._value.read, 2**16) |
| 330 |
while chunk: |
| 331 |
await writer.write(chunk) |
| 332 |
chunk = await loop.run_in_executor(None, self._value.read, 2**16) |
| 333 |
finally: |
| 334 |
await loop.run_in_executor(None, self._value.close) |
| 335 |
|
| 336 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 337 |
return "".join(r.decode(encoding, errors) for r in self._value.readlines()) |
| 338 |
|
| 339 |
|
| 340 |
class TextIOPayload(IOBasePayload): |
| 341 |
_value: io.TextIOBase |
| 342 |
|
| 343 |
def __init__( |
| 344 |
self, |
| 345 |
value: TextIO, |
| 346 |
*args: Any, |
| 347 |
encoding: Optional[str] = None, |
| 348 |
content_type: Optional[str] = None, |
| 349 |
**kwargs: Any, |
| 350 |
) -> None: |
| 351 |
|
| 352 |
if encoding is None: |
| 353 |
if content_type is None: |
| 354 |
encoding = "utf-8" |
| 355 |
content_type = "text/plain; charset=utf-8" |
| 356 |
else: |
| 357 |
mimetype = parse_mimetype(content_type) |
| 358 |
encoding = mimetype.parameters.get("charset", "utf-8") |
| 359 |
else: |
| 360 |
if content_type is None: |
| 361 |
content_type = "text/plain; charset=%s" % encoding |
| 362 |
|
| 363 |
super().__init__( |
| 364 |
value, |
| 365 |
content_type=content_type, |
| 366 |
encoding=encoding, |
| 367 |
*args, |
| 368 |
**kwargs, |
| 369 |
) |
| 370 |
|
| 371 |
@property |
| 372 |
def size(self) -> Optional[int]: |
| 373 |
try: |
| 374 |
return os.fstat(self._value.fileno()).st_size - self._value.tell() |
| 375 |
except OSError: |
| 376 |
return None |
| 377 |
|
| 378 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 379 |
return self._value.read() |
| 380 |
|
| 381 |
async def write(self, writer: AbstractStreamWriter) -> None: |
| 382 |
loop = asyncio.get_event_loop() |
| 383 |
try: |
| 384 |
chunk = await loop.run_in_executor(None, self._value.read, 2**16) |
| 385 |
while chunk: |
| 386 |
data = ( |
| 387 |
chunk.encode(encoding=self._encoding) |
| 388 |
if self._encoding |
| 389 |
else chunk.encode() |
| 390 |
) |
| 391 |
await writer.write(data) |
| 392 |
chunk = await loop.run_in_executor(None, self._value.read, 2**16) |
| 393 |
finally: |
| 394 |
await loop.run_in_executor(None, self._value.close) |
| 395 |
|
| 396 |
|
| 397 |
class BytesIOPayload(IOBasePayload): |
| 398 |
_value: io.BytesIO |
| 399 |
|
| 400 |
@property |
| 401 |
def size(self) -> int: |
| 402 |
position = self._value.tell() |
| 403 |
end = self._value.seek(0, os.SEEK_END) |
| 404 |
self._value.seek(position) |
| 405 |
return end - position |
| 406 |
|
| 407 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 408 |
return self._value.read().decode(encoding, errors) |
| 409 |
|
| 410 |
|
| 411 |
class BufferedReaderPayload(IOBasePayload): |
| 412 |
_value: io.BufferedIOBase |
| 413 |
|
| 414 |
@property |
| 415 |
def size(self) -> Optional[int]: |
| 416 |
try: |
| 417 |
return os.fstat(self._value.fileno()).st_size - self._value.tell() |
| 418 |
except (OSError, AttributeError): |
| 419 |
# data.fileno() is not supported, e.g. |
| 420 |
# io.BufferedReader(io.BytesIO(b'data')) |
| 421 |
# For some file-like objects (e.g. tarfile), the fileno() attribute may |
| 422 |
# not exist at all, and will instead raise an AttributeError. |
| 423 |
return None |
| 424 |
|
| 425 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 426 |
return self._value.read().decode(encoding, errors) |
| 427 |
|
| 428 |
|
| 429 |
class JsonPayload(BytesPayload): |
| 430 |
def __init__( |
| 431 |
self, |
| 432 |
value: Any, |
| 433 |
encoding: str = "utf-8", |
| 434 |
content_type: str = "application/json", |
| 435 |
dumps: JSONEncoder = json.dumps, |
| 436 |
*args: Any, |
| 437 |
**kwargs: Any, |
| 438 |
) -> None: |
| 439 |
|
| 440 |
super().__init__( |
| 441 |
dumps(value).encode(encoding), |
| 442 |
content_type=content_type, |
| 443 |
encoding=encoding, |
| 444 |
*args, |
| 445 |
**kwargs, |
| 446 |
) |
| 447 |
|
| 448 |
|
| 449 |
if TYPE_CHECKING: |
| 450 |
from typing import AsyncIterable, AsyncIterator |
| 451 |
|
| 452 |
_AsyncIterator = AsyncIterator[bytes] |
| 453 |
_AsyncIterable = AsyncIterable[bytes] |
| 454 |
else: |
| 455 |
from collections.abc import AsyncIterable, AsyncIterator |
| 456 |
|
| 457 |
_AsyncIterator = AsyncIterator |
| 458 |
_AsyncIterable = AsyncIterable |
| 459 |
|
| 460 |
|
| 461 |
class AsyncIterablePayload(Payload): |
| 462 |
|
| 463 |
_iter: Optional[_AsyncIterator] = None |
| 464 |
_value: _AsyncIterable |
| 465 |
|
| 466 |
def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None: |
| 467 |
if not isinstance(value, AsyncIterable): |
| 468 |
raise TypeError( |
| 469 |
"value argument must support " |
| 470 |
"collections.abc.AsyncIterable interface, " |
| 471 |
"got {!r}".format(type(value)) |
| 472 |
) |
| 473 |
|
| 474 |
if "content_type" not in kwargs: |
| 475 |
kwargs["content_type"] = "application/octet-stream" |
| 476 |
|
| 477 |
super().__init__(value, *args, **kwargs) |
| 478 |
|
| 479 |
self._iter = value.__aiter__() |
| 480 |
|
| 481 |
async def write(self, writer: AbstractStreamWriter) -> None: |
| 482 |
if self._iter: |
| 483 |
try: |
| 484 |
# iter is not None check prevents rare cases |
| 485 |
# when the case iterable is used twice |
| 486 |
while True: |
| 487 |
chunk = await self._iter.__anext__() |
| 488 |
await writer.write(chunk) |
| 489 |
except StopAsyncIteration: |
| 490 |
self._iter = None |
| 491 |
|
| 492 |
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: |
| 493 |
raise TypeError("Unable to decode.") |
| 494 |
|
| 495 |
|
| 496 |
class StreamReaderPayload(AsyncIterablePayload): |
| 497 |
def __init__(self, value: StreamReader, *args: Any, **kwargs: Any) -> None: |
| 498 |
super().__init__(value.iter_any(), *args, **kwargs) |
| 499 |
|
| 500 |
|
| 501 |
PAYLOAD_REGISTRY = PayloadRegistry() |
| 502 |
PAYLOAD_REGISTRY.register(BytesPayload, (bytes, bytearray, memoryview)) |
| 503 |
PAYLOAD_REGISTRY.register(StringPayload, str) |
| 504 |
PAYLOAD_REGISTRY.register(StringIOPayload, io.StringIO) |
| 505 |
PAYLOAD_REGISTRY.register(TextIOPayload, io.TextIOBase) |
| 506 |
PAYLOAD_REGISTRY.register(BytesIOPayload, io.BytesIO) |
| 507 |
PAYLOAD_REGISTRY.register(BufferedReaderPayload, (io.BufferedReader, io.BufferedRandom)) |
| 508 |
PAYLOAD_REGISTRY.register(IOBasePayload, io.IOBase) |
| 509 |
PAYLOAD_REGISTRY.register(StreamReaderPayload, StreamReader) |
| 510 |
# try_last for giving a chance to more specialized async interables like |
| 511 |
# multidict.BodyPartReaderPayload override the default |
| 512 |
PAYLOAD_REGISTRY.register(AsyncIterablePayload, AsyncIterable, order=Order.try_last) |