| 1 |
""" |
| 2 |
Adapt s3 to package_streaming |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import typing |
| 8 |
from contextlib import closing |
| 9 |
from typing import Any |
| 10 |
|
| 11 |
from . import package_streaming |
| 12 |
|
| 13 |
if typing.TYPE_CHECKING: # pragma: no cover |
| 14 |
from mypy_boto3_s3 import Client |
| 15 |
from mypy_boto3_s3.type_defs import GetObjectOutputTypeDef |
| 16 |
else: |
| 17 |
Client = GetObjectOutputTypeDef = None |
| 18 |
|
| 19 |
from .url import conda_reader_for_url |
| 20 |
|
| 21 |
__all__ = ["stream_conda_info", "conda_reader_for_s3"] |
| 22 |
|
| 23 |
|
| 24 |
class ResponseFacade: |
| 25 |
def __init__(self, response: GetObjectOutputTypeDef): |
| 26 |
self.response = response |
| 27 |
self.raw: Any = response["Body"] |
| 28 |
|
| 29 |
def raise_for_status(self): |
| 30 |
# s3 get_object raises automatically? |
| 31 |
pass |
| 32 |
|
| 33 |
@property |
| 34 |
def status_code(self): |
| 35 |
return self.response["ResponseMetadata"]["HTTPStatusCode"] |
| 36 |
|
| 37 |
@property |
| 38 |
def headers(self): |
| 39 |
# a case-sensitive dict; keys may be lowercased always? |
| 40 |
return self.response["ResponseMetadata"]["HTTPHeaders"] |
| 41 |
|
| 42 |
def iter_content(self, n: int): |
| 43 |
return iter(lambda: self.raw.read(n), b"") |
| 44 |
|
| 45 |
|
| 46 |
class SessionFacade: |
| 47 |
""" |
| 48 |
Make s3 client look just enough like a requests.session for LazyZipOverHTTP |
| 49 |
""" |
| 50 |
|
| 51 |
def __init__(self, client: Client, bucket: str, key: str): |
| 52 |
self.client = client |
| 53 |
self.bucket = bucket |
| 54 |
self.key = key |
| 55 |
|
| 56 |
def get(self, url, *, headers: dict | None = None, stream=True): |
| 57 |
if headers and "Range" in headers: |
| 58 |
response = self.client.get_object( |
| 59 |
Bucket=self.bucket, Key=self.key, Range=headers["Range"] |
| 60 |
) |
| 61 |
else: |
| 62 |
response = self.client.get_object(Bucket=self.bucket, Key=self.key) |
| 63 |
return ResponseFacade(response) |
| 64 |
|
| 65 |
|
| 66 |
def stream_conda_info(client, bucket, key): |
| 67 |
""" |
| 68 |
Yield (tar, member) for conda package. |
| 69 |
|
| 70 |
Just "info/" for .conda, all members for tar. |
| 71 |
""" |
| 72 |
filename, conda = conda_reader_for_s3(client, bucket, key) |
| 73 |
|
| 74 |
with closing(conda): |
| 75 |
yield from package_streaming.stream_conda_info(filename, conda) |
| 76 |
|
| 77 |
|
| 78 |
def conda_reader_for_s3(client: Client, bucket: str, key: str): |
| 79 |
""" |
| 80 |
Return (name, file_like) suitable for package_streaming APIs |
| 81 |
""" |
| 82 |
session: Any = SessionFacade(client, bucket, key) |
| 83 |
return conda_reader_for_url(key, session) |