Files
mtusi2026lab7/src/object_store.py
T

103 lines
3.1 KiB
Python

from contextlib import contextmanager
import urllib3
from minio import Minio
from minio.credentials import Credentials, Provider
from minio.error import S3Error
from src import identity, secure_http, telemetry
from src.errors import DomainError
from src.settings import secret
BUCKET = "messenger"
class CurrentCredentials(Provider):
def retrieve(self):
return Credentials(secret("S3_ACCESS_KEY"), secret("S3_SECRET_KEY"))
class ObjectStore:
def __init__(self):
self.http = (
secure_http.pool if identity.enabled() else urllib3.PoolManager
)(
maxsize=32,
block=True,
timeout=urllib3.Timeout(connect=1, read=3),
retries=urllib3.Retry(total=0),
)
self.client = Minio(
"s3:9443" if identity.enabled() else "s3:9000",
credentials=CurrentCredentials(),
secure=identity.enabled(),
region="us-east-1",
http_client=self.http,
)
@contextmanager
def operation(self, name="request"):
try:
with telemetry.span("s3." + name, attributes={"operation": name}):
yield
except S3Error, urllib3.exceptions.HTTPError, OSError:
raise DomainError(
503, "unavailable", "Object store unavailable"
) from None
def ping(self):
with self.operation("head_bucket"):
if identity.enabled():
result = self.http.request(
"GET", "https://s3:9443/minio/health/ready"
)
if result.status != 200:
raise DomainError(
503, "unavailable", "Object store unavailable"
)
return
if not self.client.bucket_exists(BUCKET):
raise DomainError(
503, "unavailable", "Object store unavailable"
)
def put(self, *, key, stream, size, content_type, sha256):
stream.seek(0)
with self.operation("put"):
self.client.put_object(
BUCKET,
key,
stream,
length=size,
content_type=content_type,
metadata={"sha256": sha256},
part_size=10 * 1024 * 1024,
num_parallel_uploads=1,
)
def head(self, *, key):
with self.operation("head"):
try:
return self.client.stat_object(BUCKET, key)
except S3Error as exc:
if exc.code in {"NoSuchKey", "NoSuchObject"}:
return None
raise
def get(self, *, key):
with self.operation("get"):
return self.client.get_object(BUCKET, key)
def delete(self, *, key):
with self.operation("delete"):
self.client.remove_object(BUCKET, key)
def objects(self):
with self.operation("list"):
yield from self.client.list_objects(
BUCKET, prefix="objects/", recursive=True
)
def close(self):
self.http.clear()