Carry over the lab 5 solution

Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.

This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-29 03:51:58 +03:00
co-authored by Claude Opus 5.5
parent a0d3947710
commit 5ae3d77152
204 changed files with 18547 additions and 1 deletions
+259
View File
@@ -0,0 +1,259 @@
import asyncio
import base64
import hashlib
import json
import os
import re
import subprocess
import time
from collections.abc import AsyncIterator, Iterator
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from typing import Any
from uuid import uuid4
import pytest
from dishka import Provider, Scope, make_async_container, provide
from dishka_faststream import setup_dishka
from faststream.rabbit import Channel, RabbitBroker
from conftest import ROOT, STARTUP_SECONDS, container, image, published
from fakes import NullLogger
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import ProcessJob
from messenger.attachments.domain.jobs import Job, Outcome
from messenger.attachments.entrypoints.worker import subscribe
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
from messenger.shared.application.errors import Unavailable
from messenger.shared.application.ports import Logger
RABBITMQ_IMAGE = re.compile(r"image: (rabbitmq:\S+)")
PASSWORDS = {role: os.urandom(12).hex() for role in ("api", "worker", "ops")}
GRANTS = {
"api": ("^$", "^attachments$", "^$"),
"worker": ("^$", "^$", "^attachments\\.process$"),
"ops": (".*", ".*", ".*"),
}
def user(role: str) -> dict[str, Any]:
salt = os.urandom(4)
digest = hashlib.sha256(salt + PASSWORDS[role].encode()).digest()
return {
"name": f"messenger-{role}",
"password_hash": base64.b64encode(salt + digest).decode(),
"hashing_algorithm": "rabbit_password_hashing_sha256",
"tags": ["administrator"] if role == "ops" else [],
}
def definitions() -> dict[str, Any]:
return {
"users": [user(role) for role in PASSWORDS],
"permissions": [
{
"user": f"messenger-{role}",
"vhost": "messenger",
**dict(zip(("configure", "write", "read"), grant, strict=True)),
}
for role, grant in GRANTS.items()
],
}
def ready(name: str) -> bool:
probe = ["docker", "exec", name, "rabbitmq-diagnostics", "-q", "check_port_connectivity"]
return subprocess.run(probe, capture_output=True, check=False).returncode == 0
@pytest.fixture(scope="session")
def rabbitmq() -> Iterator[dict[str, Any]]:
name = f"mtusi-lab6-test-rabbitmq-{uuid4().hex[:8]}"
folder = ROOT / "build" / name
folder.mkdir(parents=True)
users = folder / "20-users.json"
users.write_text(json.dumps(definitions()))
users.chmod(0o644)
infra = ROOT / "infra" / "rabbitmq"
mounts = [
f"{infra / 'rabbitmq.conf'}:/etc/rabbitmq/conf.d/20-messenger.conf:ro",
f"{infra / 'enabled_plugins'}:/etc/rabbitmq/enabled_plugins:ro",
f"{infra / 'definitions.json'}:/etc/rabbitmq/definitions.d/10-topology.json:ro",
f"{users}:/etc/rabbitmq/definitions.d/20-users.json:ro",
]
volumes = [part for mount in mounts for part in ("-v", mount)]
container(
name,
"--hostname",
"broker",
"--user",
"100:101",
*volumes,
"-p",
"127.0.0.1::5672",
image(RABBITMQ_IMAGE),
)
try:
deadline = time.monotonic() + STARTUP_SECONDS * 2
while not ready(name):
assert time.monotonic() < deadline, "RabbitMQ не стал готов"
time.sleep(1)
port = published(name, 5672)
urls = {
role: f"amqp://messenger-{role}:{secret}@127.0.0.1:{port}/messenger"
for role, secret in PASSWORDS.items()
}
yield {"name": name, "urls": urls}
finally:
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=False)
users.unlink()
folder.rmdir()
def depth(broker: dict[str, Any], queue: str) -> int:
listing = subprocess.run(
[
"docker",
"exec",
broker["name"],
"rabbitmqctl",
"-q",
"list_queues",
"-p",
"messenger",
"name",
"messages",
"--formatter",
"json",
],
capture_output=True,
check=True,
text=True,
).stdout
return {row["name"]: row["messages"] for row in json.loads(listing)}[queue]
async def wait_for(probe: Any, seconds: float = 20) -> None:
deadline = time.monotonic() + seconds
while not probe():
assert time.monotonic() < deadline
await asyncio.sleep(0.1)
class NoEvents:
@asynccontextmanager
async def transaction(self) -> AsyncIterator[None]:
yield
async def commit(self) -> None: ...
def record(self, event: object) -> None: ...
def collect_new_events(self) -> list[Any]:
return []
class Recorder:
def __init__(self) -> None:
self.jobs: list[Job] = []
self.failures = 0
async def __call__(self, command: ProcessJob) -> Outcome:
if self.failures:
self.failures -= 1
raise Unavailable("PostgreSQL недоступен")
self.jobs.append(command.job)
return Outcome.DONE
class FakeBus(Provider):
def __init__(self, recorder: Recorder) -> None:
super().__init__()
self._recorder = recorder
@provide(scope=Scope.APP)
def logger(self) -> Logger:
return NullLogger()
@provide(scope=Scope.REQUEST)
def bus(self) -> AttachmentsCommandBus:
return AttachmentsCommandBus({ProcessJob: self._recorder}, NoEvents(), NoPublisher())
class NoPublisher:
async def publish(self, events: Any) -> None: ...
@asynccontextmanager
async def worker(rabbitmq: dict[str, Any], recorder: Recorder) -> AsyncIterator[None]:
broker = RabbitBroker(rabbitmq["urls"]["worker"], logger=None, graceful_timeout=2)
subscribe(broker, 2)
setup_dishka(make_async_container(FakeBus(recorder)), broker=broker, auto_inject=True)
await broker.start()
try:
yield
finally:
await broker.stop()
@asynccontextmanager
async def publisher(
rabbitmq: dict[str, Any], role: str = "api"
) -> AsyncIterator[RabbitJobPublisher]:
broker = RabbitBroker(
rabbitmq["urls"][role],
default_channel=Channel(publisher_confirms=True, on_return_raises=True),
logger=None,
)
await broker.connect()
try:
yield RabbitJobPublisher(broker, 5)
finally:
await broker.stop()
def job() -> Job:
return Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC))
def body(payload: dict[str, Any]) -> bytes:
return json.dumps(payload).encode()
async def test_confirmed_job_is_consumed_and_acked(rabbitmq: dict[str, Any]) -> None:
recorder, sent = Recorder(), job()
async with publisher(rabbitmq) as jobs:
await jobs.publish(sent.id, body(sent.payload()))
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 1)
async with worker(rabbitmq, recorder):
await wait_for(lambda: recorder.jobs)
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 0)
assert recorder.jobs == [sent]
async def test_message_off_the_schema_goes_to_the_dead_letter_queue(
rabbitmq: dict[str, Any],
) -> None:
before = depth(rabbitmq, "attachments.process.dlq")
async with publisher(rabbitmq) as jobs:
await jobs.publish(uuid4(), body({"schema_version": 2, "job_id": str(uuid4())}))
async with worker(rabbitmq, Recorder()):
await wait_for(lambda: depth(rabbitmq, "attachments.process.dlq") == before + 1)
assert depth(rabbitmq, "attachments.process") == 0
async def test_failed_processing_is_requeued_and_retried(rabbitmq: dict[str, Any]) -> None:
recorder, sent = Recorder(), job()
recorder.failures = 1
async with publisher(rabbitmq) as jobs:
await jobs.publish(sent.id, body(sent.payload()))
async with worker(rabbitmq, recorder):
await wait_for(lambda: recorder.jobs)
assert recorder.jobs == [sent]
async def test_worker_account_cannot_publish(rabbitmq: dict[str, Any]) -> None:
sent = job()
with pytest.raises(Unavailable):
async with publisher(rabbitmq, "worker") as jobs:
await jobs.publish(sent.id, body(sent.payload()))
+95
View File
@@ -0,0 +1,95 @@
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-lab6-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)