Files
mtusi2026lab4/student-tests/adapters/test_s3_storage.py
T
ArtyomandClaude Opus 5.5 5aa766acff Run RustFS with a private bucket in the stand
MinIO community images can no longer be pulled on this arm64 host, so
the stand runs RustFS 1.0.4 pinned by digest as non-root with a read
only root, no published port, the console off and data on the s3data
volume. A one-off s3-init with rc v0.1.36 creates the bucket, keeps it
private for anonymous clients, creates the API user with a policy on
the objects and listing of that one bucket, imports a lifecycle rule
for incomplete multipart uploads and checks itself; the API replicas
start only after it succeeded. Root keys reach only s3, s3-init and the
operator s3-cli; the API gets its own key and the S3 settings through
an anchor merged into its environment.

secrets.sh creates hex S3 keys, the restart hook restarts S3 next to
PostgreSQL and Valkey and waits until it is healthy, the limits policy
covers the S3 services, and the stack evidence lists the new packages.
The object storage adapter is tested against a throwaway RustFS of the
same image: a 10 MiB round trip, a missing object, an idempotent delete
and an unreachable endpoint failing within the request budget.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:50:03 +03:00

96 lines
3.3 KiB
Python

import os
import re
import subprocess
import time
from collections.abc import AsyncIterator, Iterator
from contextlib import asynccontextmanager
from uuid import uuid4
import httpx
import pytest
from conftest import STARTUP_SECONDS, container, image, published
from messenger.attachments.application.errors import ObjectMissingError
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
from messenger.shared.application.errors import Unavailable
RUSTFS_IMAGE = re.compile(r"image: (rustfs/rustfs:\S+)")
ROOT_KEY, ROOT_SECRET = "testroot", "testroot-secret-key"
BUCKET = "messenger-attachments"
@pytest.fixture(scope="session")
def rustfs() -> Iterator[str]:
name = f"mtusi-lab4-test-rustfs-{uuid4().hex[:8]}"
keys = ["-e", f"RUSTFS_ACCESS_KEY={ROOT_KEY}", "-e", f"RUSTFS_SECRET_KEY={ROOT_SECRET}"]
container(name, *keys, "-p", "127.0.0.1::9000", image(RUSTFS_IMAGE))
try:
endpoint = f"http://127.0.0.1:{published(name, 9000)}"
deadline = time.monotonic() + STARTUP_SECONDS
while True:
try:
if httpx.get(f"{endpoint}/health/ready", timeout=1).status_code == 200:
break
except httpx.TransportError:
pass
assert time.monotonic() < deadline, "RustFS не стал готов"
time.sleep(0.3)
yield endpoint
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
@asynccontextmanager
async def storage(endpoint: str) -> AsyncIterator[S3ObjectStorage]:
async with s3_client(
endpoint=endpoint,
region="us-east-1",
access_key_id=ROOT_KEY,
secret_access_key=ROOT_SECRET,
connect_timeout=1,
read_timeout=2,
max_attempts=2,
) as client:
buckets = await client.list_buckets()
if BUCKET not in {bucket["Name"] for bucket in buckets.get("Buckets", [])}:
await client.create_bucket(Bucket=BUCKET)
yield S3ObjectStorage(client, BUCKET)
async def test_round_trip_of_the_largest_object(rustfs: str) -> None:
data = os.urandom(10_485_760)
key = f"attachments/{uuid4()}"
async with storage(rustfs) as objects:
await objects.put(key, data, "image/png")
content = await objects.open(key)
assert content.size == len(data)
assert b"".join([chunk async for chunk in content.chunks]) == data
await objects.delete(key)
with pytest.raises(ObjectMissingError):
await objects.open(key)
await objects.delete(key)
async def test_unreachable_endpoint_is_unavailable_in_bounded_time() -> None:
started = time.monotonic()
async with storage_without_bucket("http://127.0.0.1:1") as objects:
with pytest.raises(Unavailable):
await objects.put("attachments/x", b"x", "image/png")
with pytest.raises(Unavailable):
await objects.open("attachments/x")
assert time.monotonic() - started < 8
@asynccontextmanager
async def storage_without_bucket(endpoint: str) -> AsyncIterator[S3ObjectStorage]:
async with s3_client(
endpoint=endpoint,
region="us-east-1",
access_key_id=ROOT_KEY,
secret_access_key=ROOT_SECRET,
connect_timeout=1,
read_timeout=2,
max_attempts=2,
) as client:
yield S3ObjectStorage(client, BUCKET)