forked from mtusi2026/mtusi2026lab7
feat: core func lab7
This commit is contained in:
@@ -26,6 +26,8 @@ from config import (
|
||||
from infrastructure.security import read_secret
|
||||
from infrastructure.utils import STORAGE_UNAVAILABLE_ERRORS, storage_error_code
|
||||
|
||||
from infrastructure.security.tls import CA_FILE, client_context
|
||||
|
||||
STARTUP_RETRY_INTERVAL_SEC = 1
|
||||
|
||||
ANONYMOUS_CHECK_TIMEOUT_SEC = 3
|
||||
@@ -53,6 +55,8 @@ class ObjectStorageManager:
|
||||
read_timeout: float,
|
||||
max_attempts: int,
|
||||
) -> None:
|
||||
if not endpoint.startswith("https://"):
|
||||
raise ValueError("Для S3 требуется HTTPS")
|
||||
self._endpoint = endpoint
|
||||
self._region = region
|
||||
self.bucket = bucket
|
||||
@@ -65,7 +69,7 @@ class ObjectStorageManager:
|
||||
self.client: AioBaseClient | None = None
|
||||
self._exit_stack = AsyncExitStack()
|
||||
|
||||
async def create_client(self) -> AioBaseClient:
|
||||
async def create_client(self, credentials: dict[str, str] | None = None) -> AioBaseClient:
|
||||
"""
|
||||
Создание клиента; соединения открываются лениво при первом запросе.
|
||||
|
||||
@@ -83,12 +87,18 @@ class ObjectStorageManager:
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
if credentials is None:
|
||||
credentials = {
|
||||
"accessKey": read_secret(self._access_key_file),
|
||||
"secretKey": read_secret(self._secret_key_file),
|
||||
}
|
||||
client = get_session().create_client(
|
||||
"s3",
|
||||
endpoint_url=self._endpoint,
|
||||
region_name=self._region,
|
||||
aws_access_key_id=read_secret(self._access_key_file),
|
||||
aws_secret_access_key=read_secret(self._secret_key_file),
|
||||
aws_access_key_id=credentials["accessKey"],
|
||||
aws_secret_access_key=credentials["secretKey"],
|
||||
verify=str(CA_FILE),
|
||||
config=config,
|
||||
)
|
||||
self.client = await self._exit_stack.enter_async_context(client)
|
||||
@@ -108,7 +118,7 @@ class ObjectStorageManager:
|
||||
assert self.client is not None
|
||||
try:
|
||||
async with asyncio.timeout(self.connect_timeout):
|
||||
await self.client.head_bucket(Bucket=self.bucket)
|
||||
await self.client.list_objects_v2(Bucket=self.bucket, Prefix="originals/", MaxKeys=1)
|
||||
except STORAGE_UNAVAILABLE_ERRORS:
|
||||
return False
|
||||
return True
|
||||
@@ -152,7 +162,9 @@ class ObjectStorageManager:
|
||||
"""
|
||||
url = f"{self._endpoint.rstrip('/')}/{self.bucket}"
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=ANONYMOUS_CHECK_TIMEOUT_SEC):
|
||||
with urllib.request.urlopen(
|
||||
url, timeout=ANONYMOUS_CHECK_TIMEOUT_SEC, context=client_context()
|
||||
):
|
||||
pass
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 403:
|
||||
|
||||
Reference in New Issue
Block a user