Implement lab 7 transport security and worker containment
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import asyncio
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import PASSWORD, basic, new_user, running_app, sql_connection
|
||||
|
||||
|
||||
async def test_login_budget_shared_between_independent_apps(database: str) -> None:
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(text("DELETE FROM login_budget"))
|
||||
async with (
|
||||
running_app(login_attempts=3, login_window_seconds=60) as first,
|
||||
running_app(login_attempts=3, login_window_seconds=60) as second,
|
||||
):
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
text("INSERT INTO login_budget VALUES (1, floor(extract(epoch FROM now())/60), 1)")
|
||||
)
|
||||
responses = await asyncio.gather(
|
||||
*[
|
||||
http.post("/api/v1/auth/sessions", headers=basic("absent_user", PASSWORD))
|
||||
for http in [first, second] * 4
|
||||
]
|
||||
)
|
||||
assert sum(response.status_code == 401 for response in responses) == 2
|
||||
rejected = [response for response in responses if response.status_code == 429]
|
||||
assert len(rejected) == 6
|
||||
assert all(response.headers["retry-after"] == "60" for response in rejected)
|
||||
|
||||
|
||||
async def test_successful_login_upgrades_old_hash_without_changing_password(database: str) -> None:
|
||||
old = PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1)
|
||||
async with running_app() as http:
|
||||
user = new_user("rehash")
|
||||
registered = await http.post("/api/v1/users", json=user)
|
||||
assert registered.status_code == 201
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
text("UPDATE users SET password_hash=:hash WHERE username=:username"),
|
||||
{"hash": old.hash(PASSWORD), "username": user["username"]},
|
||||
)
|
||||
response = await http.post(
|
||||
"/api/v1/auth/sessions", headers=basic(user["username"], PASSWORD)
|
||||
)
|
||||
assert response.status_code == 201
|
||||
async with sql_connection() as connection:
|
||||
current = (
|
||||
await connection.execute(
|
||||
text("SELECT password_hash FROM users WHERE username=:username"),
|
||||
{"username": user["username"]},
|
||||
)
|
||||
).scalar_one()
|
||||
assert "m=19456,t=2,p=1" in current
|
||||
assert old.verify(current, PASSWORD)
|
||||
@@ -0,0 +1,274 @@
|
||||
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, free_port, image, published
|
||||
from fakes import NullLogger
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import ProcessJob
|
||||
from messenger.attachments.application.ports import JobObserver
|
||||
from messenger.attachments.domain.jobs import Job, Outcome
|
||||
from messenger.attachments.entrypoints.worker import subscribe
|
||||
from messenger.attachments.infrastructure.rabbitmq import RabbitJobPublisher
|
||||
from messenger.attachments.infrastructure.telemetry import OtelJobObserver
|
||||
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"
|
||||
config = folder / "rabbitmq.conf"
|
||||
config.write_text((infra / "rabbitmq.conf").read_text().replace("127.0.0.1", "0.0.0.0"))
|
||||
mounts = [
|
||||
f"{config}:/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",
|
||||
f"127.0.0.1:{free_port()}: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()
|
||||
config.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.APP)
|
||||
def observer(self) -> JobObserver:
|
||||
return OtelJobObserver()
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failures", [1, 12])
|
||||
async def test_failed_processing_is_requeued_and_retried(
|
||||
rabbitmq: dict[str, Any], failures: int
|
||||
) -> None:
|
||||
recorder, sent = Recorder(), job()
|
||||
recorder.failures = failures
|
||||
before = depth(rabbitmq, "attachments.process.dlq")
|
||||
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, seconds=40)
|
||||
await wait_for(lambda: depth(rabbitmq, "attachments.process") == 0)
|
||||
assert recorder.jobs == [sent]
|
||||
assert depth(rabbitmq, "attachments.process.dlq") == before
|
||||
|
||||
|
||||
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()))
|
||||
@@ -0,0 +1,120 @@
|
||||
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, free_port, 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", f"127.0.0.1:{free_port()}: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_listing_is_paged_in_byte_order_and_stat_reads_size(rustfs: str) -> None:
|
||||
prefix = f"reconcile-{uuid4().hex}/"
|
||||
keys = [f"{prefix}{name}" for name in ("b", "a", "Z", "a-1", "é")]
|
||||
async with storage(rustfs) as objects:
|
||||
for size, key in enumerate(keys, start=1):
|
||||
await objects.put(key, b"x" * size, "image/png")
|
||||
pages = [page async for page in objects.listing(prefix, 2)]
|
||||
assert [len(page) for page in pages] == [2, 2, 1]
|
||||
listed = [item.key for page in pages for item in page]
|
||||
assert listed == sorted(keys, key=str.encode)
|
||||
sizes = {item.key: item.size for page in pages for item in page}
|
||||
assert sizes == {key: size for size, key in enumerate(keys, start=1)}
|
||||
found = await objects.stat(keys[0])
|
||||
assert found is not None
|
||||
assert found.size == 1
|
||||
assert await objects.stat(f"{prefix}absent") is None
|
||||
for key in keys:
|
||||
await objects.delete(key)
|
||||
assert not [item async for page in objects.listing(prefix, 2) for item in page]
|
||||
|
||||
|
||||
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")
|
||||
with pytest.raises(Unavailable):
|
||||
await objects.stat("attachments/x")
|
||||
with pytest.raises(Unavailable):
|
||||
await anext(aiter(objects.listing("attachments/", 10)))
|
||||
assert time.monotonic() - started < 12
|
||||
|
||||
|
||||
@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)
|
||||
@@ -0,0 +1,120 @@
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import select
|
||||
|
||||
from conftest import actor, keyed, make_chat, register, sql_connection
|
||||
from messenger.messaging.infrastructure.postgres import ChatRow
|
||||
|
||||
|
||||
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
response = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_unknown_chat_is_indistinguishable_from_foreign(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
foreign = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
|
||||
missing = await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(eve))
|
||||
assert foreign.status_code == missing.status_code == 404
|
||||
assert foreign.json()["error"]["code"] == missing.json()["error"]["code"]
|
||||
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
|
||||
|
||||
|
||||
async def test_outsider_cannot_write(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "чужое"},
|
||||
headers=keyed(eve),
|
||||
)
|
||||
assert response.status_code == 404
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
async def test_outsider_cannot_read_history(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_access_checked_before_body(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
headers=keyed(eve),
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_chat_list_hides_foreign_chats(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
for member in (alice, bob):
|
||||
listed = await client.get("/api/v1/chats?limit=100", headers=actor(member))
|
||||
assert any(item["id"] == chat["id"] for item in listed.json()["items"])
|
||||
hidden = await client.get("/api/v1/chats?limit=100", headers=actor(eve))
|
||||
assert hidden.json()["items"] == []
|
||||
|
||||
|
||||
async def test_403_is_never_used(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
paths = [
|
||||
f"/api/v1/chats/{chat['id']}",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
]
|
||||
for path in paths:
|
||||
assert (await client.get(path, headers=actor(eve))).status_code != 403
|
||||
|
||||
|
||||
async def test_request_shape_is_checked_before_access(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
for chat_id in (chat["id"], uuid4()):
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
unkeyed = await client.post(path, json={"text": "чужое"}, headers=actor(eve))
|
||||
extra = await client.post(path, json={"text": "x", "a": 1}, headers=keyed(eve))
|
||||
assert unkeyed.status_code == extra.status_code == 400
|
||||
assert unkeyed.json()["error"]["code"] == extra.json()["error"]["code"] == "invalid_request"
|
||||
blank = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": " "}, headers=keyed(eve)
|
||||
)
|
||||
assert blank.status_code == 404
|
||||
|
||||
|
||||
async def test_outsider_does_not_wait_for_members_lock(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
async with sql_connection() as holder:
|
||||
await holder.execute(
|
||||
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
|
||||
)
|
||||
started = time.perf_counter()
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
|
||||
)
|
||||
elapsed = time.perf_counter() - started
|
||||
assert response.status_code == 404
|
||||
assert elapsed < 0.5
|
||||
@@ -0,0 +1,342 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from hashlib import sha256
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
from PIL import Image
|
||||
|
||||
from conftest import actor, make_chat, register, resolve, running_app, scalar
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG, GIF, JPEG, SAMPLE, WEBP, png
|
||||
from pipeline import settle
|
||||
|
||||
LIMIT = 10_485_760
|
||||
PNG = {"Content-Type": "image/png"}
|
||||
|
||||
|
||||
async def upload(
|
||||
http: AsyncClient,
|
||||
user: dict[str, Any],
|
||||
chat: dict[str, Any],
|
||||
content: bytes | AsyncIterator[bytes] = SAMPLE,
|
||||
*,
|
||||
filename: str | None = "sample.png",
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Response:
|
||||
query = "" if filename is None else f"?filename={quote(filename, safe='')}"
|
||||
return await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments{query}",
|
||||
content=content,
|
||||
headers={**actor(user), **(PNG if headers is None else headers)},
|
||||
)
|
||||
|
||||
|
||||
async def storage(http: AsyncClient) -> MemoryObjectStorage:
|
||||
found = await resolve(http, ObjectStorage)
|
||||
assert isinstance(found, MemoryObjectStorage)
|
||||
return found
|
||||
|
||||
|
||||
async def trio(http: AsyncClient) -> tuple[dict[str, Any], ...]:
|
||||
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
|
||||
return alice, bob, eve, await make_chat(http, alice, bob)
|
||||
|
||||
|
||||
async def test_member_uploads_and_another_member_downloads(client: AsyncClient) -> None:
|
||||
alice, bob, eve, chat = await trio(client)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
attachment = response.json()
|
||||
assert set(attachment) == {
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"status",
|
||||
"variants",
|
||||
"error_code",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
}
|
||||
assert attachment["chat_id"] == chat["id"]
|
||||
assert attachment["owner_id"] == alice["id"]
|
||||
assert attachment["filename"] == "sample.png"
|
||||
assert attachment["content_type"] == "image/png"
|
||||
assert attachment["size_bytes"] == len(SAMPLE) == 111817
|
||||
assert attachment["sha256"] == sha256(SAMPLE).hexdigest()
|
||||
assert (attachment["status"], attachment["variants"], attachment["error_code"]) == (
|
||||
"queued",
|
||||
[],
|
||||
None,
|
||||
)
|
||||
assert attachment["created_at"].endswith("Z")
|
||||
path = f"/api/v1/attachments/{attachment['id']}"
|
||||
assert (await client.get(path, headers=actor(bob))).json() == attachment
|
||||
await settle(client)
|
||||
ready = (await client.get(path, headers=actor(bob))).json()
|
||||
assert (ready["status"], ready["error_code"], ready["sha256"]) == (
|
||||
"ready",
|
||||
None,
|
||||
attachment["sha256"],
|
||||
)
|
||||
assert [variant["name"] for variant in ready["variants"]] == ["crop", "optimized", "thumbnail"]
|
||||
content = await client.get(
|
||||
f"{path}/content", headers={**actor(bob), "Accept": "application/json"}
|
||||
)
|
||||
assert content.status_code == 200
|
||||
assert content.content == SAMPLE
|
||||
assert content.headers["content-type"] == "image/png"
|
||||
assert content.headers["content-length"] == str(len(SAMPLE))
|
||||
assert content.headers["x-content-type-options"] == "nosniff"
|
||||
assert content.headers["x-request-id"]
|
||||
assert content.headers["x-instance-id"]
|
||||
for suffix in ("", "/content"):
|
||||
stranger = await client.get(f"{path}{suffix}", headers=actor(eve))
|
||||
assert stranger.status_code == 404
|
||||
assert stranger.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_object_keys_are_assigned_by_server(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat, filename="a.png")).json()
|
||||
staging = await scalar("SELECT staging_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert staging == f"staging/{attachment['id']}"
|
||||
assert set((await storage(client)).objects) >= {staging}
|
||||
await settle(client)
|
||||
original = await scalar("SELECT original_key FROM attachments WHERE id = $1", attachment["id"])
|
||||
assert original == f"originals/{attachment['id']}"
|
||||
assert (await storage(client)).objects[original][0] == SAMPLE
|
||||
|
||||
|
||||
async def test_jpeg_is_accepted_by_content(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, JPEG, headers={"Content-Type": "IMAGE/JPEG"})
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["content_type"] == "image/jpeg"
|
||||
await settle(client)
|
||||
download = await client.get(
|
||||
f"/api/v1/attachments/{response.json()['id']}/content", headers=actor(bob)
|
||||
)
|
||||
assert (download.content, download.headers["content-type"]) == (JPEG, "image/jpeg")
|
||||
|
||||
|
||||
async def test_access_is_checked_before_content(client: AsyncClient) -> None:
|
||||
alice, _, eve, chat = await trio(client)
|
||||
assert (await upload(client, eve, chat, b"not an image", filename="../x")).status_code == 404
|
||||
missing = {"id": str(uuid4())}
|
||||
assert (await upload(client, alice, missing)).status_code == 404
|
||||
anonymous = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", content=SAMPLE, headers=PNG
|
||||
)
|
||||
assert anonymous.status_code == 401
|
||||
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
async def test_token_is_checked_before_the_declared_size() -> None:
|
||||
async with running_app(max_upload_bytes=4096) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
oversized = png(16, 16, size=8192)
|
||||
anonymous = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", content=oversized, headers=PNG
|
||||
)
|
||||
assert anonymous.status_code == 401
|
||||
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
|
||||
assert (await upload(http, alice, chat, oversized)).status_code == 413
|
||||
|
||||
|
||||
async def test_exact_limit_is_accepted(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, png(16, 16, size=LIMIT))
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["size_bytes"] == LIMIT
|
||||
|
||||
|
||||
async def test_one_byte_over_with_content_length(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, png(16, 16, size=LIMIT + 1))
|
||||
assert response.status_code == 413
|
||||
assert response.json()["error"]["code"] == "payload_too_large"
|
||||
|
||||
|
||||
async def test_one_byte_over_chunked(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
body = png(16, 16, size=LIMIT + 1)
|
||||
|
||||
async def chunked() -> AsyncIterator[bytes]:
|
||||
for start in range(0, len(body), 1 << 20):
|
||||
yield body[start : start + (1 << 20)]
|
||||
|
||||
before = await scalar("SELECT count(*) FROM attachments")
|
||||
response = await upload(client, alice, chat, chunked())
|
||||
assert response.status_code == 413
|
||||
assert await scalar("SELECT count(*) FROM attachments") == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("width", "height", "status"),
|
||||
[(8000, 5000, 202), (8001, 5000, 413), (100_000, 100_000, 413)],
|
||||
)
|
||||
async def test_pixel_limit_is_read_from_header(
|
||||
client: AsyncClient, width: int, height: int, status: int
|
||||
) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
body = png(width, height, rows=width * height <= 40_000_000)
|
||||
assert len(body) < 64_000
|
||||
response = await upload(client, alice, chat, body)
|
||||
assert response.status_code == status, response.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("content", "header"),
|
||||
[
|
||||
(BROKEN_PNG, "image/png"),
|
||||
(DUPLICATE_IHDR_PNG, "image/png"),
|
||||
(JPEG, "image/png"),
|
||||
(GIF, "image/png"),
|
||||
(WEBP, "image/png"),
|
||||
(b"plain text, not an image", "image/png"),
|
||||
(SAMPLE, "image/jpeg"),
|
||||
(SAMPLE[: len(SAMPLE) // 2], "image/png"),
|
||||
(JPEG[: len(JPEG) // 2], "image/jpeg"),
|
||||
(b"", "image/png"),
|
||||
(SAMPLE, "application/octet-stream"),
|
||||
(SAMPLE, "image/gif"),
|
||||
],
|
||||
ids=[
|
||||
"invalid-zlib",
|
||||
"duplicate-ihdr",
|
||||
"jpeg-as-png",
|
||||
"gif-as-png",
|
||||
"webp-as-png",
|
||||
"text-as-png",
|
||||
"png-as-jpeg",
|
||||
"truncated-png",
|
||||
"truncated-jpeg",
|
||||
"empty",
|
||||
"octet-stream",
|
||||
"gif-type",
|
||||
],
|
||||
)
|
||||
async def test_type_is_checked_by_content(client: AsyncClient, content: bytes, header: str) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, content, headers={"Content-Type": header})
|
||||
assert response.status_code == 415, response.text
|
||||
assert response.json()["error"]["code"] == "unsupported_media_type"
|
||||
|
||||
|
||||
async def test_missing_content_type_is_unsupported(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, headers={})
|
||||
assert response.status_code == 415
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"filename",
|
||||
[
|
||||
*("../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\x01.png", "a\x7f.png"),
|
||||
*("", " ", "x" * 256, None),
|
||||
],
|
||||
)
|
||||
async def test_dangerous_filename_is_rejected(client: AsyncClient, filename: str | None) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
assert response.status_code == 400, response.text
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filename", ["фото 1.png", "я" * 255, "%41.png"])
|
||||
async def test_display_name_is_kept(client: AsyncClient, filename: str) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()["filename"] == filename
|
||||
|
||||
|
||||
async def test_content_waits_for_ready_and_serves_every_variant(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
for variant in ("original", "thumbnail", "crop", "optimized"):
|
||||
early = await client.get(f"{path}?variant={variant}", headers=actor(bob))
|
||||
assert early.status_code == 409, early.text
|
||||
assert early.json()["error"]["code"] == "conflict"
|
||||
await settle(client)
|
||||
assert (await client.get(f"{path}?variant=original", headers=actor(alice))).status_code == 200
|
||||
meta = (await client.get(path.removesuffix("/content"), headers=actor(bob))).json()
|
||||
expected = {
|
||||
"crop": ("image/jpeg", "JPEG", (128, 128)),
|
||||
"optimized": ("image/webp", "WEBP", (320, 200)),
|
||||
"thumbnail": ("image/jpeg", "JPEG", (256, 160)),
|
||||
}
|
||||
for variant in meta["variants"]:
|
||||
served = await client.get(f"{path}?variant={variant['name']}", headers=actor(bob))
|
||||
content_type, kind, size = expected[variant["name"]]
|
||||
assert (served.headers["content-type"], variant["content_type"]) == (content_type,) * 2
|
||||
assert len(served.content) == variant["size_bytes"]
|
||||
assert sha256(served.content).hexdigest() == variant["sha256"]
|
||||
image = Image.open(BytesIO(served.content))
|
||||
assert (image.format, image.size, (variant["width"], variant["height"])) == (
|
||||
kind,
|
||||
size,
|
||||
size,
|
||||
)
|
||||
await scalar(
|
||||
"DELETE FROM attachment_variants WHERE attachment_id = $1 AND name = 'crop'",
|
||||
UUID(attachment["id"]),
|
||||
)
|
||||
missing = await client.get(f"{path}?variant=crop", headers=actor(alice))
|
||||
assert missing.status_code == 404
|
||||
assert (await client.get(f"{path}?variant=preview", headers=actor(alice))).status_code == 400
|
||||
assert (
|
||||
await client.get("/api/v1/attachments/x/content", headers=actor(alice))
|
||||
).status_code == 400
|
||||
unknown = await client.get(f"/api/v1/attachments/{uuid4()}", headers=actor(alice))
|
||||
assert unknown.status_code == 404
|
||||
|
||||
|
||||
async def test_storage_failure_leaves_nothing_visible(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
ready = await upload(client, alice, chat)
|
||||
await settle(client)
|
||||
store = await storage(client)
|
||||
store.failing = True
|
||||
try:
|
||||
failed = await upload(client, alice, chat, filename="failed.png")
|
||||
download = await client.get(
|
||||
f"/api/v1/attachments/{ready.json()['id']}/content", headers=actor(alice)
|
||||
)
|
||||
metadata = await client.get(
|
||||
f"/api/v1/attachments/{ready.json()['id']}", headers=actor(alice)
|
||||
)
|
||||
finally:
|
||||
store.failing = False
|
||||
assert failed.status_code == 503
|
||||
assert failed.json()["error"]["code"] == "unavailable"
|
||||
assert download.status_code == 503
|
||||
assert metadata.status_code == 200
|
||||
status = await scalar(
|
||||
"SELECT string_agg(status, ',') FROM attachments WHERE chat_id = $1 AND filename = $2",
|
||||
chat["id"],
|
||||
"failed.png",
|
||||
)
|
||||
assert status == "pending"
|
||||
|
||||
|
||||
async def test_lost_object_is_not_found(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
await settle(client)
|
||||
(await storage(client)).objects.clear()
|
||||
response = await client.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=actor(alice)
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
@@ -0,0 +1,298 @@
|
||||
import ast
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "src" / "messenger"
|
||||
IDENTITY = "messenger.identity"
|
||||
MESSAGING = "messenger.messaging"
|
||||
ATTACHMENTS = "messenger.attachments"
|
||||
ZONES = ("identity", "messaging", "attachments")
|
||||
|
||||
|
||||
def imports_of(path: Path) -> list[str]:
|
||||
tree = ast.parse(path.read_text(), filename=str(path))
|
||||
found: list[str] = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module:
|
||||
found.append(node.module)
|
||||
elif isinstance(node, ast.Import):
|
||||
found.extend(alias.name for alias in node.names)
|
||||
return found
|
||||
|
||||
|
||||
def modules_under(*parts: str) -> list[Path]:
|
||||
root = SOURCE.joinpath(*parts)
|
||||
return [path for path in root.rglob("*.py") if path.name != "__init__.py"]
|
||||
|
||||
|
||||
def test_identity_does_not_know_about_messaging() -> None:
|
||||
offenders = {
|
||||
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(MESSAGING)]
|
||||
for path in modules_under("identity")
|
||||
}
|
||||
assert not {k: v for k, v in offenders.items() if v}
|
||||
|
||||
|
||||
def test_attachments_and_other_zones_do_not_import_each_other() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone, foreign in (
|
||||
("attachments", (IDENTITY, MESSAGING)),
|
||||
("identity", (ATTACHMENTS,)),
|
||||
("messaging", (ATTACHMENTS,)),
|
||||
):
|
||||
for path in modules_under(zone):
|
||||
borrowed = [m for m in imports_of(path) if m.startswith(foreign)]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_domains_do_not_import_infrastructure() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in (*ZONES, "shared"):
|
||||
for layer in ("domain", "application"):
|
||||
for path in modules_under(zone, layer):
|
||||
borrowed = [m for m in imports_of(path) if ".infrastructure" in m]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_core_layers_do_not_import_pydantic() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for zone in (*ZONES, "shared"):
|
||||
for layer in ("domain", "application"):
|
||||
for path in modules_under(zone, layer):
|
||||
borrowed = [m for m in imports_of(path) if m.split(".")[0] == "pydantic"]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders, "схемы pydantic живут на границе: в entrypoints/ и config.py"
|
||||
|
||||
|
||||
def test_shared_knows_nothing_about_zones() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in modules_under("shared"):
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
TRANSPORT = ("fastapi", "starlette", "uvicorn", "gunicorn")
|
||||
|
||||
|
||||
def test_shared_core_is_free_of_transport() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for layer in ("domain", "application", "infrastructure"):
|
||||
for path in modules_under("shared", layer):
|
||||
borrowed = [module for module in imports_of(path) if module.split(".")[0] in TRANSPORT]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders, "ядро shared обязано жить без веб-фреймворка"
|
||||
|
||||
|
||||
def test_shared_core_holds_only_platform() -> None:
|
||||
names = {
|
||||
path.name
|
||||
for layer in ("domain", "application", "infrastructure")
|
||||
for path in modules_under("shared", layer)
|
||||
}
|
||||
assert names == {
|
||||
"errors.py",
|
||||
"events.py",
|
||||
"commands.py",
|
||||
"messagebus.py",
|
||||
"ports.py",
|
||||
"clock.py",
|
||||
"ids.py",
|
||||
"logging.py",
|
||||
"postgres.py",
|
||||
"telemetry.py",
|
||||
"trace_context.py",
|
||||
"runtime_metrics.py",
|
||||
"readiness.py",
|
||||
}
|
||||
|
||||
|
||||
def test_shared_entrypoints_hold_only_transport() -> None:
|
||||
names = {path.name for path in modules_under("shared", "entrypoints")}
|
||||
assert names == {
|
||||
"actor.py",
|
||||
"config.py",
|
||||
"errors.py",
|
||||
"health.py",
|
||||
"ioc.py",
|
||||
"pipeline.py",
|
||||
"schemas.py",
|
||||
"telemetry.py",
|
||||
}
|
||||
|
||||
|
||||
def test_every_zone_owns_its_errors_events_and_commands() -> None:
|
||||
for zone in ZONES:
|
||||
assert (SOURCE / zone / "domain" / "errors.py").is_file()
|
||||
assert (SOURCE / zone / "domain" / "events.py").is_file()
|
||||
assert (SOURCE / zone / "application" / "commands.py").is_file()
|
||||
|
||||
|
||||
def test_every_zone_owns_its_http_layer() -> None:
|
||||
for zone in ZONES:
|
||||
for part in ("http.py", "ioc.py", "errors.py", "journal.py"):
|
||||
assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}"
|
||||
|
||||
|
||||
PROCESSES = {"relay.py": (ATTACHMENTS,), "worker.py": (ATTACHMENTS,), "admin.py": (ATTACHMENTS,)}
|
||||
|
||||
|
||||
def test_only_main_knows_several_zones() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in SOURCE.rglob("*.py"):
|
||||
relative = path.relative_to(SOURCE)
|
||||
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in ZONES:
|
||||
continue
|
||||
allowed = PROCESSES.get(str(relative), ())
|
||||
borrowed = [
|
||||
module
|
||||
for module in imports_of(path)
|
||||
if module.startswith((IDENTITY, MESSAGING, ATTACHMENTS))
|
||||
and not module.startswith(allowed or ("-",))
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(relative)] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_broker_framework_stays_out_of_shared_and_core_layers() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in [
|
||||
*modules_under("shared"),
|
||||
*(
|
||||
p
|
||||
for zone in ZONES
|
||||
for layer in ("domain", "application")
|
||||
for p in modules_under(zone, layer)
|
||||
),
|
||||
]:
|
||||
borrowed = [
|
||||
m for m in imports_of(path) if m.split(".")[0] in {"faststream", "aio_pika", "aiormq"}
|
||||
]
|
||||
if borrowed:
|
||||
offenders[str(path.relative_to(SOURCE))] = borrowed
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_application_has_no_separate_entrypoints_root() -> None:
|
||||
assert not (SOURCE / "entrypoints").exists()
|
||||
assert (SOURCE / "main.py").is_file()
|
||||
|
||||
|
||||
ZONE_WORDS = (
|
||||
"username",
|
||||
"display_name",
|
||||
"chat",
|
||||
"member",
|
||||
"history",
|
||||
"cursor",
|
||||
"sender",
|
||||
"message_id",
|
||||
"message_text",
|
||||
"attachment",
|
||||
"filename",
|
||||
)
|
||||
|
||||
|
||||
def test_shared_source_mentions_no_domain_vocabulary() -> None:
|
||||
offenders: dict[str, list[str]] = {}
|
||||
for path in modules_under("shared"):
|
||||
source = path.read_text().lower()
|
||||
hits = sorted({word for word in ZONE_WORDS if word in source})
|
||||
if hits:
|
||||
offenders[str(path.relative_to(SOURCE))] = hits
|
||||
assert not offenders
|
||||
|
||||
|
||||
def test_shared_declares_no_concrete_commands_or_events() -> None:
|
||||
for path in modules_under("shared"):
|
||||
tree = ast.parse(path.read_text(), filename=str(path))
|
||||
declared = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]
|
||||
concrete = [
|
||||
name
|
||||
for name in declared
|
||||
if name not in {"Command", "DomainEvent", "DomainError"}
|
||||
and (
|
||||
name.endswith("Event")
|
||||
or name in {"RegisterUser", "CreateChat", "PostMessage", "UploadAttachment"}
|
||||
)
|
||||
]
|
||||
assert not concrete, f"{path.name}: {concrete}"
|
||||
|
||||
|
||||
def test_shared_has_no_test_doubles() -> None:
|
||||
for path in modules_under("shared"):
|
||||
source = path.read_text()
|
||||
for marker in ("Frozen", "Fake", "Stub", "Null", "Dummy"):
|
||||
assert marker not in source, f"{path.name} содержит подделку {marker}"
|
||||
|
||||
|
||||
def test_zone_errors_do_not_leak_transport_codes() -> None:
|
||||
for zone in (*ZONES, "shared"):
|
||||
source = (SOURCE / zone / "domain" / "errors.py").read_text()
|
||||
assert "http_status" not in source
|
||||
assert "invalid_request" not in source
|
||||
assert "404" not in source
|
||||
|
||||
|
||||
IDENTITY_TABLES = ("users", "sessions")
|
||||
MESSAGING_TABLES = ("chats", "chat_members", "messages", "idempotency_keys", "message_attachments")
|
||||
ATTACHMENT_TABLES = ("attachments", "attachment_variants", "jobs", "outbox", "job_events")
|
||||
|
||||
|
||||
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
|
||||
words: set[str] = set()
|
||||
for path in modules_under(zone):
|
||||
tree = ast.parse(path.read_text(), filename=str(path))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value))
|
||||
if (
|
||||
isinstance(node, ast.Assign)
|
||||
and any(
|
||||
isinstance(target, ast.Name) and target.id == "__tablename__"
|
||||
for target in node.targets
|
||||
)
|
||||
and isinstance(node.value, ast.Constant)
|
||||
and isinstance(node.value.value, str)
|
||||
):
|
||||
words.add(node.value.value)
|
||||
return words & set(tables)
|
||||
|
||||
|
||||
def test_sql_of_each_zone_reads_only_its_tables() -> None:
|
||||
owned = {
|
||||
"identity": IDENTITY_TABLES,
|
||||
"messaging": MESSAGING_TABLES,
|
||||
"attachments": ATTACHMENT_TABLES,
|
||||
}
|
||||
every = {table for tables in owned.values() for table in tables}
|
||||
for zone, tables in owned.items():
|
||||
assert sql_tables(zone, tuple(every)) == set(tables), zone
|
||||
|
||||
|
||||
def test_messaging_does_not_import_identity_at_all() -> None:
|
||||
borrowed = {
|
||||
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(IDENTITY)]
|
||||
for path in modules_under("messaging")
|
||||
}
|
||||
assert not {key: value for key, value in borrowed.items() if value}
|
||||
|
||||
|
||||
def test_sqlalchemy_stays_in_infrastructure_and_asyncpg_is_only_a_driver() -> None:
|
||||
for path in SOURCE.rglob("*.py"):
|
||||
modules = {module.split(".")[0] for module in imports_of(path)}
|
||||
assert "asyncpg" not in modules
|
||||
if "infrastructure" not in path.parts:
|
||||
assert "sqlalchemy" not in modules
|
||||
@@ -0,0 +1,226 @@
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from redis.asyncio import Redis
|
||||
from sqlalchemy import select
|
||||
|
||||
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
|
||||
from messenger.identity.application.ports import SessionDirectory
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.identity.infrastructure.postgres import (
|
||||
PostgresIdentityUnitOfWork,
|
||||
PostgresSessionDirectory,
|
||||
PostgresSessionRepository,
|
||||
SessionRow,
|
||||
)
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def key_of(token: str) -> str:
|
||||
return f"session:{sha256(token.encode()).hexdigest()}"
|
||||
|
||||
|
||||
def token_of(user: dict) -> str:
|
||||
return actor(user)["Authorization"].split()[1]
|
||||
|
||||
|
||||
async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None:
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
hits = (await cache.info("stats"))["keyspace_hits"]
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
|
||||
key = key_of(token_of(alice))
|
||||
stored = str(await cache.get(key))
|
||||
expires_at: datetime = await scalar(
|
||||
select(SessionRow.expires_at).where(SessionRow.user_id == UUID(alice["id"]))
|
||||
)
|
||||
assert alice["id"] in stored and token_of(alice) not in stored
|
||||
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
async def test_logout_leaves_tombstone_after_commit(valkey: dict[str, str]) -> None:
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
).status_code == 204
|
||||
assert await cache.get(key_of(token_of(alice))) == b"-"
|
||||
response = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"] == BEARER
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["remove", "commit"])
|
||||
async def test_logout_rejected_by_database_changes_nothing(
|
||||
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, failure: str
|
||||
) -> None:
|
||||
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
|
||||
async def broken_commit(self: PostgresIdentityUnitOfWork) -> None:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
logout = "/api/v1/auth/sessions/current"
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
with monkeypatch.context() as patch:
|
||||
if failure == "remove":
|
||||
patch.setattr(PostgresSessionRepository, "remove", broken)
|
||||
else:
|
||||
patch.setattr(PostgresIdentityUnitOfWork, "commit", broken_commit)
|
||||
failed = await http.delete(logout, headers=actor(alice))
|
||||
assert failed.status_code == 503
|
||||
assert failed.json()["error"]["code"] == "unavailable"
|
||||
assert await cache.get(key_of(token_of(alice))) is None
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (await http.delete(logout, headers=actor(alice))).status_code == 204
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
|
||||
async def test_fill_racing_with_logout_does_not_revive_token(
|
||||
valkey: dict[str, str], loss: str
|
||||
) -> None:
|
||||
async with (
|
||||
Redis.from_url(valkey["url"]) as cache,
|
||||
running_app(cache_url=valkey["url"]) as http,
|
||||
):
|
||||
alice = await register(http, "alice")
|
||||
directory = await resolve(http, SessionDirectory)
|
||||
assert isinstance(directory, CachedSessionDirectory)
|
||||
origin = directory._origin
|
||||
stale: list[Session | None] = []
|
||||
entered, released = asyncio.Event(), asyncio.Event()
|
||||
|
||||
class SlowOrigin:
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
stale.append(await origin.find(token_hash, now))
|
||||
entered.set()
|
||||
await released.wait()
|
||||
return stale[-1]
|
||||
|
||||
directory._origin = SlowOrigin()
|
||||
async with asyncio.TaskGroup() as group:
|
||||
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
directory._origin = origin
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
).status_code == 204
|
||||
key = key_of(token_of(alice))
|
||||
assert await cache.get(f"{key}:fill") is None
|
||||
if loss == "flushall":
|
||||
await cache.flushall()
|
||||
elif loss in {"evict", "replacement"}:
|
||||
await cache.delete(key)
|
||||
if loss == "replacement":
|
||||
await cache.set(f"{key}:fill", "another-reader", px=1000)
|
||||
finally:
|
||||
released.set()
|
||||
assert reader.result().status_code == 200
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loss", ["flushall", "evict"])
|
||||
async def test_cache_loss_before_logout_commit_cannot_refill_deleted_session(
|
||||
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, loss: str
|
||||
) -> None:
|
||||
revoked, release_commit, reading = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
||||
revoke = CachedSessionDirectory.revoke
|
||||
find = PostgresSessionDirectory.find
|
||||
|
||||
async def paused_revoke(self: CachedSessionDirectory, session: Session) -> None:
|
||||
await revoke(self, session)
|
||||
revoked.set()
|
||||
await release_commit.wait()
|
||||
|
||||
async def observed_find(
|
||||
self: PostgresSessionDirectory, token_hash: bytes, now: datetime
|
||||
) -> Session | None:
|
||||
reading.set()
|
||||
return await find(self, token_hash, now)
|
||||
|
||||
async with (
|
||||
Redis.from_url(valkey["url"]) as cache,
|
||||
running_app(cache_url=valkey["url"]) as http,
|
||||
):
|
||||
alice = await register(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
monkeypatch.setattr(CachedSessionDirectory, "revoke", paused_revoke)
|
||||
async with asyncio.TaskGroup() as group:
|
||||
logout = group.create_task(
|
||||
http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(revoked.wait(), 5)
|
||||
if loss == "flushall":
|
||||
await cache.flushall()
|
||||
else:
|
||||
await cache.delete(key_of(token_of(alice)))
|
||||
monkeypatch.setattr(PostgresSessionDirectory, "find", observed_find)
|
||||
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
|
||||
await asyncio.wait_for(reading.wait(), 5)
|
||||
done, _ = await asyncio.wait({reader}, timeout=0.1)
|
||||
assert not done
|
||||
finally:
|
||||
release_commit.set()
|
||||
assert logout.result().status_code == 204
|
||||
assert reader.result().status_code == 401
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
|
||||
|
||||
|
||||
async def test_flushall_loses_nothing(valkey: dict[str, str]) -> None:
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
async with running_app(cache_url=valkey["url"]) as http:
|
||||
alice = await register(http, "alice")
|
||||
bob = await register(http, "bob")
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(bob))
|
||||
).status_code == 204
|
||||
await cache.flushall()
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(bob))).status_code == 401
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
|
||||
async with running_app(cache_url="redis://127.0.0.1:1/0") as http:
|
||||
alice = await register(http, "alice")
|
||||
started = time.perf_counter()
|
||||
me = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
|
||||
elapsed = time.perf_counter() - started
|
||||
ready = await http.get("/health/ready")
|
||||
chat = await make_chat(http, alice)
|
||||
posted = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без кэша"}, headers=keyed(alice)
|
||||
)
|
||||
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
still = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
assert me.json() == alice
|
||||
assert stranger.status_code == 401
|
||||
assert stranger.headers["WWW-Authenticate"] == BEARER
|
||||
assert elapsed < 1
|
||||
assert ready.status_code == 200
|
||||
assert posted.status_code == 201
|
||||
assert logout.status_code == 503
|
||||
assert logout.json()["error"]["code"] == "unavailable"
|
||||
assert still.status_code == 200
|
||||
@@ -0,0 +1,107 @@
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import PASSWORD, actor, keyed, make_chat, register
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
|
||||
CLIENTS = 10
|
||||
PER_CLIENT = 10
|
||||
TOTAL = CLIENTS * PER_CLIENT
|
||||
|
||||
|
||||
async def drain(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
|
||||
collected: list[dict] = []
|
||||
cursor: str | None = None
|
||||
while True:
|
||||
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = (
|
||||
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
|
||||
).json()
|
||||
collected.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return collected
|
||||
|
||||
|
||||
async def flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]:
|
||||
async def writer(worker: int) -> list[int]:
|
||||
codes = []
|
||||
for index in range(PER_CLIENT):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"нагрузка-{worker}-{index}"},
|
||||
headers=keyed(sender),
|
||||
)
|
||||
codes.append(response.status_code)
|
||||
return codes
|
||||
|
||||
batches = await asyncio.gather(*(writer(worker) for worker in range(CLIENTS)))
|
||||
return [code for batch in batches for code in batch]
|
||||
|
||||
|
||||
async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
|
||||
codes = await flood(client, chat, alice)
|
||||
assert codes.count(201) == TOTAL, f"неуспешные ответы: {set(codes) - {201}}"
|
||||
|
||||
history = await drain(client, chat, bob)
|
||||
assert len(history) == TOTAL
|
||||
assert len({item["id"] for item in history}) == TOTAL
|
||||
assert len({item["text"] for item in history}) == TOTAL
|
||||
|
||||
keys = [(item["created_at"], item["id"]) for item in history]
|
||||
assert keys == sorted(keys), "история не упорядочена по (created_at, id)"
|
||||
stamps = [item["created_at"] for item in history]
|
||||
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
|
||||
|
||||
|
||||
async def test_history_follows_the_clock_but_never_moves_back(
|
||||
monkeypatch: pytest.MonkeyPatch, client: AsyncClient
|
||||
) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
base = datetime.now(UTC) + timedelta(minutes=10)
|
||||
stamps = []
|
||||
for moment in (base, base - timedelta(minutes=5), base + timedelta(seconds=5)):
|
||||
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self, moment=moment: moment)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": "часы"}, headers=keyed(alice)
|
||||
)
|
||||
stamps.append(datetime.fromisoformat(response.json()["created_at"]))
|
||||
assert stamps == [base, base + timedelta(microseconds=1), base + timedelta(seconds=5)]
|
||||
|
||||
|
||||
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
|
||||
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
|
||||
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
|
||||
codes = [response.status_code for response in responses]
|
||||
assert codes.count(201) == 1
|
||||
assert codes.count(409) == len(codes) - 1
|
||||
|
||||
|
||||
async def test_parallel_chat_creation_is_atomic(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": f"Чат {index}", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
for index in range(20)
|
||||
)
|
||||
)
|
||||
assert all(response.status_code == 201 for response in responses)
|
||||
listed = (await client.get("/api/v1/chats?limit=100", headers=actor(bob))).json()
|
||||
assert len(listed["items"]) == 20
|
||||
keys = [(item["created_at"], item["id"]) for item in listed["items"]]
|
||||
assert keys == sorted(keys)
|
||||
@@ -0,0 +1,197 @@
|
||||
import asyncio
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from conftest import PASSWORD, actor, keyed, make_chat, new_user, register, running_app, scalar
|
||||
from messenger.identity.infrastructure.postgres import UserRow
|
||||
from messenger.messaging.infrastructure.postgres import ChatMemberRow, ChatRow
|
||||
|
||||
REGISTRATIONS = 25
|
||||
|
||||
|
||||
async def drain_history(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
|
||||
collected: list[dict] = []
|
||||
cursor: str | None = None
|
||||
while True:
|
||||
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = (
|
||||
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
|
||||
).json()
|
||||
collected.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return collected
|
||||
|
||||
|
||||
async def test_registration_is_visible_to_chats_immediately() -> None:
|
||||
async with running_app() as client:
|
||||
for _ in range(REGISTRATIONS):
|
||||
user = await register(client, "race")
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Сразу после регистрации", "member_ids": [user["id"]]},
|
||||
headers=actor(user),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
|
||||
|
||||
async def test_parallel_registrations_are_all_usable_as_members() -> None:
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
bodies = [new_user(f"par{index}") for index in range(REGISTRATIONS)]
|
||||
responses = await asyncio.gather(
|
||||
*(client.post("/api/v1/users", json=body) for body in bodies)
|
||||
)
|
||||
assert all(response.status_code == 201 for response in responses)
|
||||
created = [response.json()["id"] for response in responses]
|
||||
chat = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Все параллельные", "member_ids": [alice["id"], *created]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
assert chat.status_code == 201, chat.text
|
||||
assert len(chat.json()["member_ids"]) == REGISTRATIONS + 1
|
||||
|
||||
|
||||
async def test_rejected_registration_leaves_no_trace() -> None:
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
duplicate = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": alice["username"], "display_name": "Двойник", "password": PASSWORD},
|
||||
)
|
||||
assert duplicate.status_code == 409
|
||||
invalid = await client.post(
|
||||
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
sql = select(func.count()).select_from(UserRow).where(UserRow.username == alice["username"])
|
||||
assert await scalar(sql) == 1
|
||||
|
||||
|
||||
async def test_failed_chat_creation_rolls_back_both_tables() -> None:
|
||||
title = f"Откат {uuid4().hex}"
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
before = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
|
||||
rejected = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
assert rejected.status_code == 400
|
||||
assert rejected.json()["error"]["code"] == "invalid_request"
|
||||
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
|
||||
assert after["items"] == before["items"]
|
||||
assert (
|
||||
await scalar(select(func.count()).select_from(ChatRow).where(ChatRow.title == title)) == 0
|
||||
)
|
||||
members = (
|
||||
select(func.count())
|
||||
.select_from(ChatMemberRow)
|
||||
.where(ChatMemberRow.user_id == UUID(alice["id"]))
|
||||
)
|
||||
assert await scalar(members) == 0
|
||||
|
||||
|
||||
async def test_rejected_message_does_not_enter_history() -> None:
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
|
||||
assert (
|
||||
await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": " "},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
).status_code == 400
|
||||
assert (
|
||||
await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "чужое"},
|
||||
headers=keyed(eve),
|
||||
)
|
||||
).status_code == 404
|
||||
|
||||
assert await drain_history(client, chat, alice) == []
|
||||
|
||||
|
||||
async def test_confirmed_write_is_visible_to_next_read() -> None:
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
|
||||
for index in range(30):
|
||||
posted = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"подтверждение {index}"},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert posted.status_code == 201
|
||||
history = await drain_history(client, chat, bob)
|
||||
assert history[-1]["id"] == posted.json()["id"]
|
||||
assert len(history) == index + 1
|
||||
|
||||
|
||||
async def test_parallel_writes_across_zones_keep_counts_consistent() -> None:
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
chats = [await make_chat(client, alice) for _ in range(4)]
|
||||
|
||||
async def writer(chat: dict, worker: int) -> None:
|
||||
for index in range(10):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"поток-{worker}-{index}"},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert response.status_code == 201
|
||||
|
||||
async def registrar(index: int) -> str:
|
||||
return (await register(client, f"parallel{index}"))["id"]
|
||||
|
||||
results = await asyncio.gather(
|
||||
*(writer(chat, number) for number, chat in enumerate(chats)),
|
||||
*(registrar(index) for index in range(10)),
|
||||
)
|
||||
|
||||
registered = [item for item in results if isinstance(item, str)]
|
||||
assert len(set(registered)) == 10
|
||||
for chat in chats:
|
||||
history = await drain_history(client, chat, alice)
|
||||
assert len(history) == 10
|
||||
assert len({item["id"] for item in history}) == 10
|
||||
keys = [(item["created_at"], item["id"]) for item in history]
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
async def test_chat_membership_survives_parallel_reads_and_writes() -> None:
|
||||
async with running_app() as client:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
|
||||
async def write(index: int) -> None:
|
||||
await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"параллельно {index}"},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
|
||||
async def intruder() -> int:
|
||||
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
|
||||
return response.status_code
|
||||
|
||||
results = await asyncio.gather(
|
||||
*(write(index) for index in range(20)),
|
||||
*(intruder() for _ in range(20)),
|
||||
)
|
||||
assert {code for code in results if isinstance(code, int)} == {404}
|
||||
assert len(await drain_history(client, chat, bob)) == 20
|
||||
@@ -0,0 +1,26 @@
|
||||
import pytest
|
||||
from opentelemetry.sdk.trace.sampling import Decision
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from conftest import actor, register, running_app
|
||||
from messenger.shared.infrastructure.telemetry import ServerRoots
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
async def test_controlled_errors_are_opt_in(enabled: bool) -> None:
|
||||
async with running_app(cost_experiment=enabled) as client:
|
||||
user = await register(client, "cost")
|
||||
result = await client.get(
|
||||
"/api/v1/users/me", headers={**actor(user), "X-Lab-Cost": "error"}
|
||||
)
|
||||
assert result.status_code == (503 if enabled else 200)
|
||||
assert (await client.get("/api/v1/users/me", headers=actor(user))).status_code == 200
|
||||
|
||||
|
||||
def test_head_zero_drops_roots_and_full_keeps_them() -> None:
|
||||
for kind in (SpanKind.SERVER, SpanKind.PRODUCER, SpanKind.CONSUMER):
|
||||
assert ServerRoots(0).should_sample(None, 42, "root", kind).decision == Decision.DROP
|
||||
assert (
|
||||
ServerRoots(1).should_sample(None, 42, "root", kind).decision
|
||||
== Decision.RECORD_AND_SAMPLE
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from conftest import DATABASE, free_port, new_user
|
||||
from messenger.shared.infrastructure.readiness import DRAINING
|
||||
|
||||
DRAIN = 1.0
|
||||
SHUTDOWN = 3
|
||||
GUNICORN = (
|
||||
"-m",
|
||||
"gunicorn",
|
||||
"--config",
|
||||
"python:messenger.gunicorn_conf",
|
||||
"messenger.main:create_app()",
|
||||
)
|
||||
|
||||
|
||||
async def test_draining_replica_is_not_ready_but_alive(client: httpx.AsyncClient) -> None:
|
||||
DRAINING.set()
|
||||
try:
|
||||
ready = await client.get("/health/ready")
|
||||
live = await client.get("/health/live")
|
||||
finally:
|
||||
DRAINING.clear()
|
||||
assert ready.status_code == 503
|
||||
assert ready.json()["error"]["code"] == "unavailable"
|
||||
assert ready.headers["X-Instance-Id"]
|
||||
assert live.status_code == 200
|
||||
assert (await client.get("/health/ready")).status_code == 200
|
||||
|
||||
|
||||
def status(port: int, path: str) -> int:
|
||||
try:
|
||||
return httpx.get(f"http://127.0.0.1:{port}{path}", timeout=1, trust_env=False).status_code
|
||||
except httpx.TransportError:
|
||||
return 0
|
||||
|
||||
|
||||
def answer_of(connection: socket.socket) -> tuple[str, dict[str, str], dict]:
|
||||
data = b""
|
||||
while chunk := connection.recv(4096):
|
||||
data += chunk
|
||||
connection.close()
|
||||
head, _, body = data.partition(b"\r\n\r\n")
|
||||
status, *lines = head.decode("latin-1").split("\r\n")
|
||||
headers = dict(line.lower().split(": ", 1) for line in lines)
|
||||
return status, headers, json.loads(body) if body else {}
|
||||
|
||||
|
||||
def begin_registration(port: int) -> tuple[socket.socket, bytes]:
|
||||
body = json.dumps(new_user("drain")).encode()
|
||||
head = (
|
||||
"POST /api/v1/users HTTP/1.1\r\nHost: replica\r\nContent-Type: application/json\r\n"
|
||||
f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
connection = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
connection.sendall(head.encode() + body[:8])
|
||||
return connection, body[8:]
|
||||
|
||||
|
||||
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests(tmp_path: Path) -> None:
|
||||
port = free_port()
|
||||
settings = {
|
||||
"HOST": "127.0.0.1",
|
||||
"PORT": str(port),
|
||||
"WEB_CONCURRENCY": "2",
|
||||
"DATABASE_URL": DATABASE["url"],
|
||||
"CURSOR_SECRET": "test-secret-for-cursors",
|
||||
"S3_ACCESS_KEY_ID": "test-key",
|
||||
"S3_SECRET_ACCESS_KEY": "test-secret-key",
|
||||
"LOG_LEVEL": "WARNING",
|
||||
"DRAIN_SECONDS": str(DRAIN),
|
||||
"SHUTDOWN_TIMEOUT_SECONDS": str(SHUTDOWN),
|
||||
}
|
||||
log_path = tmp_path / "gunicorn.log"
|
||||
log = log_path.open("w")
|
||||
server = subprocess.Popen(
|
||||
[sys.executable, *GUNICORN],
|
||||
env={**os.environ, **settings},
|
||||
stdout=log,
|
||||
stderr=log,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
while status(port, "/health/ready") != 200:
|
||||
assert server.poll() is None and time.monotonic() < deadline, log_path.read_text()
|
||||
time.sleep(0.2)
|
||||
pending, rest = begin_registration(port)
|
||||
stuck, _ = begin_registration(port)
|
||||
sent = time.monotonic()
|
||||
server.send_signal(signal.SIGTERM)
|
||||
time.sleep(0.3)
|
||||
during = status(port, "/health/ready"), status(port, "/health/live")
|
||||
while status(port, "/health/live") == 200:
|
||||
assert time.monotonic() - sent < SHUTDOWN + 2, log_path.read_text()
|
||||
time.sleep(0.05)
|
||||
closed = time.monotonic() - sent
|
||||
pending.sendall(rest)
|
||||
answer = pending.recv(64).split(b"\r\n")[0].decode()
|
||||
pending.close()
|
||||
code = server.wait(timeout=SHUTDOWN + 2)
|
||||
exited = time.monotonic() - sent
|
||||
cancelled, headers, error = answer_of(stuck)
|
||||
finally:
|
||||
if server.poll() is None:
|
||||
server.kill()
|
||||
server.wait(timeout=5)
|
||||
log.close()
|
||||
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
|
||||
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
|
||||
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
|
||||
print(f" content-type {headers.get('content-type')}, тело {error}")
|
||||
assert during == (503, 200)
|
||||
assert answer == "HTTP/1.1 201 Created"
|
||||
assert cancelled == "HTTP/1.1 503 Service Unavailable"
|
||||
assert headers["content-type"] == "application/json"
|
||||
assert headers["x-instance-id"]
|
||||
assert error["error"]["code"] == "unavailable"
|
||||
assert error["error"]["request_id"] == headers["x-request-id"]
|
||||
assert DRAIN - 0.2 <= closed < SHUTDOWN
|
||||
assert exited < SHUTDOWN
|
||||
assert code == 0
|
||||
@@ -0,0 +1,112 @@
|
||||
import asyncio
|
||||
from dataclasses import fields
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from conftest import keyed, make_chat, register, split_settings
|
||||
from fakes import NullLogger
|
||||
from messenger.identity.domain.events import UserRegistered
|
||||
from messenger.main import create_app
|
||||
from messenger.messaging.domain.events import MessagePosted
|
||||
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
|
||||
|
||||
|
||||
def posted() -> MessagePosted:
|
||||
return MessagePosted(
|
||||
message_id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
sender_id=uuid4(),
|
||||
text_length=5,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
async def test_event_has_no_message_text() -> None:
|
||||
names = {field.name for field in fields(posted())}
|
||||
assert names == {"name", "message_id", "chat_id", "sender_id", "text_length", "created_at"}
|
||||
|
||||
|
||||
async def test_every_subscriber_receives_event() -> None:
|
||||
bus = EventBus(NullLogger())
|
||||
seen: list[str] = []
|
||||
|
||||
async def first(_event: MessagePosted) -> None:
|
||||
seen.append("first")
|
||||
|
||||
async def second(_event: MessagePosted) -> None:
|
||||
seen.append("second")
|
||||
|
||||
bus.subscribe(MessagePosted, first)
|
||||
bus.subscribe(MessagePosted, second)
|
||||
bus.start()
|
||||
await InMemoryEventPublisher(bus).publish([posted()])
|
||||
await bus.stop()
|
||||
assert sorted(seen) == ["first", "second"]
|
||||
|
||||
|
||||
async def test_failing_subscriber_does_not_block_others() -> None:
|
||||
bus = EventBus(NullLogger())
|
||||
survived: list[str] = []
|
||||
|
||||
async def broken(_event: MessagePosted) -> None:
|
||||
raise RuntimeError("обработчик упал")
|
||||
|
||||
async def healthy(_event: MessagePosted) -> None:
|
||||
survived.append("ok")
|
||||
|
||||
bus.subscribe(MessagePosted, broken)
|
||||
bus.subscribe(MessagePosted, healthy)
|
||||
bus.start()
|
||||
await InMemoryEventPublisher(bus).publish([posted()])
|
||||
await bus.stop()
|
||||
assert survived == ["ok"]
|
||||
|
||||
|
||||
async def test_queue_overflow_drops_events_without_raising() -> None:
|
||||
bus = EventBus(NullLogger(), max_queue=16)
|
||||
|
||||
async def never_called(_event: MessagePosted) -> None:
|
||||
raise AssertionError("обработчик не должен вызываться без запущенной шины")
|
||||
|
||||
bus.subscribe(MessagePosted, never_called)
|
||||
publisher = InMemoryEventPublisher(bus)
|
||||
await publisher.publish([posted() for _ in range(64)])
|
||||
assert bus.dropped > 0
|
||||
assert bus.pending <= 16
|
||||
|
||||
|
||||
async def test_publication_does_not_delay_response() -> None:
|
||||
app = create_app(**split_settings(log_level="CRITICAL"))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
bus = await app.state.dishka_container.get(EventBus)
|
||||
slow = asyncio.Event()
|
||||
|
||||
async def blocker(_event: MessagePosted) -> None:
|
||||
await slow.wait()
|
||||
|
||||
bus.subscribe(MessagePosted, blocker)
|
||||
response = await asyncio.wait_for(
|
||||
http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "не ждём обработчик"},
|
||||
headers=keyed(alice),
|
||||
),
|
||||
timeout=2,
|
||||
)
|
||||
assert response.status_code == 201
|
||||
slow.set()
|
||||
|
||||
|
||||
async def test_null_logger_hides_everything() -> None:
|
||||
logger = NullLogger()
|
||||
logger.info("x", route="/")
|
||||
logger.warning("x")
|
||||
logger.error("x")
|
||||
assert isinstance(UserRegistered, type)
|
||||
@@ -0,0 +1,64 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import HistogramDataPoint, InMemoryMetricReader
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from conftest import new_user, split_settings
|
||||
from fakes import MemoryStorageProvider
|
||||
from messenger.main import create_app
|
||||
from messenger.shared.entrypoints.telemetry import instrument_http
|
||||
|
||||
MARKER = "текст-маркер-телеметрии"
|
||||
|
||||
|
||||
async def test_server_spans_and_duration_follow_the_route_template() -> None:
|
||||
exporter = InMemorySpanExporter()
|
||||
tracer = TracerProvider(shutdown_on_exit=False)
|
||||
tracer.add_span_processor(SimpleSpanProcessor(exporter))
|
||||
reader = InMemoryMetricReader()
|
||||
app = create_app(**split_settings(), overrides=(MemoryStorageProvider(),))
|
||||
instrument_http(app, tracer, MeterProvider(metric_readers=[reader], shutdown_on_exit=False))
|
||||
chat = uuid4()
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
created = await http.post("/api/v1/users", json=new_user("otel"))
|
||||
ready = await http.get("/health/ready")
|
||||
denied = await http.post(
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
json={"text": MARKER},
|
||||
headers={"Idempotency-Key": "otel-1", "Authorization": "Bearer not-a-token"},
|
||||
)
|
||||
assert (created.status_code, ready.status_code, denied.status_code) == (201, 200, 401)
|
||||
|
||||
spans = exporter.get_finished_spans()
|
||||
servers = {span.name: span for span in spans if span.kind is SpanKind.SERVER}
|
||||
assert set(servers) == {"POST /api/v1/users", "POST /api/v1/chats/{chat_id}/messages"}
|
||||
users = servers["POST /api/v1/users"].attributes or {}
|
||||
assert users["messenger.request_id"] == created.headers["X-Request-Id"]
|
||||
assert users["http.route"] == "/api/v1/users"
|
||||
assert users["http.response.status_code"] == 201
|
||||
exported = repr([dict(span.attributes or {}) for span in spans])
|
||||
assert MARKER not in exported
|
||||
assert "not-a-token" not in exported
|
||||
|
||||
data = reader.get_metrics_data()
|
||||
assert data is not None
|
||||
points = [
|
||||
point
|
||||
for resource in data.resource_metrics
|
||||
for scope in resource.scope_metrics
|
||||
for metric in scope.metrics
|
||||
if metric.name == "http.server.request.duration" and metric.unit == "s"
|
||||
for point in metric.data.data_points
|
||||
if isinstance(point, HistogramDataPoint)
|
||||
]
|
||||
routes = {(point.attributes or {}).get("http.route") for point in points}
|
||||
assert routes == {"/api/v1/users", "/api/v1/chats/{chat_id}/messages"}
|
||||
assert str(chat) not in repr([dict(point.attributes or {}) for point in points])
|
||||
@@ -0,0 +1,162 @@
|
||||
import asyncio
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from conftest import actor, keyed, make_chat, register, running_app, scalar
|
||||
from messenger.messaging.infrastructure.postgres import IdempotencyKeyRow
|
||||
|
||||
INVALID_KEYS = ["", "k" * 129, "два слова", "a b", "a/b", "ключ"]
|
||||
|
||||
|
||||
async def send(http: AsyncClient, chat: dict, user: dict, text: str, key: str) -> Response:
|
||||
return await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(user, key)
|
||||
)
|
||||
|
||||
|
||||
async def history(http: AsyncClient, chat: dict, user: dict) -> list[dict[str, Any]]:
|
||||
response = await http.get(f"/api/v1/chats/{chat['id']}/messages?limit=100", headers=actor(user))
|
||||
return response.json()["items"]
|
||||
|
||||
|
||||
async def test_replay_returns_the_same_message(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
first = await send(client, chat, alice, "один раз", "replay-1")
|
||||
again = await send(client, chat, alice, "один раз", "replay-1")
|
||||
assert first.status_code == again.status_code == 201
|
||||
assert again.json() == first.json()
|
||||
assert [item["id"] for item in await history(client, chat, alice)] == [first.json()["id"]]
|
||||
|
||||
|
||||
async def test_same_json_in_other_layout_is_a_replay(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
first = await send(client, chat, alice, "форма", "layout-1")
|
||||
again = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
content='{ "text" : "форма" }'.encode(),
|
||||
headers={**keyed(alice, "layout-1"), "Content-Type": "application/json"},
|
||||
)
|
||||
assert again.status_code == 201
|
||||
assert again.json() == first.json()
|
||||
|
||||
|
||||
async def test_other_body_with_same_key_conflicts(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await send(client, chat, alice, "первое", "conflict-1")
|
||||
response = await send(client, chat, alice, "другое", "conflict-1")
|
||||
assert response.status_code == 409
|
||||
assert response.json()["error"]["code"] == "conflict"
|
||||
assert len(await history(client, chat, alice)) == 1
|
||||
|
||||
|
||||
async def test_missing_key_is_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без ключа"}, headers=actor(alice)
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert await history(client, chat, alice) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", INVALID_KEYS, ids=range(len(INVALID_KEYS)))
|
||||
async def test_malformed_key_is_rejected(client: AsyncClient, key: str) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
headers = {**actor(alice), "Idempotency-Key": key}
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "ключ плохой"},
|
||||
headers={name.encode(): value.encode() for name, value in headers.items()},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert await history(client, chat, alice) == []
|
||||
|
||||
|
||||
async def test_rejected_attempt_does_not_take_the_key(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
assert (await send(client, chat, alice, "", "spare-1")).status_code == 400
|
||||
assert (await send(client, chat, eve, "чужое", "spare-1")).status_code == 404
|
||||
assert (await send(client, chat, alice, "теперь можно", "spare-1")).status_code == 201
|
||||
|
||||
|
||||
async def test_key_is_scoped_by_user_and_chat(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
other = await make_chat(client, alice)
|
||||
cases = [(chat, alice, "алиса"), (chat, bob, "боб"), (other, alice, "другой чат")]
|
||||
messages = []
|
||||
for target, user, text in cases:
|
||||
response = await send(client, target, user, text, "shared-1")
|
||||
assert response.status_code == 201
|
||||
message = response.json()
|
||||
assert (message["chat_id"], message["sender_id"], message["text"]) == (
|
||||
target["id"],
|
||||
user["id"],
|
||||
text,
|
||||
)
|
||||
messages.append(message)
|
||||
ids = {message["id"] for message in messages}
|
||||
assert len(ids) == 3
|
||||
for (target, user, text), message in zip(cases, messages, strict=True):
|
||||
assert (await send(client, target, user, text, "shared-1")).json() == message
|
||||
|
||||
|
||||
async def test_replay_checks_session_and_access_again(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
chat = await make_chat(client, alice)
|
||||
assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 201
|
||||
assert (await send(client, chat, eve, "до выхода", "recheck-1")).status_code == 404
|
||||
logout = await client.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
assert logout.status_code == 204
|
||||
assert (await send(client, chat, alice, "до выхода", "recheck-1")).status_code == 401
|
||||
|
||||
|
||||
async def test_expired_key_starts_over() -> None:
|
||||
async with running_app(idempotency_ttl_seconds=1) as http:
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
first = await send(http, chat, alice, "давно", "expire-1")
|
||||
await asyncio.sleep(1.1)
|
||||
later = await send(http, chat, alice, "заново", "expire-1")
|
||||
assert later.status_code == 201
|
||||
assert later.json()["id"] != first.json()["id"]
|
||||
assert len(await history(http, chat, alice)) == 2
|
||||
|
||||
|
||||
async def test_concurrent_retries_through_two_replicas_store_one_message() -> None:
|
||||
async with (
|
||||
running_app(instance_id="replica-a") as first,
|
||||
running_app(instance_id="replica-b") as second,
|
||||
):
|
||||
alice = await register(first, "alice")
|
||||
chat = await make_chat(first, alice)
|
||||
key, text = uuid4().hex, "гонка ключа"
|
||||
responses = await asyncio.gather(
|
||||
*(send(http, chat, alice, text, key) for http in (first, second) * 4)
|
||||
)
|
||||
assert {response.status_code for response in responses} == {201}
|
||||
assert {response.headers["X-Instance-Id"] for response in responses} == {
|
||||
"replica-a",
|
||||
"replica-b",
|
||||
}
|
||||
assert all(response.json() == responses[0].json() for response in responses)
|
||||
assert [item["text"] for item in await history(second, chat, alice)] == [text]
|
||||
assert (
|
||||
await scalar(
|
||||
select(func.count()).select_from(IdempotencyKeyRow).where(IdempotencyKeyRow.key == key)
|
||||
)
|
||||
== 1
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
import socket
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient, Response
|
||||
|
||||
from conftest import actor, register, running_app, split_settings
|
||||
from messenger.main import create_app
|
||||
from messenger.shared.config import PlatformSettings
|
||||
|
||||
REPLICA = "replica-7f3a"
|
||||
|
||||
|
||||
def stamped(response: Response) -> bool:
|
||||
return bool(response.headers.get("X-Request-Id")) and (
|
||||
response.headers.get("X-Instance-Id") == REPLICA
|
||||
)
|
||||
|
||||
|
||||
async def test_every_response_names_the_replica() -> None:
|
||||
async with running_app(instance_id=REPLICA) as http:
|
||||
alice = await register(http, "alice")
|
||||
probes = [
|
||||
await http.get("/health/live"),
|
||||
await http.get("/health/ready"),
|
||||
await http.get("/api/v1/users/me", headers=actor(alice)),
|
||||
await http.get("/api/v1/users/me"),
|
||||
await http.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
|
||||
await http.get("/nothing-here"),
|
||||
await http.delete("/health/live"),
|
||||
await http.post("/api/v1/users", json={"username": "x"}),
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice)),
|
||||
]
|
||||
assert [probe.status_code for probe in probes] == [200, 200, 200, 401, 404, 404, 404, 400, 204]
|
||||
assert all(stamped(probe) for probe in probes)
|
||||
|
||||
|
||||
async def test_rejected_body_names_the_replica() -> None:
|
||||
async with running_app(instance_id=REPLICA, max_body_bytes=4096) as http:
|
||||
response = await http.post("/api/v1/users", content=b"x" * 5000)
|
||||
assert response.status_code == 413
|
||||
assert stamped(response)
|
||||
|
||||
|
||||
async def test_unhandled_error_names_the_replica() -> None:
|
||||
app = create_app(**split_settings(instance_id=REPLICA))
|
||||
|
||||
async def boom() -> None:
|
||||
raise RuntimeError("сбой")
|
||||
|
||||
app.add_api_route("/health/boom", boom)
|
||||
transport = ASGITransport(app=app, raise_app_exceptions=False)
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=transport, base_url="http://testserver") as http,
|
||||
):
|
||||
response = await http.get("/health/boom")
|
||||
assert response.status_code == 500
|
||||
assert response.json()["error"]["code"] == "internal_error"
|
||||
assert stamped(response)
|
||||
|
||||
|
||||
def test_replica_defaults_to_container_hostname() -> None:
|
||||
settings = PlatformSettings.model_validate({"database_url": "postgresql://u@h/d"})
|
||||
assert settings.instance_id == socket.gethostname()
|
||||
@@ -0,0 +1,62 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from httpx import AsyncClient
|
||||
from test_pipeline import accepted, job_of
|
||||
|
||||
from conftest import DATABASE
|
||||
|
||||
PROBE = """
|
||||
import asyncio, os
|
||||
from datetime import timedelta
|
||||
from uuid import uuid4
|
||||
from messenger.worker import create_worker
|
||||
from messenger.attachments.infrastructure.postgres import PostgresAttachmentsUnitOfWork
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
async def main():
|
||||
db = Database(os.environ['TEST_DATABASE_URL'], max_size=2, connect_timeout=2,
|
||||
acquire_timeout=2, command_timeout=3)
|
||||
job = JobMessage.model_validate_json(os.environ['TEST_JOB']).job()
|
||||
async def claim():
|
||||
uow = PostgresAttachmentsUnitOfWork(db)
|
||||
async with uow.transaction():
|
||||
claimed = await uow.jobs.claim(job, uuid4(), timedelta(seconds=5))
|
||||
assert claimed is not None
|
||||
assert claimed.lease.job.attempt == 1
|
||||
assert claimed.lease.job.created_at == job.created_at
|
||||
try:
|
||||
await asyncio.gather(claim(), claim())
|
||||
finally:
|
||||
await db.close()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
|
||||
async def test_cold_worker_claim_returning_is_stable(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
job = await job_of(ident)
|
||||
for seed in range(24):
|
||||
child = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
"-c",
|
||||
PROBE,
|
||||
env={
|
||||
**os.environ,
|
||||
"PYTHONHASHSEED": str(seed),
|
||||
"TEST_DATABASE_URL": DATABASE["url"],
|
||||
"TEST_JOB": json.dumps(job.payload()),
|
||||
},
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
_, errors = await asyncio.wait_for(child.communicate(), 20)
|
||||
finally:
|
||||
if child.returncode is None:
|
||||
child.kill()
|
||||
await child.wait()
|
||||
assert child.returncode == 0, f"seed={seed}: {errors.decode()}"
|
||||
@@ -0,0 +1,149 @@
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register, resolve
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from pictures import SAMPLE
|
||||
from pipeline import settle
|
||||
|
||||
|
||||
async def attach(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
|
||||
response = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png",
|
||||
content=SAMPLE,
|
||||
headers={**actor(user), "Content-Type": "image/png"},
|
||||
)
|
||||
assert response.status_code == 202, response.text
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
async def send(
|
||||
http: AsyncClient, user: dict[str, Any], chat: dict[str, Any], body: Any, key: str | None = None
|
||||
) -> Any:
|
||||
return await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json=body, headers=keyed(user, key)
|
||||
)
|
||||
|
||||
|
||||
async def scene(http: AsyncClient) -> tuple[dict[str, Any], ...]:
|
||||
alice, bob, eve = [await register(http, label) for label in ("alice", "bob", "eve")]
|
||||
return alice, bob, eve, await make_chat(http, alice, bob), await make_chat(http, alice)
|
||||
|
||||
|
||||
async def test_text_message_carries_empty_list(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
response = await send(client, alice, chat, {"text": "привет"})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["attachment_ids"] == []
|
||||
|
||||
|
||||
async def test_empty_text_with_attachment_keeps_order(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat, _ = await scene(client)
|
||||
ids = [await attach(client, alice, chat) for _ in range(3)]
|
||||
ordered = [ids[2], ids[0], ids[1]]
|
||||
response = await send(client, bob, chat, {"text": "", "attachment_ids": ordered})
|
||||
assert response.status_code == 201, response.text
|
||||
message = response.json()
|
||||
assert message["attachment_ids"] == ordered
|
||||
again = await send(client, alice, chat, {"text": "ещё раз", "attachment_ids": [ids[0]]})
|
||||
assert again.status_code == 201
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob))
|
||||
assert history.json()["items"] == [message, again.json()]
|
||||
|
||||
|
||||
async def test_replay_with_attachments_and_default_list(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
first_id, second_id = await attach(client, alice, chat), await attach(client, alice, chat)
|
||||
body = {"text": "", "attachment_ids": [first_id, second_id]}
|
||||
first = await send(client, alice, chat, body, "with-files")
|
||||
assert (await send(client, alice, chat, body, "with-files")).json() == first.json()
|
||||
swapped = {"text": "", "attachment_ids": [second_id, first_id]}
|
||||
assert (await send(client, alice, chat, swapped, "with-files")).status_code == 409
|
||||
plain = await send(client, alice, chat, {"text": "x"}, "plain")
|
||||
explicit = await send(client, alice, chat, {"attachment_ids": [], "text": "x"}, "plain")
|
||||
assert (explicit.status_code, explicit.json()) == (201, plain.json())
|
||||
|
||||
|
||||
async def test_attachment_of_another_chat_or_unknown(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, solo = await scene(client)
|
||||
foreign = await attach(client, alice, solo)
|
||||
for ids in ([foreign], [str(uuid4())]):
|
||||
response = await send(client, alice, chat, {"text": "x", "attachment_ids": ids})
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
|
||||
assert history.json()["items"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["eleven", "duplicate", "not-uuid", "empty", "blank"])
|
||||
async def test_invalid_attachment_lists(client: AsyncClient, kind: str) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
file = await attach(client, alice, chat)
|
||||
body = {
|
||||
"eleven": {"text": "x", "attachment_ids": [file] + [str(uuid4()) for _ in range(10)]},
|
||||
"duplicate": {"text": "x", "attachment_ids": [file, file]},
|
||||
"not-uuid": {"text": "x", "attachment_ids": ["not-a-uuid"]},
|
||||
"empty": {"text": "", "attachment_ids": []},
|
||||
"blank": {"text": " ", "attachment_ids": [file]},
|
||||
}[kind]
|
||||
response = await send(client, alice, chat, body)
|
||||
assert response.status_code == 400, response.text
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_outsider_gets_not_found_before_validation(client: AsyncClient) -> None:
|
||||
alice, _, eve, chat, _ = await scene(client)
|
||||
file = await attach(client, alice, chat)
|
||||
for body in ({"text": "", "attachment_ids": []}, {"text": "x", "attachment_ids": [file] * 11}):
|
||||
assert (await send(client, eve, chat, body)).status_code == 404
|
||||
|
||||
|
||||
async def test_one_attachment_in_several_messages(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat, _ = await scene(client)
|
||||
file = await attach(client, alice, chat)
|
||||
for user in (alice, bob):
|
||||
response = await send(client, user, chat, {"text": "", "attachment_ids": [file]})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["attachment_ids"] == [file]
|
||||
|
||||
|
||||
async def broken(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
|
||||
attachment_id = await attach(http, user, chat)
|
||||
store = await resolve(http, ObjectStorage)
|
||||
assert isinstance(store, MemoryObjectStorage)
|
||||
store.objects[f"staging/{attachment_id}"] = (b"\x89PNG\r\n\x1a\n broken", "image/png")
|
||||
await settle(http)
|
||||
return attachment_id
|
||||
|
||||
|
||||
async def test_queued_attachment_is_sent_and_failed_is_conflict(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat, _ = await scene(client)
|
||||
queued = await attach(client, alice, chat)
|
||||
early = await send(client, alice, chat, {"text": "", "attachment_ids": [queued]})
|
||||
assert early.status_code == 201, early.text
|
||||
failed = await broken(client, bob, chat)
|
||||
meta = (await client.get(f"/api/v1/attachments/{failed}", headers=actor(alice))).json()
|
||||
assert (meta["status"], meta["error_code"]) == ("failed", "invalid_image")
|
||||
refused = await send(client, alice, chat, {"text": "x", "attachment_ids": [queued, failed]})
|
||||
assert refused.status_code == 409
|
||||
assert refused.json()["error"]["code"] == "conflict"
|
||||
content = await client.get(f"/api/v1/attachments/{failed}/content", headers=actor(bob))
|
||||
assert content.status_code == 409
|
||||
|
||||
|
||||
async def test_replay_survives_a_later_failure(client: AsyncClient) -> None:
|
||||
alice, _, _, chat, _ = await scene(client)
|
||||
attachment_id = await attach(client, alice, chat)
|
||||
body = {"text": "", "attachment_ids": [attachment_id]}
|
||||
first = await send(client, alice, chat, body, key="replay-after-failure")
|
||||
store = await resolve(client, ObjectStorage)
|
||||
assert isinstance(store, MemoryObjectStorage)
|
||||
store.objects[f"staging/{attachment_id}"] = (b"garbage", "image/png")
|
||||
await settle(client)
|
||||
again = await send(client, alice, chat, body, key="replay-after-failure")
|
||||
assert (first.status_code, again.status_code) == (201, 201)
|
||||
assert again.json() == first.json()
|
||||
@@ -0,0 +1,548 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.script import ScriptDirectory
|
||||
from alembic.util import CommandError
|
||||
from sqlalchemy import MetaData, Table, case, func, insert, inspect, literal, make_url, select, text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from conftest import DATABASE, ROOT, migration_config, sql_connection, upgrade
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
AttachmentRow,
|
||||
JobEventRow,
|
||||
JobRow,
|
||||
OutboxRow,
|
||||
VariantRow,
|
||||
)
|
||||
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
ChatMemberRow,
|
||||
ChatRow,
|
||||
IdempotencyKeyRow,
|
||||
MessageAttachmentRow,
|
||||
MessageRow,
|
||||
)
|
||||
from messenger.shared.infrastructure.postgres import Base
|
||||
|
||||
VERSIONS = [
|
||||
"0001_init",
|
||||
"0002_idempotency_keys",
|
||||
"0003_attachments",
|
||||
"0004_jobs",
|
||||
"0005_failed_registry",
|
||||
"0006_attachment_quarantine",
|
||||
"0007_trace_context",
|
||||
"0008_login_budget",
|
||||
]
|
||||
TABLES = [
|
||||
UserRow,
|
||||
SessionRow,
|
||||
ChatRow,
|
||||
ChatMemberRow,
|
||||
MessageRow,
|
||||
IdempotencyKeyRow,
|
||||
AttachmentRow,
|
||||
JobRow,
|
||||
OutboxRow,
|
||||
JobEventRow,
|
||||
VariantRow,
|
||||
MessageAttachmentRow,
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def empty_database(database: str) -> AsyncIterator[str]:
|
||||
name = f"migration_test_{uuid4().hex}"
|
||||
url = make_url(database).set(drivername="postgresql+asyncpg")
|
||||
engine = create_async_engine(url, isolation_level="AUTOCOMMIT", poolclass=NullPool)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
|
||||
yield url.set(database=name).render_as_string(hide_password=False)
|
||||
finally:
|
||||
async with engine.connect() as connection:
|
||||
await connection.exec_driver_sql(f"DROP DATABASE {name} WITH (FORCE)")
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def legacy(dsn: str, versions: int = 6) -> None:
|
||||
async with sql_connection(dsn) as connection:
|
||||
await connection.execute(
|
||||
text(
|
||||
"CREATE TABLE schema_migrations (version text PRIMARY KEY, checksum text NOT NULL, "
|
||||
"applied_at timestamptz NOT NULL DEFAULT now())"
|
||||
)
|
||||
)
|
||||
journal = await connection.run_sync(
|
||||
lambda sync: Table("schema_migrations", MetaData(), autoload_with=sync)
|
||||
)
|
||||
for version in VERSIONS[:versions]:
|
||||
sql = (ROOT / "student-tests" / "fixtures" / "legacy" / f"{version}.sql").read_text()
|
||||
for statement in sql.split(";"):
|
||||
if statement.strip():
|
||||
await connection.execute(text(statement))
|
||||
await connection.execute(
|
||||
insert(journal).values(
|
||||
version=version, checksum=hashlib.sha256(sql.encode()).hexdigest()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def seed(dsn: str, versions: int = 6) -> None:
|
||||
user, chat, message = uuid4(), uuid4(), uuid4()
|
||||
stamp = datetime.now(UTC)
|
||||
rows = [
|
||||
(
|
||||
UserRow,
|
||||
{
|
||||
"id": user,
|
||||
"username": "legacy_user",
|
||||
"display_name": "Старые данные",
|
||||
"password_hash": "$argon2id$legacy",
|
||||
"created_at": stamp,
|
||||
},
|
||||
),
|
||||
(
|
||||
SessionRow,
|
||||
{
|
||||
"token_hash": b"s" * 32,
|
||||
"user_id": user,
|
||||
"created_at": stamp,
|
||||
"expires_at": stamp + timedelta(days=1),
|
||||
},
|
||||
),
|
||||
(
|
||||
ChatRow,
|
||||
{
|
||||
"id": chat,
|
||||
"title": "Существующий чат",
|
||||
"created_at": stamp,
|
||||
"last_message_at": stamp,
|
||||
},
|
||||
),
|
||||
(
|
||||
ChatMemberRow,
|
||||
{"chat_id": chat, "user_id": user, "position": 1, "chat_created_at": stamp},
|
||||
),
|
||||
(
|
||||
MessageRow,
|
||||
{
|
||||
"id": message,
|
||||
"chat_id": chat,
|
||||
"sender_id": user,
|
||||
"text": "Сохранить",
|
||||
"created_at": stamp,
|
||||
},
|
||||
),
|
||||
(
|
||||
IdempotencyKeyRow,
|
||||
{
|
||||
"chat_id": chat,
|
||||
"user_id": user,
|
||||
"key": "legacy-key",
|
||||
"fingerprint": b"f" * 32,
|
||||
"message_id": message,
|
||||
"created_at": stamp,
|
||||
},
|
||||
),
|
||||
]
|
||||
async with sql_connection(dsn) as connection:
|
||||
for model, row in rows[: 5 if versions == 1 else 6]:
|
||||
await connection.execute(insert(model).values(**row))
|
||||
if versions >= 3:
|
||||
attachment = uuid4()
|
||||
row = {
|
||||
"id": attachment,
|
||||
"chat_id": chat,
|
||||
"owner_id": user,
|
||||
"filename": "legacy.png",
|
||||
"content_type": "image/png",
|
||||
"size_bytes": 17,
|
||||
"sha256": "a" * 64,
|
||||
"width": 1,
|
||||
"height": 1,
|
||||
"object_key": f"attachments/{attachment}",
|
||||
"status": "ready",
|
||||
"created_at": stamp,
|
||||
"updated_at": stamp,
|
||||
}
|
||||
if versions >= 4:
|
||||
row.update(original_key=row["object_key"], published_version=1)
|
||||
if versions >= 6:
|
||||
row.update(quarantine_reason="missing", quarantined_at=stamp)
|
||||
table = await connection.run_sync(
|
||||
lambda sync: Table("attachments", MetaData(), autoload_with=sync)
|
||||
)
|
||||
await connection.execute(insert(table).values(**row))
|
||||
await connection.execute(
|
||||
insert(MessageAttachmentRow).values(
|
||||
message_id=message, position=0, chat_id=chat, attachment_id=attachment
|
||||
)
|
||||
)
|
||||
if versions >= 4:
|
||||
job = uuid4()
|
||||
await connection.execute(
|
||||
insert(JobRow).values(
|
||||
job_id=job,
|
||||
attachment_id=attachment,
|
||||
pipeline_version=1,
|
||||
status="processing",
|
||||
attempt=2,
|
||||
claims=3,
|
||||
lease_token=uuid4(),
|
||||
lease_until=stamp + timedelta(minutes=1),
|
||||
created_at=stamp,
|
||||
updated_at=stamp,
|
||||
)
|
||||
)
|
||||
await connection.execute(
|
||||
insert(OutboxRow).values(
|
||||
job_id=job,
|
||||
payload={"job_id": str(job)},
|
||||
available_at=stamp,
|
||||
)
|
||||
)
|
||||
await connection.execute(
|
||||
insert(JobEventRow).values(
|
||||
job_id=job,
|
||||
attachment_id=attachment,
|
||||
kind="claimed",
|
||||
attempt=2,
|
||||
)
|
||||
)
|
||||
await connection.execute(
|
||||
insert(VariantRow).values(
|
||||
attachment_id=attachment,
|
||||
pipeline_version=1,
|
||||
name="thumbnail",
|
||||
object_key=f"variants/{attachment}/1/thumbnail.jpg",
|
||||
content_type="image/jpeg",
|
||||
size_bytes=17,
|
||||
width=1,
|
||||
height=1,
|
||||
sha256="a" * 64,
|
||||
created_at=stamp,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def contents(dsn: str) -> dict:
|
||||
async with sql_connection(dsn) as connection:
|
||||
tables = await connection.run_sync(lambda sync: inspect(sync).get_table_names())
|
||||
result = {}
|
||||
for model in TABLES:
|
||||
if model.__tablename__ not in tables:
|
||||
continue
|
||||
table = await connection.run_sync(
|
||||
lambda sync, name=model.__tablename__: Table(name, MetaData(), autoload_with=sync)
|
||||
)
|
||||
missing: dict[str, Any] = {}
|
||||
if model is AttachmentRow and "published_version" not in table.c:
|
||||
missing = {
|
||||
"original_key": case((table.c.status == "ready", table.c.object_key)),
|
||||
"staging_key": case((table.c.status == "pending", table.c.object_key)),
|
||||
"published_version": case((table.c.status == "ready", 1), else_=0),
|
||||
}
|
||||
if model in (JobRow, OutboxRow):
|
||||
missing["trace_context"] = literal({}, type_=JSONB)
|
||||
columns = [
|
||||
table.c[col.name]
|
||||
if col.name in table.c
|
||||
else missing.get(col.name, literal(None)).label(col.name)
|
||||
for col in model.__table__.columns
|
||||
]
|
||||
result[model.__tablename__] = (
|
||||
await connection.execute(select(*columns).order_by(*table.primary_key))
|
||||
).all()
|
||||
return result
|
||||
|
||||
|
||||
async def revision(dsn: str) -> str | None:
|
||||
async with sql_connection(dsn) as connection:
|
||||
return await connection.run_sync(
|
||||
lambda sync: MigrationContext.configure(sync).get_current_revision()
|
||||
)
|
||||
|
||||
|
||||
async def test_migrations_are_ordered_and_versioned() -> None:
|
||||
scripts = ScriptDirectory.from_config(migration_config(DATABASE["url"]))
|
||||
assert [script.revision for script in reversed(list(scripts.walk_revisions()))] == VERSIONS
|
||||
assert await revision(DATABASE["url"]) == VERSIONS[-1]
|
||||
|
||||
|
||||
async def test_fresh_schema_matches_models(empty_database: str) -> None:
|
||||
await upgrade(empty_database)
|
||||
async with sql_connection(empty_database) as connection:
|
||||
assert (
|
||||
await connection.run_sync(
|
||||
lambda sync: compare_metadata(MigrationContext.configure(sync), Base.metadata)
|
||||
)
|
||||
== []
|
||||
)
|
||||
await asyncio.to_thread(command.check, migration_config(empty_database))
|
||||
|
||||
|
||||
async def test_rerun_changes_nothing(empty_database: str) -> None:
|
||||
await upgrade(empty_database)
|
||||
await seed(empty_database)
|
||||
before = await contents(empty_database)
|
||||
await upgrade(empty_database)
|
||||
assert await contents(empty_database) == before
|
||||
assert await revision(empty_database) == VERSIONS[-1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("versions", [1, 2, 3, 4, 5, 6])
|
||||
async def test_legacy_upgrade_preserves_every_row(empty_database: str, versions: int) -> None:
|
||||
await legacy(empty_database, versions)
|
||||
await seed(empty_database, versions)
|
||||
before = await contents(empty_database)
|
||||
async with sql_connection(empty_database) as connection:
|
||||
journal = (
|
||||
await connection.execute(text("SELECT * FROM schema_migrations ORDER BY version"))
|
||||
).all()
|
||||
await upgrade(empty_database)
|
||||
after = await contents(empty_database)
|
||||
assert {name: after[name] for name in before} == before
|
||||
assert await revision(empty_database) == VERSIONS[-1]
|
||||
async with sql_connection(empty_database) as connection:
|
||||
assert (
|
||||
await connection.execute(text("SELECT * FROM schema_migrations ORDER BY version"))
|
||||
).all() == journal
|
||||
assert (
|
||||
await connection.scalar(
|
||||
text("SELECT count(*) FROM pg_namespace WHERE nspname LIKE 'alembic_verify_%'")
|
||||
)
|
||||
== 0
|
||||
)
|
||||
await upgrade(empty_database)
|
||||
assert await contents(empty_database) == after
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"damage",
|
||||
[
|
||||
"DROP INDEX messages_history_idx",
|
||||
"ALTER TABLE messages DROP CONSTRAINT messages_chat_id_sender_id_fkey",
|
||||
"ALTER TABLE users DROP CONSTRAINT users_username_format",
|
||||
"ALTER TABLE users ALTER COLUMN display_name TYPE varchar",
|
||||
'ALTER TABLE users ALTER COLUMN username TYPE text COLLATE "C"',
|
||||
"ALTER TABLE sessions SET UNLOGGED",
|
||||
"ALTER TABLE sessions ALTER COLUMN expires_at DROP NOT NULL",
|
||||
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'",
|
||||
"DELETE FROM schema_migrations WHERE version = '0001_init'",
|
||||
"UPDATE schema_migrations SET version = 'unknown' WHERE version = '0002_idempotency_keys'",
|
||||
"DROP TABLE schema_migrations",
|
||||
"ALTER TABLE attachments DROP CONSTRAINT attachments_owner_fkey",
|
||||
"ALTER TABLE attachments DROP CONSTRAINT attachments_quarantine_check",
|
||||
"ALTER TABLE message_attachments DROP CONSTRAINT message_attachments_attachment_fkey",
|
||||
'ALTER TABLE attachments ALTER COLUMN object_key TYPE text COLLATE "default"',
|
||||
"DROP INDEX attachments_pending_idx",
|
||||
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0003_attachments'",
|
||||
],
|
||||
)
|
||||
async def test_legacy_drift_is_refused_without_stamping(empty_database: str, damage: str) -> None:
|
||||
await legacy(empty_database)
|
||||
await seed(empty_database)
|
||||
before = await contents(empty_database)
|
||||
async with sql_connection(empty_database) as connection:
|
||||
await connection.execute(text(damage))
|
||||
with pytest.raises(RuntimeError, match=r"[Ll]egacy|[Ee]xisting|Unknown"):
|
||||
await upgrade(empty_database)
|
||||
assert await revision(empty_database) is None
|
||||
assert await contents(empty_database) == before
|
||||
|
||||
|
||||
async def test_unknown_revision_is_refused(empty_database: str) -> None:
|
||||
await upgrade(empty_database)
|
||||
await seed(empty_database)
|
||||
before = await contents(empty_database)
|
||||
async with sql_connection(empty_database) as connection:
|
||||
await connection.execute(text("UPDATE alembic_version SET version_num = 'unknown'"))
|
||||
with pytest.raises(CommandError, match="unknown"):
|
||||
await upgrade(empty_database)
|
||||
assert await contents(empty_database) == before
|
||||
assert await revision(empty_database) == "unknown"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("existing", [False, True])
|
||||
async def test_simultaneous_migration_processes_serialize(
|
||||
empty_database: str, existing: bool
|
||||
) -> None:
|
||||
if existing:
|
||||
await legacy(empty_database)
|
||||
await seed(empty_database)
|
||||
before = await contents(empty_database)
|
||||
processes = []
|
||||
try:
|
||||
for _ in range(2):
|
||||
processes.append(
|
||||
await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
"-m",
|
||||
"alembic",
|
||||
"upgrade",
|
||||
"head",
|
||||
cwd=ROOT,
|
||||
env={**os.environ, "DATABASE_URL": empty_database},
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
)
|
||||
async with asyncio.timeout(30):
|
||||
output = await asyncio.gather(*(process.communicate() for process in processes))
|
||||
assert [process.returncode for process in processes] == [0, 0], output
|
||||
finally:
|
||||
for process in processes:
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
after = await contents(empty_database)
|
||||
assert {name: after[name] for name in before} == before
|
||||
assert await revision(empty_database) == VERSIONS[-1]
|
||||
|
||||
|
||||
async def test_sender_must_be_member_even_bypassing_api() -> None:
|
||||
with pytest.raises(IntegrityError) as failure:
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
insert(MessageRow).values(
|
||||
id=uuid4(), chat_id=uuid4(), sender_id=uuid4(), text="x", created_at=func.now()
|
||||
)
|
||||
)
|
||||
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
|
||||
|
||||
|
||||
async def test_key_needs_a_member_and_a_message() -> None:
|
||||
with pytest.raises(IntegrityError) as failure:
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
insert(IdempotencyKeyRow).values(
|
||||
chat_id=uuid4(),
|
||||
user_id=uuid4(),
|
||||
key="k-1",
|
||||
fingerprint=b"x" * 32,
|
||||
message_id=uuid4(),
|
||||
created_at=func.now(),
|
||||
)
|
||||
)
|
||||
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
|
||||
|
||||
|
||||
async def test_failed_revision_rolls_back_ddl_and_version(
|
||||
empty_database: str, tmp_path: Path
|
||||
) -> None:
|
||||
await upgrade(empty_database)
|
||||
await seed(empty_database)
|
||||
before = await contents(empty_database)
|
||||
scripts = tmp_path / "alembic"
|
||||
shutil.copytree(ROOT / "alembic", scripts, ignore=shutil.ignore_patterns("__pycache__"))
|
||||
(scripts / "versions" / "0003_failure.py").write_text(
|
||||
"from alembic import op\n"
|
||||
"import sqlalchemy as sa\n"
|
||||
"revision = '0003_failure'\n"
|
||||
"down_revision = '0008_login_budget'\n"
|
||||
"def upgrade():\n"
|
||||
" op.create_table('must_rollback', sa.Column('id', sa.Integer, primary_key=True))\n"
|
||||
" raise RuntimeError('migration failed')\n"
|
||||
)
|
||||
config = migration_config(empty_database)
|
||||
config.set_main_option("script_location", str(scripts))
|
||||
with pytest.raises(RuntimeError, match="migration failed"):
|
||||
await asyncio.to_thread(command.upgrade, config, "head")
|
||||
assert await revision(empty_database) == VERSIONS[-1]
|
||||
assert await contents(empty_database) == before
|
||||
async with sql_connection(empty_database) as connection:
|
||||
assert not await connection.run_sync(lambda sync: inspect(sync).has_table("must_rollback"))
|
||||
|
||||
|
||||
async def test_attachment_owner_must_be_member() -> None:
|
||||
with pytest.raises(IntegrityError, match="attachments_owner_fkey"):
|
||||
async with sql_connection() as connection:
|
||||
await connection.execute(
|
||||
insert(AttachmentRow).values(
|
||||
id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename="a.png",
|
||||
content_type="image/png",
|
||||
size_bytes=1,
|
||||
sha256="0" * 64,
|
||||
width=1,
|
||||
height=1,
|
||||
object_key="attachments/x",
|
||||
status="pending",
|
||||
created_at=func.now(),
|
||||
updated_at=func.now(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def test_message_links_only_attachments_of_its_chat(empty_database: str) -> None:
|
||||
await upgrade(empty_database)
|
||||
await seed(empty_database)
|
||||
with pytest.raises(IntegrityError, match="message_attachments_attachment_fkey"):
|
||||
async with sql_connection(empty_database) as connection:
|
||||
attachment = (await connection.execute(select(AttachmentRow.id))).scalar_one()
|
||||
user = (await connection.execute(select(UserRow.id))).scalar_one()
|
||||
chat, message = uuid4(), uuid4()
|
||||
await connection.execute(
|
||||
insert(ChatRow).values(id=chat, title="Other", created_at=func.now())
|
||||
)
|
||||
await connection.execute(
|
||||
insert(ChatMemberRow).values(
|
||||
chat_id=chat, user_id=user, position=1, chat_created_at=func.now()
|
||||
)
|
||||
)
|
||||
await connection.execute(
|
||||
insert(MessageRow).values(
|
||||
id=message, chat_id=chat, sender_id=user, text="", created_at=func.now()
|
||||
)
|
||||
)
|
||||
assert (
|
||||
await connection.scalar(select(MessageRow.text).where(MessageRow.id == message))
|
||||
== ""
|
||||
)
|
||||
await connection.execute(
|
||||
insert(MessageAttachmentRow).values(
|
||||
message_id=message,
|
||||
position=0,
|
||||
chat_id=chat,
|
||||
attachment_id=attachment,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def test_pipeline_tables_have_the_columns_the_suite_reads(empty_database: str) -> None:
|
||||
await upgrade(empty_database)
|
||||
async with sql_connection(empty_database) as connection:
|
||||
for model in (JobRow, OutboxRow, VariantRow, JobEventRow):
|
||||
columns = await connection.run_sync(
|
||||
lambda sync, name=model.__tablename__: inspect(sync).get_columns(name)
|
||||
)
|
||||
assert {col["name"] for col in columns} == set(model.__table__.columns.keys())
|
||||
|
||||
|
||||
async def test_one_variant_row_per_effect_key(empty_database: str) -> None:
|
||||
await upgrade(empty_database)
|
||||
await seed(empty_database)
|
||||
async with sql_connection(empty_database) as connection:
|
||||
row = (await connection.execute(select(VariantRow.__table__))).mappings().one()
|
||||
duplicate = dict(row, object_key="variants/duplicate")
|
||||
with pytest.raises(IntegrityError, match="attachment_variants_pkey"):
|
||||
async with sql_connection(empty_database) as connection:
|
||||
await connection.execute(insert(VariantRow).values(**duplicate))
|
||||
@@ -0,0 +1,196 @@
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import PASSWORD, actor, keyed, make_chat, register
|
||||
|
||||
ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
}
|
||||
|
||||
|
||||
def assert_error(response, expected_status: int) -> None:
|
||||
assert response.status_code == expected_status, response.text
|
||||
assert response.headers.get("content-type", "").startswith("application/json")
|
||||
body = response.json()
|
||||
assert set(body) == {"error"}
|
||||
assert set(body["error"]) == {"code", "message", "request_id"}
|
||||
assert body["error"]["code"] == ERROR_CODES[expected_status]
|
||||
assert body["error"]["message"]
|
||||
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_malformed_json(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
content=b'{"username": ',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_unexpected_field(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"},
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_wrong_types(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234}
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"username": "Alice", "display_name": "X", "password": PASSWORD},
|
||||
{"username": "ab", "display_name": "X", "password": PASSWORD},
|
||||
{"username": "alice_01\n", "display_name": "X", "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": "", "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": " ", "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD},
|
||||
{"username": "abc_def", "display_name": "X", "password": "short"},
|
||||
{"username": "abc_def", "display_name": "X", "password": "x" * 129},
|
||||
{"username": "abc_def", "display_name": "X", "password": " " * 20},
|
||||
{"username": "abc_def", "display_name": "X"},
|
||||
{"username": "abc_def", "password": PASSWORD},
|
||||
],
|
||||
)
|
||||
async def test_invalid_registration(client: AsyncClient, body: dict) -> None:
|
||||
assert_error(await client.post("/api/v1/users", json=body), 400)
|
||||
|
||||
|
||||
async def test_duplicate_username(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
repeat = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD},
|
||||
)
|
||||
assert_error(repeat, 409)
|
||||
|
||||
|
||||
async def test_missing_identity(client: AsyncClient) -> None:
|
||||
assert_error(await client.get("/api/v1/users/me"), 401)
|
||||
|
||||
|
||||
BAD_AUTHORIZATIONS = [
|
||||
"",
|
||||
"Bearer",
|
||||
"Bearer ",
|
||||
"Bearer not a token",
|
||||
"Bearer " + "x" * 43,
|
||||
"Token abcdef",
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS)
|
||||
async def test_invalid_bearer(client: AsyncClient, raw: str) -> None:
|
||||
response = await client.get("/api/v1/users/me", headers={"Authorization": raw})
|
||||
assert_error(response, 401)
|
||||
assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
assert_error(response, 401)
|
||||
|
||||
|
||||
async def test_identity_checked_before_body(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
content=b"{broken",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert_error(response, 401)
|
||||
|
||||
|
||||
async def test_empty_message_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
for text in ("", " ", "\n\t"):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_long_message_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "я" * 4001},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_sender_id_not_accepted(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "подмена", "sender_id": bob["id"]},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"title": "Чат", "member_ids": []},
|
||||
{"title": "", "member_ids": None},
|
||||
{"title": " ", "member_ids": None},
|
||||
{"title": "Чат", "member_ids": ["не-uuid"]},
|
||||
{"title": "Чат", "member_ids": [1]},
|
||||
{"title": "Чат", "member_ids": "не-список"},
|
||||
],
|
||||
)
|
||||
async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None:
|
||||
alice = await register(client, "alice")
|
||||
payload = dict(body)
|
||||
if payload["member_ids"] is None:
|
||||
payload["member_ids"] = [alice["id"]]
|
||||
response = await client.post("/api/v1/chats", json=payload, headers=actor(alice))
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_creator_must_be_member(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Чат", "member_ids": [bob["id"]]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_unknown_member_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
response = await client.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
|
||||
headers=actor(alice),
|
||||
)
|
||||
assert_error(response, 400)
|
||||
|
||||
|
||||
async def test_bad_chat_id_in_path(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400)
|
||||
@@ -0,0 +1,95 @@
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
|
||||
from conftest import PASSWORD, actor, basic, keyed, make_chat, new_user, register
|
||||
|
||||
NUL_TEXTS = ["\x00", "\x00abc", "abc\x00def", "abc\x00"]
|
||||
|
||||
|
||||
def rejected(response: Response, status: int, code: str) -> None:
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
assert response.headers["X-Instance-Id"]
|
||||
assert response.headers["X-Request-Id"]
|
||||
assert set(response.json()) == {"error"}
|
||||
error = response.json()["error"]
|
||||
assert set(error) == {"code", "message", "request_id"}
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", NUL_TEXTS)
|
||||
async def test_nul_basic_matches_wrong_password(client: AsyncClient, username: str) -> None:
|
||||
user = await register(client, "nul_login")
|
||||
responses = []
|
||||
for name, password in [(user["username"], "wrong-password"), (username, PASSWORD)]:
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers={**basic(name, password), "X-Request-Id": "nul-login"},
|
||||
)
|
||||
rejected(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"'
|
||||
responses.append(response.json())
|
||||
assert responses[0] == responses[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
async def test_nul_display_name_does_not_create_user(client: AsyncClient, raw: str) -> None:
|
||||
body = {**new_user("nul_display"), "display_name": raw}
|
||||
rejected(await client.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
response = await client.post("/api/v1/users", json={**body, "display_name": "Алиса 👋"})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["display_name"] == "Алиса 👋"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
async def test_nul_title_does_not_create_chat(client: AsyncClient, raw: str) -> None:
|
||||
user = await register(client, "nul_title")
|
||||
body = {"title": raw, "member_ids": [user["id"]]}
|
||||
rejected(
|
||||
await client.post("/api/v1/chats", json=body, headers=actor(user)), 400, "invalid_request"
|
||||
)
|
||||
chats = await client.get("/api/v1/chats", headers=actor(user))
|
||||
assert chats.status_code == 200
|
||||
assert chats.json()["items"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
async def test_nul_message_does_not_take_key(client: AsyncClient, raw: str) -> None:
|
||||
user = await register(client, "nul_message")
|
||||
chat = await make_chat(client, user)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
headers = keyed(user)
|
||||
rejected(await client.post(path, json={"text": raw}, headers=headers), 400, "invalid_request")
|
||||
history = await client.get(path, headers=actor(user))
|
||||
assert history.status_code == 200
|
||||
assert history.json()["items"] == []
|
||||
text = "Исправлено\tбез потерь\n👋"
|
||||
first = await client.post(path, json={"text": text}, headers=headers)
|
||||
again = await client.post(path, json={"text": text}, headers=headers)
|
||||
assert first.status_code == again.status_code == 201
|
||||
assert first.json()["text"] == text
|
||||
assert first.json() == again.json()
|
||||
assert (await client.get(path, headers=actor(user))).json()["items"] == [first.json()]
|
||||
|
||||
|
||||
async def test_nul_message_does_not_disclose_chat(client: AsyncClient) -> None:
|
||||
owner = await register(client, "nul_owner")
|
||||
outsider = await register(client, "nul_outsider")
|
||||
chat = await make_chat(client, owner)
|
||||
responses = []
|
||||
for chat_id in [chat["id"], str(uuid4())]:
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": "abc\x00def"},
|
||||
headers={**keyed(outsider), "X-Request-Id": "nul-access"},
|
||||
)
|
||||
rejected(response, 404, "not_found")
|
||||
responses.append(response.json())
|
||||
assert responses[0] == responses[1]
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(owner))
|
||||
assert history.status_code == 200
|
||||
assert history.json()["items"] == []
|
||||
@@ -0,0 +1,171 @@
|
||||
import json
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from conftest import (
|
||||
PASSWORD,
|
||||
actor,
|
||||
keyed,
|
||||
make_chat,
|
||||
new_user,
|
||||
register,
|
||||
running_app,
|
||||
split_settings,
|
||||
)
|
||||
from messenger.main import create_app
|
||||
|
||||
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
|
||||
|
||||
|
||||
async def test_health_needs_no_identity(client: AsyncClient) -> None:
|
||||
for path in ("/health/live", "/health/ready"):
|
||||
response = await client.get(path)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
assert response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_every_response_carries_request_id(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
probes = [
|
||||
await client.get("/health/live"),
|
||||
await client.get("/api/v1/users/me", headers=actor(alice)),
|
||||
await client.get("/api/v1/users/me"),
|
||||
await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
|
||||
await client.get("/api/v1/unknown-path"),
|
||||
]
|
||||
assert all(probe.headers.get("X-Request-Id") for probe in probes)
|
||||
|
||||
|
||||
async def test_client_request_id_is_preserved(client: AsyncClient) -> None:
|
||||
response = await client.get("/health/live", headers={"X-Request-Id": "trace-42"})
|
||||
assert response.headers["X-Request-Id"] == "trace-42"
|
||||
|
||||
|
||||
async def test_unknown_public_route_is_404(client: AsyncClient) -> None:
|
||||
response = await client.get("/nothing-here")
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_unknown_protected_route_needs_identity(client: AsyncClient) -> None:
|
||||
anonymous = await client.get("/api/v1/unknown-path")
|
||||
assert anonymous.status_code == 401
|
||||
assert set(anonymous.json()["error"]) == {"code", "message", "request_id"}
|
||||
alice = await register(client, "alice")
|
||||
identified = await client.get("/api/v1/unknown-path", headers=actor(alice))
|
||||
assert identified.status_code == 404
|
||||
|
||||
|
||||
async def test_method_not_allowed_is_hidden(client: AsyncClient) -> None:
|
||||
response = await client.delete("/health/live")
|
||||
assert response.status_code == 404
|
||||
assert response.json()["error"]["code"] == "not_found"
|
||||
|
||||
|
||||
async def test_logs_do_not_contain_message_text(capsys) -> None:
|
||||
app = create_app(**split_settings(log_level="INFO"))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
response = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": MARKER_TEXT},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert response.status_code == 201
|
||||
captured = capsys.readouterr()
|
||||
assert MARKER_TEXT not in captured.out
|
||||
assert MARKER_TEXT not in captured.err
|
||||
assert alice["display_name"] not in captured.out
|
||||
assert any("request.handled" in line for line in captured.out.splitlines())
|
||||
|
||||
|
||||
async def test_log_lines_are_json(capsys) -> None:
|
||||
app = create_app(**split_settings(log_level="INFO"))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
await http.get("/health/live")
|
||||
for line in capsys.readouterr().out.splitlines():
|
||||
record = json.loads(line)
|
||||
assert {"ts", "level", "event"} <= set(record)
|
||||
|
||||
|
||||
async def test_body_limit_returns_413() -> None:
|
||||
app = create_app(**split_settings(max_body_bytes=4096))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
response = await http.post("/api/v1/users", content=b"x" * 5000)
|
||||
assert response.status_code == 413
|
||||
assert response.json()["error"]["code"] == "payload_too_large"
|
||||
|
||||
|
||||
async def test_chunked_body_is_limited_too() -> None:
|
||||
async def chunks(body: bytes) -> AsyncIterator[bytes]:
|
||||
for start in range(0, len(body), 1000):
|
||||
yield body[start : start + 1000]
|
||||
|
||||
user = json.dumps(new_user("chunked")).encode()
|
||||
async with running_app(max_body_bytes=4096) as http:
|
||||
large = await http.post("/api/v1/users", content=chunks(b"x" * 5000))
|
||||
small = await http.post(
|
||||
"/api/v1/users", content=chunks(user), headers={"Content-Type": "application/json"}
|
||||
)
|
||||
assert "content-length" not in large.request.headers
|
||||
assert large.status_code == 413
|
||||
assert large.json()["error"]["code"] == "payload_too_large"
|
||||
assert small.status_code == 201
|
||||
|
||||
|
||||
async def test_ready_turns_unavailable_without_database() -> None:
|
||||
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
|
||||
started = time.perf_counter()
|
||||
ready = await http.get("/health/ready")
|
||||
live = await http.get("/health/live")
|
||||
elapsed = time.perf_counter() - started
|
||||
assert ready.status_code == 503
|
||||
assert ready.json()["error"]["code"] == "unavailable"
|
||||
assert live.status_code == 200
|
||||
assert elapsed < 2
|
||||
|
||||
|
||||
async def test_protected_request_is_503_not_401_without_database() -> None:
|
||||
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
|
||||
response = await http.get(
|
||||
"/api/v1/users/me", headers={"Authorization": "Bearer " + "x" * 43}
|
||||
)
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_state_survives_new_process() -> None:
|
||||
async with running_app() as http:
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
async with running_app() as http:
|
||||
me = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
listed = await http.get("/api/v1/chats?limit=100", headers=actor(alice))
|
||||
assert me.json() == alice
|
||||
assert [item["id"] for item in listed.json()["items"]] == [chat["id"]]
|
||||
|
||||
|
||||
async def test_logs_do_not_contain_credentials(capsys) -> None:
|
||||
async with running_app(log_level="INFO") as http:
|
||||
alice = await register(http, "secret")
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
output = capsys.readouterr()
|
||||
captured = output.out + output.err
|
||||
assert PASSWORD not in captured
|
||||
assert actor(alice)["Authorization"].split()[1] not in captured
|
||||
assert "audit.session_opened" in captured
|
||||
@@ -0,0 +1,156 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register
|
||||
|
||||
TOTAL = 12
|
||||
|
||||
|
||||
async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]:
|
||||
texts = []
|
||||
for index in range(count):
|
||||
text = f"сообщение {index:02d}"
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=keyed(sender),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]:
|
||||
collected: list[str] = []
|
||||
cursor: str | None = None
|
||||
step = 0
|
||||
while True:
|
||||
limit = limits[min(step, len(limits) - 1)]
|
||||
query = f"?limit={limit}"
|
||||
if cursor:
|
||||
query += f"&cursor={quote(cursor, safe='')}"
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
assert len(page["items"]) <= limit
|
||||
collected.extend(item["text"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
step += 1
|
||||
if cursor is None:
|
||||
return collected
|
||||
|
||||
|
||||
async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
expected = await fill(client, chat, alice, TOTAL)
|
||||
assert await walk(client, chat, bob, [5]) == expected
|
||||
|
||||
|
||||
async def test_limit_may_change_between_pages(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
expected = await fill(client, chat, alice, TOTAL)
|
||||
assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected
|
||||
|
||||
|
||||
async def test_last_page_closes_history(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 2)
|
||||
first = (
|
||||
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice))
|
||||
).json()
|
||||
assert len(first["items"]) == 2
|
||||
assert first["next_cursor"] is None
|
||||
|
||||
|
||||
async def test_cursor_is_shared_between_members(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
bob = await register(client, "bob")
|
||||
chat = await make_chat(client, alice, bob)
|
||||
await fill(client, chat, alice, 3)
|
||||
page = (
|
||||
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice))
|
||||
).json()
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob)
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
first = await make_chat(client, alice)
|
||||
second = await make_chat(client, alice)
|
||||
await fill(client, first, alice, 3)
|
||||
await fill(client, second, alice, 3)
|
||||
page = (
|
||||
await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice))
|
||||
).json()
|
||||
cursor = quote(page["next_cursor"], safe="")
|
||||
response = await client.get(
|
||||
f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice)
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20", ""])
|
||||
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 1)
|
||||
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
||||
response = await client.get(f"{path}?limit=1&cursor={cursor}", headers=actor(alice))
|
||||
assert response.status_code == 400, f"{path}?cursor={cursor} → {response.status_code}"
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
|
||||
async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
||||
response = await client.get(f"{path}?limit={limit}", headers=actor(alice))
|
||||
assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}"
|
||||
|
||||
|
||||
async def test_default_limit_is_50(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 51)
|
||||
page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json()
|
||||
assert len(page["items"]) == 50
|
||||
assert page["next_cursor"] is not None
|
||||
|
||||
|
||||
async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
await fill(client, chat, alice, 2)
|
||||
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
|
||||
response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice))
|
||||
assert response.status_code == 200, response.text
|
||||
assert len(response.json()["items"]) == 1
|
||||
|
||||
|
||||
async def test_chat_list_pagination(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
created = [(await make_chat(client, alice))["id"] for _ in range(5)]
|
||||
collected: list[str] = []
|
||||
cursor: str | None = None
|
||||
while True:
|
||||
query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json()
|
||||
collected.extend(item["id"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
assert collected == created
|
||||
@@ -0,0 +1,300 @@
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import actor, sql_connection
|
||||
from messenger.attachments.application.pipeline import TRANSIENT_ERROR
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import ImageTooDemanding
|
||||
from messenger.attachments.domain.jobs import Job, Outcome, RetryPolicy
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from pictures import SAMPLE
|
||||
from pipeline import pipeline_of
|
||||
|
||||
|
||||
async def rows(sql: str, *args: Any) -> list[dict[str, Any]]:
|
||||
async with sql_connection() as connection:
|
||||
result = await connection.exec_driver_sql(sql, args)
|
||||
return [dict(row) for row in result.mappings()] if result.returns_rows else []
|
||||
|
||||
|
||||
async def accepted(http: AsyncClient) -> tuple[dict[str, Any], dict[str, Any], str]:
|
||||
alice, bob, _, chat = await trio(http)
|
||||
response = await upload(http, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
return alice, bob, response.json()["id"]
|
||||
|
||||
|
||||
async def state(attachment_id: str) -> dict[str, Any]:
|
||||
(row,) = await rows(
|
||||
"SELECT a.status, a.error_code, a.published_version, a.staging_key, a.original_key, "
|
||||
"j.status AS job_status, j.attempt, j.claims FROM attachments a "
|
||||
"JOIN jobs j ON j.attachment_id = a.id WHERE a.id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def variants(attachment_id: str) -> list[dict[str, Any]]:
|
||||
return await rows(
|
||||
"SELECT pipeline_version, name, sha256, size_bytes, object_key FROM attachment_variants "
|
||||
"WHERE attachment_id = $1 ORDER BY name",
|
||||
attachment_id,
|
||||
)
|
||||
|
||||
|
||||
async def events(attachment_id: str) -> list[str]:
|
||||
found = await rows(
|
||||
"SELECT kind FROM job_events WHERE attachment_id = $1 ORDER BY id", attachment_id
|
||||
)
|
||||
return [row["kind"] for row in found]
|
||||
|
||||
|
||||
async def job_of(attachment_id: str) -> Job:
|
||||
(row,) = await rows(
|
||||
"SELECT payload::text AS body FROM outbox o JOIN jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = $1 ORDER BY o.id LIMIT 1",
|
||||
attachment_id,
|
||||
)
|
||||
return JobMessage.model_validate_json(row["body"]).job()
|
||||
|
||||
|
||||
async def test_job_is_processed_once_and_staging_is_cleaned(client: AsyncClient) -> None:
|
||||
_, bob, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
outcomes = await pipeline.drain()
|
||||
assert Outcome.DONE in outcomes
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["job_status"], done["published_version"]) == ("ready", "done", 1)
|
||||
assert done["original_key"] == f"originals/{attachment_id}"
|
||||
assert done["staging_key"] == f"staging/{attachment_id}"
|
||||
pattern = rf"variants/{attachment_id}/1/(crop|optimized|thumbnail)-[0-9a-f]{{16}}\.(jpg|webp)"
|
||||
found = [re.fullmatch(pattern, row["object_key"]) for row in await variants(attachment_id)]
|
||||
assert [match.groups() for match in found if match] == [
|
||||
("crop", "jpg"),
|
||||
("optimized", "webp"),
|
||||
("thumbnail", "jpg"),
|
||||
]
|
||||
assert await pipeline.clean() >= 1
|
||||
assert (await state(attachment_id))["staging_key"] is None
|
||||
objects = (await storage(client)).objects
|
||||
assert f"staging/{attachment_id}" not in objects
|
||||
assert objects[f"originals/{attachment_id}"][0] == SAMPLE
|
||||
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(bob))
|
||||
assert content.content == SAMPLE
|
||||
assert await events(attachment_id) == ["enqueued", "claimed", "done"]
|
||||
|
||||
|
||||
async def test_message_is_a_contract_job(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
mine = [
|
||||
json.loads(body)
|
||||
for body in pipeline.publisher.bodies
|
||||
if json.loads(body)["attachment_id"] == attachment_id
|
||||
]
|
||||
assert len(mine) == 1
|
||||
assert set(mine[0]) == {
|
||||
"schema_version",
|
||||
"job_id",
|
||||
"type",
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"attempt",
|
||||
"created_at",
|
||||
}
|
||||
assert (mine[0]["pipeline_version"], mine[0]["attempt"]) == (1, 1)
|
||||
assert await pipeline.publish() == []
|
||||
|
||||
|
||||
async def test_redelivery_after_ready_changes_nothing(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
before, job = await variants(attachment_id), await job_of(attachment_id)
|
||||
assert await pipeline.process(job) is Outcome.DUPLICATE
|
||||
assert await variants(attachment_id) == before
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
assert (await events(attachment_id))[-1] == "duplicate_noop"
|
||||
|
||||
|
||||
async def test_two_copies_in_flight_give_one_result(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
outcomes = await asyncio.gather(pipeline.process(job), pipeline.process(job))
|
||||
assert sorted(outcomes) == sorted([Outcome.DONE, Outcome.DUPLICATE])
|
||||
assert len(await variants(attachment_id)) == 3
|
||||
assert (await state(attachment_id))["claims"] == 1
|
||||
|
||||
|
||||
async def test_partial_variant_set_is_never_published(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
store = await storage(client)
|
||||
|
||||
async def refuse(key: str) -> None:
|
||||
if "/optimized-" in key:
|
||||
raise Unavailable("S3 недоступно")
|
||||
|
||||
store.after_put = refuse
|
||||
try:
|
||||
assert await pipeline.process(await job_of(attachment_id)) is Outcome.RESCHEDULED
|
||||
finally:
|
||||
store.after_put = None
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
assert await variants(attachment_id) == []
|
||||
|
||||
|
||||
async def test_transient_error_reschedules_with_the_same_job(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
store = await storage(client)
|
||||
store.failing = True
|
||||
try:
|
||||
assert await pipeline.process(job) is Outcome.RESCHEDULED
|
||||
finally:
|
||||
store.failing = False
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["job_status"], queued["attempt"]) == ("queued", "queued", 2)
|
||||
(retry,) = [j for j in await pipeline.publish() if str(j.attachment_id) == attachment_id]
|
||||
assert (retry.id, retry.attempt) == (job.id, 2)
|
||||
assert await pipeline.process(retry) is Outcome.DONE
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_attempts_are_bounded(client: AsyncClient) -> None:
|
||||
alice, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["job_status"]) == (
|
||||
"failed",
|
||||
"retry_exhausted",
|
||||
"failed",
|
||||
)
|
||||
assert failed["attempt"] == pipeline.policy.max_attempts
|
||||
assert (await events(attachment_id)).count("retry_scheduled") == 4
|
||||
content = await client.get(f"/api/v1/attachments/{attachment_id}/content", headers=actor(alice))
|
||||
assert content.status_code == 409
|
||||
|
||||
|
||||
async def test_undecodable_image_fails_without_retries(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
(await storage(client)).objects[f"staging/{attachment_id}"] = (b"not a png", "image/png")
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
|
||||
"failed",
|
||||
"invalid_image",
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
class DemandingRenderer:
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
raise ImageTooDemanding("рендер дольше допустимого времени")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cause", ["limit", "missing"])
|
||||
async def test_limits_and_lost_original_fail_without_retries(
|
||||
client: AsyncClient, cause: str
|
||||
) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
if cause == "limit":
|
||||
pipeline.renderer = DemandingRenderer()
|
||||
else:
|
||||
del (await storage(client)).objects[f"staging/{attachment_id}"]
|
||||
await pipeline.drain()
|
||||
failed = await state(attachment_id)
|
||||
assert (failed["status"], failed["error_code"], failed["attempt"]) == (
|
||||
"failed",
|
||||
"processing_failed",
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
async def test_expired_lease_is_recovered_and_old_holder_is_fenced(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
uow = pipeline.uow()
|
||||
async with uow.transaction():
|
||||
claim = await uow.jobs.claim(job, uuid4(), pipeline.lease)
|
||||
await uow.commit()
|
||||
assert claim is not None
|
||||
assert (await state(attachment_id))["status"] == "processing"
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert await pipeline.recover() >= 1
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
late = pipeline.uow()
|
||||
async with late.transaction():
|
||||
outcome = await late.jobs.complete(claim.lease, [], f"originals/{attachment_id}")
|
||||
await late.commit()
|
||||
assert outcome is Outcome.FENCED
|
||||
assert await variants(attachment_id) == []
|
||||
await pipeline.drain()
|
||||
recovered = await state(attachment_id)
|
||||
assert (recovered["status"], recovered["attempt"]) == ("ready", 2)
|
||||
assert {"lease_expired", "fenced"} <= set(await events(attachment_id))
|
||||
|
||||
|
||||
async def test_unpublished_rows_stay_when_the_broker_refuses(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.publisher.failing = True
|
||||
with pytest.raises(Unavailable):
|
||||
await pipeline.publish()
|
||||
pending = await rows(
|
||||
"SELECT o.published_at FROM outbox o JOIN jobs j USING (job_id) WHERE j.attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert pending == [{"published_at": None}]
|
||||
pipeline.publisher.failing = False
|
||||
assert any(str(job.attachment_id) == attachment_id for job in await pipeline.publish())
|
||||
|
||||
|
||||
async def test_backoff_delays_the_next_attempt(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, policy=RetryPolicy(5, 30, 60))
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["attempt"]) == ("queued", 2)
|
||||
(row,) = await rows(
|
||||
"SELECT extract(epoch FROM next_attempt_at - now()) AS wait FROM jobs "
|
||||
"WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
assert 20 < row["wait"] <= 22.5
|
||||
(event,) = await rows(
|
||||
"SELECT (detail->>'delay_seconds')::float8 AS delay FROM job_events "
|
||||
"WHERE attachment_id = $1 AND kind = 'retry_scheduled'",
|
||||
attachment_id,
|
||||
)
|
||||
assert event["delay"] == 22.5
|
||||
|
||||
|
||||
class FailingFaults:
|
||||
async def reach(self, point: str) -> None:
|
||||
if point == TRANSIENT_ERROR:
|
||||
raise Unavailable(point)
|
||||
@@ -0,0 +1,232 @@
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import DBAPIError, IntegrityError
|
||||
|
||||
from conftest import (
|
||||
actor,
|
||||
keyed,
|
||||
make_chat,
|
||||
new_user,
|
||||
register,
|
||||
resolve,
|
||||
running_app,
|
||||
sql_connection,
|
||||
)
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.identity.infrastructure.postgres import (
|
||||
PostgresIdentityUnitOfWork,
|
||||
PostgresSessionDirectory,
|
||||
UserRow,
|
||||
)
|
||||
from messenger.messaging.application.ports import AttachmentStates
|
||||
from messenger.messaging.domain.models import Message
|
||||
from messenger.messaging.domain.values import MessageText
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
ChatRow,
|
||||
IdempotencyKeyRow,
|
||||
PostgresMessageLog,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.domain.events import DomainEvent
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
|
||||
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
|
||||
alice = await register(http, "alice")
|
||||
database = await resolve(http, Database)
|
||||
async with database.session() as session:
|
||||
await session.execute(select(1))
|
||||
started = time.perf_counter()
|
||||
starved = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
elapsed = time.perf_counter() - started
|
||||
recovered = await http.get("/api/v1/users/me", headers=actor(alice))
|
||||
assert starved.status_code == 503
|
||||
assert starved.json()["error"]["code"] == "unavailable"
|
||||
assert 0.25 < elapsed < 1
|
||||
assert recovered.json() == alice
|
||||
|
||||
|
||||
async def test_statement_timeout_is_set_on_connections() -> None:
|
||||
async with running_app(db_command_timeout_seconds=1.5) as http:
|
||||
database = await resolve(http, Database)
|
||||
async with database.session() as session:
|
||||
statement_timeout = await session.scalar(
|
||||
select(func.current_setting("statement_timeout"))
|
||||
)
|
||||
lock_timeout = await session.scalar(select(func.current_setting("lock_timeout")))
|
||||
idle_timeout = await session.scalar(
|
||||
select(func.current_setting("idle_in_transaction_session_timeout"))
|
||||
)
|
||||
assert statement_timeout == "1500ms"
|
||||
assert lock_timeout == "1500ms"
|
||||
assert idle_timeout == "10s"
|
||||
|
||||
|
||||
async def test_idle_session_does_not_acquire_connection() -> None:
|
||||
async with running_app(db_pool_max_size=1) as http:
|
||||
database = await resolve(http, Database)
|
||||
async with database.session(), database.session() as active:
|
||||
assert await active.scalar(select(1)) == 1
|
||||
await database.ping()
|
||||
|
||||
|
||||
async def test_closed_idle_connection_is_replaced_before_registration() -> None:
|
||||
async with running_app(db_pool_max_size=1) as http:
|
||||
database = await resolve(http, Database)
|
||||
async with database.session() as session:
|
||||
pid = await session.scalar(select(func.pg_backend_pid()))
|
||||
async with sql_connection() as connection:
|
||||
assert await connection.scalar(select(func.pg_terminate_backend(pid, 1000)))
|
||||
body = new_user("reconnect")
|
||||
response = await http.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201
|
||||
assert response.headers["X-Instance-Id"] and response.headers["X-Request-Id"]
|
||||
async with database.session() as session:
|
||||
assert (
|
||||
await session.scalar(
|
||||
select(func.count())
|
||||
.select_from(UserRow)
|
||||
.where(UserRow.username == body["username"])
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
async def test_readiness_timeout_releases_waiter() -> None:
|
||||
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=2) as http:
|
||||
database = await resolve(http, Database)
|
||||
async with database.session() as session:
|
||||
await session.execute(select(1))
|
||||
started = time.perf_counter()
|
||||
response = await http.get("/health/ready")
|
||||
elapsed = time.perf_counter() - started
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert 0.3 < elapsed < 1
|
||||
assert (await http.get("/health/ready")).status_code == 200
|
||||
|
||||
|
||||
async def test_server_statement_timeout_returns_connection() -> None:
|
||||
async with running_app(db_pool_max_size=1, db_command_timeout_seconds=1.5) as http:
|
||||
database = await resolve(http, Database)
|
||||
with pytest.raises(Unavailable) as failure:
|
||||
async with database.session() as session:
|
||||
await session.execute(select(func.set_config("statement_timeout", "100ms", True)))
|
||||
await session.execute(select(func.pg_sleep(2)))
|
||||
assert isinstance(failure.value.__cause__, DBAPIError)
|
||||
assert getattr(failure.value.__cause__.orig, "sqlstate", None) == "57014"
|
||||
await database.ping()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("commit", [False, True])
|
||||
async def test_unit_of_work_persists_sessions_and_events_only_on_commit(commit: bool) -> None:
|
||||
async with running_app(db_pool_max_size=1) as http:
|
||||
alice = await register(http, "alice")
|
||||
database = await resolve(http, Database)
|
||||
uow = PostgresIdentityUnitOfWork(database)
|
||||
now = datetime.now(UTC)
|
||||
_, session = Session.issue(user_id=UUID(alice["id"]), issued_at=now, ttl=timedelta(hours=1))
|
||||
event = DomainEvent()
|
||||
async with uow.transaction():
|
||||
await uow.sessions.add(session)
|
||||
uow.record(event)
|
||||
if commit:
|
||||
await uow.commit()
|
||||
stored = await PostgresSessionDirectory(database).find(session.token_hash, now)
|
||||
assert stored == (session if commit else None)
|
||||
assert uow.collect_new_events() == ([event] if commit else [])
|
||||
assert uow.collect_new_events() == []
|
||||
with pytest.raises(RuntimeError, match="вне транзакции"):
|
||||
_ = uow.session
|
||||
|
||||
|
||||
async def test_integrity_failure_rolls_back_and_keeps_pool_usable() -> None:
|
||||
async with running_app(db_pool_max_size=1) as http:
|
||||
database = await resolve(http, Database)
|
||||
uow = PostgresIdentityUnitOfWork(database)
|
||||
_, session = Session.issue(
|
||||
user_id=uuid4(), issued_at=datetime.now(UTC), ttl=timedelta(hours=1)
|
||||
)
|
||||
with pytest.raises(IntegrityError) as failure:
|
||||
async with uow.transaction():
|
||||
uow.record(DomainEvent())
|
||||
await uow.sessions.add(session)
|
||||
await uow.commit()
|
||||
assert getattr(failure.value.orig, "sqlstate", None) == "23503"
|
||||
assert uow.collect_new_events() == []
|
||||
assert uow.seen == []
|
||||
await database.ping()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("command_timeout", "request_timeout"), [(0.15, 5), (1.5, 0.3)], ids=["database", "request"]
|
||||
)
|
||||
async def test_blocked_message_times_out_without_taking_key(
|
||||
command_timeout: float, request_timeout: float
|
||||
) -> None:
|
||||
async with running_app(
|
||||
db_command_timeout_seconds=command_timeout, request_timeout_seconds=request_timeout
|
||||
) as http:
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
database = await resolve(http, Database)
|
||||
headers = keyed(alice)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
async with database.session() as session:
|
||||
await session.execute(
|
||||
select(ChatRow.id).where(ChatRow.id == UUID(chat["id"])).with_for_update()
|
||||
)
|
||||
started = time.perf_counter()
|
||||
blocked = await http.post(path, json={"text": "повтор"}, headers=headers)
|
||||
assert time.perf_counter() - started < 2
|
||||
assert blocked.status_code == 503
|
||||
assert blocked.json()["error"]["code"] == "unavailable"
|
||||
recovered = await http.post(path, json={"text": "повтор"}, headers=headers)
|
||||
replay = await http.post(path, json={"text": "повтор"}, headers=headers)
|
||||
history = await http.get(path, headers=actor(alice))
|
||||
assert recovered.status_code == replay.status_code == 201
|
||||
assert replay.json() == recovered.json()
|
||||
assert history.json()["items"] == [recovered.json()]
|
||||
|
||||
|
||||
async def test_message_integrity_failure_rolls_back_receipt_and_timestamp() -> None:
|
||||
async with running_app() as http:
|
||||
alice = await register(http, "alice")
|
||||
chat = await make_chat(http, alice)
|
||||
database = await resolve(http, Database)
|
||||
log = PostgresMessageLog(database, await resolve(http, AttachmentStates))
|
||||
now = datetime.now(UTC)
|
||||
since = now - timedelta(days=1)
|
||||
message = Message(uuid4(), UUID(chat["id"]), UUID(alice["id"]), MessageText("текст"), now)
|
||||
fingerprint = b"x" * 32
|
||||
first = await log.post(message, "first", fingerprint, since)
|
||||
assert first is not None
|
||||
with pytest.raises(IntegrityError):
|
||||
await log.post(message, "retry", fingerprint, since)
|
||||
async with database.session() as session:
|
||||
assert (
|
||||
await session.scalar(
|
||||
select(ChatRow.last_message_at).where(ChatRow.id == message.chat_id)
|
||||
)
|
||||
== first.message.created_at
|
||||
)
|
||||
assert (
|
||||
await session.scalar(
|
||||
select(func.count())
|
||||
.select_from(IdempotencyKeyRow)
|
||||
.where(
|
||||
IdempotencyKeyRow.chat_id == message.chat_id,
|
||||
IdempotencyKeyRow.key == "retry",
|
||||
)
|
||||
)
|
||||
== 0
|
||||
)
|
||||
retry = await log.post(replace(message, id=uuid4()), "retry", fingerprint, since)
|
||||
assert retry is not None
|
||||
assert retry.message.created_at > first.message.created_at
|
||||
@@ -0,0 +1,432 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import make_url
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import actor, keyed, running_app, upgrade
|
||||
from fakes import MemoryObjectStorage, NullLogger, RecordingPublisher
|
||||
from messenger.attachments.application.commands import ReconcileStorage
|
||||
from messenger.attachments.application.reconcile import Reconciliation, StorageReconciler
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded
|
||||
from messenger.attachments.entrypoints import reconcile as entrypoint
|
||||
from messenger.attachments.entrypoints.reconcile import LOCK_KEY
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
PostgresSingleRun,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
from pictures import SAMPLE
|
||||
from pipeline import settle
|
||||
|
||||
GRACE = timedelta(seconds=60)
|
||||
OLD = timedelta(hours=2)
|
||||
AGED_PENDING = """UPDATE attachments SET status = 'pending', staging_key = object_key,
|
||||
original_key = NULL, updated_at = created_at,
|
||||
created_at = created_at - interval '2 hours' WHERE id = $1"""
|
||||
LATE_ROW = """INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, width, height, object_key, staging_key, status, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), chat_id, owner_id, 'late.png', content_type, size_bytes, sha256,
|
||||
width, height, $2, $2, 'pending', now(), now()
|
||||
FROM attachments WHERE id = $1"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dsn(database: str) -> str:
|
||||
name = f"reconcile_{uuid4().hex[:12]}"
|
||||
|
||||
async def create() -> None:
|
||||
engine = create_async_engine(
|
||||
make_url(database).set(drivername="postgresql+asyncpg"),
|
||||
isolation_level="AUTOCOMMIT",
|
||||
poolclass=NullPool,
|
||||
)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.exec_driver_sql(f"CREATE DATABASE {name}")
|
||||
finally:
|
||||
await engine.dispose()
|
||||
await upgrade(target)
|
||||
|
||||
target = f"{database.rsplit('/', 1)[0]}/{name}"
|
||||
asyncio.run(create())
|
||||
return target
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Stand:
|
||||
http: AsyncClient
|
||||
store: MemoryObjectStorage
|
||||
database: Database
|
||||
users: tuple[dict[str, Any], ...]
|
||||
published: RecordingPublisher
|
||||
|
||||
async def run(self, *, apply: bool = False, deep: bool = False) -> Reconciliation:
|
||||
reconciler = StorageReconciler(
|
||||
lambda: PostgresAttachmentsUnitOfWork(self.database),
|
||||
self.store,
|
||||
PostgresSingleRun(self.database, LOCK_KEY),
|
||||
MonotonicUtcClock(),
|
||||
logger=NullLogger(),
|
||||
publisher=self.published,
|
||||
)
|
||||
command = ReconcileStorage(
|
||||
apply=apply, grace=GRACE, skew=timedelta(0), deep=deep, page_size=2
|
||||
)
|
||||
return await reconciler(command)
|
||||
|
||||
async def sql(self, query: str, *args: Any) -> Any:
|
||||
async with self.database.session() as session:
|
||||
connection = await session.connection()
|
||||
result = await connection.exec_driver_sql(query, args)
|
||||
rows = result.mappings().all() if result.returns_rows else []
|
||||
await session.commit()
|
||||
return rows
|
||||
|
||||
async def upload(self) -> dict[str, Any]:
|
||||
alice, _, _, chat = self.users
|
||||
response = await upload(self.http, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
attachment = response.json()
|
||||
legacy_key = key(attachment)
|
||||
staging_key = f"staging/{attachment['id']}"
|
||||
self.store.objects[legacy_key] = self.store.objects.pop(staging_key)
|
||||
self.store.modified[legacy_key] = self.store.modified.pop(staging_key)
|
||||
await self.sql(
|
||||
"DELETE FROM outbox WHERE job_id IN (SELECT job_id FROM jobs WHERE attachment_id = $1)",
|
||||
attachment["id"],
|
||||
)
|
||||
await self.sql("DELETE FROM jobs WHERE attachment_id = $1", attachment["id"])
|
||||
await self.sql(
|
||||
"UPDATE attachments SET status = 'ready', object_key = $2, original_key = $2, "
|
||||
"staging_key = NULL, published_version = 1 WHERE id = $1",
|
||||
attachment["id"],
|
||||
legacy_key,
|
||||
)
|
||||
return attachment
|
||||
|
||||
def age(self, key: str) -> None:
|
||||
self.store.modified[key] = datetime.now(UTC) - OLD
|
||||
|
||||
def state(self) -> dict[str, bytes]:
|
||||
return {key: data for key, (data, _) in self.store.objects.items()}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def stand(dsn: str) -> AsyncIterator[Stand]:
|
||||
async with running_app(database_url=dsn) as http:
|
||||
database = Database(
|
||||
dsn, max_size=12, connect_timeout=2, acquire_timeout=2, command_timeout=5
|
||||
)
|
||||
await database.open()
|
||||
try:
|
||||
yield Stand(http, await storage(http), database, await trio(http), RecordingPublisher())
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
def key(attachment: dict[str, Any]) -> str:
|
||||
return f"attachments/{attachment['id']}"
|
||||
|
||||
|
||||
async def damage(s: Stand) -> dict[str, Any]:
|
||||
alice, _, _, chat = s.users
|
||||
healthy, missing, sized, flipped, stale, fresh = [await s.upload() for _ in range(6)]
|
||||
posted = await s.http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [missing["id"]]},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert posted.status_code == 201, posted.text
|
||||
del s.store.objects[key(missing)]
|
||||
s.store.objects[key(sized)] = (SAMPLE[:100], "image/png")
|
||||
s.store.objects[key(flipped)] = (SAMPLE[::-1], "image/png")
|
||||
await s.sql(AGED_PENDING, stale["id"])
|
||||
await s.sql(
|
||||
"UPDATE attachments SET status = 'pending', staging_key = object_key, "
|
||||
"original_key = NULL WHERE id = $1",
|
||||
fresh["id"],
|
||||
)
|
||||
orphan, newborn = f"attachments/{uuid4()}", f"attachments/{uuid4()}"
|
||||
s.store.objects[orphan] = s.store.objects[newborn] = (SAMPLE, "image/png")
|
||||
s.store.modified[newborn] = datetime.now(UTC)
|
||||
s.age(orphan)
|
||||
return {
|
||||
"healthy": healthy,
|
||||
"missing": missing,
|
||||
"sized": sized,
|
||||
"flipped": flipped,
|
||||
"stale": stale,
|
||||
"fresh": fresh,
|
||||
"orphan": orphan,
|
||||
"newborn": newborn,
|
||||
"message": posted.json(),
|
||||
}
|
||||
|
||||
|
||||
EVERY_CLASS = {
|
||||
"orphan_stale": 1,
|
||||
"orphan_fresh": 1,
|
||||
"missing": 1,
|
||||
"size_mismatch": 1,
|
||||
"sha_mismatch": 1,
|
||||
"pending_stale": 1,
|
||||
"pending_fresh": 1,
|
||||
}
|
||||
|
||||
|
||||
async def test_dry_run_reports_every_class_and_changes_nothing(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
await damage(s)
|
||||
objects = s.state()
|
||||
rows = await s.sql("SELECT id, status, quarantine_reason FROM attachments ORDER BY id")
|
||||
shallow = await s.run()
|
||||
deep = await s.run(deep=True)
|
||||
assert s.state() == objects
|
||||
assert (
|
||||
await s.sql("SELECT id, status, quarantine_reason FROM attachments ORDER BY id") == rows
|
||||
)
|
||||
assert dict(deep.found) == EVERY_CLASS
|
||||
assert dict(shallow.found) == {k: v for k, v in EVERY_CLASS.items() if k != "sha_mismatch"}
|
||||
assert not deep.fixed
|
||||
assert not shallow.fixed
|
||||
assert shallow.requests == {"s3_list": 4, "sql": 3}
|
||||
assert deep.requests["s3_get"] == 2
|
||||
|
||||
|
||||
async def test_apply_fixes_what_it_found_and_repeats_as_noop(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
damaged = await damage(s)
|
||||
alice, bob, _, chat = s.users
|
||||
first = await s.run(apply=True, deep=True)
|
||||
second = await s.run(apply=True, deep=True)
|
||||
reasons = {
|
||||
str(row["id"]): row["quarantine_reason"]
|
||||
for row in await s.sql("SELECT id, quarantine_reason FROM attachments")
|
||||
}
|
||||
history = await s.http.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(bob))
|
||||
meta = await s.http.get(
|
||||
f"/api/v1/attachments/{damaged['flipped']['id']}", headers=actor(bob)
|
||||
)
|
||||
broken = await s.http.get(
|
||||
f"/api/v1/attachments/{damaged['flipped']['id']}/content", headers=actor(bob)
|
||||
)
|
||||
intact = await s.http.get(
|
||||
f"/api/v1/attachments/{damaged['healthy']['id']}/content", headers=actor(alice)
|
||||
)
|
||||
objects = s.state()
|
||||
assert {name: first.fixed[name] for name in EVERY_CLASS} == {
|
||||
**EVERY_CLASS,
|
||||
"orphan_fresh": 0,
|
||||
"pending_fresh": 0,
|
||||
}
|
||||
assert not second.fixed
|
||||
assert dict(second.found) == {"orphan_fresh": 1, "pending_fresh": 1, "quarantined": 3}
|
||||
assert reasons[damaged["missing"]["id"]] == "missing"
|
||||
assert reasons[damaged["sized"]["id"]] == "size_mismatch"
|
||||
assert reasons[damaged["flipped"]["id"]] == "sha_mismatch"
|
||||
assert reasons[damaged["healthy"]["id"]] is None
|
||||
assert [
|
||||
(event.attachment_id, event.reason)
|
||||
for event in s.published.events
|
||||
if isinstance(event, AttachmentDiscarded)
|
||||
] == [(UUID(damaged["stale"]["id"]), "reconcile")]
|
||||
assert reasons[damaged["fresh"]["id"]] is None
|
||||
assert damaged["stale"]["id"] not in reasons
|
||||
assert key(damaged["stale"]) not in objects
|
||||
assert damaged["orphan"] not in objects
|
||||
assert damaged["newborn"] in objects
|
||||
assert key(damaged["flipped"]) in objects
|
||||
assert history.json()["items"][0]["attachment_ids"] == [damaged["missing"]["id"]]
|
||||
assert meta.status_code == 200
|
||||
assert meta.json()["sha256"] == damaged["flipped"]["sha256"]
|
||||
assert broken.status_code == 404
|
||||
assert broken.json()["error"]["code"] == "not_found"
|
||||
assert intact.status_code == 200
|
||||
assert intact.content == SAMPLE
|
||||
|
||||
|
||||
async def test_restored_object_leaves_quarantine(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
_, bob, _, _ = s.users
|
||||
lost, flipped = await s.upload(), await s.upload()
|
||||
del s.store.objects[key(lost)]
|
||||
s.store.objects[key(flipped)] = (SAMPLE[::-1], "image/png")
|
||||
isolated = await s.run(apply=True, deep=True)
|
||||
s.store.objects[key(lost)] = s.store.objects[key(flipped)] = (SAMPLE, "image/png")
|
||||
s.store.modified[key(lost)] = s.store.modified[key(flipped)]
|
||||
shallow = await s.run(apply=True)
|
||||
again = await s.run(apply=True)
|
||||
content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob))
|
||||
assert isolated.fixed["missing"] == isolated.fixed["sha_mismatch"] == 1
|
||||
assert shallow.fixed["healed"] == 2
|
||||
assert shallow.requests["s3_get"] == 2
|
||||
assert not again.fixed
|
||||
assert again.requests["s3_get"] == 0
|
||||
assert hashlib.sha256(content.content).hexdigest() == lost["sha256"]
|
||||
|
||||
|
||||
async def test_other_bytes_of_the_same_length_keep_the_quarantine(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
_, bob, _, _ = s.users
|
||||
lost = await s.upload()
|
||||
del s.store.objects[key(lost)]
|
||||
isolated = await s.run(apply=True)
|
||||
s.store.objects[key(lost)] = (bytes(len(SAMPLE)), "image/png")
|
||||
s.age(key(lost))
|
||||
shallow = await s.run(apply=True)
|
||||
content = await s.http.get(f"/api/v1/attachments/{lost['id']}/content", headers=actor(bob))
|
||||
reason = await s.sql("SELECT quarantine_reason FROM attachments WHERE id = $1", lost["id"])
|
||||
assert isolated.fixed["missing"] == 1
|
||||
assert not shallow.fixed
|
||||
assert shallow.found["quarantined"] == 1
|
||||
assert shallow.requests["s3_get"] == 1
|
||||
assert content.status_code == 404
|
||||
assert reason[0]["quarantine_reason"] == "missing"
|
||||
|
||||
|
||||
async def test_pages_of_rows_are_not_followed_by_an_empty_one(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
empty = await s.run()
|
||||
for _ in range(4):
|
||||
await s.upload()
|
||||
full = await s.run()
|
||||
assert (empty.rows, empty.requests["sql"]) == (0, 1)
|
||||
assert (full.rows, full.requests["sql"]) == (4, 2)
|
||||
|
||||
|
||||
def test_any_pass_failure_ends_as_reconcile_failed(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
async def broken(*_args: Any) -> Reconciliation:
|
||||
cancelled = TimeoutError("statement timeout")
|
||||
raise ExceptionGroup("pass", [cancelled])
|
||||
|
||||
monkeypatch.setattr(entrypoint, "reconcile", broken)
|
||||
for name, value in {
|
||||
"DATABASE_URL": "postgresql://unused@127.0.0.1:1/unused",
|
||||
"S3_ACCESS_KEY_ID": "reconciler",
|
||||
"S3_SECRET_ACCESS_KEY": "reconciler-secret",
|
||||
}.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
entrypoint.main(["--apply"])
|
||||
captured = capsys.readouterr()
|
||||
assert stopped.value.code == 1
|
||||
assert captured.out == ""
|
||||
assert "reconcile.failed" in captured.err
|
||||
assert "TimeoutError" in captured.err
|
||||
assert "Traceback" not in captured.err
|
||||
|
||||
|
||||
async def test_row_written_after_listing_keeps_the_object(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
first, last = await s.upload(), await s.upload()
|
||||
fresh, late = f"{key(first)}-a", f"{key(first)}-b"
|
||||
for name in (fresh, late):
|
||||
s.store.objects[name] = (SAMPLE, "image/png")
|
||||
s.store.modified[name] = datetime.now(UTC)
|
||||
s.age(late)
|
||||
|
||||
async def row_appears() -> None:
|
||||
s.store.after_page = None
|
||||
await s.sql(LATE_ROW, first["id"], late)
|
||||
|
||||
s.store.after_page = row_appears
|
||||
report = await s.run(apply=True)
|
||||
objects = s.state()
|
||||
assert key(first) < fresh < late < key(last)
|
||||
assert report.found["orphan_stale"] == 1
|
||||
assert report.rechecked["orphan_stale"] == 1
|
||||
assert not report.fixed
|
||||
assert late in objects
|
||||
|
||||
|
||||
async def test_second_pass_is_skipped_while_one_runs(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
orphan = f"attachments/{uuid4()}"
|
||||
s.store.objects[orphan] = (SAMPLE, "image/png")
|
||||
s.age(orphan)
|
||||
async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held:
|
||||
busy = await s.run(apply=True)
|
||||
free = await s.run(apply=True)
|
||||
assert held
|
||||
assert busy.skipped
|
||||
assert not busy.found
|
||||
assert not free.skipped
|
||||
assert free.fixed["orphan_stale"] == 1
|
||||
|
||||
|
||||
async def test_storage_failure_mid_pass_ends_it_as_unavailable(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
await damage(s)
|
||||
|
||||
async def broken() -> None:
|
||||
raise Unavailable("S3 недоступно") from TimeoutError()
|
||||
|
||||
s.store.after_page = broken
|
||||
with pytest.raises(Unavailable) as failed:
|
||||
await s.run(apply=True, deep=True)
|
||||
assert isinstance(failed.value.__cause__, TimeoutError)
|
||||
|
||||
|
||||
async def test_cancelled_pass_releases_its_autocommit_lock(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def hold() -> None:
|
||||
async with PostgresSingleRun(s.database, LOCK_KEY).hold() as held:
|
||||
assert held
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
task = asyncio.create_task(hold())
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
states = await s.sql(
|
||||
"SELECT a.state FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid "
|
||||
"WHERE l.locktype = 'advisory' AND l.objid = $1",
|
||||
LOCK_KEY,
|
||||
)
|
||||
assert [row["state"] for row in states] == ["idle"]
|
||||
finally:
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
locks = await s.sql(
|
||||
"SELECT count(*) AS total FROM pg_locks WHERE locktype = 'advisory' AND objid = $1",
|
||||
LOCK_KEY,
|
||||
)
|
||||
assert locks[0]["total"] == 0
|
||||
|
||||
|
||||
async def test_legacy_reconciler_does_not_touch_pipeline_objects(dsn: str) -> None:
|
||||
async with stand(dsn) as s:
|
||||
alice, _, _, chat = s.users
|
||||
response = await upload(s.http, alice, chat)
|
||||
assert response.status_code == 202
|
||||
await settle(s.http)
|
||||
before = s.state()
|
||||
assert {key.split("/", 1)[0] for key in before} == {"staging", "originals", "variants"}
|
||||
for object_key in before:
|
||||
s.age(object_key)
|
||||
report = await s.run(apply=True, deep=True)
|
||||
assert report.rows == report.objects == 0
|
||||
assert not report.fixed and not report.errors
|
||||
assert s.state() == before
|
||||
content = await s.http.get(
|
||||
f"/api/v1/attachments/{response.json()['id']}/content", headers=actor(alice)
|
||||
)
|
||||
assert content.status_code == 200 and content.content == SAMPLE
|
||||
@@ -0,0 +1,307 @@
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_attachments import storage
|
||||
from test_pipeline import FailingFaults, accepted, events, job_of, rows, state, variants
|
||||
|
||||
from conftest import DATABASE
|
||||
from fakes import NullLogger
|
||||
from messenger.admin import serve
|
||||
from messenger.attachments.application.pipeline import (
|
||||
AFTER_CLAIM,
|
||||
AFTER_COMMIT_BEFORE_ACK,
|
||||
AFTER_COMMIT_BEFORE_PUBLISH,
|
||||
AFTER_PUBLISH_BEFORE_CONFIRM,
|
||||
AFTER_S3_WRITE,
|
||||
STALL_AFTER_CLAIM,
|
||||
TRANSIENT_ERROR,
|
||||
)
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.jobs import Outcome, ReplayResult
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from pipeline import InlinePipeline, InlineRenderer, pipeline_of
|
||||
|
||||
WORKER_POINTS = [
|
||||
AFTER_CLAIM,
|
||||
STALL_AFTER_CLAIM,
|
||||
TRANSIENT_ERROR,
|
||||
AFTER_S3_WRITE,
|
||||
AFTER_COMMIT_BEFORE_ACK,
|
||||
]
|
||||
|
||||
|
||||
class Crash(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class RecordingFaults:
|
||||
__slots__ = ("crash_at", "reached")
|
||||
|
||||
def __init__(self, crash_at: str = "") -> None:
|
||||
self.crash_at = crash_at
|
||||
self.reached: list[str] = []
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
self.reached.append(point)
|
||||
if point == self.crash_at:
|
||||
raise Crash(point)
|
||||
|
||||
|
||||
class SlowRenderer:
|
||||
__slots__ = ("seconds",)
|
||||
|
||||
def __init__(self, seconds: float) -> None:
|
||||
self.seconds = seconds
|
||||
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
await asyncio.sleep(self.seconds)
|
||||
return await InlineRenderer().render(data, pipeline_version)
|
||||
|
||||
|
||||
class ExpiringFaults:
|
||||
__slots__ = ("attachment_id", "pipeline")
|
||||
|
||||
def __init__(self, pipeline: InlinePipeline, attachment_id: str) -> None:
|
||||
self.pipeline = pipeline
|
||||
self.attachment_id = attachment_id
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
if point == STALL_AFTER_CLAIM:
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' "
|
||||
"WHERE attachment_id = $1",
|
||||
self.attachment_id,
|
||||
)
|
||||
await self.pipeline.recover()
|
||||
|
||||
|
||||
async def outbox(attachment_id: str) -> list[bool]:
|
||||
found = await rows(
|
||||
"SELECT o.published_at IS NOT NULL AS published FROM outbox o JOIN jobs j USING (job_id) "
|
||||
"WHERE j.attachment_id = $1 ORDER BY o.id",
|
||||
attachment_id,
|
||||
)
|
||||
return [row["published"] for row in found]
|
||||
|
||||
|
||||
def stored(objects: dict[str, tuple[bytes, str]], attachment_id: str) -> list[str]:
|
||||
return sorted(key for key in objects if key.startswith(f"variants/{attachment_id}/"))
|
||||
|
||||
|
||||
async def test_fault_points_are_reached_in_order(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
faults = RecordingFaults()
|
||||
pipeline.faults = faults
|
||||
published = await pipeline.publish()
|
||||
assert faults.reached[:2] == [AFTER_COMMIT_BEFORE_PUBLISH, AFTER_PUBLISH_BEFORE_CONFIRM]
|
||||
faults.reached.clear()
|
||||
(job,) = [job for job in published if str(job.attachment_id) == attachment_id]
|
||||
assert await pipeline.process(job) is Outcome.DONE
|
||||
assert faults.reached == WORKER_POINTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("point", [AFTER_COMMIT_BEFORE_PUBLISH, AFTER_PUBLISH_BEFORE_CONFIRM])
|
||||
async def test_relay_crash_leaves_the_row_for_the_next_relay(
|
||||
client: AsyncClient, point: str
|
||||
) -> None:
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline.faults = RecordingFaults(point)
|
||||
with pytest.raises(Crash):
|
||||
await pipeline.publish()
|
||||
assert await outbox(attachment_id) == [False]
|
||||
sent = [body for body in pipeline.publisher.bodies if attachment_id.encode() in body]
|
||||
assert len(sent) == (point == AFTER_PUBLISH_BEFORE_CONFIRM)
|
||||
pipeline.faults = RecordingFaults()
|
||||
outcomes = await pipeline.drain()
|
||||
assert Outcome.DONE in outcomes
|
||||
assert await outbox(attachment_id) == [True]
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_crash_after_s3_write_is_finished_by_the_next_attempt(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, lease=timedelta(seconds=60))
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
pipeline.faults = RecordingFaults(AFTER_S3_WRITE)
|
||||
with pytest.raises(Crash):
|
||||
await pipeline.process(job)
|
||||
objects = (await storage(client)).objects
|
||||
written = stored(objects, attachment_id)
|
||||
assert len(written) == 3
|
||||
assert await variants(attachment_id) == []
|
||||
assert (await state(attachment_id))["status"] == "processing"
|
||||
await rows(
|
||||
"UPDATE jobs SET lease_until = now() - interval '1 second' WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
pipeline.faults = RecordingFaults()
|
||||
assert await pipeline.recover() >= 1
|
||||
await pipeline.drain()
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["attempt"]) == ("ready", 2)
|
||||
assert stored(objects, attachment_id) == written
|
||||
assert sorted(row["object_key"] for row in await variants(attachment_id)) == written
|
||||
|
||||
|
||||
async def test_crash_after_commit_is_a_duplicate_on_redelivery(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
pipeline.faults = RecordingFaults(AFTER_COMMIT_BEFORE_ACK)
|
||||
with pytest.raises(Crash):
|
||||
await pipeline.process(job)
|
||||
before = await variants(attachment_id)
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
pipeline.faults = RecordingFaults()
|
||||
assert await pipeline.process(job) is Outcome.DUPLICATE
|
||||
assert await variants(attachment_id) == before
|
||||
|
||||
|
||||
async def test_long_render_keeps_its_lease(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client, lease=timedelta(seconds=1))
|
||||
pipeline.renderer = SlowRenderer(2.5)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
|
||||
async def sweep() -> None:
|
||||
for _ in range(4):
|
||||
await asyncio.sleep(0.6)
|
||||
await pipeline.recover()
|
||||
|
||||
outcome, _ = await asyncio.gather(pipeline.process(job), sweep())
|
||||
assert outcome is Outcome.DONE
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["attempt"], done["claims"]) == ("ready", 1, 1)
|
||||
assert "lease_expired" not in await events(attachment_id)
|
||||
|
||||
|
||||
async def test_lost_lease_stops_before_side_effects(client: AsyncClient) -> None:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
job = await job_of(attachment_id)
|
||||
pipeline.faults = ExpiringFaults(pipeline, attachment_id)
|
||||
assert await pipeline.process(job) is Outcome.FENCED
|
||||
objects = (await storage(client)).objects
|
||||
assert stored(objects, attachment_id) == []
|
||||
assert f"originals/{attachment_id}" not in objects
|
||||
assert (await state(attachment_id))["status"] == "queued"
|
||||
assert (await events(attachment_id))[-2:] == ["lease_expired", "fenced"]
|
||||
pipeline.faults = RecordingFaults()
|
||||
await pipeline.drain()
|
||||
assert (await state(attachment_id))["status"] == "ready"
|
||||
|
||||
|
||||
async def test_environment_faults_stall_once_and_fail_transiently() -> None:
|
||||
stall = EnvironmentFaults(STALL_AFTER_CLAIM, NullLogger(), stall_seconds=0.3)
|
||||
started = asyncio.get_running_loop().time()
|
||||
await stall.reach(AFTER_CLAIM)
|
||||
await stall.reach(STALL_AFTER_CLAIM)
|
||||
await stall.reach(STALL_AFTER_CLAIM)
|
||||
assert 0.3 <= asyncio.get_running_loop().time() - started < 0.6
|
||||
with pytest.raises(Unavailable):
|
||||
await EnvironmentFaults(TRANSIENT_ERROR, NullLogger()).reach(TRANSIENT_ERROR)
|
||||
|
||||
|
||||
def test_environment_fault_crashes_the_process_with_137() -> None:
|
||||
script = (
|
||||
"import asyncio\n"
|
||||
"from fakes import NullLogger\n"
|
||||
"from messenger.attachments.infrastructure.faults import EnvironmentFaults\n"
|
||||
"asyncio.run(EnvironmentFaults('after_commit_before_ack', NullLogger())"
|
||||
".reach('after_commit_before_ack'))\n"
|
||||
"print('survived')\n"
|
||||
)
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-c", script],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
env={"PYTHONPATH": ":".join(sys.path)},
|
||||
)
|
||||
assert (done.returncode, done.stdout) == (137, "")
|
||||
|
||||
|
||||
async def failed(client: AsyncClient) -> tuple[InlinePipeline, str]:
|
||||
_, _, attachment_id = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
pipeline.faults = FailingFaults()
|
||||
await pipeline.drain()
|
||||
pipeline.faults = RecordingFaults()
|
||||
assert (await state(attachment_id))["error_code"] == "retry_exhausted"
|
||||
return pipeline, attachment_id
|
||||
|
||||
|
||||
async def test_replay_of_failed_reaches_ready_once(client: AsyncClient) -> None:
|
||||
pipeline, attachment_id = await failed(client)
|
||||
job = await job_of(attachment_id)
|
||||
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.REPLAYED
|
||||
queued = await state(attachment_id)
|
||||
assert (queued["status"], queued["job_status"], queued["attempt"], queued["error_code"]) == (
|
||||
"queued",
|
||||
"queued",
|
||||
1,
|
||||
None,
|
||||
)
|
||||
assert await outbox(attachment_id) == [True] * 5 + [False]
|
||||
await pipeline.drain()
|
||||
done = await state(attachment_id)
|
||||
assert (done["status"], done["attempt"]) == ("ready", 1)
|
||||
assert (await job_of(attachment_id)).id == job.id
|
||||
before = await variants(attachment_id)
|
||||
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.NOOP
|
||||
assert await outbox(attachment_id) == [True] * 6
|
||||
assert await variants(attachment_id) == before
|
||||
assert (await events(attachment_id))[-1] == "replay_noop"
|
||||
assert "replayed" in await events(attachment_id)
|
||||
assert await pipeline.replay(uuid4()) is ReplayResult.NOT_FOUND
|
||||
|
||||
|
||||
async def test_failed_staging_is_kept_for_the_retention_period(client: AsyncClient) -> None:
|
||||
pipeline, attachment_id = await failed(client)
|
||||
_, _, waiting = await accepted(client)
|
||||
objects = (await storage(client)).objects
|
||||
await pipeline.clean(timedelta(days=1))
|
||||
assert (await state(attachment_id))["staging_key"] == f"staging/{attachment_id}"
|
||||
assert f"staging/{attachment_id}" in objects
|
||||
await pipeline.clean(timedelta(0))
|
||||
assert (await state(attachment_id))["staging_key"] is None
|
||||
assert f"staging/{attachment_id}" not in objects
|
||||
assert (await state(waiting))["staging_key"] == f"staging/{waiting}"
|
||||
assert f"staging/{waiting}" in objects
|
||||
assert await pipeline.replay(UUID(attachment_id)) is ReplayResult.EXPIRED
|
||||
assert (await state(attachment_id))["status"] == "failed"
|
||||
|
||||
|
||||
async def test_operator_cli_lists_failed_jobs_and_replays(
|
||||
client: AsyncClient, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_, attachment_id = await failed(client)
|
||||
monkeypatch.setenv("DATABASE_URL", DATABASE["url"])
|
||||
monkeypatch.setenv("LOG_LEVEL", "WARNING")
|
||||
assert await serve(["failed", "--limit", "500"]) == 0
|
||||
registry = json.loads(capsys.readouterr().out.splitlines()[-1])["failed"]
|
||||
(mine,) = [row for row in registry if row["attachment_id"] == attachment_id]
|
||||
assert datetime.fromisoformat(mine["failed_at"]).utcoffset() == timedelta(0)
|
||||
assert (mine["error_code"], mine["attempt"], mine["last_error"]) == (
|
||||
"retry_exhausted",
|
||||
5,
|
||||
"Unavailable",
|
||||
)
|
||||
assert await serve(["replay", "--attachment-id", attachment_id, "--operator", "alice"]) == 0
|
||||
report = json.loads(capsys.readouterr().out.splitlines()[-1])
|
||||
assert report == {"result": "replayed", "attachment_id": attachment_id, "operator": "alice"}
|
||||
assert await serve(["replay", "--attachment-id", str(uuid4())]) == 1
|
||||
@@ -0,0 +1,203 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from hashlib import sha256
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from conftest import (
|
||||
PASSWORD,
|
||||
actor,
|
||||
basic,
|
||||
bearer,
|
||||
login,
|
||||
make_chat,
|
||||
new_user,
|
||||
register,
|
||||
running_app,
|
||||
scalar,
|
||||
)
|
||||
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||
|
||||
BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def challenged(response, challenge: str) -> None:
|
||||
assert response.status_code == 401, response.text
|
||||
assert response.headers["WWW-Authenticate"] == challenge
|
||||
assert response.json()["error"]["code"] == "unauthorized"
|
||||
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_login_returns_session_for_registered_user(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
user = (await client.post("/api/v1/users", json=body)).json()
|
||||
session = await login(client, body["username"])
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert session["user"] == user
|
||||
assert len(session["token"]) >= 43
|
||||
assert body["username"] not in session["token"] and user["id"] not in session["token"]
|
||||
assert session["expires_at"].endswith("Z")
|
||||
expires = datetime.fromisoformat(session["expires_at"])
|
||||
created = datetime.fromisoformat(user["created_at"])
|
||||
assert timedelta(seconds=3500) < expires - created < timedelta(seconds=3700)
|
||||
|
||||
|
||||
async def test_registration_response_hides_password(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
response = await client.post("/api/v1/users", json=body)
|
||||
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
|
||||
assert PASSWORD not in response.text
|
||||
|
||||
|
||||
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
stored = await scalar(select(UserRow.password_hash).where(UserRow.id == UUID(alice["id"])))
|
||||
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||
assert PASSWORD not in stored
|
||||
|
||||
|
||||
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
token = actor(alice)["Authorization"].split()[1]
|
||||
rows = select(func.count()).select_from(SessionRow)
|
||||
assert await scalar(rows.where(SessionRow.token_hash == sha256(token.encode()).digest())) == 1
|
||||
assert await scalar(rows.where(SessionRow.token_hash == token.encode())) == 0
|
||||
|
||||
|
||||
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
wrong = await client.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20))
|
||||
unknown = await client.post("/api/v1/auth/sessions", headers=basic("u_ghost_000", PASSWORD))
|
||||
challenged(wrong, BASIC)
|
||||
challenged(unknown, BASIC)
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"headers",
|
||||
[{}, {"Authorization": "Basic !!!"}, {"Authorization": "Bearer abc"}, {"X-User-Id": "x"}],
|
||||
)
|
||||
async def test_login_without_valid_basic(client: AsyncClient, headers: dict) -> None:
|
||||
challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw", [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]
|
||||
)
|
||||
async def test_non_ascii_basic_matches_wrong_password(client: AsyncClient, raw: bytes) -> None:
|
||||
alice = await register(client, "non_ascii_basic")
|
||||
count = (
|
||||
select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(alice["id"]))
|
||||
)
|
||||
before = await scalar(count)
|
||||
wrong = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers={**basic(alice["username"], "wrong-password"), "X-Request-Id": "non-ascii-basic"},
|
||||
)
|
||||
invalid = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers={b"Authorization": raw, b"X-Request-Id": b"non-ascii-basic"},
|
||||
)
|
||||
for response in [wrong, invalid]:
|
||||
challenged(response, BASIC)
|
||||
assert response.headers["X-Instance-Id"]
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
assert set(response.json()) == {"error"}
|
||||
assert set(response.json()["error"]) == {"code", "message", "request_id"}
|
||||
assert response.json()["error"]["message"]
|
||||
assert wrong.json() == invalid.json()
|
||||
assert await scalar(count) == before
|
||||
|
||||
|
||||
async def test_password_with_colon_logs_in(client: AsyncClient) -> None:
|
||||
body = new_user("colon", password="пароль:с:двоеточием")
|
||||
assert (await client.post("/api/v1/users", json=body)).status_code == 201
|
||||
assert (await login(client, body["username"], body["password"]))["token"]
|
||||
|
||||
|
||||
async def test_login_with_body_is_rejected(client: AsyncClient) -> None:
|
||||
body = new_user("body")
|
||||
await client.post("/api/v1/users", json=body)
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions", headers=basic(body["username"], PASSWORD), json={"x": 1}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
async def test_basic_on_business_endpoint_gets_bearer_challenge(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
await client.post("/api/v1/users", json=body)
|
||||
challenged(
|
||||
await client.get("/api/v1/users/me", headers=basic(body["username"], PASSWORD)), BEARER
|
||||
)
|
||||
|
||||
|
||||
async def test_user_id_header_does_not_override_owner(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
eve = await register(client, "eve")
|
||||
response = await client.get(
|
||||
"/api/v1/users/me", headers={**actor(alice), "X-User-Id": eve["id"]}
|
||||
)
|
||||
assert response.json() == alice
|
||||
|
||||
|
||||
async def test_authentication_precedes_validation(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/api/v1/chats/not-a-uuid/messages",
|
||||
content=b"{broken",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
challenged(response, BEARER)
|
||||
|
||||
|
||||
async def test_logout_revokes_only_current_session(client: AsyncClient) -> None:
|
||||
body = new_user("alice")
|
||||
await client.post("/api/v1/users", json=body)
|
||||
first = (await login(client, body["username"]))["token"]
|
||||
second = (await login(client, body["username"]))["token"]
|
||||
logout = await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
|
||||
assert logout.status_code == 204
|
||||
assert logout.content == b""
|
||||
assert logout.headers["X-Request-Id"]
|
||||
challenged(await client.get("/api/v1/users/me", headers=bearer(first)), BEARER)
|
||||
challenged(await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)), BEARER)
|
||||
assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200
|
||||
|
||||
|
||||
async def test_short_ttl_session_expires() -> None:
|
||||
async with running_app(session_ttl_seconds=1) as client:
|
||||
alice = await register(client, "alice")
|
||||
assert (await client.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
await asyncio.sleep(1.2)
|
||||
challenged(await client.get("/api/v1/users/me", headers=actor(alice)), BEARER)
|
||||
|
||||
|
||||
async def test_expired_sessions_are_purged_on_next_login() -> None:
|
||||
async with running_app(session_ttl_seconds=1) as client:
|
||||
body = new_user("purge")
|
||||
user = (await client.post("/api/v1/users", json=body)).json()
|
||||
await login(client, body["username"])
|
||||
await asyncio.sleep(1.2)
|
||||
await login(client, body["username"])
|
||||
sql = select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(user["id"]))
|
||||
assert await scalar(sql) == 1
|
||||
|
||||
|
||||
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
|
||||
alice = await register(client, "alice")
|
||||
chat = await make_chat(client, alice)
|
||||
for method, path in [
|
||||
("GET", "/api/v1/chats"),
|
||||
("POST", "/api/v1/chats"),
|
||||
("GET", f"/api/v1/chats/{chat['id']}"),
|
||||
("GET", f"/api/v1/chats/{chat['id']}/messages"),
|
||||
("POST", f"/api/v1/chats/{chat['id']}/messages"),
|
||||
("DELETE", "/api/v1/auth/sessions/current"),
|
||||
]:
|
||||
challenged(await client.request(method, path, headers={"X-User-Id": alice["id"]}), BEARER)
|
||||
@@ -0,0 +1,148 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import actor, keyed, make_chat, register, resolve, running_app, scalar
|
||||
from fakes import MemoryObjectStorage
|
||||
from messenger.attachments.application.ports import ObjectStorage
|
||||
from messenger.messaging.application import handlers
|
||||
from messenger.messaging.domain.events import MessagePosted
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from pictures import SAMPLE, png
|
||||
from pipeline import settle
|
||||
|
||||
MARKER = "текст-который-не-должен-утечь-при-таймауте"
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def slow_post(delay: float) -> AsyncIterator[None]:
|
||||
original: Callable = handlers.PostMessageHandler.__call__
|
||||
|
||||
async def stalled(self, command):
|
||||
await asyncio.sleep(delay)
|
||||
return await original(self, command)
|
||||
|
||||
handlers.PostMessageHandler.__call__ = stalled
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
handlers.PostMessageHandler.__call__ = original
|
||||
|
||||
|
||||
async def post(client: AsyncClient, chat: dict, sender: dict, text: str):
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=keyed(sender)
|
||||
)
|
||||
|
||||
|
||||
async def prepared(client: AsyncClient) -> tuple[dict, dict]:
|
||||
alice = await register(client, "alice")
|
||||
return alice, await make_chat(client, alice)
|
||||
|
||||
|
||||
async def test_timeout_returns_unavailable_error_body() -> None:
|
||||
async with running_app(request_timeout_seconds=0.15) as client:
|
||||
alice, chat = await prepared(client)
|
||||
async with slow_post(1.0):
|
||||
response = await post(client, chat, alice, "медленная запись")
|
||||
assert response.status_code == 503
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_timeout_does_not_break_following_requests() -> None:
|
||||
async with running_app(request_timeout_seconds=0.15) as client:
|
||||
alice, chat = await prepared(client)
|
||||
async with slow_post(1.0):
|
||||
assert (await post(client, chat, alice, "зависшая запись")).status_code == 503
|
||||
assert (await post(client, chat, alice, "нормальная запись")).status_code == 201
|
||||
assert (await client.get("/health/ready")).status_code == 200
|
||||
|
||||
|
||||
async def test_timeout_is_logged_without_message_text(capsys) -> None:
|
||||
async with running_app(request_timeout_seconds=0.15, log_level="INFO") as client:
|
||||
alice, chat = await prepared(client)
|
||||
async with slow_post(1.0):
|
||||
assert (await post(client, chat, alice, MARKER)).status_code == 503
|
||||
captured = capsys.readouterr()
|
||||
assert "request.timeout" in captured.out
|
||||
assert MARKER not in captured.out
|
||||
assert MARKER not in captured.err
|
||||
|
||||
|
||||
async def test_normal_request_is_not_affected_by_timeout() -> None:
|
||||
async with running_app(request_timeout_seconds=5.0) as client:
|
||||
alice, chat = await prepared(client)
|
||||
assert (await post(client, chat, alice, "обычная запись")).status_code == 201
|
||||
|
||||
|
||||
async def test_slow_event_handler_does_not_trigger_timeout() -> None:
|
||||
async with running_app(request_timeout_seconds=0.3) as client:
|
||||
alice, chat = await prepared(client)
|
||||
blocked = asyncio.Event()
|
||||
bus = await resolve(client, EventBus)
|
||||
|
||||
async def stall(_event: MessagePosted) -> None:
|
||||
await blocked.wait()
|
||||
|
||||
bus.subscribe(MessagePosted, stall)
|
||||
response = await post(client, chat, alice, "ответ не ждёт обработчик")
|
||||
blocked.set()
|
||||
assert response.status_code == 201
|
||||
|
||||
|
||||
async def test_healthcheck_stays_fast(client: AsyncClient) -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
assert loop.time() - started < 1.0
|
||||
|
||||
|
||||
async def trickled(data: bytes, size: int, delay: float) -> AsyncIterator[bytes]:
|
||||
for start in range(0, len(data), size):
|
||||
await asyncio.sleep(delay)
|
||||
yield data[start : start + size]
|
||||
|
||||
|
||||
async def upload(client: AsyncClient, user: dict, chat: dict, body: AsyncIterator[bytes]):
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=slow.png",
|
||||
content=body,
|
||||
headers={**actor(user), "Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
|
||||
async def test_steady_slow_transfer_outlives_the_request_timeout() -> None:
|
||||
picture = png(16, 16, size=1 << 20)
|
||||
async with running_app(request_timeout_seconds=0.4, min_transfer_rate_bytes=16_384) as client:
|
||||
alice, chat = await prepared(client)
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
uploaded = await upload(client, alice, chat, trickled(picture, 65_536, 0.1))
|
||||
assert uploaded.status_code == 202, uploaded.text
|
||||
assert loop.time() - started > 1.0
|
||||
await settle(client)
|
||||
store = await resolve(client, ObjectStorage)
|
||||
assert isinstance(store, MemoryObjectStorage)
|
||||
store.delay = 0.1
|
||||
started = loop.time()
|
||||
content = await client.get(
|
||||
f"/api/v1/attachments/{uploaded.json()['id']}/content", headers=actor(alice)
|
||||
)
|
||||
assert (content.status_code, content.content) == (200, picture)
|
||||
assert loop.time() - started > 1.0
|
||||
|
||||
|
||||
async def test_body_slower_than_the_minimal_rate_is_cut() -> None:
|
||||
async with running_app(request_timeout_seconds=0.3, min_transfer_rate_bytes=1 << 20) as client:
|
||||
alice, chat = await prepared(client)
|
||||
before = await scalar("SELECT count(*) FROM attachments")
|
||||
loop = asyncio.get_running_loop()
|
||||
started = loop.time()
|
||||
response = await upload(client, alice, chat, trickled(SAMPLE, 4_096, 0.1))
|
||||
assert (response.status_code, response.json()["error"]["code"]) == (503, "unavailable")
|
||||
assert loop.time() - started < 1.0
|
||||
assert await scalar("SELECT count(*) FROM attachments") == before
|
||||
@@ -0,0 +1,65 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from httpx import AsyncClient
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.trace import SpanKind
|
||||
from sqlalchemy import select
|
||||
from test_pipeline import accepted, job_of
|
||||
|
||||
from conftest import sql_connection
|
||||
from messenger.attachments.infrastructure.postgres import JobRow, OutboxRow, PostgresJobRepository
|
||||
from messenger.shared.infrastructure.trace_context import capture_context, restored_context
|
||||
from pipeline import pipeline_of
|
||||
|
||||
|
||||
async def test_context_survives_outbox_delivery_and_lease_recovery(client: AsyncClient) -> None:
|
||||
provider = TracerProvider(shutdown_on_exit=False)
|
||||
tracer = provider.get_tracer("test")
|
||||
with tracer.start_as_current_span("upload", kind=SpanKind.SERVER):
|
||||
origin = capture_context()
|
||||
_, _, attachment_id = await accepted(client)
|
||||
job = await job_of(attachment_id)
|
||||
async with sql_connection() as connection:
|
||||
assert (
|
||||
await connection.scalar(select(JobRow.trace_context).where(JobRow.job_id == job.id))
|
||||
== origin
|
||||
)
|
||||
assert (
|
||||
await connection.scalar(
|
||||
select(OutboxRow.trace_context).where(OutboxRow.job_id == job.id)
|
||||
)
|
||||
== origin
|
||||
)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.publish()
|
||||
assert pipeline.publisher.contexts == [origin]
|
||||
uow = pipeline.uow()
|
||||
async with uow.transaction():
|
||||
claim = await uow.jobs.claim(job, UUID(int=1), timedelta(seconds=-1))
|
||||
assert claim is not None
|
||||
await uow.commit()
|
||||
await pipeline.recover()
|
||||
await asyncio.sleep(0.02)
|
||||
await pipeline.publish()
|
||||
assert len(pipeline.publisher.contexts) == 2
|
||||
assert pipeline.publisher.contexts[-1] == origin
|
||||
with restored_context(origin), tracer.start_as_current_span("retry", kind=SpanKind.CONSUMER):
|
||||
retry = capture_context()
|
||||
async with uow.transaction():
|
||||
await PostgresJobRepository(uow.session)._enqueue(job)
|
||||
await uow.commit()
|
||||
async with sql_connection() as connection:
|
||||
assert (
|
||||
await connection.scalar(
|
||||
select(OutboxRow.trace_context)
|
||||
.where(OutboxRow.job_id == job.id)
|
||||
.order_by(OutboxRow.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
== retry
|
||||
)
|
||||
assert retry["traceparent"].split("-")[1] == origin["traceparent"].split("-")[1]
|
||||
assert retry != origin
|
||||
provider.shutdown()
|
||||
@@ -0,0 +1,255 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from httpx import AsyncClient
|
||||
from starlette.types import Message
|
||||
from test_attachments import storage, trio, upload
|
||||
|
||||
from conftest import APPS, actor, keyed, resolve, running_app, scalar, sql_connection
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded
|
||||
from messenger.attachments.entrypoints.sweeper import UploadSweeper
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from pictures import SAMPLE
|
||||
from pipeline import settle
|
||||
|
||||
AGED = "UPDATE attachments SET created_at = created_at - interval '1 hour' WHERE id = $1"
|
||||
|
||||
|
||||
async def execute(sql: str, *args: Any) -> None:
|
||||
async with sql_connection() as connection:
|
||||
await connection.exec_driver_sql(sql, args)
|
||||
|
||||
|
||||
def sweeper(http: AsyncClient) -> UploadSweeper:
|
||||
return APPS[id(http)].state.sweeper
|
||||
|
||||
|
||||
async def discarded(http: AsyncClient) -> asyncio.Queue[AttachmentDiscarded]:
|
||||
seen: asyncio.Queue[AttachmentDiscarded] = asyncio.Queue()
|
||||
(await resolve(http, EventBus)).subscribe(AttachmentDiscarded, seen.put)
|
||||
return seen
|
||||
|
||||
|
||||
async def delivered(seen: asyncio.Queue[AttachmentDiscarded], count: int) -> list[str]:
|
||||
async with asyncio.timeout(2):
|
||||
events = [await seen.get() for _ in range(count)]
|
||||
assert seen.empty()
|
||||
return sorted(f"{event.reason} {event.attachment_id}" for event in events)
|
||||
|
||||
|
||||
async def intent(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
|
||||
store = await storage(http)
|
||||
store.failing = True
|
||||
name = f"intent-{uuid4().hex}.png"
|
||||
try:
|
||||
assert (await upload(http, user, chat, filename=name)).status_code == 503
|
||||
finally:
|
||||
store.failing = False
|
||||
found = await scalar(
|
||||
"SELECT id::text FROM attachments WHERE filename = $1 AND status = 'pending'", name
|
||||
)
|
||||
assert found is not None
|
||||
store.objects[f"staging/{found}"] = (SAMPLE, "image/png")
|
||||
return found
|
||||
|
||||
|
||||
async def exists(attachment_id: str) -> bool:
|
||||
return await scalar("SELECT count(*) FROM attachments WHERE id = $1", attachment_id) == 1
|
||||
|
||||
|
||||
async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
store = await storage(client)
|
||||
name = f"fail-{uuid4().hex}.png"
|
||||
trigger = f"lab4_fail_{uuid4().hex[:8]}"
|
||||
await execute(
|
||||
f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'injected' USING ERRCODE = '55P03'; END $$"""
|
||||
)
|
||||
await execute(
|
||||
f"""CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
|
||||
WHEN (NEW.filename = '{name}' AND NEW.status = 'queued') EXECUTE FUNCTION {trigger}()"""
|
||||
)
|
||||
before, seen = set(store.objects), await discarded(client)
|
||||
try:
|
||||
response = await upload(client, alice, chat, filename=name)
|
||||
finally:
|
||||
await execute(f"DROP TRIGGER {trigger} ON attachments")
|
||||
await execute(f"DROP FUNCTION {trigger}()")
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||
assert (
|
||||
await scalar(
|
||||
"SELECT count(*) FROM jobs j JOIN attachments a ON a.id = j.attachment_id "
|
||||
"WHERE a.filename = $1",
|
||||
name,
|
||||
)
|
||||
== 0
|
||||
)
|
||||
assert set(store.objects) == before
|
||||
assert [event.split()[0] for event in await delivered(seen, 1)] == ["compensation"]
|
||||
|
||||
|
||||
async def test_lost_intent_gives_503_and_no_object(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
store = await storage(client)
|
||||
|
||||
async def swept_meanwhile(key: str) -> None:
|
||||
await execute("DELETE FROM attachments WHERE staging_key = $1", key)
|
||||
|
||||
store.after_put = swept_meanwhile
|
||||
before = set(store.objects)
|
||||
try:
|
||||
response = await upload(client, alice, chat, filename="late.png")
|
||||
finally:
|
||||
store.after_put = None
|
||||
assert response.status_code == 503
|
||||
assert set(store.objects) == before
|
||||
|
||||
|
||||
async def test_failed_put_leaves_an_intent_until_grace_ends(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
pending = await intent(client, alice, chat)
|
||||
await sweeper(client).sweep()
|
||||
assert await exists(pending)
|
||||
await execute(AGED, pending)
|
||||
assert await sweeper(client).sweep() >= 1
|
||||
assert not await exists(pending)
|
||||
assert f"staging/{pending}" not in (await storage(client)).objects
|
||||
|
||||
|
||||
async def test_sweep_keeps_fresh_intents_and_ready_attachments(client: AsyncClient) -> None:
|
||||
alice, bob, _, chat = await trio(client)
|
||||
ready = (await upload(client, alice, chat)).json()
|
||||
await settle(client)
|
||||
sent = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [ready["id"]]},
|
||||
headers=keyed(alice),
|
||||
)
|
||||
assert sent.status_code == 201
|
||||
old, fresh = await intent(client, alice, chat), await intent(client, alice, chat)
|
||||
await execute(AGED, old)
|
||||
await execute(AGED, ready["id"])
|
||||
assert await sweeper(client).sweep() == 1
|
||||
objects = (await storage(client)).objects
|
||||
assert not await exists(old)
|
||||
assert f"staging/{old}" not in objects
|
||||
assert await exists(fresh)
|
||||
assert f"staging/{fresh}" in objects
|
||||
download = await client.get(f"/api/v1/attachments/{ready['id']}/content", headers=actor(bob))
|
||||
assert download.status_code == 200
|
||||
assert download.content == SAMPLE
|
||||
assert await sweeper(client).sweep() == 0
|
||||
|
||||
|
||||
async def test_parallel_sweeps_share_the_work(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
pending = [await intent(client, alice, chat) for _ in range(5)]
|
||||
for attachment_id in pending:
|
||||
await execute(AGED, attachment_id)
|
||||
seen = await discarded(client)
|
||||
first, second = await asyncio.gather(sweeper(client).sweep(), sweeper(client).sweep())
|
||||
assert first + second == 5
|
||||
assert await delivered(seen, 5) == sorted(f"abandoned {item}" for item in pending)
|
||||
assert await sweeper(client).sweep() == 0
|
||||
objects = (await storage(client)).objects
|
||||
assert not any(f"staging/{attachment_id}" in objects for attachment_id in pending)
|
||||
|
||||
|
||||
async def test_background_sweeper_removes_abandoned_intents() -> None:
|
||||
async with running_app(upload_sweep_interval_seconds=0.05) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
pending = await intent(http, alice, chat)
|
||||
await execute(AGED, pending)
|
||||
for _ in range(100):
|
||||
if not await exists(pending):
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert not await exists(pending)
|
||||
|
||||
|
||||
async def test_upload_waits_for_a_free_slot() -> None:
|
||||
async with running_app(upload_concurrency=1) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
gate, holding, read = asyncio.Event(), asyncio.Event(), []
|
||||
|
||||
async def held() -> AsyncIterator[bytes]:
|
||||
read.append("first")
|
||||
holding.set()
|
||||
yield SAMPLE[:1000]
|
||||
await gate.wait()
|
||||
yield SAMPLE[1000:]
|
||||
|
||||
async def queued() -> AsyncIterator[bytes]:
|
||||
read.append("second")
|
||||
yield SAMPLE
|
||||
|
||||
first = asyncio.create_task(upload(http, alice, chat, held()))
|
||||
await holding.wait()
|
||||
second = asyncio.create_task(upload(http, alice, chat, queued()))
|
||||
await asyncio.sleep(0.3)
|
||||
assert read == ["first"]
|
||||
gate.set()
|
||||
assert [(await first).status_code, (await second).status_code] == [202, 202]
|
||||
assert read == ["first", "second"]
|
||||
|
||||
|
||||
async def test_aborted_upload_is_a_client_error(client: AsyncClient) -> None:
|
||||
alice, _, _, chat = await trio(client)
|
||||
name = f"abort-{uuid4().hex}.png"
|
||||
headers = [(k.lower().encode(), v.encode()) for k, v in actor(alice).items()]
|
||||
scope = {
|
||||
"type": "http",
|
||||
"asgi": {"version": "3.0"},
|
||||
"http_version": "1.1",
|
||||
"method": "POST",
|
||||
"scheme": "http",
|
||||
"path": f"/api/v1/chats/{chat['id']}/attachments",
|
||||
"raw_path": f"/api/v1/chats/{chat['id']}/attachments".encode(),
|
||||
"query_string": f"filename={name}".encode(),
|
||||
"root_path": "",
|
||||
"headers": [
|
||||
*headers,
|
||||
(b"content-type", b"image/png"),
|
||||
(b"content-length", b"1000000"),
|
||||
],
|
||||
"client": ("127.0.0.1", 50000),
|
||||
"server": ("testserver", 80),
|
||||
}
|
||||
messages = iter(
|
||||
[
|
||||
{"type": "http.request", "body": SAMPLE[:1000], "more_body": True},
|
||||
{"type": "http.disconnect"},
|
||||
]
|
||||
)
|
||||
sent: list[Message] = []
|
||||
|
||||
async def receive() -> dict[str, Any]:
|
||||
return next(messages, {"type": "http.disconnect"})
|
||||
|
||||
async def send(message: Message) -> None:
|
||||
sent.append(message)
|
||||
|
||||
await APPS[id(client)](scope, receive, send)
|
||||
assert sent[0]["status"] == 400
|
||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||
|
||||
|
||||
async def test_stalled_upload_times_out_and_frees_the_slot() -> None:
|
||||
async with running_app(upload_concurrency=1, request_timeout_seconds=0.5) as http:
|
||||
alice, _, _, chat = await trio(http)
|
||||
name = f"stalled-{uuid4().hex}.png"
|
||||
|
||||
async def stalled() -> AsyncIterator[bytes]:
|
||||
yield SAMPLE[:1000]
|
||||
await asyncio.Event().wait()
|
||||
|
||||
response = await upload(http, alice, chat, stalled(), filename=name)
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
|
||||
assert (await upload(http, alice, chat)).status_code == 202
|
||||
@@ -0,0 +1,200 @@
|
||||
import asyncio
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from test_attachments import storage
|
||||
from test_pipeline import accepted, job_of, rows
|
||||
|
||||
from conftest import DATABASE, actor
|
||||
from messenger.admin import serve
|
||||
from messenger.attachments.application.commands import ReprocessAttachment
|
||||
from messenger.attachments.application.pipeline import (
|
||||
AFTER_CLAIM,
|
||||
AFTER_S3_WRITE,
|
||||
ReprocessAttachmentHandler,
|
||||
)
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import ImageTooDemanding
|
||||
from messenger.attachments.domain.jobs import Outcome, ReprocessResult
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from pipeline import InlinePipeline, InlineRenderer, pipeline_of
|
||||
|
||||
|
||||
async def reprocess(pipeline: InlinePipeline, ident: str, version: int = 2) -> ReprocessResult:
|
||||
handler = ReprocessAttachmentHandler(pipeline.uow(), Uuid7Generator(), MonotonicUtcClock())
|
||||
return await handler(ReprocessAttachment(UUID(ident), version, "test"))
|
||||
|
||||
|
||||
async def attachment(ident: str) -> dict:
|
||||
(row,) = await rows(
|
||||
"SELECT status, published_version, error_code FROM attachments WHERE id = $1", ident
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
async def versions(pipeline: InlinePipeline, ident: str) -> dict:
|
||||
return {
|
||||
job.pipeline_version: job
|
||||
for job in await pipeline.publish()
|
||||
if str(job.attachment_id) == ident
|
||||
}
|
||||
|
||||
|
||||
async def test_concurrent_reprocess_creates_one_job_and_outbox(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
results = await asyncio.gather(*(reprocess(pipeline, ident) for _ in range(6)))
|
||||
assert results.count(ReprocessResult.QUEUED) == 1
|
||||
assert results.count(ReprocessResult.NOOP) == 5
|
||||
jobs = await rows(
|
||||
"SELECT pipeline_version, count(*) FROM jobs WHERE attachment_id = $1 GROUP BY 1", ident
|
||||
)
|
||||
assert {r["pipeline_version"]: r["count"] for r in jobs} == {1: 1, 2: 1}
|
||||
assert len(await versions(pipeline, ident)) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("order", [(1, 2), (2, 1)])
|
||||
async def test_version_order_never_reverts_published_bytes(
|
||||
client: AsyncClient, order: tuple[int, int]
|
||||
) -> None:
|
||||
_, bob, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
for version in order:
|
||||
outcome = await pipeline.process(jobs[version])
|
||||
assert outcome is (Outcome.SUPERSEDED if order == (2, 1) and version == 1 else Outcome.DONE)
|
||||
assert (await attachment(ident))["status"] == "ready"
|
||||
await pipeline.clean()
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
|
||||
stored = await rows(
|
||||
"SELECT pipeline_version, name, sha256 FROM attachment_variants WHERE attachment_id = $1",
|
||||
ident,
|
||||
)
|
||||
current = {r["name"]: r["sha256"] for r in stored if r["pipeline_version"] == 2}
|
||||
older = {r["name"]: r["sha256"] for r in stored if r["pipeline_version"] == 1}
|
||||
assert current != older
|
||||
assert {r["name"]: r["sha256"] for r in public["variants"]} == current
|
||||
assert await pipeline.process(jobs[1]) is Outcome.DUPLICATE
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.NOOP
|
||||
assert (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json() == public
|
||||
|
||||
|
||||
class PausedEffect:
|
||||
def __init__(self, point: str) -> None:
|
||||
self.point = point
|
||||
self.reached = asyncio.Event()
|
||||
self.resume = asyncio.Event()
|
||||
|
||||
async def reach(self, point: str) -> None:
|
||||
if point == self.point:
|
||||
self.reached.set()
|
||||
await self.resume.wait()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("point", [AFTER_CLAIM, AFTER_S3_WRITE])
|
||||
async def test_old_holder_finishes_after_new_publication(client: AsyncClient, point: str) -> None:
|
||||
_, bob, ident = await accepted(client)
|
||||
old, new = await pipeline_of(client), await pipeline_of(client)
|
||||
old.faults = pause = PausedEffect(point)
|
||||
job = await job_of(ident)
|
||||
running = asyncio.create_task(old.process(job))
|
||||
try:
|
||||
await asyncio.wait_for(pause.reached.wait(), 5)
|
||||
assert await reprocess(new, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(new, ident)
|
||||
assert await new.process(jobs[2]) is Outcome.DONE
|
||||
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
|
||||
assert await new.clean() == 0
|
||||
pause.resume.set()
|
||||
assert await asyncio.wait_for(running, 5) is Outcome.SUPERSEDED
|
||||
assert await new.clean() == 1
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
assert (
|
||||
await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))
|
||||
).json() == public
|
||||
finally:
|
||||
pause.resume.set()
|
||||
await running
|
||||
|
||||
|
||||
class RejectingRenderer:
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
raise ImageTooDemanding("test limit")
|
||||
|
||||
|
||||
async def test_failed_old_version_keeps_other_version_active(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
pipeline.renderer = RejectingRenderer()
|
||||
assert await pipeline.process(jobs[1]) is Outcome.FAILED
|
||||
assert (await attachment(ident))["status"] in ("queued", "processing")
|
||||
pipeline.renderer = InlineRenderer()
|
||||
assert await pipeline.process(jobs[2]) is Outcome.DONE
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
|
||||
|
||||
async def test_concurrent_failures_leave_no_stuck_attachment(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
pipeline.renderer = RejectingRenderer()
|
||||
assert await asyncio.gather(*(pipeline.process(job) for job in jobs.values())) == [
|
||||
Outcome.FAILED,
|
||||
Outcome.FAILED,
|
||||
]
|
||||
assert (await attachment(ident))["status"] == "failed"
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.CONFLICT
|
||||
assert await pipeline.publish() == []
|
||||
|
||||
|
||||
async def test_failed_new_version_keeps_ready_original(client: AsyncClient) -> None:
|
||||
_, bob, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
public = (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json()
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
assert (await attachment(ident))["status"] == "ready"
|
||||
jobs = await versions(pipeline, ident)
|
||||
pipeline.renderer = RejectingRenderer()
|
||||
assert await pipeline.process(jobs[2]) is Outcome.FAILED
|
||||
assert (await client.get(f"/api/v1/attachments/{ident}", headers=actor(bob))).json() == public
|
||||
|
||||
|
||||
async def test_reprocess_rejects_unknown_id_and_version(client: AsyncClient) -> None:
|
||||
pipeline = await pipeline_of(client)
|
||||
assert await reprocess(pipeline, str(uuid4())) is ReprocessResult.NOT_FOUND
|
||||
with pytest.raises(ValueError, match="версия"):
|
||||
await reprocess(pipeline, str(uuid4()), 3)
|
||||
|
||||
|
||||
async def test_operator_cli_schedules_version_once(
|
||||
client: AsyncClient, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
monkeypatch.setenv("DATABASE_URL", DATABASE["url"])
|
||||
monkeypatch.setenv("LOG_LEVEL", "WARNING")
|
||||
args = ["reprocess", "--attachment-id", ident, "--pipeline-version", "2"]
|
||||
for expected in ("queued", "noop"):
|
||||
assert await serve(args) == 0
|
||||
report = json.loads(capsys.readouterr().out.splitlines()[-1])
|
||||
assert report["result"] == expected
|
||||
assert report["pipeline_version"] == 2
|
||||
|
||||
|
||||
async def test_ready_reprocess_survives_cleanup_before_metadata_commit(client: AsyncClient) -> None:
|
||||
_, _, ident = await accepted(client)
|
||||
pipeline = await pipeline_of(client)
|
||||
await pipeline.drain()
|
||||
await (await storage(client)).delete(f"staging/{ident}")
|
||||
assert await reprocess(pipeline, ident) is ReprocessResult.QUEUED
|
||||
jobs = await versions(pipeline, ident)
|
||||
assert await pipeline.process(jobs[2]) is Outcome.DONE
|
||||
assert (await attachment(ident))["published_version"] == 2
|
||||
@@ -0,0 +1,69 @@
|
||||
import json
|
||||
import re
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from httpx import Response
|
||||
|
||||
from conftest import bearer, login, new_user, running_app
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
|
||||
RFC3339_UTC = re.compile(r"\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z\Z")
|
||||
MOMENTS = [
|
||||
datetime(2026, 10, 12, 8, 49, 2, tzinfo=UTC),
|
||||
datetime(2026, 10, 12, 8, 49, 2, 120, tzinfo=UTC),
|
||||
]
|
||||
|
||||
|
||||
def assert_wire(response: Response, expected: dict[str, Any]) -> None:
|
||||
assert (
|
||||
response.content == json.dumps(expected, ensure_ascii=False, separators=(",", ":")).encode()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("moment", MOMENTS, ids=["whole-second", "microseconds"])
|
||||
async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment: datetime) -> None:
|
||||
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self: moment)
|
||||
stamp = moment.isoformat().replace("+00:00", "Z")
|
||||
assert RFC3339_UTC.match(stamp)
|
||||
async with running_app() as http:
|
||||
body = new_user("wire")
|
||||
response = await http.post("/api/v1/users", json=body)
|
||||
user_id = response.json()["id"]
|
||||
user = {
|
||||
"id": user_id,
|
||||
"username": body["username"],
|
||||
"display_name": body["display_name"],
|
||||
"created_at": stamp,
|
||||
}
|
||||
assert_wire(response, user)
|
||||
session = await login(http, body["username"])
|
||||
headers = bearer(session["token"])
|
||||
assert session["user"] == user
|
||||
assert_wire(await http.get("/api/v1/users/me", headers=headers), user)
|
||||
|
||||
response = await http.post(
|
||||
"/api/v1/chats", json={"title": "Чат", "member_ids": [user_id]}, headers=headers
|
||||
)
|
||||
chat_id = response.json()["id"]
|
||||
chat = {"id": chat_id, "title": "Чат", "member_ids": [user_id], "created_at": stamp}
|
||||
assert_wire(response, chat)
|
||||
assert_wire(await http.get(f"/api/v1/chats/{chat_id}", headers=headers), chat)
|
||||
listed = await http.get("/api/v1/chats", headers=headers)
|
||||
assert_wire(listed, {"items": [chat], "next_cursor": None})
|
||||
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
sent = {**headers, "Idempotency-Key": "wire-1"}
|
||||
response = await http.post(path, json={"text": "привет"}, headers=sent)
|
||||
message = {
|
||||
"id": response.json()["id"],
|
||||
"chat_id": chat_id,
|
||||
"sender_id": user_id,
|
||||
"text": "привет",
|
||||
"created_at": stamp,
|
||||
"attachment_ids": [],
|
||||
}
|
||||
assert_wire(response, message)
|
||||
history = await http.get(path, headers=headers)
|
||||
assert_wire(history, {"items": [message], "next_cursor": None})
|
||||
@@ -0,0 +1,263 @@
|
||||
import asyncio
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
from base64 import b64encode
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import make_url
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from fakes import MemoryStorageProvider
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.identity.config import IdentitySettings
|
||||
from messenger.main import create_app
|
||||
from messenger.messaging.config import MessagingSettings
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.entrypoints.config import TransportSettings
|
||||
from messenger.shared.infrastructure.postgres import unavailable
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
POSTGRES_IMAGE = re.compile(r"image: (postgres:\S+)")
|
||||
VALKEY_IMAGE = re.compile(r"image: (valkey/valkey:\S+)")
|
||||
STARTUP_SECONDS = 60
|
||||
PASSWORD = "Пароль-для-тестов-01"
|
||||
APPS: dict[int, FastAPI] = {}
|
||||
TOKENS: dict[str, str] = {}
|
||||
DATABASE: dict[str, str] = {}
|
||||
|
||||
|
||||
def docker(*args: str) -> str:
|
||||
done = subprocess.run(["docker", *args], check=True, capture_output=True, text=True)
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
def migration_config(dsn: str) -> Config:
|
||||
config = Config(str(ROOT / "alembic.ini"))
|
||||
config.attributes["database_url"] = dsn
|
||||
return config
|
||||
|
||||
|
||||
async def upgrade(dsn: str, revision: str = "head") -> None:
|
||||
await asyncio.to_thread(command.upgrade, migration_config(dsn), revision)
|
||||
|
||||
|
||||
async def migrated(dsn: str) -> None:
|
||||
deadline = time.monotonic() + STARTUP_SECONDS
|
||||
while True:
|
||||
try:
|
||||
await upgrade(dsn)
|
||||
return
|
||||
except Exception as error:
|
||||
if not unavailable(error) or time.monotonic() > deadline:
|
||||
raise
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def sql_connection(dsn: str | None = None) -> AsyncIterator[AsyncConnection]:
|
||||
engine = create_async_engine(
|
||||
make_url(dsn or DATABASE["url"]).set(drivername="postgresql+asyncpg"),
|
||||
poolclass=NullPool,
|
||||
hide_parameters=True,
|
||||
)
|
||||
try:
|
||||
async with engine.begin() as connection:
|
||||
yield connection
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
for port in range(26000, 27000):
|
||||
with socket.socket() as probe:
|
||||
try:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
return port
|
||||
except OSError:
|
||||
continue
|
||||
raise RuntimeError("No free test port in 26000–26999")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def database_for_api(request: pytest.FixtureRequest) -> None:
|
||||
if "api" in request.node.path.parts:
|
||||
request.getfixturevalue("database")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def clean_api_database(request: pytest.FixtureRequest, database_for_api: None) -> None:
|
||||
if "api" in request.node.path.parts:
|
||||
async with sql_connection() as connection:
|
||||
await connection.exec_driver_sql("TRUNCATE users, login_budget CASCADE")
|
||||
|
||||
|
||||
def image(pattern: re.Pattern[str]) -> str:
|
||||
found = pattern.search((ROOT / "compose.yaml").read_text())
|
||||
assert found is not None
|
||||
return found[1]
|
||||
|
||||
|
||||
def published(name: str, port: int) -> int:
|
||||
return int(docker("port", name, f"{port}/tcp").splitlines()[0].rsplit(":", 1)[1])
|
||||
|
||||
|
||||
def container(name: str, *args: str) -> None:
|
||||
docker("run", "-d", "--rm", "--name", name, *args)
|
||||
|
||||
|
||||
def answering(name: str, *probe: str) -> bool:
|
||||
done = subprocess.run(["docker", "exec", name, *probe], capture_output=True, check=False)
|
||||
return done.returncode == 0 and b"PONG" in done.stdout
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def valkey() -> Iterator[dict[str, str]]:
|
||||
name = f"mtusi-lab6-test-valkey-{uuid4().hex[:8]}"
|
||||
container(name, "-p", f"127.0.0.1:{free_port()}:6379", image(VALKEY_IMAGE))
|
||||
try:
|
||||
deadline = time.monotonic() + STARTUP_SECONDS
|
||||
while not answering(name, "valkey-cli", "ping"):
|
||||
assert time.monotonic() < deadline
|
||||
time.sleep(0.2)
|
||||
yield {"name": name, "url": f"redis://127.0.0.1:{published(name, 6379)}/0"}
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-fv", name], capture_output=True, check=False)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def database() -> Iterator[str]:
|
||||
name = f"mtusi-lab6-test-{uuid4().hex[:8]}"
|
||||
tuning = ["-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
|
||||
environment = ["-e", "POSTGRES_PASSWORD=test", "-e", "POSTGRES_DB=messenger"]
|
||||
container(
|
||||
name, *environment, "-p", f"127.0.0.1:{free_port()}:5432", image(POSTGRES_IMAGE), *tuning
|
||||
)
|
||||
try:
|
||||
dsn = f"postgresql://postgres:test@127.0.0.1:{published(name, 5432)}/messenger"
|
||||
asyncio.run(migrated(dsn))
|
||||
DATABASE["url"] = dsn
|
||||
yield dsn
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-fv", name], capture_output=True, check=False)
|
||||
|
||||
|
||||
def split_settings(**overrides: Any) -> dict[str, Any]:
|
||||
base: dict[str, Any] = {
|
||||
"log_level": "CRITICAL",
|
||||
"login_attempts": 0,
|
||||
"cursor_secret": "test-secret-for-cursors",
|
||||
"database_url": DATABASE.get("url", "postgresql://unused@127.0.0.1:1/unused"),
|
||||
"s3_access_key_id": "test-key",
|
||||
"s3_secret_access_key": "test-secret-key",
|
||||
}
|
||||
base.update(overrides)
|
||||
groups = {
|
||||
"platform": PlatformSettings,
|
||||
"transport": TransportSettings,
|
||||
"identity": IdentitySettings,
|
||||
"messaging": MessagingSettings,
|
||||
"attachments": AttachmentsSettings,
|
||||
}
|
||||
return {
|
||||
name: kind.model_validate(
|
||||
{key: value for key, value in base.items() if key in kind.model_fields}
|
||||
)
|
||||
for name, kind in groups.items()
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def running_app(**overrides: Any) -> AsyncIterator[AsyncClient]:
|
||||
app = create_app(**split_settings(**overrides), overrides=(MemoryStorageProvider(),))
|
||||
async with (
|
||||
app.router.lifespan_context(app),
|
||||
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
|
||||
):
|
||||
APPS[id(http)] = app
|
||||
try:
|
||||
yield http
|
||||
finally:
|
||||
APPS.pop(id(http), None)
|
||||
|
||||
|
||||
async def resolve[DependencyT](http: AsyncClient, dependency: type[DependencyT]) -> DependencyT:
|
||||
return await APPS[id(http)].state.dishka_container.get(dependency)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client() -> AsyncIterator[AsyncClient]:
|
||||
async with running_app() as http:
|
||||
yield http
|
||||
|
||||
|
||||
async def scalar(statement: Any, *args: Any) -> Any:
|
||||
async with sql_connection() as connection:
|
||||
if isinstance(statement, str):
|
||||
result = await connection.exec_driver_sql(statement, args)
|
||||
return result.scalar() if result.returns_rows else None
|
||||
return await connection.scalar(statement)
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
encoded = b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {encoded}"}
|
||||
|
||||
|
||||
def bearer(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def new_user(label: str, password: str = PASSWORD) -> dict[str, str]:
|
||||
return {
|
||||
"username": f"u_{label}_{uuid4().hex[:12]}",
|
||||
"display_name": f"Студент {label}",
|
||||
"password": password,
|
||||
}
|
||||
|
||||
|
||||
async def login(http: AsyncClient, username: str, password: str = PASSWORD) -> dict[str, Any]:
|
||||
response = await http.post("/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
async def register(http: AsyncClient, label: str, password: str = PASSWORD) -> dict[str, Any]:
|
||||
body = new_user(label, password)
|
||||
response = await http.post("/api/v1/users", json=body)
|
||||
assert response.status_code == 201, response.text
|
||||
user = response.json()
|
||||
TOKENS[user["id"]] = (await login(http, body["username"], password))["token"]
|
||||
return user
|
||||
|
||||
|
||||
async def make_chat(
|
||||
http: AsyncClient, owner: dict[str, Any], *members: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
member_ids = [owner["id"], *[member["id"] for member in members]]
|
||||
response = await http.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Тестовый чат", "member_ids": member_ids},
|
||||
headers=actor(owner),
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def actor(user: dict[str, Any]) -> dict[str, str]:
|
||||
return bearer(TOKENS[user["id"]])
|
||||
|
||||
|
||||
def keyed(user: dict[str, Any], key: str | None = None) -> dict[str, str]:
|
||||
return {**actor(user), "Idempotency-Key": key or uuid4().hex}
|
||||
@@ -0,0 +1,113 @@
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
|
||||
from messenger.attachments.application.errors import ObjectMissingError
|
||||
from messenger.attachments.application.ports import ObjectContent, ObjectStorage, StoredObject
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
|
||||
class NullLogger:
|
||||
__slots__ = ()
|
||||
|
||||
def info(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
def warning(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
def error(self, event: str, /, **fields: Any) -> None: ...
|
||||
|
||||
|
||||
class FrozenClock:
|
||||
__slots__ = ("_current",)
|
||||
|
||||
def __init__(self, start: datetime) -> None:
|
||||
self._current = start
|
||||
|
||||
def now(self) -> datetime:
|
||||
self._current += timedelta(microseconds=1)
|
||||
return self._current
|
||||
|
||||
|
||||
async def pieces(data: bytes, size: int = 65_536, delay: float = 0.0) -> AsyncIterator[bytes]:
|
||||
for start in range(0, len(data), size):
|
||||
await asyncio.sleep(delay)
|
||||
yield data[start : start + size]
|
||||
|
||||
|
||||
class MemoryObjectStorage:
|
||||
__slots__ = ("after_page", "after_put", "delay", "failing", "modified", "objects")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.objects: dict[str, tuple[bytes, str]] = {}
|
||||
self.modified: dict[str, datetime] = {}
|
||||
self.failing = False
|
||||
self.delay = 0.0
|
||||
self.after_put: Callable[[str], Awaitable[None]] | None = None
|
||||
self.after_page: Callable[[], Awaitable[None]] | None = None
|
||||
|
||||
async def put(self, key: str, data: bytes, content_type: str) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
self.objects[key] = (bytes(data), content_type)
|
||||
self.modified[key] = datetime.now(UTC)
|
||||
if self.after_put is not None:
|
||||
await self.after_put(key)
|
||||
|
||||
async def listing(self, prefix: str, page_size: int) -> AsyncIterator[Sequence[StoredObject]]:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
keys = sorted(key for key in self.objects if key.startswith(prefix))
|
||||
for start in range(0, len(keys), page_size):
|
||||
yield [self._stored(key) for key in keys[start : start + page_size]]
|
||||
if self.after_page is not None:
|
||||
await self.after_page()
|
||||
|
||||
async def stat(self, key: str) -> StoredObject | None:
|
||||
return self._stored(key) if key in self.objects else None
|
||||
|
||||
def _stored(self, key: str) -> StoredObject:
|
||||
return StoredObject(key, len(self.objects[key][0]), self.modified[key])
|
||||
|
||||
async def open(self, key: str) -> ObjectContent:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
if key not in self.objects:
|
||||
raise ObjectMissingError(key)
|
||||
data = self.objects[key][0]
|
||||
return ObjectContent(size=len(data), chunks=pieces(data, delay=self.delay))
|
||||
|
||||
async def read(self, key: str) -> bytes:
|
||||
content = await self.open(key)
|
||||
return b"".join([chunk async for chunk in content.chunks])
|
||||
|
||||
async def copy(self, source: str, target: str) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
if source not in self.objects:
|
||||
raise ObjectMissingError(source)
|
||||
self.objects[target] = self.objects[source]
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("S3 недоступно")
|
||||
self.objects.pop(key, None)
|
||||
self.modified.pop(key, None)
|
||||
|
||||
|
||||
class MemoryStorageProvider(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def storage(self) -> ObjectStorage:
|
||||
return MemoryObjectStorage()
|
||||
|
||||
|
||||
class RecordingPublisher:
|
||||
__slots__ = ("events",)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.events: list[Any] = []
|
||||
|
||||
async def publish(self, events: Sequence[Any]) -> None:
|
||||
self.events.extend(events)
|
||||
@@ -0,0 +1,46 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL CONSTRAINT users_username_key UNIQUE
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL CHECK (password_hash LIKE '$argon2id$%'),
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL,
|
||||
last_message_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL CHECK (position BETWEEN 1 AND 100),
|
||||
chat_created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_created_at, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
chat_id uuid NOT NULL,
|
||||
user_id uuid NOT NULL,
|
||||
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32),
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id, key),
|
||||
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
@@ -0,0 +1,37 @@
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_check,
|
||||
ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
owner_id uuid NOT NULL,
|
||||
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
object_key text COLLATE "C" NOT NULL CONSTRAINT attachments_object_key_key UNIQUE,
|
||||
status text NOT NULL CHECK (status IN ('pending', 'ready')),
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_chat_key UNIQUE (id, chat_id),
|
||||
CONSTRAINT attachments_owner_fkey FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
|
||||
chat_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
PRIMARY KEY (message_id, position),
|
||||
UNIQUE (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id)
|
||||
REFERENCES attachments (id, chat_id) ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
@@ -0,0 +1,70 @@
|
||||
ALTER TABLE attachments
|
||||
DROP CONSTRAINT attachments_status_check,
|
||||
ADD CONSTRAINT attachments_status_check
|
||||
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed')),
|
||||
ADD COLUMN staging_key text COLLATE "C" CONSTRAINT attachments_staging_key_key UNIQUE,
|
||||
ADD COLUMN original_key text COLLATE "C" CONSTRAINT attachments_original_key_key UNIQUE,
|
||||
ADD COLUMN published_version integer NOT NULL DEFAULT 0 CHECK (published_version >= 0),
|
||||
ADD COLUMN error_code text
|
||||
CHECK (error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')),
|
||||
ALTER COLUMN object_key DROP NOT NULL;
|
||||
|
||||
UPDATE attachments SET original_key = object_key, published_version = 1 WHERE status = 'ready';
|
||||
UPDATE attachments SET staging_key = object_key WHERE status = 'pending';
|
||||
|
||||
CREATE INDEX attachments_staged_idx ON attachments (updated_at) WHERE staging_key IS NOT NULL;
|
||||
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
object_key text COLLATE "C" NOT NULL CONSTRAINT attachment_variants_object_key_key UNIQUE,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes >= 1),
|
||||
width integer NOT NULL CHECK (width >= 1),
|
||||
height integer NOT NULL CHECK (height >= 1),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
CREATE TABLE jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
status text NOT NULL CHECK (status IN ('queued', 'processing', 'done', 'failed', 'superseded')),
|
||||
attempt integer NOT NULL CHECK (attempt >= 1),
|
||||
claims integer NOT NULL DEFAULT 0 CHECK (claims >= 0),
|
||||
lease_token uuid,
|
||||
lease_until timestamptz,
|
||||
next_attempt_at timestamptz,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT jobs_effect_key UNIQUE (attachment_id, pipeline_version)
|
||||
);
|
||||
|
||||
CREATE INDEX jobs_lease_idx ON jobs (lease_until) WHERE status = 'processing';
|
||||
|
||||
CREATE TABLE outbox (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES jobs (job_id),
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL,
|
||||
published_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_pending_idx ON outbox (available_at, id) WHERE published_at IS NULL;
|
||||
CREATE INDEX outbox_job_idx ON outbox (job_id);
|
||||
|
||||
CREATE TABLE job_events (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
job_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
kind text NOT NULL,
|
||||
attempt integer,
|
||||
detail jsonb NOT NULL DEFAULT '{}',
|
||||
at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX job_events_attachment_idx ON job_events (attachment_id, id);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX jobs_failed_idx ON jobs (updated_at DESC) WHERE status = 'failed';
|
||||
@@ -0,0 +1,6 @@
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN quarantine_reason text
|
||||
CHECK (quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')),
|
||||
ADD COLUMN quarantined_at timestamptz,
|
||||
ADD CONSTRAINT attachments_quarantine_check
|
||||
CHECK ((quarantine_reason IS NULL) = (quarantined_at IS NULL));
|
||||
@@ -0,0 +1,62 @@
|
||||
import struct
|
||||
import zlib
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
SAMPLE = (Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
crc = zlib.crc32(kind + data)
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", crc)
|
||||
|
||||
|
||||
def png_from_idat(
|
||||
data: bytes,
|
||||
width: int = 1,
|
||||
height: int = 1,
|
||||
*,
|
||||
depth: int = 8,
|
||||
color: int = 2,
|
||||
interlace: int = 0,
|
||||
chunk_size: int = 65_536,
|
||||
) -> bytes:
|
||||
header = struct.pack(">IIBBBBB", width, height, depth, color, 0, 0, interlace)
|
||||
palette = chunk(b"PLTE", bytes(range(256)) * 3) if color == 3 else b""
|
||||
blocks = [
|
||||
chunk(b"IDAT", data[start : start + chunk_size])
|
||||
for start in range(0, len(data), chunk_size)
|
||||
]
|
||||
return SIGNATURE + chunk(b"IHDR", header) + palette + b"".join(blocks) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
BROKEN_PNG = png_from_idat(b"not a zlib stream")
|
||||
DUPLICATE_IHDR_PNG = (
|
||||
SIGNATURE
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
|
||||
+ png_from_idat(zlib.compress(bytes(4)), 2, 2)[len(SIGNATURE) :]
|
||||
)
|
||||
|
||||
|
||||
def png(width: int, height: int, *, size: int | None = None, rows: bool = True) -> bytes:
|
||||
header = struct.pack(">IIBBBBB", width, height, 1, 0, 0, 0, 0)
|
||||
raw = (b"\x00" * (1 + (width + 7) // 8)) * height if rows else b"\x00"
|
||||
head = SIGNATURE + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw, 9))
|
||||
tail = chunk(b"IEND", b"")
|
||||
if size is not None:
|
||||
head += chunk(b"prVt", b"\x00" * (size - len(head) - len(tail) - 12))
|
||||
return head + tail
|
||||
|
||||
|
||||
def encoded(kind: str, width: int = 640, height: int = 480) -> bytes:
|
||||
buffer = BytesIO()
|
||||
Image.effect_noise((width, height), 64).convert("RGB").save(buffer, kind)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
JPEG = encoded("JPEG")
|
||||
GIF = encoded("GIF")
|
||||
WEBP = encoded("WEBP")
|
||||
@@ -0,0 +1,168 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from httpx import AsyncClient
|
||||
|
||||
from conftest import resolve
|
||||
from fakes import NullLogger
|
||||
from messenger.attachments.application.commands import (
|
||||
CleanStaging,
|
||||
ProcessJob,
|
||||
PublishOutbox,
|
||||
RecoverExpiredLeases,
|
||||
ReplayAttachment,
|
||||
)
|
||||
from messenger.attachments.application.pipeline import (
|
||||
CleanStagingHandler,
|
||||
ProcessJobHandler,
|
||||
PublishOutboxHandler,
|
||||
RecoverExpiredLeasesHandler,
|
||||
ReplayAttachmentHandler,
|
||||
)
|
||||
from messenger.attachments.application.ports import (
|
||||
Faults,
|
||||
Jitter,
|
||||
ObjectStorage,
|
||||
Rendition,
|
||||
VariantRenderer,
|
||||
)
|
||||
from messenger.attachments.domain.jobs import Job, Outcome, ReplayResult, RetryPolicy
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
|
||||
from messenger.attachments.infrastructure.postgres import PostgresAttachmentsUnitOfWork
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.infrastructure.ids import Uuid7Generator
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
IDLE_SECONDS = 0.1
|
||||
HALF = 0.5
|
||||
LIMITS = RenderLimits(10_485_760, 40_000_000)
|
||||
FAST = RetryPolicy(max_attempts=5, base_seconds=0.001, cap_seconds=0.001)
|
||||
|
||||
|
||||
class FixedJitter:
|
||||
__slots__ = ("_spread",)
|
||||
|
||||
def __init__(self, spread: float) -> None:
|
||||
self._spread = spread
|
||||
|
||||
def spread(self) -> float:
|
||||
return self._spread
|
||||
|
||||
|
||||
class InlineRenderer:
|
||||
__slots__ = ()
|
||||
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
return render_variants(data, LIMITS, pipeline_version)
|
||||
|
||||
|
||||
class CapturingPublisher:
|
||||
__slots__ = ("bodies", "contexts", "failing", "job_ids")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.bodies: list[bytes] = []
|
||||
self.contexts: list[dict[str, str]] = []
|
||||
self.job_ids: list[UUID] = []
|
||||
self.failing = False
|
||||
|
||||
async def publish(
|
||||
self, job_id: UUID, body: bytes, trace_context: dict[str, str] | None = None
|
||||
) -> None:
|
||||
if self.failing:
|
||||
raise Unavailable("брокер недоступен")
|
||||
self.job_ids.append(job_id)
|
||||
self.bodies.append(body)
|
||||
self.contexts.append(trace_context or {})
|
||||
|
||||
|
||||
class InlinePipeline:
|
||||
__slots__ = (
|
||||
"_database",
|
||||
"faults",
|
||||
"jitter",
|
||||
"lease",
|
||||
"policy",
|
||||
"publisher",
|
||||
"renderer",
|
||||
"storage",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database: Database,
|
||||
storage: ObjectStorage,
|
||||
*,
|
||||
policy: RetryPolicy = FAST,
|
||||
lease: timedelta = timedelta(seconds=60),
|
||||
) -> None:
|
||||
self._database = database
|
||||
self.storage = storage
|
||||
self.policy = policy
|
||||
self.lease = lease
|
||||
self.publisher = CapturingPublisher()
|
||||
self.renderer: VariantRenderer = InlineRenderer()
|
||||
self.faults: Faults = EnvironmentFaults("", NullLogger())
|
||||
self.jitter: Jitter = FixedJitter(HALF)
|
||||
|
||||
def uow(self) -> PostgresAttachmentsUnitOfWork:
|
||||
return PostgresAttachmentsUnitOfWork(self._database)
|
||||
|
||||
async def publish(self) -> list[Job]:
|
||||
start = len(self.publisher.bodies)
|
||||
await PublishOutboxHandler(self.uow(), self.publisher, self.faults)(PublishOutbox(100))
|
||||
return [
|
||||
JobMessage.model_validate_json(body).job() for body in self.publisher.bodies[start:]
|
||||
]
|
||||
|
||||
async def process(self, job: Job) -> Outcome:
|
||||
handler = ProcessJobHandler(
|
||||
self.uow(),
|
||||
self.storage,
|
||||
self.renderer,
|
||||
self.faults,
|
||||
ids=Uuid7Generator(),
|
||||
jitter=self.jitter,
|
||||
policy=self.policy,
|
||||
lease=self.lease,
|
||||
)
|
||||
return await handler(ProcessJob(job))
|
||||
|
||||
async def drain(self, rounds: int = 20, idle: int = 3) -> list[Outcome]:
|
||||
outcomes: list[Outcome] = []
|
||||
quiet = 0
|
||||
for _ in range(rounds):
|
||||
jobs = await self.publish()
|
||||
quiet = 0 if jobs else quiet + 1
|
||||
if quiet == idle:
|
||||
return outcomes
|
||||
if not jobs:
|
||||
await asyncio.sleep(IDLE_SECONDS)
|
||||
outcomes.extend([await self.process(job) for job in jobs])
|
||||
return outcomes
|
||||
|
||||
async def recover(self) -> int:
|
||||
handler = RecoverExpiredLeasesHandler(self.uow(), self.policy)
|
||||
return await handler(RecoverExpiredLeases(100))
|
||||
|
||||
async def clean(self, retention: timedelta = timedelta(days=1)) -> int:
|
||||
command = CleanStaging(100, retention)
|
||||
return await CleanStagingHandler(self.uow(), self.storage)(command)
|
||||
|
||||
async def replay(self, attachment_id: UUID, operator: str = "test") -> ReplayResult:
|
||||
command = ReplayAttachment(attachment_id, operator)
|
||||
return await ReplayAttachmentHandler(self.uow())(command)
|
||||
|
||||
|
||||
async def pipeline_of(
|
||||
http: AsyncClient, *, policy: RetryPolicy = FAST, lease: timedelta = timedelta(seconds=60)
|
||||
) -> InlinePipeline:
|
||||
database = await resolve(http, Database)
|
||||
storage = await resolve(http, ObjectStorage)
|
||||
return InlinePipeline(database, storage, policy=policy, lease=lease)
|
||||
|
||||
|
||||
async def settle(http: AsyncClient) -> list[Outcome]:
|
||||
return await (await pipeline_of(http)).drain()
|
||||
@@ -0,0 +1,122 @@
|
||||
import struct
|
||||
import zlib
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from pictures import SIGNATURE, chunk
|
||||
|
||||
PASSES = (
|
||||
(0, 0, 8, 8),
|
||||
(4, 0, 8, 8),
|
||||
(0, 4, 4, 8),
|
||||
(2, 0, 4, 4),
|
||||
(0, 2, 2, 4),
|
||||
(1, 0, 2, 2),
|
||||
(0, 1, 1, 2),
|
||||
)
|
||||
|
||||
|
||||
def boundary_png(depth: int, transparent: tuple[int, ...]) -> bytes:
|
||||
width, height = 8000, 5000
|
||||
neighbor = (transparent[0] ^ 1, *transparent[1:])
|
||||
row = b"\x00" + packed(list(transparent) * (width // 2) + list(neighbor) * (width // 2), depth)
|
||||
compressor = zlib.compressobj()
|
||||
payload = b"".join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||||
header = struct.pack(
|
||||
">IIBBBBB", width, height, depth, 0 if len(transparent) == 1 else 2, 0, 0, 0
|
||||
)
|
||||
return (
|
||||
SIGNATURE
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"tRNS", b"".join(value.to_bytes(2, "big") for value in transparent))
|
||||
+ chunk(b"IDAT", payload)
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def packed(samples: list[int], depth: int) -> bytes:
|
||||
if depth >= 8:
|
||||
return b"".join(value.to_bytes(depth // 8, "big") for value in samples)
|
||||
per_byte = 8 // depth
|
||||
padded = samples + [0] * (-len(samples) % per_byte)
|
||||
return bytes(
|
||||
sum(value << (8 - depth * (i + 1)) for i, value in enumerate(padded[j : j + per_byte]))
|
||||
for j in range(0, len(padded), per_byte)
|
||||
)
|
||||
|
||||
|
||||
def filtered(row: bytes, previous: bytes, bpp: int, method: int) -> bytes:
|
||||
result = bytearray([method])
|
||||
for i, value in enumerate(row):
|
||||
left = row[i - bpp] if i >= bpp else 0
|
||||
above = previous[i]
|
||||
corner = previous[i - bpp] if i >= bpp else 0
|
||||
estimate = left + above - corner
|
||||
paeth = min((left, above, corner), key=lambda candidate: abs(estimate - candidate))
|
||||
predictor = (0, left, above, (left + above) // 2, paeth)[method]
|
||||
result.append((value - predictor) % 256)
|
||||
return bytes(result)
|
||||
|
||||
|
||||
def png_with_trns(
|
||||
depth: int,
|
||||
transparent: tuple[int, ...],
|
||||
*,
|
||||
size: tuple[int, int] = (64, 64),
|
||||
filtering: int = 0,
|
||||
interlace: int = 0,
|
||||
orientation: int = 1,
|
||||
) -> tuple[bytes, bytes]:
|
||||
width, height = size
|
||||
neighbors = [
|
||||
tuple(value ^ (1 << bit) if i == channel else value for i, value in enumerate(transparent))
|
||||
for bit in ([0, 8] if depth == 16 else [0])
|
||||
for channel in range(len(transparent))
|
||||
]
|
||||
neighbors.insert(0, ((transparent[0] + 1) % (1 << depth), *transparent[1:]))
|
||||
pixels = [
|
||||
[
|
||||
transparent if x < (width + 1) // 2 else neighbors[(y // 8) % len(neighbors)]
|
||||
for x in range(width)
|
||||
]
|
||||
for y in range(height)
|
||||
]
|
||||
raw = bytearray()
|
||||
for x0, y0, dx, dy in PASSES if interlace else ((0, 0, 1, 1),):
|
||||
columns = range(x0, width, dx)
|
||||
if not columns:
|
||||
continue
|
||||
previous = bytes((len(columns) * len(transparent) * depth + 7) // 8)
|
||||
for y in range(y0, height, dy):
|
||||
row = packed([value for x in columns for value in pixels[y][x]], depth)
|
||||
raw.extend(filtered(row, previous, max(1, len(transparent) * depth // 8), filtering))
|
||||
previous = row
|
||||
header = struct.pack(
|
||||
">IIBBBBB", width, height, depth, 0 if len(transparent) == 1 else 2, 0, 0, interlace
|
||||
)
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = orientation
|
||||
compressed = zlib.compress(raw)
|
||||
data = (
|
||||
SIGNATURE
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"tRNS", b"".join(value.to_bytes(2, "big") for value in transparent))
|
||||
+ chunk(b"eXIf", exif.tobytes()[6:])
|
||||
+ b"".join(chunk(b"IDAT", compressed[i : i + 7]) for i in range(0, len(compressed), 7))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
expected = bytearray()
|
||||
for row in pixels:
|
||||
for pixel in row:
|
||||
channels = tuple(
|
||||
v >> 8 if depth == 16 else v * 255 // ((1 << depth) - 1) for v in pixel
|
||||
)
|
||||
expected.extend(
|
||||
(255, 255, 255)
|
||||
if pixel == transparent
|
||||
else channels * (3 if len(channels) == 1 else 1)
|
||||
)
|
||||
buffer = BytesIO()
|
||||
Image.frombytes("RGB", size, expected).save(buffer, "PNG", exif=exif)
|
||||
return data, buffer.getvalue()
|
||||
@@ -0,0 +1,579 @@
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Iterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from hashlib import sha256
|
||||
from http.client import HTTPResponse
|
||||
from typing import Any
|
||||
from urllib.parse import quote, urlsplit
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
|
||||
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG, GIF, JPEG, SAMPLE, WEBP, png
|
||||
from stand import BASE_URL, bearer, compose, enroll, lb_up, psql, waited
|
||||
|
||||
pytestmark = pytest.mark.stack
|
||||
LIMIT = 10_485_760
|
||||
BUCKET = "messenger-attachments"
|
||||
REQUEST_TIMEOUT = 8
|
||||
SWEEP_WAIT = 90
|
||||
CODES = {
|
||||
400: "invalid_request",
|
||||
404: "not_found",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
}
|
||||
HEAD = (
|
||||
'curl -s -o /dev/null -w "%{http_code}" -I --aws-sigv4 "aws:amz:${RUSTFS_REGION:-us-east-1}:s3"'
|
||||
' --user "$(cat /run/secrets/s3_root_user):$(cat /run/secrets/s3_root_password)"'
|
||||
' "http://127.0.0.1:9000/$BUCKET/$KEY"'
|
||||
)
|
||||
FAULTS = """
|
||||
CREATE TABLE lab4_fault_seen (id uuid PRIMARY KEY, object_key text, filename text);
|
||||
CREATE FUNCTION lab4_fault_seen() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
INSERT INTO lab4_fault_seen VALUES (NEW.id, NEW.staging_key, NEW.filename);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE FUNCTION lab4_fault_commit() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.filename LIKE 'fault-fail-%' THEN
|
||||
RAISE EXCEPTION 'injected commit failure' USING ERRCODE = '55P03';
|
||||
END IF;
|
||||
PERFORM pg_sleep(1.8);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE FUNCTION lab4_fault_sleeper() RETURNS text LANGUAGE plpgsql AS $$
|
||||
DECLARE found text;
|
||||
BEGIN
|
||||
FOR i IN 1..500 LOOP
|
||||
PERFORM pg_stat_clear_snapshot();
|
||||
SELECT host(client_addr) INTO found FROM pg_stat_activity
|
||||
WHERE wait_event = 'PgSleep' AND query LIKE 'UPDATE attachments%' LIMIT 1;
|
||||
IF found IS NOT NULL THEN RETURN found; END IF;
|
||||
PERFORM pg_sleep(0.02);
|
||||
END LOOP;
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
CREATE TRIGGER lab4_fault_seen AFTER INSERT ON attachments FOR EACH ROW
|
||||
WHEN (NEW.filename LIKE 'fault-%') EXECUTE FUNCTION lab4_fault_seen();
|
||||
CREATE TRIGGER lab4_fault_commit BEFORE UPDATE ON attachments FOR EACH ROW
|
||||
WHEN (NEW.filename LIKE 'fault-%' AND OLD.status = 'pending' AND NEW.status = 'queued')
|
||||
EXECUTE FUNCTION lab4_fault_commit();
|
||||
"""
|
||||
CLEANUP = """
|
||||
DROP TRIGGER IF EXISTS lab4_fault_commit ON attachments;
|
||||
DROP TRIGGER IF EXISTS lab4_fault_seen ON attachments;
|
||||
DROP FUNCTION IF EXISTS lab4_fault_commit(), lab4_fault_seen(), lab4_fault_sleeper();
|
||||
DROP TABLE IF EXISTS lab4_fault_seen;
|
||||
"""
|
||||
|
||||
|
||||
def sql(text: str, **variables: str) -> str:
|
||||
return psql(text, ON_ERROR_STOP="1", **variables)
|
||||
|
||||
|
||||
def object_status(key: str) -> int:
|
||||
found = compose(
|
||||
"exec", "-T", "-e", f"KEY={key}", "-e", f"BUCKET={BUCKET}", "s3", "sh", "-c", HEAD
|
||||
)
|
||||
return int(found)
|
||||
|
||||
|
||||
def bucket_keys() -> set[str]:
|
||||
listing = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"s3-cli",
|
||||
"object",
|
||||
"list",
|
||||
"--recursive",
|
||||
"--json",
|
||||
f"root/{BUCKET}/staging/",
|
||||
)
|
||||
return {item["key"] for item in json.loads(listing)["items"]}
|
||||
|
||||
|
||||
def seen(name: str) -> tuple[str, str] | None:
|
||||
row = sql("SELECT id, object_key FROM lab4_fault_seen WHERE filename = :'name'", name=name)
|
||||
if not row:
|
||||
return None
|
||||
attachment_id, key = row.split("|")
|
||||
return attachment_id, key
|
||||
|
||||
|
||||
def status_of(attachment_id: str) -> str:
|
||||
return sql("SELECT status FROM attachments WHERE id = :'id'", id=attachment_id)
|
||||
|
||||
|
||||
def logs(since: str) -> list[dict[str, Any]]:
|
||||
out = compose("logs", "api", "--since", since, "--no-log-prefix")
|
||||
return [json.loads(line) for line in out.splitlines() if line.startswith("{")]
|
||||
|
||||
|
||||
def moment() -> str:
|
||||
return (datetime.now(UTC) - timedelta(seconds=1)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def kill(container: str) -> None:
|
||||
subprocess.run(["docker", "kill", "-s", "KILL", container], check=True, capture_output=True)
|
||||
|
||||
|
||||
def replica_at(address: str) -> str:
|
||||
ids = compose("ps", "-q", "api").split()
|
||||
template = "{{.Id}} {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}"
|
||||
found = subprocess.run(
|
||||
["docker", "inspect", "-f", template, *ids], check=True, capture_output=True, text=True
|
||||
).stdout.split("\n")
|
||||
return next(line.split()[0] for line in found if line.endswith(f" {address}"))
|
||||
|
||||
|
||||
def raw(
|
||||
path: str,
|
||||
headers: dict[str, str],
|
||||
body: bytes,
|
||||
*,
|
||||
hang_up: bool,
|
||||
piece: int = 0,
|
||||
delay: float = 0.0,
|
||||
) -> tuple[int, dict[str, Any], float]:
|
||||
parts = urlsplit(BASE_URL)
|
||||
head = f"POST {path} HTTP/1.1\r\nHost: {parts.netloc}\r\nConnection: close\r\n"
|
||||
head += "".join(f"{name}: {value}\r\n" for name, value in headers.items()) + "\r\n"
|
||||
started = time.perf_counter()
|
||||
with socket.create_connection((parts.hostname, parts.port or 80), timeout=30) as sock:
|
||||
sock.sendall(head.encode("latin-1"))
|
||||
for start in range(0, len(body), piece or max(len(body), 1)):
|
||||
sock.sendall(body[start : start + (piece or len(body))])
|
||||
time.sleep(delay)
|
||||
if hang_up:
|
||||
return 0, {}, 0.0
|
||||
response = HTTPResponse(sock)
|
||||
response.begin()
|
||||
return response.status, json.loads(response.read()), time.perf_counter() - started
|
||||
|
||||
|
||||
READER = """
|
||||
import hashlib, http.client, sys, time
|
||||
path, token, request_id, piece, delay = sys.argv[1:6]
|
||||
connection = http.client.HTTPConnection("lb", 8080, timeout=30)
|
||||
headers = {"Authorization": "Bearer " + token, "X-Request-Id": request_id}
|
||||
connection.request("GET", path, headers=headers)
|
||||
response, digest, started = connection.getresponse(), hashlib.sha256(), time.monotonic()
|
||||
while chunk := response.read(int(piece)):
|
||||
digest.update(chunk)
|
||||
time.sleep(float(delay))
|
||||
print(response.status, digest.hexdigest(), round(time.monotonic() - started, 2))
|
||||
"""
|
||||
|
||||
|
||||
def slow_read(path: str, token: str, request_id: str, piece: int, delay: float) -> list[str]:
|
||||
template = "{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}"
|
||||
networks = subprocess.run(
|
||||
["docker", "inspect", "-f", template, compose("ps", "-q", "lb")],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.split()
|
||||
image = subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.Config.Image}}", compose("ps", "-q", "api").split()[0]],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
command = [
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--network",
|
||||
next(name for name in networks if name.endswith("_edge")),
|
||||
"--sysctl",
|
||||
"net.ipv4.tcp_rmem=4096 16384 65536",
|
||||
"--entrypoint",
|
||||
"python",
|
||||
image,
|
||||
"-c",
|
||||
READER,
|
||||
path,
|
||||
token,
|
||||
request_id,
|
||||
str(piece),
|
||||
str(delay),
|
||||
]
|
||||
return subprocess.run(command, check=True, capture_output=True, text=True).stdout.split()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def http() -> AsyncIterator[AsyncClient]:
|
||||
async with AsyncClient(base_url=BASE_URL, timeout=30, trust_env=False) as client:
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def faults() -> Iterator[None]:
|
||||
sql(CLEANUP + FAULTS)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
sql(CLEANUP)
|
||||
|
||||
|
||||
async def scene(http: AsyncClient) -> dict[str, Any]:
|
||||
(alice, alice_token), (bob, bob_token), (eve, eve_token) = [
|
||||
await enroll(http, label) for label in ("alice", "bob", "eve")
|
||||
]
|
||||
chats = []
|
||||
for owner, token, members in (
|
||||
(alice, alice_token, [bob]),
|
||||
(alice, alice_token, []),
|
||||
(eve, eve_token, []),
|
||||
):
|
||||
created = await http.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": "Стенд", "member_ids": [owner["id"], *(m["id"] for m in members)]},
|
||||
headers=bearer(token),
|
||||
)
|
||||
assert created.status_code == 201
|
||||
chats.append(created.json()["id"])
|
||||
return {"alice": alice_token, "bob": bob_token, "eve": eve_token, "chats": chats}
|
||||
|
||||
|
||||
async def upload(
|
||||
http: AsyncClient,
|
||||
token: str,
|
||||
chat: str,
|
||||
body: bytes | AsyncIterator[bytes] = SAMPLE,
|
||||
*,
|
||||
filename: str | None = "sample.png",
|
||||
kind: str | None = "image/png",
|
||||
) -> Response:
|
||||
query = "" if filename is None else f"?filename={quote(filename, safe='')}"
|
||||
headers = {**bearer(token), **({"Content-Type": kind} if kind else {})}
|
||||
return await http.post(
|
||||
f"/api/v1/chats/{chat}/attachments{query}", content=body, headers=headers
|
||||
)
|
||||
|
||||
|
||||
async def message(http: AsyncClient, token: str, chat: str, body: dict[str, Any]) -> Response:
|
||||
headers = {**bearer(token), "Idempotency-Key": uuid4().hex}
|
||||
return await http.post(f"/api/v1/chats/{chat}/messages", json=body, headers=headers)
|
||||
|
||||
|
||||
def expect(label: str, response: Response, status: int) -> None:
|
||||
print(f"{label}: {response.status_code}")
|
||||
assert response.status_code == status, f"{label}: {response.status_code} {response.text}"
|
||||
assert response.headers["X-Instance-Id"]
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == CODES[status]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
async def test_user_errors_never_become_500(http: AsyncClient) -> None:
|
||||
since = moment()
|
||||
s = await scene(http)
|
||||
alice, eve, (chat, solo, other) = s["alice"], s["eve"], s["chats"]
|
||||
created = 0
|
||||
attachment = await upload(http, alice, chat)
|
||||
exact = await upload(http, alice, chat, png(16, 16, size=LIMIT))
|
||||
assert (attachment.status_code, exact.status_code) == (202, 202)
|
||||
assert exact.json()["size_bytes"] == LIMIT
|
||||
created += 2
|
||||
mine = attachment.json()["id"]
|
||||
foreign = (await upload(http, alice, solo)).json()["id"]
|
||||
created_elsewhere = 1
|
||||
oversize = png(16, 16, size=LIMIT + 1)
|
||||
|
||||
async def chunked() -> AsyncIterator[bytes]:
|
||||
for start in range(0, len(oversize), 1 << 20):
|
||||
yield oversize[start : start + (1 << 20)]
|
||||
|
||||
path = f"/api/v1/chats/{chat}/attachments?filename=big.png"
|
||||
status, body, _ = await asyncio.to_thread(
|
||||
raw,
|
||||
path,
|
||||
{**bearer(alice), "Content-Type": "image/png", "Content-Length": str(LIMIT + 1)},
|
||||
b"",
|
||||
hang_up=False,
|
||||
)
|
||||
print(f"10 MiB + 1 с Content-Length, тело не отправлено: {status}")
|
||||
assert (status, body["error"]["code"]) == (413, "payload_too_large")
|
||||
expect("10 MiB + 1 chunked", await upload(http, alice, chat, chunked()), 413)
|
||||
expect(
|
||||
"PNG 100000×100000 (бомба)",
|
||||
await upload(http, alice, chat, png(100_000, 100_000, rows=False)),
|
||||
413,
|
||||
)
|
||||
expect("PNG 8001×5000", await upload(http, alice, chat, png(8001, 5000, rows=False)), 413)
|
||||
for label, content, kind in (
|
||||
("PNG с корректными CRC и битым IDAT", BROKEN_PNG, "image/png"),
|
||||
("PNG с повторным IHDR", DUPLICATE_IHDR_PNG, "image/png"),
|
||||
("обрезанный PNG", SAMPLE[: len(SAMPLE) // 2], "image/png"),
|
||||
("обрезанный JPEG", JPEG[: len(JPEG) // 2], "image/jpeg"),
|
||||
("JPEG как image/png", JPEG, "image/png"),
|
||||
("GIF как image/png", GIF, "image/png"),
|
||||
("WebP как image/png", WEBP, "image/png"),
|
||||
("текст как image/png", b"plain text, not an image", "image/png"),
|
||||
("PNG как image/jpeg", SAMPLE, "image/jpeg"),
|
||||
("пустое тело", b"", "image/png"),
|
||||
("application/octet-stream", SAMPLE, "application/octet-stream"),
|
||||
("без Content-Type", SAMPLE, None),
|
||||
):
|
||||
expect(label, await upload(http, alice, chat, content, kind=kind), 415)
|
||||
for name in (
|
||||
"../a.png",
|
||||
"a/b.png",
|
||||
"a\\b.png",
|
||||
"a\x00.png",
|
||||
"a\x01.png",
|
||||
"a\x7f.png",
|
||||
"",
|
||||
" ",
|
||||
"x" * 256,
|
||||
None,
|
||||
):
|
||||
expect(f"filename={name!r}"[:40], await upload(http, alice, chat, filename=name), 400)
|
||||
expect("посторонний: upload в чужой чат", await upload(http, eve, chat), 404)
|
||||
expect(
|
||||
"посторонний: метаданные",
|
||||
await http.get(f"/api/v1/attachments/{mine}", headers=bearer(eve)),
|
||||
404,
|
||||
)
|
||||
expect(
|
||||
"посторонний: /content",
|
||||
await http.get(f"/api/v1/attachments/{mine}/content", headers=bearer(eve)),
|
||||
404,
|
||||
)
|
||||
expect(
|
||||
"посторонний: ссылка на чужое вложение",
|
||||
await message(http, eve, other, {"text": "x", "attachment_ids": [mine]}),
|
||||
404,
|
||||
)
|
||||
expect(
|
||||
"вложение другого чата",
|
||||
await message(http, alice, chat, {"text": "x", "attachment_ids": [foreign]}),
|
||||
404,
|
||||
)
|
||||
expect(
|
||||
"неизвестное вложение",
|
||||
await message(http, alice, chat, {"text": "x", "attachment_ids": [str(uuid4())]}),
|
||||
404,
|
||||
)
|
||||
for label, ids in (
|
||||
("11 вложений", [mine] + [str(uuid4()) for _ in range(10)]),
|
||||
("повтор вложения", [mine, mine]),
|
||||
("невалидный UUID", ["not-a-uuid"]),
|
||||
):
|
||||
expect(label, await message(http, alice, chat, {"text": "x", "attachment_ids": ids}), 400)
|
||||
expect(
|
||||
"пустой текст без вложений",
|
||||
await message(http, alice, chat, {"text": "", "attachment_ids": []}),
|
||||
400,
|
||||
)
|
||||
expect(
|
||||
"невалидный id вложения",
|
||||
await http.get("/api/v1/attachments/x/content", headers=bearer(alice)),
|
||||
400,
|
||||
)
|
||||
expect(
|
||||
"variant=preview",
|
||||
await http.get(
|
||||
f"/api/v1/attachments/{mine}/content?variant=preview", headers=bearer(alice)
|
||||
),
|
||||
400,
|
||||
)
|
||||
rows = sql("SELECT count(*) FROM attachments WHERE chat_id = :'chat'", chat=chat)
|
||||
assert int(rows) == created
|
||||
assert sql("SELECT count(*) FROM attachments WHERE chat_id = :'chat'", chat=solo) == str(
|
||||
created_elsewhere
|
||||
)
|
||||
statuses = [entry["status"] for entry in logs(since) if entry.get("event") == "request.handled"]
|
||||
print(
|
||||
f"строк вложений в чате: {rows} (= ответов 202); ответов в журнале реплик: "
|
||||
f"{len(statuses)}, из них 5xx: {sum(code >= 500 for code in statuses)}"
|
||||
)
|
||||
assert not [status for status in statuses if status >= 500]
|
||||
|
||||
|
||||
async def test_commit_failure_is_compensated_at_once(http: AsyncClient, faults: None) -> None:
|
||||
since = moment()
|
||||
s = await scene(http)
|
||||
name = f"fault-fail-{uuid4().hex}.png"
|
||||
response = await upload(http, s["alice"], s["chats"][0], filename=name)
|
||||
print(
|
||||
"отказ COMMIT после записи объекта:",
|
||||
response.status_code,
|
||||
response.json()["error"]["code"],
|
||||
)
|
||||
assert response.status_code == 503
|
||||
found = seen(name)
|
||||
assert found is not None
|
||||
attachment_id, key = found
|
||||
print(
|
||||
f"сразу после ответа: строка {status_of(attachment_id) or 'нет'},",
|
||||
f"объект HEAD {object_status(key)}",
|
||||
)
|
||||
assert status_of(attachment_id) == ""
|
||||
assert object_status(key) == 404
|
||||
|
||||
def journaled() -> bool:
|
||||
return any(
|
||||
entry.get("event") == "audit.attachment_discarded"
|
||||
and entry.get("attachment_id") == attachment_id
|
||||
and entry.get("reason") == "compensation"
|
||||
for entry in logs(since)
|
||||
)
|
||||
|
||||
await waited(journaled, 10)
|
||||
print("журнал: audit.attachment_discarded reason=compensation")
|
||||
|
||||
|
||||
async def crash(http: AsyncClient, token: str, chat: str) -> tuple[str, str]:
|
||||
name = f"fault-crash-{uuid4().hex}.png"
|
||||
sent = asyncio.create_task(upload(http, token, chat, filename=name))
|
||||
address = await asyncio.to_thread(sql, "SELECT lab4_fault_sleeper()")
|
||||
assert address, "UPDATE queued не дошёл до триггера"
|
||||
victim = replica_at(address)
|
||||
kill(victim)
|
||||
try:
|
||||
outcome = str((await sent).status_code)
|
||||
except httpx.HTTPError as error:
|
||||
outcome = type(error).__name__
|
||||
compose("up", "-d", "--wait", "--no-deps", "--no-recreate", "api")
|
||||
await waited(lambda: lb_up() == 2, 60)
|
||||
found = seen(name)
|
||||
assert found is not None
|
||||
print(f"реплика {victim[:12]} убита между PUT и COMMIT, клиент получил {outcome}")
|
||||
return found
|
||||
|
||||
|
||||
async def test_crash_between_put_and_commit_is_swept_after_grace(
|
||||
http: AsyncClient, faults: None
|
||||
) -> None:
|
||||
s = await scene(http)
|
||||
alice, chat = s["alice"], s["chats"][0]
|
||||
kept = (await upload(http, alice, chat, filename="kept.png")).json()
|
||||
await waited(lambda: status_of(kept["id"]) == "ready", 60)
|
||||
assert (
|
||||
await message(http, alice, chat, {"text": "", "attachment_ids": [kept["id"]]})
|
||||
).status_code == 201
|
||||
old, fresh = await crash(http, alice, chat), await crash(http, alice, chat)
|
||||
for attachment_id, key in (old, fresh):
|
||||
state = (status_of(attachment_id), object_status(key))
|
||||
print(f"остаток после падения: строка {state[0]}, объект HEAD {state[1]}")
|
||||
assert state == ("pending", 200)
|
||||
aged = "UPDATE attachments SET created_at = created_at - interval '2 hours' WHERE id = :'id'"
|
||||
sql(aged, id=old[0])
|
||||
sql(aged, id=kept["id"])
|
||||
swept = await waited(lambda: status_of(old[0]) == "", SWEEP_WAIT)
|
||||
print(f"старше grace: строка убрана через {swept:.1f} с, объект HEAD {object_status(old[1])}")
|
||||
assert object_status(old[1]) == 404
|
||||
print(f"моложе grace: строка {status_of(fresh[0])}, объект HEAD {object_status(fresh[1])}")
|
||||
assert (status_of(fresh[0]), object_status(fresh[1])) == ("pending", 200)
|
||||
sql(aged, id=fresh[0])
|
||||
swept = await waited(lambda: status_of(fresh[0]) == "", SWEEP_WAIT)
|
||||
print(f"тот же после сдвига: убран через {swept:.1f} с, объект HEAD {object_status(fresh[1])}")
|
||||
assert object_status(fresh[1]) == 404
|
||||
content = await http.get(f"/api/v1/attachments/{kept['id']}/content", headers=bearer(s["bob"]))
|
||||
assert content.status_code == 200
|
||||
assert sha256(content.content).hexdigest() == kept["sha256"]
|
||||
print("готовое вложение в сообщении со сдвинутым created_at скачивается, SHA-256 совпадает")
|
||||
|
||||
|
||||
async def test_aborted_upload_leaves_nothing(http: AsyncClient, faults: None) -> None:
|
||||
since = moment()
|
||||
s = await scene(http)
|
||||
name, request_id = f"fault-abort-{uuid4().hex}.png", f"abort-{uuid4().hex}"
|
||||
before = bucket_keys()
|
||||
headers = {
|
||||
**bearer(s["alice"]),
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": str(5 << 20),
|
||||
"X-Request-Id": request_id,
|
||||
}
|
||||
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename={name}"
|
||||
await asyncio.to_thread(raw, path, headers, SAMPLE[:8] + bytes(256 << 10), hang_up=True)
|
||||
|
||||
def handled() -> list[int]:
|
||||
return [
|
||||
e["status"]
|
||||
for e in logs(since)
|
||||
if e.get("request_id") == request_id and e.get("event") == "request.handled"
|
||||
]
|
||||
|
||||
await waited(lambda: bool(handled()), 15)
|
||||
print(
|
||||
f"обрыв после 256 KiB из 5 MiB: статус в журнале реплики {handled()},",
|
||||
f"намерение {seen(name)}",
|
||||
)
|
||||
assert handled() == [400]
|
||||
assert seen(name) is None
|
||||
assert bucket_keys() == before
|
||||
|
||||
|
||||
async def test_stalled_upload_is_cut_and_leaves_nothing(http: AsyncClient, faults: None) -> None:
|
||||
s = await scene(http)
|
||||
name = f"fault-stall-{uuid4().hex}.png"
|
||||
headers = {**bearer(s["alice"]), "Content-Type": "image/png", "Content-Length": str(1 << 20)}
|
||||
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename={name}"
|
||||
status, body, elapsed = await asyncio.to_thread(
|
||||
raw, path, headers, SAMPLE[:1024], hang_up=False
|
||||
)
|
||||
print(f"тело зависло после 1 KiB: {status} {body['error']['code']} за {elapsed:.2f} с")
|
||||
assert (status, body["error"]["code"]) == (503, "unavailable")
|
||||
assert elapsed <= REQUEST_TIMEOUT + 2
|
||||
assert seen(name) is None
|
||||
assert (await upload(http, s["alice"], s["chats"][0])).status_code == 202
|
||||
|
||||
|
||||
async def test_token_is_checked_before_the_declared_size(http: AsyncClient) -> None:
|
||||
s = await scene(http)
|
||||
headers = {"Content-Type": "image/png", "Content-Length": str(LIMIT + 1)}
|
||||
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=a.png"
|
||||
status, body, _ = await asyncio.to_thread(raw, path, headers, SAMPLE[:1024], hang_up=False)
|
||||
print(f"без токена, Content-Length {LIMIT + 1}: {status} {body['error']['code']}")
|
||||
assert (status, body["error"]["code"]) == (401, "unauthorized")
|
||||
|
||||
|
||||
async def test_slow_but_steady_transfers_outlive_the_request_timeout(http: AsyncClient) -> None:
|
||||
since = moment()
|
||||
s = await scene(http)
|
||||
picture = png(16, 16, size=3 << 20)
|
||||
sent, read = f"slow-upload-{uuid4().hex}", f"slow-download-{uuid4().hex}"
|
||||
headers = {
|
||||
**bearer(s["alice"]),
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": str(len(picture)),
|
||||
"X-Request-Id": sent,
|
||||
}
|
||||
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=slow.png"
|
||||
status, body, up = await asyncio.to_thread(
|
||||
raw, path, headers, picture, hang_up=False, piece=64 << 10, delay=0.25
|
||||
)
|
||||
assert status == 202, body
|
||||
assert body["sha256"] == sha256(picture).hexdigest()
|
||||
await waited(lambda: status_of(body["id"]) == "ready", 60)
|
||||
content = f"/api/v1/attachments/{body['id']}/content"
|
||||
code, digest, down = await asyncio.to_thread(slow_read, content, s["bob"], read, 64 << 10, 0.33)
|
||||
assert (code, digest) == ("200", body["sha256"])
|
||||
|
||||
def handled() -> dict[str, tuple[int, float]]:
|
||||
return {
|
||||
e["request_id"]: (e["status"], e["duration_ms"] / 1000)
|
||||
for e in logs(since)
|
||||
if e.get("event") == "request.handled" and e.get("request_id") in (sent, read)
|
||||
}
|
||||
|
||||
await waited(lambda: len(handled()) == 2, 15)
|
||||
replica = handled()
|
||||
print(f"upload 3 MiB ≈ 256 KiB/s: клиент {up:.1f} с, реплика {replica[sent]}")
|
||||
print(f"скачивание 3 MiB ≈ 192 KiB/s из сети edge: клиент {down} с, реплика {replica[read]}")
|
||||
assert replica[sent][0] == 202 and replica[sent][1] > REQUEST_TIMEOUT
|
||||
assert replica[read][0] == 200 and replica[read][1] > REQUEST_TIMEOUT
|
||||
@@ -0,0 +1,279 @@
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from stand import (
|
||||
BASE_URL,
|
||||
BASIC,
|
||||
BEARER,
|
||||
basic,
|
||||
bearer,
|
||||
compose,
|
||||
enroll,
|
||||
inside_replica,
|
||||
lb_up,
|
||||
new_user,
|
||||
psql,
|
||||
report,
|
||||
restart_stack,
|
||||
started_at,
|
||||
timed,
|
||||
valkey,
|
||||
wait_ready,
|
||||
waited,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.stack
|
||||
RACERS = 50
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def http() -> AsyncIterator[AsyncClient]:
|
||||
async with AsyncClient(base_url=BASE_URL, timeout=10, trust_env=False) as client:
|
||||
yield client
|
||||
|
||||
|
||||
async def test_registration_race_yields_exactly_one_user(http: AsyncClient) -> None:
|
||||
body = new_user("race")
|
||||
responses = await asyncio.gather(
|
||||
*(http.post("/api/v1/users", json=body) for _ in range(RACERS))
|
||||
)
|
||||
codes = sorted(response.status_code for response in responses)
|
||||
print(f"гонка {RACERS} регистраций: 201×{codes.count(201)}, 409×{codes.count(409)}")
|
||||
assert codes.count(201) == 1
|
||||
assert codes.count(409) == RACERS - 1
|
||||
assert psql("SELECT count(*) FROM users WHERE username = :'name'", name=body["username"]) == "1"
|
||||
|
||||
|
||||
async def test_chat_creation_rolls_back_on_unknown_member(http: AsyncClient) -> None:
|
||||
alice, token = await enroll(http, "alice")
|
||||
title = f"Откат {uuid4().hex}"
|
||||
response = await http.post(
|
||||
"/api/v1/chats",
|
||||
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
|
||||
headers=bearer(token),
|
||||
)
|
||||
code = response.json()["error"]["code"]
|
||||
print(f"чат с несуществующим участником: {response.status_code} {code}")
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert psql("SELECT count(*) FROM chats WHERE title = :'title'", title=title) == "0"
|
||||
members = "SELECT count(*) FROM chat_members WHERE user_id = :'id'::uuid"
|
||||
assert psql(members, id=alice["id"]) == "0"
|
||||
|
||||
|
||||
async def test_wrong_password_and_unknown_user_get_same_basic_challenge(http: AsyncClient) -> None:
|
||||
alice, _ = await enroll(http, "alice")
|
||||
wrong, wrong_time = await timed(
|
||||
http.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20))
|
||||
)
|
||||
unknown, unknown_time = await timed(
|
||||
http.post("/api/v1/auth/sessions", headers=basic(f"u_ghost_{uuid4().hex[:8]}"))
|
||||
)
|
||||
report("неверный пароль", wrong, wrong_time)
|
||||
report("неизвестный пользователь", unknown, unknown_time)
|
||||
for response in (wrong, unknown):
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"] == BASIC
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
async def test_logout_then_token_is_dead(http: AsyncClient) -> None:
|
||||
_, token = await enroll(http, "alice")
|
||||
assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 200
|
||||
logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
after = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
again = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
print(f"logout: {logout.status_code}, затем {after.status_code}, повтор {again.status_code}")
|
||||
assert (logout.status_code, logout.content) == (204, b"")
|
||||
assert after.status_code == again.status_code == 401
|
||||
assert again.headers["WWW-Authenticate"] == BEARER
|
||||
|
||||
|
||||
async def test_valkey_serves_repeated_checks(http: AsyncClient) -> None:
|
||||
_, token = await enroll(http, "cache")
|
||||
await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
before = int(valkey("info stats").split("keyspace_hits:")[1].split()[0])
|
||||
for _ in range(5):
|
||||
assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 200
|
||||
after = int(valkey("info stats").split("keyspace_hits:")[1].split()[0])
|
||||
print(f"5 проверок токена: keyspace_hits {before} → {after}")
|
||||
assert after - before >= 5
|
||||
|
||||
|
||||
async def test_valkey_stopped_is_bypassed_but_logout_waits(http: AsyncClient) -> None:
|
||||
user, token = await enroll(http, "nocache")
|
||||
try:
|
||||
compose("stop", "valkey")
|
||||
me, me_time = await timed(http.get("/api/v1/users/me", headers=bearer(token)))
|
||||
stranger, stranger_time = await timed(
|
||||
http.get("/api/v1/users/me", headers=bearer("x" * 43))
|
||||
)
|
||||
ready = await http.get("/health/ready")
|
||||
login = await http.post("/api/v1/auth/sessions", headers=basic(user["username"]))
|
||||
logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
report("valkey остановлен, действующий токен", me, me_time)
|
||||
report("valkey остановлен, неизвестный токен", stranger, stranger_time)
|
||||
codes = (ready.status_code, login.status_code, logout.status_code)
|
||||
print("valkey остановлен: ready {}, вход {}, выход {}".format(*codes))
|
||||
assert me.json() == user and me_time < 1
|
||||
assert stranger.status_code == 401 and stranger.headers["WWW-Authenticate"] == BEARER
|
||||
assert ready.status_code == 200
|
||||
assert login.status_code == 201
|
||||
assert logout.status_code == 503 and logout.json()["error"]["code"] == "unavailable"
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
await asyncio.sleep(1.2)
|
||||
retried = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
print(f"valkey снова запущен: повторный выход {retried.status_code}")
|
||||
assert retried.status_code == 204
|
||||
assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 401
|
||||
|
||||
|
||||
async def test_valkey_restart_keeps_cache_and_revocations(http: AsyncClient) -> None:
|
||||
_, alive = await enroll(http, "alive")
|
||||
_, revoked = await enroll(http, "revoked")
|
||||
assert (await http.get("/api/v1/users/me", headers=bearer(alive))).status_code == 200
|
||||
assert (await http.get("/api/v1/users/me", headers=bearer(revoked))).status_code == 200
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=bearer(revoked))
|
||||
).status_code == 204
|
||||
keys_before = valkey("dbsize")
|
||||
compose("restart", "valkey")
|
||||
compose("up", "-d", "--wait", "valkey")
|
||||
keys_after = valkey("dbsize")
|
||||
await asyncio.sleep(1.2)
|
||||
still = await http.get("/api/v1/users/me", headers=bearer(alive))
|
||||
dead = await http.get("/api/v1/users/me", headers=bearer(revoked))
|
||||
print(f"рестарт valkey: ключей {keys_before} → {keys_after}")
|
||||
print(f"рестарт valkey: живой {still.status_code}, отозванный {dead.status_code}")
|
||||
assert keys_after == keys_before
|
||||
assert still.status_code == 200
|
||||
assert dead.status_code == 401
|
||||
|
||||
|
||||
async def test_valkey_flushall_loses_nothing(http: AsyncClient) -> None:
|
||||
_, alive = await enroll(http, "alive")
|
||||
_, revoked = await enroll(http, "revoked")
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=bearer(revoked))
|
||||
).status_code == 204
|
||||
valkey("flushall")
|
||||
still = await http.get("/api/v1/users/me", headers=bearer(alive))
|
||||
dead = await http.get("/api/v1/users/me", headers=bearer(revoked))
|
||||
print(f"FLUSHALL: живой {still.status_code}, отозванный {dead.status_code}")
|
||||
assert still.status_code == 200
|
||||
assert dead.status_code == 401
|
||||
|
||||
|
||||
async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient) -> None:
|
||||
user, token = await enroll(http, "nodb")
|
||||
assert (await http.get("/api/v1/users/me", headers=bearer(token))).status_code == 200
|
||||
api_started = started_at("api")
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
checks = {
|
||||
"ready": await timed(http.get("/health/ready")),
|
||||
"me": await timed(http.get("/api/v1/users/me", headers=bearer(token))),
|
||||
"stranger": await timed(http.get("/api/v1/users/me", headers=bearer("x" * 43))),
|
||||
"login": await timed(
|
||||
http.post("/api/v1/auth/sessions", headers=basic(user["username"]))
|
||||
),
|
||||
"register": await timed(http.post("/api/v1/users", json=new_user("nodb"))),
|
||||
}
|
||||
live_inside = inside_replica("/health/live")
|
||||
excluded = await waited(lambda: lb_up() == 0, 5)
|
||||
through_lb = await http.get("/health/live")
|
||||
for name, (response, elapsed) in checks.items():
|
||||
report(f"postgres остановлен, {name}", response, elapsed)
|
||||
assert elapsed < 2
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == "unavailable"
|
||||
print(
|
||||
f"live внутри реплики {live_inside}; LB исключил все реплики ещё через {excluded:.2f} с"
|
||||
)
|
||||
report("live через LB без реплик", through_lb, 0)
|
||||
assert live_inside == 200
|
||||
assert lb_up() == 0
|
||||
assert excluded < 2
|
||||
assert through_lb.status_code == 503
|
||||
assert through_lb.json()["error"]["request_id"] == through_lb.headers["X-Request-Id"]
|
||||
assert "X-Instance-Id" not in through_lb.headers
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
recovered = await wait_ready(http)
|
||||
await waited(lambda: lb_up() == len(compose("ps", "-q", "api").split()))
|
||||
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
|
||||
assert me.json() == user
|
||||
instances = set()
|
||||
for _ in range(40):
|
||||
response = await http.post("/api/v1/users", json=new_user("recovered"))
|
||||
assert response.status_code == 201
|
||||
instances.add(response.headers["X-Instance-Id"])
|
||||
print(f"postgres запущен: 40 регистраций 201 через {len(instances)} реплики без рестарта API")
|
||||
assert len(instances) >= 2
|
||||
assert started_at("api") == api_started
|
||||
|
||||
|
||||
async def test_api_restart_keeps_session_without_extending_it(http: AsyncClient) -> None:
|
||||
body = new_user("restart")
|
||||
assert (await http.post("/api/v1/users", json=body)).status_code == 201
|
||||
session = (await http.post("/api/v1/auth/sessions", headers=basic(body["username"]))).json()
|
||||
compose("restart", "api")
|
||||
recovered = await wait_ready(http)
|
||||
me = await http.get("/api/v1/users/me", headers=bearer(session["token"]))
|
||||
stored = psql(
|
||||
"SELECT to_char(expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
|
||||
"FROM sessions s JOIN users u ON u.id = s.user_id WHERE u.username = :'name'",
|
||||
name=body["username"],
|
||||
)
|
||||
print(f"рестарт api: готовность через {recovered:.1f} с, токен {me.status_code}")
|
||||
print(f"expires_at при входе {session['expires_at']}, в БД после рестарта {stored}")
|
||||
assert me.status_code == 200
|
||||
assert stored.rstrip("Z").rstrip("0") == session["expires_at"].rstrip("Z").rstrip("0")
|
||||
|
||||
|
||||
async def test_full_restart_keeps_session_until_logout(http: AsyncClient) -> None:
|
||||
user, token = await enroll(http, "fullrestart")
|
||||
restart_stack()
|
||||
recovered = await wait_ready(http)
|
||||
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
after = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
print(
|
||||
f"restart.sh: готовность через {recovered:.1f} с, прежний токен {me.status_code}, "
|
||||
f"выход {logout.status_code}, затем {after.status_code}"
|
||||
)
|
||||
assert me.json() == user
|
||||
assert logout.status_code == 204
|
||||
assert after.status_code == 401
|
||||
|
||||
|
||||
async def test_session_expires_after_restart_at_original_time(http: AsyncClient) -> None:
|
||||
user, token = await enroll(http, "shortrestart")
|
||||
expires_at = float(
|
||||
psql(
|
||||
"UPDATE sessions s SET expires_at = now() + interval '20 seconds' FROM users u "
|
||||
"WHERE u.id = s.user_id AND u.username = :'name' "
|
||||
"RETURNING extract(epoch FROM s.expires_at)",
|
||||
name=user["username"],
|
||||
).splitlines()[0]
|
||||
)
|
||||
compose("restart", "api")
|
||||
recovered = await wait_ready(http)
|
||||
fresh = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
await asyncio.sleep(max(0.0, expires_at - time.time()) + 0.5)
|
||||
stale = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
print(
|
||||
f"срок сессии сокращён до 20 с, рестарт api: готовность через {recovered:.1f} с, "
|
||||
f"до срока {fresh.status_code}, после срока {stale.status_code}"
|
||||
)
|
||||
assert fresh.status_code == 200
|
||||
assert stale.status_code == 401
|
||||
assert stale.headers["WWW-Authenticate"] == BEARER
|
||||
@@ -0,0 +1,136 @@
|
||||
import asyncio
|
||||
import csv
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from base64 import b64encode
|
||||
from collections.abc import Awaitable, Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from httpx import AsyncClient, Response, TransportError
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
PASSWORD = "Пароль-для-стенда-01"
|
||||
BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER = 'Bearer realm="messenger"'
|
||||
VALKEY_AUTH = 'REDISCLI_AUTH="$(sed -n "s/^requirepass //p" /run/secrets/valkey.conf)"'
|
||||
|
||||
|
||||
def compose(*args: str, stdin: str | None = None) -> str:
|
||||
done = subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
input=stdin,
|
||||
)
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
def restart_stack() -> None:
|
||||
subprocess.run(["sh", "scripts/restart.sh"], cwd=ROOT, check=True, capture_output=True)
|
||||
|
||||
|
||||
def psql(sql: str, **variables: str) -> str:
|
||||
assigned = [item for name, value in variables.items() for item in ("-v", f"{name}={value}")]
|
||||
command = ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tA"]
|
||||
return compose(*command, *assigned, stdin=sql)
|
||||
|
||||
|
||||
def valkey(command: str) -> str:
|
||||
return compose("exec", "-T", "valkey", "sh", "-c", f"{VALKEY_AUTH} valkey-cli {command}")
|
||||
|
||||
|
||||
def started_at(service: str) -> str:
|
||||
return subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{.State.StartedAt}}",
|
||||
*compose("ps", "-q", service).split(),
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def inside_replica(path: str) -> int:
|
||||
replica = compose("ps", "-q", "api").split()[0]
|
||||
probe = f"import urllib.request as u;print(u.urlopen('http://127.0.0.1:8080{path}').status)"
|
||||
done = subprocess.run(
|
||||
["docker", "exec", replica, "python", "-c", probe],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return int(done.stdout.strip() or 0)
|
||||
|
||||
|
||||
def lb_up() -> int:
|
||||
stats = httpx.get(f"http://{compose('port', 'lb', '8404')}/stats;csv", timeout=2).text
|
||||
rows = csv.DictReader(stats.lstrip("# ").splitlines())
|
||||
servers = (r for r in rows if r["pxname"] == "api" and r["svname"] != "BACKEND")
|
||||
return sum(1 for r in servers if r["status"].startswith("UP"))
|
||||
|
||||
|
||||
def basic(username: str, password: str = PASSWORD) -> dict[str, str]:
|
||||
return {"Authorization": "Basic " + b64encode(f"{username}:{password}".encode()).decode()}
|
||||
|
||||
|
||||
def bearer(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def new_user(label: str) -> dict[str, str]:
|
||||
return {
|
||||
"username": f"u_{label}_{uuid4().hex[:12]}",
|
||||
"display_name": f"Стенд {label}",
|
||||
"password": PASSWORD,
|
||||
}
|
||||
|
||||
|
||||
async def enroll(http: AsyncClient, label: str) -> tuple[dict[str, Any], str]:
|
||||
body = new_user(label)
|
||||
created = await http.post("/api/v1/users", json=body)
|
||||
assert created.status_code == 201, created.text
|
||||
session = await http.post("/api/v1/auth/sessions", headers=basic(body["username"]))
|
||||
assert session.status_code == 201, session.text
|
||||
return created.json(), session.json()["token"]
|
||||
|
||||
|
||||
async def timed(call: Awaitable[Response]) -> tuple[Response, float]:
|
||||
started = time.perf_counter()
|
||||
response = await call
|
||||
return response, time.perf_counter() - started
|
||||
|
||||
|
||||
async def wait_ready(http: AsyncClient, seconds: float = 60) -> float:
|
||||
started = time.perf_counter()
|
||||
while time.perf_counter() - started < seconds:
|
||||
try:
|
||||
if (await http.get("/health/ready")).status_code == 200:
|
||||
return time.perf_counter() - started
|
||||
except TransportError:
|
||||
pass
|
||||
await asyncio.sleep(0.25)
|
||||
raise AssertionError("стенд не вернулся в готовность")
|
||||
|
||||
|
||||
async def waited(condition: Callable[[], bool], seconds: float = 30) -> float:
|
||||
started = time.perf_counter()
|
||||
while time.perf_counter() - started < seconds:
|
||||
if condition():
|
||||
return time.perf_counter() - started
|
||||
await asyncio.sleep(0.05)
|
||||
raise AssertionError("условие не выполнилось за отведённое время")
|
||||
|
||||
|
||||
def report(event: str, response: Response, elapsed: float) -> None:
|
||||
print(f"{event}: {response.status_code} за {elapsed:.3f} с")
|
||||
@@ -0,0 +1,59 @@
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
from collections import Counter
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
def command(*args: str) -> str:
|
||||
return subprocess.check_output(args, text=True).strip()
|
||||
|
||||
|
||||
project = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi2026lab6")
|
||||
containers = [
|
||||
json.loads(line)
|
||||
for line in command(
|
||||
"docker",
|
||||
"ps",
|
||||
"--format",
|
||||
'{"name":"{{.Names}}","project":"{{.Label "com.docker.compose.project"}}"}',
|
||||
).splitlines()
|
||||
]
|
||||
own = {row["name"] for row in containers if row["project"] == project}
|
||||
stats = [
|
||||
json.loads(line)
|
||||
for line in command("docker", "stats", "--no-stream", "--format", "{{json .}}").splitlines()
|
||||
]
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
"runtime_sha": command("git", "rev-parse", "HEAD"),
|
||||
"platform": platform.system(),
|
||||
"architecture": platform.machine(),
|
||||
"host_cpus": os.cpu_count(),
|
||||
"host_load": os.getloadavg(),
|
||||
"docker": command(
|
||||
"docker",
|
||||
"info",
|
||||
"--format",
|
||||
"{{.NCPU}} CPUs; {{.MemTotal}} bytes; {{.ServerVersion}}",
|
||||
),
|
||||
"own_project": project,
|
||||
"own": [
|
||||
{key: row[key] for key in ("Name", "CPUPerc", "MemUsage", "PIDs")}
|
||||
for row in stats
|
||||
if row["Name"] in own
|
||||
],
|
||||
"other_projects": dict(
|
||||
Counter(
|
||||
row["project"] or "unlabelled" for row in containers if row["name"] not in own
|
||||
)
|
||||
),
|
||||
"sampling": "Shared Docker snapshot; no throughput claim",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
base = urlsplit(os.environ.get("BASE_URL", "http://127.0.0.1:18086"))
|
||||
seen = set()
|
||||
checks = []
|
||||
password = "Пароль-проверки-01"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, status=200):
|
||||
request_id = "validation-wire"
|
||||
assert base.hostname
|
||||
conn = http.client.HTTPConnection(base.hostname, base.port, timeout=12)
|
||||
head = {"X-Request-Id": request_id, "Content-Type": "application/json", **(headers or {})}
|
||||
conn.request(method, path, None if body is None else json.dumps(body).encode(), head)
|
||||
response = conn.getresponse()
|
||||
data = response.read()
|
||||
instance = response.getheader("X-Instance-Id")
|
||||
assert response.status == status, (method, path, response.status, status)
|
||||
assert instance
|
||||
assert response.getheader("X-Request-Id") == request_id
|
||||
seen.add(instance)
|
||||
result = json.loads(data) if data else None
|
||||
if status >= 400:
|
||||
assert result is not None
|
||||
assert result["error"]["request_id"] == request_id
|
||||
if status == 401:
|
||||
assert response.getheader("WWW-Authenticate") == (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if path == "/api/v1/auth/sessions"
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
conn.close()
|
||||
return result, instance
|
||||
|
||||
|
||||
def basic(name, secret=password):
|
||||
return {"Authorization": "Basic " + base64.b64encode(f"{name}:{secret}".encode()).decode()}
|
||||
|
||||
|
||||
def enroll():
|
||||
name = "wire_" + uuid.uuid4().hex[:15]
|
||||
user, _ = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": name, "password": password, "display_name": "Алиса 👋"},
|
||||
status=201,
|
||||
)
|
||||
login, _ = call("POST", "/api/v1/auth/sessions", headers=basic(name), status=201)
|
||||
return user, {"Authorization": "Bearer " + login["token"]}
|
||||
|
||||
|
||||
user, auth = enroll()
|
||||
wrong, _ = call(
|
||||
"POST", "/api/v1/auth/sessions", headers=basic(user["username"], "wrong-password"), status=401
|
||||
)
|
||||
for raw in [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]:
|
||||
result, instance = call(
|
||||
"POST", "/api/v1/auth/sessions", headers={"Authorization": raw}, status=401
|
||||
)
|
||||
assert result == wrong
|
||||
checks.append(
|
||||
{"case": "non_ascii_basic", "raw_hex": raw.hex(), "status": 401, "instance": instance}
|
||||
)
|
||||
for text in ["\x00", "\x00abc", "abc\x00def", "abc\x00"]:
|
||||
result, instance = call("POST", "/api/v1/auth/sessions", headers=basic(text), status=401)
|
||||
assert result == wrong
|
||||
body = {"username": "wire_" + uuid.uuid4().hex[:15], "password": password, "display_name": text}
|
||||
call("POST", "/api/v1/users", body, status=400)
|
||||
call("POST", "/api/v1/users", {**body, "display_name": "Алиса 👋"}, status=201)
|
||||
call("POST", "/api/v1/chats", {"title": text, "member_ids": [user["id"]]}, auth, status=400)
|
||||
chats, _ = call("GET", "/api/v1/chats", headers=auth)
|
||||
assert not chats["items"]
|
||||
checks.append(
|
||||
{
|
||||
"case": "nul_basic_display_title",
|
||||
"position": repr(text),
|
||||
"status": [401, 400, 201, 400],
|
||||
"instance": instance,
|
||||
}
|
||||
)
|
||||
chat, _ = call(
|
||||
"POST", "/api/v1/chats", {"title": "Проверка 👋", "member_ids": [user["id"]]}, auth, status=201
|
||||
)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
messages = []
|
||||
for text in ["\x00", "\x00abc", "abc\x00def", "abc\x00"]:
|
||||
headers = {**auth, "Idempotency-Key": uuid.uuid4().hex}
|
||||
call("POST", path, {"text": text}, headers, status=400)
|
||||
page, _ = call("GET", path, headers=auth)
|
||||
assert page["items"] == messages
|
||||
first, one = call("POST", path, {"text": "Исправлено\tбез потерь\n👋"}, headers, status=201)
|
||||
again, two = call("POST", path, {"text": first["text"]}, headers, status=201)
|
||||
assert first == again and one != two
|
||||
messages.append(first)
|
||||
page, _ = call("GET", path, headers=auth)
|
||||
assert page["items"] == messages
|
||||
checks.append(
|
||||
{
|
||||
"case": "nul_message_corrected_retry",
|
||||
"position": repr(text),
|
||||
"instances": [one, two],
|
||||
"status": [400, 201, 201],
|
||||
"copies": 1,
|
||||
}
|
||||
)
|
||||
_, outsider = enroll()
|
||||
for target in [chat["id"], str(uuid.uuid4())]:
|
||||
call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{target}/messages",
|
||||
{"text": "abc\x00def"},
|
||||
{**outsider, "Idempotency-Key": uuid.uuid4().hex},
|
||||
status=404,
|
||||
)
|
||||
checks.append({"case": "nul_access", "status": [404, 404]})
|
||||
call("DELETE", "/api/v1/auth/sessions/current", headers=auth, status=204)
|
||||
for _ in range(4):
|
||||
call("GET", "/api/v1/users/me", headers=auth, status=401)
|
||||
checks.append({"case": "logout_across_replicas", "status": [204, 401, 401, 401, 401]})
|
||||
assert len(seen) >= 2
|
||||
print(
|
||||
json.dumps(
|
||||
{"checks": checks, "instances": sorted(seen), "pass": True}, ensure_ascii=False, indent=2
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,386 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
from scripts import pipeline_suite as ps
|
||||
|
||||
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
|
||||
from png_trns_fixtures import boundary_png, png_with_trns
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
MODE = sys.argv.pop(1)
|
||||
OUT = Path(os.environ.get("FORWARD_EVIDENCE_DIR", "evidence/forward-published")) / (MODE + ".json")
|
||||
if OUT.exists():
|
||||
raise SystemExit("Result exists; do not repeat completed evidence")
|
||||
SUITE = ps.Suite(ps.arguments())
|
||||
STACK = SUITE.stack
|
||||
REPORT: dict[str, Any] = {
|
||||
"mode": MODE,
|
||||
"source_sha": ps.run(["git", "rev-parse", "HEAD"]).strip(),
|
||||
"started_at": ps.now(),
|
||||
"cases": [],
|
||||
}
|
||||
LIMITS = RenderLimits(10485760, 40000000)
|
||||
|
||||
|
||||
def save():
|
||||
REPORT["accepted_ids"] = SUITE.api.accepted if SUITE.api else []
|
||||
OUT.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
def case(name, function):
|
||||
row = {"name": name, "started_at": ps.now()}
|
||||
REPORT["cases"].append(row)
|
||||
save()
|
||||
began = time.monotonic()
|
||||
try:
|
||||
row["observed"] = function()
|
||||
row["result"] = "PASS"
|
||||
except Exception as error:
|
||||
row.update(result="FAIL", error=str(error))
|
||||
row["elapsed_seconds"] = round(time.monotonic() - began, 3)
|
||||
save()
|
||||
print(name, row["result"], row.get("error", ""), flush=True)
|
||||
|
||||
|
||||
def containers():
|
||||
return STACK.dc("ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}").splitlines()
|
||||
|
||||
|
||||
def outage():
|
||||
assert SUITE.api is not None
|
||||
SUITE.drained()
|
||||
before_dlq = STACK.queues()[ps.DLQ]
|
||||
STACK.stop("worker")
|
||||
att = SUITE.api.fixture()
|
||||
ident = att["id"]
|
||||
ps.poll(
|
||||
lambda: all(r["published"] for r in STACK.sql("outbox", id=ident)), 30, "published outbox"
|
||||
)
|
||||
jobs = STACK.sql("jobs", id=ident)
|
||||
REPORT["outage_checkpoint"] = {
|
||||
"attachment_id": ident,
|
||||
"jobs_before": jobs,
|
||||
"dlq_before": before_dlq,
|
||||
}
|
||||
save()
|
||||
STACK.stop("postgres")
|
||||
REPORT["outage_checkpoint"]["stopped_containers"] = containers()
|
||||
save()
|
||||
since = ps.now()
|
||||
worker_id = STACK.dc("ps", "-aq", "worker").strip()
|
||||
assert worker_id
|
||||
ps.run(["docker", "start", worker_id])
|
||||
|
||||
def requeues():
|
||||
logs = STACK.dc("logs", "--no-color", "--since", since, "worker")
|
||||
rows = [
|
||||
line
|
||||
for line in logs.splitlines()
|
||||
if "job.requeued" in line and jobs[0]["job_id"] in line
|
||||
]
|
||||
return rows if len(rows) >= 12 else None
|
||||
|
||||
try:
|
||||
lines = ps.poll(requeues, 90, "12 real database failures", 1)
|
||||
OUT.with_name(OUT.stem + "-worker.txt").write_text("\n".join(lines) + "\n")
|
||||
during = STACK.queues()
|
||||
finally:
|
||||
STACK.up("postgres")
|
||||
ps.poll(lambda: ps.http_ready(SUITE.args.base_url), 30, "API after PostgreSQL")
|
||||
ready = SUITE.api.wait(ident)
|
||||
SUITE.verify(ready)
|
||||
SUITE.drained()
|
||||
after = STACK.sql("jobs", id=ident)
|
||||
assert (
|
||||
after[0]["job_id"] == jobs[0]["job_id"] and after[0]["attempt"] == jobs[0]["attempt"] == 1
|
||||
)
|
||||
assert after[0]["status"] == "done"
|
||||
assert STACK.queues()[ps.DLQ] == before_dlq
|
||||
assert len(STACK.sql("variants", id=ident)) == 3
|
||||
return {
|
||||
"attachment_id": ident,
|
||||
"jobs_before": jobs,
|
||||
"jobs_after": after,
|
||||
"requeues": len(lines),
|
||||
"queues_during": during,
|
||||
"queues_after": STACK.queues(),
|
||||
"replay": False,
|
||||
"stopped_containers": REPORT["outage_checkpoint"]["stopped_containers"],
|
||||
}
|
||||
|
||||
|
||||
def png(name, data, reference):
|
||||
assert SUITE.api is not None
|
||||
att = SUITE.api.upload(data, name=name + ".png")
|
||||
ident = att["id"]
|
||||
results = []
|
||||
for version in (1, 2):
|
||||
if version == 2:
|
||||
STACK.admin("reprocess", "--attachment-id", ident, "--pipeline-version", "2")
|
||||
ps.poll(lambda: SUITE.record(ident)["published_version"] == 2, 90, "published v2")
|
||||
ready = SUITE.api.wait(ident)
|
||||
SUITE.verify(ready)
|
||||
assert SUITE.api.content(ident)["bytes"] == data
|
||||
expected = {r.name: r for r in render_variants(reference, LIMITS, version)}
|
||||
variants = []
|
||||
for variant in ready["variants"]:
|
||||
content = SUITE.api.content(ident, variant["name"])["bytes"]
|
||||
assert content == expected[variant["name"]].data, (
|
||||
variant["name"] + " differs from independent white reference"
|
||||
)
|
||||
with Image.open(BytesIO(content)) as image:
|
||||
assert not image.getexif()
|
||||
assert not any(key in image.info for key in ("icc_profile", "xmp", "transparency"))
|
||||
variants.append(
|
||||
{
|
||||
"name": variant["name"],
|
||||
"sha256": hashlib.sha256(content).hexdigest(),
|
||||
"bytes": len(content),
|
||||
"dimensions": [variant["width"], variant["height"]],
|
||||
}
|
||||
)
|
||||
results.append({"version": version, "variants": variants})
|
||||
before = SUITE.snapshot(ident)
|
||||
STACK.publish(SUITE.payload(ident, 1))
|
||||
STACK.publish(SUITE.payload(ident, 2))
|
||||
SUITE.drained()
|
||||
assert SUITE.snapshot(ident) == before
|
||||
assert len(STACK.sql("variants", id=ident)) == 6
|
||||
return {
|
||||
"attachment_id": ident,
|
||||
"input_sha256": hashlib.sha256(data).hexdigest(),
|
||||
"input_bytes": len(data),
|
||||
"versions": results,
|
||||
"stale_and_duplicate_noop": True,
|
||||
}
|
||||
|
||||
|
||||
FIXTURES = ROOT / "build/forward-png"
|
||||
FIXTURES.mkdir(parents=True, exist_ok=True)
|
||||
for fixture_name, fixture_depth, fixture_key in (
|
||||
("gray2", 2, (1,)),
|
||||
("gray4", 4, (5,)),
|
||||
("gray16", 16, (12345,)),
|
||||
("rgb16", 16, (12345, 23456, 34567)),
|
||||
):
|
||||
(FIXTURES / (fixture_name + "-40mp.png")).write_bytes(boundary_png(fixture_depth, fixture_key))
|
||||
ps.SQL["timed_events"] = (
|
||||
"SELECT attachment_id,job_id,kind,at FROM job_events "
|
||||
"WHERE attachment_id = ANY(:'ids'::uuid[]) AND kind IN ('claimed','done') ORDER BY id"
|
||||
)
|
||||
|
||||
|
||||
def without_trns(data):
|
||||
result, offset = data[:8], 8
|
||||
while offset < len(data):
|
||||
size = struct.unpack(">I", data[offset : offset + 4])[0] + 12
|
||||
if data[offset + 4 : offset + 8] != b"tRNS":
|
||||
result += data[offset : offset + size]
|
||||
offset += size
|
||||
return result
|
||||
|
||||
|
||||
def verify_large(ident, data, transparent):
|
||||
assert SUITE.api is not None
|
||||
ready = SUITE.api.wait(ident)
|
||||
SUITE.verify(ready)
|
||||
assert SUITE.api.content(ident)["bytes"] == data
|
||||
variants = []
|
||||
for variant in ready["variants"]:
|
||||
content = SUITE.api.content(ident, variant["name"])["bytes"]
|
||||
with Image.open(BytesIO(content)) as image:
|
||||
left = image.getpixel((5, image.height // 2))
|
||||
right = image.getpixel((image.width - 6, image.height // 2))
|
||||
assert (left == (255, 255, 255)) == transparent
|
||||
assert right != (255, 255, 255)
|
||||
assert not image.getexif()
|
||||
variants.append({**variant, "left_pixel": left, "right_pixel": right})
|
||||
return variants
|
||||
|
||||
|
||||
def duplicate_check(ident):
|
||||
before = SUITE.snapshot(ident)
|
||||
STACK.publish(SUITE.payload(ident, 1))
|
||||
STACK.publish(SUITE.payload(ident, 2))
|
||||
SUITE.drained()
|
||||
assert SUITE.snapshot(ident) == before
|
||||
assert len(STACK.sql("variants", id=ident)) == 6
|
||||
|
||||
|
||||
def large(name, data, transparent=True):
|
||||
assert SUITE.api is not None
|
||||
att = SUITE.api.upload(data, name=name + ".png")
|
||||
ident = att["id"]
|
||||
versions = [{"version": 1, "variants": verify_large(ident, data, transparent)}]
|
||||
STACK.admin("reprocess", "--attachment-id", ident, "--pipeline-version", "2")
|
||||
ps.poll(lambda: SUITE.record(ident)["published_version"] == 2, 90, "v2 publication")
|
||||
versions.append({"version": 2, "variants": verify_large(ident, data, transparent)})
|
||||
duplicate_check(ident)
|
||||
return {
|
||||
"attachment_id": ident,
|
||||
"input_sha256": hashlib.sha256(data).hexdigest(),
|
||||
"bytes": len(data),
|
||||
"versions": versions,
|
||||
"memory_peak": int(STACK.cgroup("worker", "memory.peak")),
|
||||
"memory_max": int(STACK.cgroup("worker", "memory.max")),
|
||||
}
|
||||
|
||||
|
||||
def concurrent():
|
||||
assert SUITE.api is not None
|
||||
data = (FIXTURES / "rgb16-40mp.png").read_bytes()
|
||||
SUITE.drained()
|
||||
STACK.stop("worker")
|
||||
try:
|
||||
ids = [SUITE.api.upload(data, name="concurrent-rgb16.png")["id"] for _ in range(2)]
|
||||
SUITE.queued(2)
|
||||
finally:
|
||||
ps.run(["docker", "start", STACK.dc("ps", "-aq", "worker").strip()])
|
||||
versions = []
|
||||
for version in (1, 2):
|
||||
if version == 2:
|
||||
STACK.stop("worker")
|
||||
try:
|
||||
for ident in ids:
|
||||
STACK.admin("reprocess", "--attachment-id", ident, "--pipeline-version", "2")
|
||||
SUITE.queued(2)
|
||||
finally:
|
||||
ps.run(["docker", "start", STACK.dc("ps", "-aq", "worker").strip()])
|
||||
for ident in ids:
|
||||
ps.poll(
|
||||
lambda ident=ident, version=version: (
|
||||
SUITE.record(ident)["published_version"] == version
|
||||
),
|
||||
90,
|
||||
"concurrent publication",
|
||||
)
|
||||
variants = {ident: verify_large(ident, data, True) for ident in ids}
|
||||
events = STACK.sql("timed_events", ids="{" + ",".join(ids) + "}")
|
||||
job_ids = {
|
||||
row["job_id"]
|
||||
for ident in ids
|
||||
for row in STACK.sql("jobs", id=ident)
|
||||
if row["pipeline_version"] == version
|
||||
}
|
||||
selected = [e for e in events if e["job_id"] in job_ids]
|
||||
claims = [e["at"] for e in selected if e["kind"] == "claimed"]
|
||||
done = [e["at"] for e in selected if e["kind"] == "done"]
|
||||
assert len(claims) == len(done) == 2
|
||||
assert max(claims) < min(done), selected
|
||||
versions.append(
|
||||
{
|
||||
"version": version,
|
||||
"events": selected,
|
||||
"processing_overlapped": True,
|
||||
"variants": variants,
|
||||
}
|
||||
)
|
||||
for ident in ids:
|
||||
duplicate_check(ident)
|
||||
peak, limit = (int(STACK.cgroup("worker", name)) for name in ("memory.peak", "memory.max"))
|
||||
assert peak < limit
|
||||
return {
|
||||
"attachment_ids": ids,
|
||||
"versions": versions,
|
||||
"memory_peak": peak,
|
||||
"memory_max": limit,
|
||||
"memory_events": STACK.cgroup("worker", "memory.events"),
|
||||
}
|
||||
|
||||
|
||||
def forced(**overrides):
|
||||
data = (FIXTURES / "rgb16-40mp.png").read_bytes()
|
||||
result = SUITE.limited(data, **overrides)
|
||||
STACK.restore()
|
||||
result["next_normal"] = SUITE.smoke_pipeline()
|
||||
return result
|
||||
|
||||
|
||||
try:
|
||||
SUITE.detect_api()
|
||||
SUITE.api = ps.Api(SUITE.args)
|
||||
dead_before = STACK.queues()[ps.DLQ][0]
|
||||
REPORT["conditions"] = {
|
||||
"host_load": os.getloadavg(),
|
||||
"containers": containers(),
|
||||
"running": ps.run(["docker", "ps", "--format", "{{.Names}} {{.Status}}"]),
|
||||
"worker_limits": STACK.dc(
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"printenv",
|
||||
"RENDER_MEMORY_MB",
|
||||
"RENDER_TIMEOUT_SECONDS",
|
||||
"WORKER_CONCURRENCY",
|
||||
),
|
||||
}
|
||||
save()
|
||||
if MODE == "postgres-outage":
|
||||
case("published_outbox_database_outage", outage)
|
||||
elif MODE == "png-http":
|
||||
for name, depth, color in [
|
||||
("gray1", 1, (0,)),
|
||||
("gray2", 2, (1,)),
|
||||
("gray4", 4, (5,)),
|
||||
("gray8", 8, (85,)),
|
||||
("gray16", 16, (12345,)),
|
||||
("rgb8", 8, (255, 0, 0)),
|
||||
("rgb16", 16, (12345, 23456, 34567)),
|
||||
]:
|
||||
case(
|
||||
name,
|
||||
lambda name=name, depth=depth, color=color: png(name, *png_with_trns(depth, color)),
|
||||
)
|
||||
case(
|
||||
"rgb16-adam7-filter4-exif6",
|
||||
lambda: png(
|
||||
"adam7",
|
||||
*png_with_trns(
|
||||
16,
|
||||
(12345, 23456, 34567),
|
||||
size=(65, 63),
|
||||
interlace=1,
|
||||
filtering=4,
|
||||
orientation=6,
|
||||
),
|
||||
),
|
||||
)
|
||||
elif MODE == "png-boundary":
|
||||
for name in ("gray2", "gray4", "gray16", "rgb16"):
|
||||
case(
|
||||
name, lambda name=name: large(name, (FIXTURES / (name + "-40mp.png")).read_bytes())
|
||||
)
|
||||
case(
|
||||
"gray16-without-trns",
|
||||
lambda: large(
|
||||
"gray16-opaque", without_trns((FIXTURES / "gray16-40mp.png").read_bytes()), False
|
||||
),
|
||||
)
|
||||
case("concurrent-rgb16", concurrent)
|
||||
case("forced-timeout", lambda: forced(FAULT_RENDER_TIMEOUT_SECONDS="0.01"))
|
||||
case("forced-memory", lambda: forced(FAULT_RENDER_MEMORY_MB="200"))
|
||||
ids = "{" + ",".join(SUITE.api.accepted) + "}"
|
||||
ps.poll(lambda: not STACK.sql("staging_left", ids=ids), 45, "staging sweep")
|
||||
SUITE.drained()
|
||||
REPORT["invariants"] = SUITE.invariants(dead_before)
|
||||
finally:
|
||||
STACK.up("postgres")
|
||||
STACK.restore()
|
||||
REPORT["finished_at"] = ps.now()
|
||||
REPORT["result"] = (
|
||||
"PASS"
|
||||
if REPORT["cases"]
|
||||
and all(x.get("result") == "PASS" for x in REPORT["cases"] + REPORT.get("invariants", []))
|
||||
else "FAIL"
|
||||
)
|
||||
save()
|
||||
raise SystemExit(0 if REPORT["result"] == "PASS" else 1)
|
||||
@@ -0,0 +1,43 @@
|
||||
import http.client
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
status = int(sys.argv[1])
|
||||
path = {502: "/bad", 503: "/none", 504: "/slow"}[status]
|
||||
if status != 503:
|
||||
for _ in range(60):
|
||||
conn = http.client.HTTPConnection("lb", 8080, timeout=2)
|
||||
conn.request("GET", "/health/ready")
|
||||
response = conn.getresponse()
|
||||
response.read()
|
||||
conn.close()
|
||||
if response.status == 200:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("Backend never became ready")
|
||||
else:
|
||||
time.sleep(5)
|
||||
for value in ['a"b', "a\\b", "a\tb", "x" * 200]:
|
||||
conn = http.client.HTTPConnection("lb", 8080, timeout=20)
|
||||
start = time.monotonic()
|
||||
conn.request("GET", path, headers={"X-Request-Id": value})
|
||||
response = conn.getresponse()
|
||||
payload = json.loads(response.read())
|
||||
assert response.status == status, response.status
|
||||
assert response.getheader("X-Request-Id") == value
|
||||
assert payload["error"]["request_id"] == value
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": status,
|
||||
"request_id": value,
|
||||
"json_valid": True,
|
||||
"echo_matches": True,
|
||||
"seconds": round(time.monotonic() - start, 3),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
conn.close()
|
||||
@@ -0,0 +1,25 @@
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b
|
||||
volumes: [../../../infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
|
||||
init: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
api:
|
||||
image: ${API_IMAGE:?Set the image built by the lab6 stack}
|
||||
entrypoint: [python, /fixture/server.py]
|
||||
volumes: [./:/fixture:ro]
|
||||
init: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
probe:
|
||||
image: ${API_IMAGE:?Set the image built by the lab6 stack}
|
||||
entrypoint: [python, /fixture/client.py]
|
||||
volumes: [./:/fixture:ro]
|
||||
profiles: [probe]
|
||||
init: true
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128m}
|
||||
@@ -0,0 +1,20 @@
|
||||
import socketserver
|
||||
import time
|
||||
|
||||
|
||||
class Handler(socketserver.StreamRequestHandler):
|
||||
def handle(self) -> None:
|
||||
request = self.rfile.readline(8192)
|
||||
while self.rfile.readline(8192) not in {b"\r\n", b""}:
|
||||
pass
|
||||
path = request.split(b" ")[1]
|
||||
if path == b"/bad":
|
||||
self.wfile.write(b"NOT-HTTP\r\n\r\n")
|
||||
elif path == b"/slow":
|
||||
time.sleep(12)
|
||||
else:
|
||||
self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
|
||||
|
||||
|
||||
with socketserver.ThreadingTCPServer(("0.0.0.0", 8080), Handler) as server:
|
||||
server.serve_forever()
|
||||
@@ -0,0 +1,139 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from io import BytesIO
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image
|
||||
from sqlalchemy import func, insert, make_url, select
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
from messenger.attachments.config import AttachmentsSettings
|
||||
from messenger.attachments.infrastructure.postgres import AttachmentRow
|
||||
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
|
||||
from messenger.identity.infrastructure.postgres import UserRow
|
||||
from messenger.messaging.infrastructure.postgres import ChatMemberRow
|
||||
from messenger.shared.config import PlatformSettings
|
||||
|
||||
MODELS = (UserRow, ChatMemberRow, AttachmentRow)
|
||||
COLUMNS = (
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"width",
|
||||
"height",
|
||||
"object_key",
|
||||
"status",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
)
|
||||
|
||||
|
||||
def picture() -> bytes:
|
||||
buffer = BytesIO()
|
||||
Image.effect_noise((8, 8), 64).convert("RGB").save(buffer, "PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
async def seed(count: int, concurrency: int) -> dict[str, object]:
|
||||
platform, settings = PlatformSettings(), AttachmentsSettings()
|
||||
body = picture()
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
engine = create_async_engine(
|
||||
make_url(platform.database_url.get_secret_value()).set(drivername="postgresql+asyncpg"),
|
||||
hide_parameters=True,
|
||||
)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
member = (
|
||||
(
|
||||
await connection.execute(
|
||||
select(ChatMemberRow.chat_id, ChatMemberRow.user_id).limit(1)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.first()
|
||||
)
|
||||
if member is None:
|
||||
raise SystemExit("нет ни одного чата: сначала make test")
|
||||
ids = [uuid4() for _ in range(count)]
|
||||
pending = iter(ids)
|
||||
completed = 0
|
||||
started = time.monotonic()
|
||||
async with s3_client(
|
||||
endpoint=settings.s3_endpoint,
|
||||
region=settings.s3_region,
|
||||
access_key_id=settings.s3_access_key_id.get_secret_value(),
|
||||
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
|
||||
connect_timeout=settings.s3_connect_timeout_seconds,
|
||||
read_timeout=settings.s3_read_timeout_seconds,
|
||||
max_attempts=3,
|
||||
) as client:
|
||||
storage = S3ObjectStorage(client, settings.s3_bucket)
|
||||
|
||||
async def worker() -> None:
|
||||
nonlocal completed
|
||||
for attachment_id in pending:
|
||||
await storage.put(f"attachments/{attachment_id}", body, "image/png")
|
||||
completed += 1
|
||||
if completed % 10000 == 0 or completed == count:
|
||||
print(json.dumps({"progress": completed, "target": count}), flush=True)
|
||||
|
||||
await asyncio.gather(*(worker() for _ in range(concurrency)))
|
||||
stored = time.monotonic()
|
||||
stamp = datetime.now(UTC) - timedelta(hours=2)
|
||||
records = [
|
||||
(
|
||||
attachment_id,
|
||||
member["chat_id"],
|
||||
member["user_id"],
|
||||
f"seed-{number}.png",
|
||||
"image/png",
|
||||
len(body),
|
||||
digest,
|
||||
8,
|
||||
8,
|
||||
f"attachments/{attachment_id}",
|
||||
"ready",
|
||||
stamp,
|
||||
stamp,
|
||||
)
|
||||
for number, attachment_id in enumerate(ids)
|
||||
]
|
||||
async with engine.begin() as connection:
|
||||
for start in range(0, count, 1000):
|
||||
await connection.execute(
|
||||
insert(AttachmentRow),
|
||||
[dict(zip(COLUMNS, row, strict=True)) for row in records[start : start + 1000]],
|
||||
)
|
||||
total = await connection.scalar(select(func.count()).select_from(AttachmentRow))
|
||||
finally:
|
||||
await engine.dispose()
|
||||
return {
|
||||
"added": count,
|
||||
"rows_total": total,
|
||||
"object_bytes": len(body),
|
||||
"seconds": {
|
||||
"s3_put": round(stored - started, 3),
|
||||
"pg_insert": round(time.monotonic() - stored, 3),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Наполнить bucket и attachments N вложениями")
|
||||
parser.add_argument("--count", type=int, required=True)
|
||||
parser.add_argument("--concurrency", type=int, default=32)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(asyncio.run(seed(args.count, args.concurrency))))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,96 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments.domain.errors import InvalidFilename, UnsupportedImage
|
||||
from messenger.attachments.domain.events import AttachmentDiscarded, AttachmentQueued
|
||||
from messenger.attachments.domain.models import Attachment, AttachmentStatus
|
||||
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
|
||||
|
||||
MOMENT = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
[
|
||||
*("", " ", "\t\n", "../a.png", "a/b.png", "a\\b.png"),
|
||||
*("a\x00.png", "a\x01.png", "a\x7f.png", "a\n.png", "\x9f.png", "x" * 256),
|
||||
],
|
||||
)
|
||||
def test_filename_rejects_dangerous_and_empty(raw: str) -> None:
|
||||
with pytest.raises(InvalidFilename):
|
||||
Filename(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["sample.png", "фото 1.png", "я" * 255, "👋.jpg", "a..b.png"])
|
||||
def test_filename_keeps_display_names(raw: str) -> None:
|
||||
assert Filename(raw).value == raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("header", "kind"),
|
||||
[
|
||||
("image/png", ImageKind.PNG),
|
||||
("IMAGE/JPEG", ImageKind.JPEG),
|
||||
("image/png; charset=binary", ImageKind.PNG),
|
||||
],
|
||||
)
|
||||
def test_declared_type_ignores_case_and_parameters(header: str, kind: ImageKind) -> None:
|
||||
assert ImageKind.declared(header) is kind
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", [None, "", "image/gif", "application/octet-stream", "image/*"])
|
||||
def test_declared_type_accepts_only_png_and_jpeg(header: str | None) -> None:
|
||||
with pytest.raises(UnsupportedImage):
|
||||
ImageKind.declared(header)
|
||||
|
||||
|
||||
def test_attachment_is_pending_until_queued() -> None:
|
||||
attachment_id = uuid4()
|
||||
attachment = Attachment.stage(
|
||||
attachment_id=attachment_id,
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename=Filename("a.png"),
|
||||
image=ImageInfo(ImageKind.PNG, 2, 3),
|
||||
size_bytes=10,
|
||||
sha256="0" * 64,
|
||||
now=MOMENT,
|
||||
)
|
||||
assert attachment.status is AttachmentStatus.PENDING
|
||||
assert attachment.staging_key == f"staging/{attachment_id}"
|
||||
assert (attachment.original_key, attachment.published_version, attachment.variants) == (
|
||||
None,
|
||||
0,
|
||||
(),
|
||||
)
|
||||
assert attachment.collect_events() == []
|
||||
attachment.enqueue(MOMENT - timedelta(seconds=1))
|
||||
assert attachment.status is AttachmentStatus.QUEUED
|
||||
assert not attachment.ready
|
||||
assert attachment.updated_at == MOMENT
|
||||
events = attachment.collect_events()
|
||||
assert [type(event) for event in events] == [AttachmentQueued]
|
||||
assert attachment.collect_events() == []
|
||||
|
||||
|
||||
def test_discarded_intent_records_its_reason() -> None:
|
||||
attachment = Attachment.stage(
|
||||
attachment_id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename=Filename("a.png"),
|
||||
image=ImageInfo(ImageKind.PNG, 1, 1),
|
||||
size_bytes=1,
|
||||
sha256="0" * 64,
|
||||
now=MOMENT,
|
||||
)
|
||||
attachment.discard("abandoned")
|
||||
(event,) = attachment.collect_events()
|
||||
assert isinstance(event, AttachmentDiscarded)
|
||||
assert (event.attachment_id, event.chat_id, event.reason) == (
|
||||
attachment.id,
|
||||
attachment.chat_id,
|
||||
"abandoned",
|
||||
)
|
||||
@@ -0,0 +1,116 @@
|
||||
import json
|
||||
from base64 import b64encode
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
from starlette.types import Scope
|
||||
|
||||
from messenger.identity.application.queries import VerifyCredentials
|
||||
from messenger.identity.entrypoints.authentication import (
|
||||
BASIC_CHALLENGE,
|
||||
LOGIN_PATH,
|
||||
basic_credentials,
|
||||
bearer_token,
|
||||
challenge_for,
|
||||
guard,
|
||||
)
|
||||
from messenger.shared.application.ports import Logger
|
||||
from messenger.shared.entrypoints.pipeline import RequestPipeline
|
||||
|
||||
NON_ASCII_BASIC = [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]
|
||||
|
||||
|
||||
def encoded(raw: bytes) -> str:
|
||||
return "Basic " + b64encode(raw).decode()
|
||||
|
||||
|
||||
def test_basic_splits_on_first_colon() -> None:
|
||||
assert basic_credentials(encoded(b"alice:pa:ss:word")) == ("alice", "pa:ss:word")
|
||||
|
||||
|
||||
def test_basic_decodes_utf8_password() -> None:
|
||||
assert basic_credentials(encoded("alice:пароль👋".encode())) == ("alice", "пароль👋")
|
||||
|
||||
|
||||
def test_basic_scheme_is_case_insensitive() -> None:
|
||||
assert basic_credentials("bAsIc " + b64encode(b"alice:secret").decode()) == ("alice", "secret")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
[
|
||||
"",
|
||||
"Basic",
|
||||
"Basic ",
|
||||
"Basic !!!not-base64!!!",
|
||||
"Basic YWxpY2U",
|
||||
encoded(b"no-colon-here"),
|
||||
encoded("алиса:пароль".encode()),
|
||||
encoded(b"alice:\xff\xfe"),
|
||||
"Bearer " + b64encode(b"alice:secret").decode(),
|
||||
],
|
||||
)
|
||||
def test_basic_rejects_malformed(raw: str) -> None:
|
||||
assert basic_credentials(raw) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NON_ASCII_BASIC)
|
||||
def test_basic_rejects_non_ascii(raw: bytes) -> None:
|
||||
assert basic_credentials(raw.decode("latin-1")) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NON_ASCII_BASIC)
|
||||
async def test_non_ascii_basic_returns_401_without_credential_lookup(raw: bytes) -> None:
|
||||
verify = AsyncMock(return_value=None)
|
||||
container = SimpleNamespace(get=AsyncMock(return_value=verify))
|
||||
scope: Scope = {
|
||||
"type": "http",
|
||||
"method": "POST",
|
||||
"path": LOGIN_PATH,
|
||||
"headers": [(b"authorization", raw), (b"x-request-id", b"non-ascii-basic")],
|
||||
"app": SimpleNamespace(state=SimpleNamespace(dishka_container=container)),
|
||||
}
|
||||
endpoint, send = AsyncMock(), AsyncMock()
|
||||
pipeline = RequestPipeline(endpoint, Mock(spec=Logger), 1024, 1, guard, "test-instance")
|
||||
await pipeline(scope, AsyncMock(), send)
|
||||
start, body = [call.args[0] for call in send.await_args_list]
|
||||
assert start["status"] == 401
|
||||
headers = dict(start["headers"])
|
||||
assert headers[b"www-authenticate"] == BASIC_CHALLENGE.encode()
|
||||
assert headers[b"x-instance-id"] == b"test-instance"
|
||||
assert headers[b"x-request-id"] == b"non-ascii-basic"
|
||||
assert headers[b"content-type"] == b"application/json"
|
||||
assert json.loads(body["body"]) == {
|
||||
"error": {
|
||||
"code": "unauthorized",
|
||||
"message": "Аутентификация не предоставлена или недействительна",
|
||||
"request_id": "non-ascii-basic",
|
||||
}
|
||||
}
|
||||
container.get.assert_awaited_once_with(VerifyCredentials)
|
||||
verify.assert_not_awaited()
|
||||
endpoint.assert_not_awaited()
|
||||
assert "user" not in scope["state"]
|
||||
assert scope["state"]["actor"] is None
|
||||
|
||||
|
||||
def test_bearer_accepts_token68() -> None:
|
||||
assert bearer_token("Bearer abc-DEF_123.~+/==") == "abc-DEF_123.~+/=="
|
||||
assert bearer_token("bearer token") == "token"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["", "Bearer", "Bearer ", "Bearer a b", "Basic abc", "x" * 40])
|
||||
def test_bearer_rejects_malformed(raw: str) -> None:
|
||||
assert bearer_token(raw) is None
|
||||
|
||||
|
||||
def test_bearer_rejects_oversized_token() -> None:
|
||||
assert bearer_token("Bearer " + "x" * 513) is None
|
||||
|
||||
|
||||
def test_challenge_depends_only_on_path() -> None:
|
||||
assert challenge_for("/api/v1/auth/sessions") == 'Basic realm="messenger", charset="UTF-8"'
|
||||
assert challenge_for("/api/v1/auth/sessions/") == 'Basic realm="messenger", charset="UTF-8"'
|
||||
assert challenge_for("/api/v1/auth/sessions/current") == 'Bearer realm="messenger"'
|
||||
assert challenge_for("/api/v1/users/me") == 'Bearer realm="messenger"'
|
||||
@@ -0,0 +1,56 @@
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.messaging.domain.errors import InvalidPageRequest
|
||||
from messenger.messaging.infrastructure.cursor import SignedCursorCodec
|
||||
|
||||
KEY = (datetime(2026, 5, 17, 12, 30, 45, 123456, tzinfo=UTC), uuid4().int)
|
||||
|
||||
|
||||
def codec(secret: bytes = b"secret-for-tests") -> SignedCursorCodec:
|
||||
return SignedCursorCodec(secret)
|
||||
|
||||
|
||||
def test_roundtrip_preserves_key() -> None:
|
||||
subject = codec()
|
||||
assert subject.decode("messages:a", subject.encode("messages:a", KEY)) == KEY
|
||||
|
||||
|
||||
def test_cursor_is_opaque() -> None:
|
||||
encoded = codec().encode("messages:a", KEY)
|
||||
assert "2026" not in encoded
|
||||
assert str(KEY[1]) not in encoded
|
||||
|
||||
|
||||
def test_cursor_from_another_scope_is_rejected() -> None:
|
||||
subject = codec()
|
||||
encoded = subject.encode("messages:chat-one", KEY)
|
||||
with pytest.raises(InvalidPageRequest):
|
||||
subject.decode("messages:chat-two", encoded)
|
||||
|
||||
|
||||
def test_forged_cursor_is_rejected() -> None:
|
||||
encoded = codec(b"one-secret").encode("messages:a", KEY)
|
||||
with pytest.raises(InvalidPageRequest):
|
||||
codec(b"another-secret").decode("messages:a", encoded)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw",
|
||||
["", "garbage", "1.2.3", "2.1.2.3", "1.notanumber.ff.AAAA", "1.1.zz.AAAA"],
|
||||
)
|
||||
def test_broken_cursor_is_rejected(raw: str) -> None:
|
||||
with pytest.raises(InvalidPageRequest):
|
||||
codec().decode("messages:a", raw)
|
||||
|
||||
|
||||
def test_tampered_payload_is_rejected() -> None:
|
||||
subject = codec()
|
||||
encoded = subject.encode("messages:a", KEY)
|
||||
head, _, signature = encoded.rpartition(".")
|
||||
version, micros, identifier = head.split(".")
|
||||
tampered = f"{version}.{int(micros) + 1}.{identifier}.{signature}"
|
||||
with pytest.raises(InvalidPageRequest):
|
||||
subject.decode("messages:a", tampered)
|
||||
@@ -0,0 +1,178 @@
|
||||
from dataclasses import fields
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from itertools import pairwise
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.identity.domain.errors import InvalidUserData
|
||||
from messenger.identity.domain.models import Session, User, token_digest
|
||||
from messenger.identity.domain.values import DisplayName, Password, Username
|
||||
from messenger.messaging.domain.errors import (
|
||||
IdempotencyConflict,
|
||||
InvalidAttachmentList,
|
||||
InvalidChatData,
|
||||
InvalidMessageText,
|
||||
)
|
||||
from messenger.messaging.domain.models import Chat, Message, Receipt, attachment_list
|
||||
from messenger.messaging.domain.values import MessageText
|
||||
from messenger.shared.infrastructure.clock import MonotonicUtcClock
|
||||
|
||||
MOMENT = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
UUID_TWICE = uuid4()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw", ["ab", "a" * 33, "Alice", "alice-01", "алиса", "", "a b", "alice\n", "alice\r\n"]
|
||||
)
|
||||
def test_username_rejects_invalid(raw: str) -> None:
|
||||
with pytest.raises(InvalidUserData):
|
||||
Username(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["abc", "a_b_9", "a" * 32])
|
||||
def test_username_accepts_valid(raw: str) -> None:
|
||||
assert Username(raw).value == raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["", " ", "\t\n", "x" * 101])
|
||||
def test_display_name_rejects_invalid(raw: str) -> None:
|
||||
with pytest.raises(InvalidUserData):
|
||||
DisplayName(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["", " " * 20, "x" * 11, "x" * 129, "\t" * 12])
|
||||
def test_password_rejects_invalid(raw: str) -> None:
|
||||
with pytest.raises(InvalidUserData):
|
||||
Password(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["x" * 12, "п" * 128, "пароль:с:двоеточием", "👋" * 12])
|
||||
def test_password_counts_code_points(raw: str) -> None:
|
||||
assert Password(raw).value == raw
|
||||
|
||||
|
||||
def test_password_is_not_printed() -> None:
|
||||
assert "секретный-пароль" not in repr(Password("секретный-пароль"))
|
||||
|
||||
|
||||
def test_session_token_is_opaque_and_stored_as_digest() -> None:
|
||||
user_id = uuid4()
|
||||
token, session = Session.issue(user_id=user_id, issued_at=MOMENT, ttl=timedelta(hours=1))
|
||||
assert len(token) >= 43
|
||||
assert str(user_id) not in token
|
||||
assert session.token_hash == token_digest(token)
|
||||
assert len(session.token_hash) == 32
|
||||
assert session.expires_at == MOMENT + timedelta(hours=1)
|
||||
assert token not in repr(session)
|
||||
|
||||
|
||||
def test_session_tokens_are_unique() -> None:
|
||||
tokens = {
|
||||
Session.issue(user_id=uuid4(), issued_at=MOMENT, ttl=timedelta(seconds=1))[0]
|
||||
for _ in range(1000)
|
||||
}
|
||||
assert len(tokens) == 1000
|
||||
|
||||
|
||||
def test_message_text_counts_code_points_not_bytes() -> None:
|
||||
emoji = "👋" * 4000
|
||||
assert len(MessageText(emoji).value) == 4000
|
||||
with pytest.raises(InvalidMessageText):
|
||||
MessageText("👋" * 4001)
|
||||
|
||||
|
||||
def test_message_text_rejects_whitespace() -> None:
|
||||
for raw in (" ", "\n\t "):
|
||||
with pytest.raises(InvalidMessageText):
|
||||
MessageText(raw)
|
||||
assert MessageText("").value == ""
|
||||
|
||||
|
||||
def test_chat_requires_creator_in_members() -> None:
|
||||
members = [uuid4(), uuid4()]
|
||||
with pytest.raises(InvalidChatData):
|
||||
Chat.create(
|
||||
chat_id=uuid4(),
|
||||
title="Чат",
|
||||
member_ids=members,
|
||||
creator_id=uuid4(),
|
||||
created_at=MOMENT,
|
||||
)
|
||||
|
||||
|
||||
def test_chat_rejects_duplicate_members() -> None:
|
||||
same = uuid4()
|
||||
with pytest.raises(InvalidChatData):
|
||||
Chat.create(
|
||||
chat_id=uuid4(),
|
||||
title="Чат",
|
||||
member_ids=[same, same],
|
||||
creator_id=same,
|
||||
created_at=MOMENT,
|
||||
)
|
||||
|
||||
|
||||
def test_chat_rejects_more_than_hundred_members() -> None:
|
||||
members = [uuid4() for _ in range(101)]
|
||||
with pytest.raises(InvalidChatData):
|
||||
Chat.create(
|
||||
chat_id=uuid4(),
|
||||
title="Чат",
|
||||
member_ids=members,
|
||||
creator_id=members[0],
|
||||
created_at=MOMENT,
|
||||
)
|
||||
|
||||
|
||||
def test_empty_text_needs_an_attachment() -> None:
|
||||
ids = (uuid4(), uuid4())
|
||||
with pytest.raises(InvalidMessageText):
|
||||
attachment_list(MessageText(""), ())
|
||||
assert attachment_list(MessageText(""), ids) == ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ids", [[uuid4() for _ in range(11)], [UUID_TWICE, UUID_TWICE]])
|
||||
def test_attachment_list_is_bounded_and_unique(ids: list[UUID]) -> None:
|
||||
with pytest.raises(InvalidAttachmentList):
|
||||
attachment_list(MessageText("x"), ids)
|
||||
|
||||
|
||||
def test_receipt_replays_only_the_same_request() -> None:
|
||||
message = Message(uuid4(), uuid4(), uuid4(), MessageText("раз"), MOMENT)
|
||||
receipt = Receipt("key-1", b"a" * 32, message)
|
||||
assert receipt.replay(b"a" * 32) is message
|
||||
with pytest.raises(IdempotencyConflict):
|
||||
receipt.replay(b"b" * 32)
|
||||
|
||||
|
||||
def test_posted_message_describes_itself() -> None:
|
||||
message = Message(uuid4(), uuid4(), uuid4(), MessageText("пять"), MOMENT)
|
||||
event = message.posted()
|
||||
assert (event.message_id, event.chat_id, event.sender_id) == (
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
)
|
||||
assert (event.text_length, event.created_at, event.name) == (4, MOMENT, "message.posted")
|
||||
|
||||
|
||||
def test_user_registration_emits_event() -> None:
|
||||
user, event = User.register(
|
||||
user_id=uuid4(),
|
||||
username=Username("alice_01"),
|
||||
display_name=DisplayName("Алиса"),
|
||||
password_hash="$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
|
||||
registered_at=MOMENT,
|
||||
)
|
||||
assert event.name == "user.registered"
|
||||
assert {field.name for field in fields(event)} == {"name", "user_id", "registered_at"}
|
||||
assert user.created_at == MOMENT
|
||||
assert "argon2id" not in repr(user)
|
||||
|
||||
|
||||
def test_clock_is_strictly_increasing() -> None:
|
||||
clock = MonotonicUtcClock()
|
||||
stamps = [clock.now() for _ in range(1000)]
|
||||
assert all(later > earlier for earlier, later in pairwise(stamps))
|
||||
assert all(stamp.tzinfo is UTC for stamp in stamps)
|
||||
@@ -0,0 +1,26 @@
|
||||
import json
|
||||
import shlex
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
CONFIG = Path(__file__).resolve().parents[2] / "infra/haproxy/haproxy.cfg"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [502, 503, 504])
|
||||
@pytest.mark.parametrize("request_id", ['a"b', "a\\b", "a\tb", "aÿb", "x" * 200])
|
||||
def test_error_templates_escape_json_without_changing_header(status: int, request_id: str) -> None:
|
||||
line = next(
|
||||
line.strip()
|
||||
for line in CONFIG.read_text().splitlines()
|
||||
if line.strip().startswith(f"http-error status {status} ")
|
||||
)
|
||||
tokens = shlex.split(line)
|
||||
header = tokens[tokens.index("hdr") + 1 : tokens.index("lf-string")]
|
||||
assert header == ["X-Request-Id", "%[var(txn.request_id)]"]
|
||||
template = tokens[tokens.index("lf-string") + 1]
|
||||
escaped = json.dumps(request_id, ensure_ascii=True)[1:-1]
|
||||
rendered = template.replace("%[var(txn.request_id),json(ascii)]", escaped)
|
||||
body = json.loads(rendered)
|
||||
assert body["error"]["request_id"] == request_id
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
@@ -0,0 +1,279 @@
|
||||
import struct
|
||||
import tracemalloc
|
||||
import zlib
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageFile
|
||||
|
||||
from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImage
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.infrastructure import png as png_decoder
|
||||
from messenger.attachments.infrastructure.images import PillowImageInspector
|
||||
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG, JPEG, SAMPLE, chunk, png, png_from_idat
|
||||
|
||||
FORMATS = [(0, d, 1) for d in (1, 2, 4, 8, 16)] + [
|
||||
(color, depth, samples)
|
||||
for color, depths, samples in (
|
||||
(2, (8, 16), 3),
|
||||
(3, (1, 2, 4, 8), 1),
|
||||
(4, (8, 16), 2),
|
||||
(6, (8, 16), 4),
|
||||
)
|
||||
for depth in depths
|
||||
]
|
||||
ADAM7_GRID = (
|
||||
"16462646",
|
||||
"77777777",
|
||||
"56565656",
|
||||
"77777777",
|
||||
"36463646",
|
||||
"77777777",
|
||||
"56565656",
|
||||
"77777777",
|
||||
)
|
||||
PIXEL = zlib.compress(b"\x00\x11\x22\x33")
|
||||
BAD_STREAMS = [
|
||||
pytest.param(b"not a zlib stream", id="invalid-zlib"),
|
||||
pytest.param(PIXEL[:-1], id="truncated-zlib-footer"),
|
||||
pytest.param(PIXEL[:-1] + bytes([PIXEL[-1] ^ 1]), id="bad-adler32"),
|
||||
pytest.param(zlib.compress(b"\x00\x11\x22"), id="short-row"),
|
||||
pytest.param(zlib.compress(b"\x00\x11\x22\x33\x44"), id="long-row"),
|
||||
pytest.param(zlib.compress(b"\x05\x11\x22\x33"), id="invalid-filter"),
|
||||
]
|
||||
|
||||
|
||||
def scanlines(width: int, height: int, bits: int, interlace: int, filtering: int = 0) -> bytes:
|
||||
rows = []
|
||||
for number in range(1, 8) if interlace else (0,):
|
||||
for y in range(height):
|
||||
columns = (
|
||||
sum(int(ADAM7_GRID[y % 8][x % 8]) == number for x in range(width))
|
||||
if interlace
|
||||
else width
|
||||
)
|
||||
if columns:
|
||||
rows.append(bytes([filtering]) + b"\x00" * ((columns * bits + 7) // 8))
|
||||
return b"".join(rows)
|
||||
|
||||
|
||||
async def test_png_with_valid_crc_and_invalid_zlib_is_rejected() -> None:
|
||||
assert len(BROKEN_PNG) == 74
|
||||
with Image.open(BytesIO(BROKEN_PNG)) as image:
|
||||
image.verify()
|
||||
with Image.open(BytesIO(BROKEN_PNG)) as image, pytest.raises(OSError):
|
||||
image.load()
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(BROKEN_PNG, ImageKind.PNG)
|
||||
|
||||
|
||||
async def test_duplicate_ihdr_cannot_disagree_with_pixel_validation() -> None:
|
||||
assert len(DUPLICATE_IHDR_PNG) == 94
|
||||
with Image.open(BytesIO(DUPLICATE_IHDR_PNG)) as image:
|
||||
assert image.size == (2, 2)
|
||||
image.verify()
|
||||
with Image.open(BytesIO(DUPLICATE_IHDR_PNG)) as image, pytest.raises(OSError):
|
||||
image.load()
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(DUPLICATE_IHDR_PNG, ImageKind.PNG)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"header",
|
||||
[
|
||||
(1, 1, 8, 2, 0, 0, 0),
|
||||
(2, 2, 8, 2, 0, 0, 0),
|
||||
(1, 1, 16, 2, 0, 0, 0),
|
||||
(1, 1, 8, 6, 0, 0, 0),
|
||||
(1, 1, 8, 2, 0, 0, 1),
|
||||
(8001, 5000, 8, 2, 0, 0, 0),
|
||||
],
|
||||
ids=["identical", "dimensions", "depth", "color", "interlace", "over-pixel-limit"],
|
||||
)
|
||||
@pytest.mark.parametrize("position", ["before-idat", "between-idat", "after-idat"])
|
||||
async def test_duplicate_headers_are_rejected_before_inflating(
|
||||
header: tuple[int, ...], position: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
data = png_from_idat(PIXEL)
|
||||
duplicate = chunk(b"IHDR", struct.pack(">IIBBBBB", *header))
|
||||
if position == "before-idat":
|
||||
data = data[:33] + duplicate + data[33:]
|
||||
elif position == "after-idat":
|
||||
data = data[:-12] + duplicate + data[-12:]
|
||||
else:
|
||||
data = (
|
||||
data[:33]
|
||||
+ chunk(b"IDAT", PIXEL[:3])
|
||||
+ duplicate
|
||||
+ chunk(b"IDAT", PIXEL[3:])
|
||||
+ data[-12:]
|
||||
)
|
||||
|
||||
def forbidden_inflate(*args: object) -> None:
|
||||
pytest.fail("ambiguous PNG header must be rejected before decompression")
|
||||
|
||||
monkeypatch.setattr(png_decoder.zlib, "decompressobj", forbidden_inflate)
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("damage", ["not-first", "missing", "short", "long"])
|
||||
async def test_ihdr_must_be_first_and_have_exact_length(damage: str) -> None:
|
||||
data = png_from_idat(PIXEL)
|
||||
if damage == "not-first":
|
||||
data = data[:8] + chunk(b"tEXt", b"name\x00value") + data[8:]
|
||||
elif damage == "missing":
|
||||
data = data[:8] + data[33:]
|
||||
else:
|
||||
header = data[16:29]
|
||||
header = header[:-1] if damage == "short" else header + b"\x00"
|
||||
data = data[:8] + chunk(b"IHDR", header) + data[33:]
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", BAD_STREAMS)
|
||||
async def test_corrupt_pixels_are_rejected_even_with_valid_chunk_crc(stream: bytes) -> None:
|
||||
data = png_from_idat(stream, chunk_size=1)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.verify()
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
||||
|
||||
|
||||
async def test_idat_chunks_must_be_consecutive() -> None:
|
||||
data = png_from_idat(PIXEL)
|
||||
data = (
|
||||
data[:33]
|
||||
+ chunk(b"IDAT", PIXEL[:3])
|
||||
+ chunk(b"tEXt", b"name\x00value")
|
||||
+ chunk(b"IDAT", PIXEL[3:])
|
||||
+ data[-12:]
|
||||
)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.verify()
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("padding", [b"\x00" * 131_072, b"unused buffer", zlib.compress(b"")])
|
||||
async def test_unused_idat_trailing_bytes_are_ignored(padding: bytes) -> None:
|
||||
data = png_from_idat(PIXEL + padding, chunk_size=1_000_000)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.load()
|
||||
assert await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG) == ImageInfo(
|
||||
ImageKind.PNG, 1, 1
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("color", "depth", "samples"), FORMATS)
|
||||
@pytest.mark.parametrize(("width", "height"), [(1, 1), (1, 9), (9, 1), (5, 5), (17, 13)])
|
||||
@pytest.mark.parametrize("interlace", [0, 1])
|
||||
async def test_supported_png_formats_match_pillow_decoding(
|
||||
*, color: int, depth: int, samples: int, width: int, height: int, interlace: int
|
||||
) -> None:
|
||||
raw = scanlines(width, height, depth * samples, interlace)
|
||||
data = png_from_idat(
|
||||
zlib.compress(raw),
|
||||
width,
|
||||
height,
|
||||
depth=depth,
|
||||
color=color,
|
||||
interlace=interlace,
|
||||
chunk_size=3,
|
||||
)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.load()
|
||||
assert image.size == (width, height)
|
||||
assert await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG) == ImageInfo(
|
||||
ImageKind.PNG, width, height
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filtering", range(5))
|
||||
@pytest.mark.parametrize("interlace", [0, 1])
|
||||
@pytest.mark.parametrize("block_size", [3, 7, 31])
|
||||
async def test_filters_and_passes_cross_decompression_blocks(
|
||||
filtering: int, interlace: int, block_size: int, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(png_decoder, "BLOCK_BYTES", block_size)
|
||||
raw = scanlines(17, 13, 32, interlace, filtering)
|
||||
data = png_from_idat(zlib.compress(raw), 17, 13, color=6, interlace=interlace)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.load()
|
||||
assert (await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)).width == 17
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interlace", [0, 1])
|
||||
@pytest.mark.parametrize("damage", ["filter", "short", "long"])
|
||||
async def test_corruption_in_later_rows_or_passes(
|
||||
interlace: int, damage: str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(png_decoder, "BLOCK_BYTES", 7)
|
||||
raw = bytearray(scanlines(17, 13, 32, interlace))
|
||||
if damage == "filter":
|
||||
raw[-69] = 255
|
||||
elif damage == "short":
|
||||
raw.pop()
|
||||
else:
|
||||
raw.append(0)
|
||||
data = png_from_idat(zlib.compress(raw), 17, 13, color=6, interlace=interlace, chunk_size=5)
|
||||
with pytest.raises(UnsupportedImage):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(data, ImageKind.PNG)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("width", "height"), [(1_000_000, 1), (1000, 1000)])
|
||||
def test_png_validation_does_not_allocate_pixels_or_whole_rows(
|
||||
width: int, height: int, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
data = png_from_idat(
|
||||
zlib.compress(b"\x00" * ((width * 8 + 1) * height)), width, height, depth=16, color=6
|
||||
)
|
||||
|
||||
def forbidden_load(*args: object, **kwargs: object) -> None:
|
||||
pytest.fail("PNG validation must not allocate a Pillow pixel buffer")
|
||||
|
||||
monkeypatch.setattr(ImageFile.ImageFile, "load", forbidden_load)
|
||||
inspector = PillowImageInspector(40_000_000, 1)
|
||||
tracemalloc.start()
|
||||
try:
|
||||
assert inspector._inspect(data, ImageKind.PNG) == ImageInfo(ImageKind.PNG, width, height)
|
||||
_, peak = tracemalloc.get_traced_memory()
|
||||
finally:
|
||||
tracemalloc.stop()
|
||||
assert peak < 2_000_000
|
||||
|
||||
|
||||
def test_excess_inflated_data_is_rejected_with_bounded_memory() -> None:
|
||||
data = png_from_idat(zlib.compress(b"\x00" * 8_000_000))
|
||||
inspector = PillowImageInspector(40_000_000, 1)
|
||||
tracemalloc.start()
|
||||
try:
|
||||
with pytest.raises(UnsupportedImage):
|
||||
inspector._inspect(data, ImageKind.PNG)
|
||||
_, peak = tracemalloc.get_traced_memory()
|
||||
finally:
|
||||
tracemalloc.stop()
|
||||
assert peak < 2_000_000
|
||||
|
||||
|
||||
async def test_pixel_limit_precedes_pixel_validation(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def forbidden_validation(data: bytes) -> None:
|
||||
pytest.fail("oversized PNG must be rejected before decompression")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"messenger.attachments.infrastructure.images.verify_png_pixels", forbidden_validation
|
||||
)
|
||||
with pytest.raises(PayloadTooLarge):
|
||||
await PillowImageInspector(40_000_000, 1).inspect(
|
||||
png(8001, 5000, rows=False), ImageKind.PNG
|
||||
)
|
||||
|
||||
|
||||
async def test_exact_pixel_limit_and_existing_fixtures_still_work() -> None:
|
||||
inspector = PillowImageInspector(40_000_000, 1)
|
||||
assert await inspector.inspect(png(8000, 5000), ImageKind.PNG) == ImageInfo(
|
||||
ImageKind.PNG, 8000, 5000
|
||||
)
|
||||
assert (await inspector.inspect(SAMPLE, ImageKind.PNG)).kind is ImageKind.PNG
|
||||
assert (await inspector.inspect(JPEG, ImageKind.JPEG)).kind is ImageKind.JPEG
|
||||
@@ -0,0 +1,75 @@
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import (
|
||||
HistogramDataPoint,
|
||||
InMemoryMetricReader,
|
||||
NumberDataPoint,
|
||||
)
|
||||
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from opentelemetry.trace import SpanKind, StatusCode
|
||||
|
||||
from messenger.attachments.domain.jobs import Job
|
||||
from messenger.attachments.infrastructure.telemetry import OtelJobObserver
|
||||
|
||||
|
||||
def job() -> Job:
|
||||
return Job(uuid4(), uuid4(), 1, 2, datetime.now(UTC))
|
||||
|
||||
|
||||
def test_job_observer_counts_by_type_and_outcome_and_marks_the_span() -> None:
|
||||
reader = InMemoryMetricReader()
|
||||
observer = OtelJobObserver(MeterProvider(metric_readers=[reader], shutdown_on_exit=False))
|
||||
exporter = InMemorySpanExporter()
|
||||
provider = TracerProvider(shutdown_on_exit=False)
|
||||
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
||||
tracer = provider.get_tracer("test")
|
||||
done, failed = job(), job()
|
||||
for item, outcome in ((done, "done"), (failed, "failed"), (done, "duplicate_noop")):
|
||||
with tracer.start_as_current_span("process", kind=SpanKind.CONSUMER):
|
||||
observer.observe(item, outcome, 0.3)
|
||||
observer.active(1)
|
||||
data = reader.get_metrics_data()
|
||||
assert data is not None
|
||||
found = {
|
||||
metric.name: metric
|
||||
for resource in data.resource_metrics
|
||||
for scope in resource.scope_metrics
|
||||
for metric in scope.metrics
|
||||
}
|
||||
assert (
|
||||
sum(
|
||||
p.count
|
||||
for p in found["messenger.job.time_to_ready"].data.data_points
|
||||
if isinstance(p, HistogramDataPoint)
|
||||
)
|
||||
== 1
|
||||
)
|
||||
busy = next(iter(found["messenger.worker.busy"].data.data_points))
|
||||
assert isinstance(busy, NumberDataPoint)
|
||||
assert busy.value == 1
|
||||
observer.active(-1)
|
||||
counted = {
|
||||
(point.attributes or {})["outcome"]: point.value
|
||||
for point in found["messenger.jobs.processed"].data.data_points
|
||||
if isinstance(point, NumberDataPoint)
|
||||
}
|
||||
assert counted == {"done": 1, "failed": 1, "duplicate_noop": 1}
|
||||
duration = found["messenger.job.duration"]
|
||||
assert duration.unit == "s"
|
||||
point = next(iter(duration.data.data_points))
|
||||
assert isinstance(point, HistogramDataPoint)
|
||||
assert set(point.attributes or {}) == {"job.type", "outcome"}
|
||||
assert point.explicit_bounds[0] == 0.05
|
||||
assert point.explicit_bounds[-1] == 60.0
|
||||
spans: tuple[ReadableSpan, ...] = exporter.get_finished_spans()
|
||||
assert [span.status.status_code for span in spans] == [
|
||||
StatusCode.UNSET,
|
||||
StatusCode.ERROR,
|
||||
StatusCode.UNSET,
|
||||
]
|
||||
assert (spans[1].attributes or {})["messenger.attachment_id"] == str(failed.attachment_id)
|
||||
assert (spans[1].attributes or {})["messenger.job.attempt"] == 2
|
||||
@@ -0,0 +1,95 @@
|
||||
from base64 import b64encode
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from starlette.types import Scope
|
||||
|
||||
from messenger.identity.application.queries import VerifyCredentials
|
||||
from messenger.identity.domain.errors import InvalidUserData
|
||||
from messenger.identity.domain.values import DisplayName
|
||||
from messenger.identity.entrypoints.authentication import (
|
||||
BASIC_CHALLENGE,
|
||||
LOGIN_PATH,
|
||||
basic_credentials,
|
||||
guard,
|
||||
)
|
||||
from messenger.messaging.application.commands import PostMessage
|
||||
from messenger.messaging.application.handlers import PostMessageHandler
|
||||
from messenger.messaging.application.ports import ChatDirectory, MessageLog, MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import ChatNotFound, InvalidChatData, InvalidMessageText
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
from messenger.shared.entrypoints.pipeline import Rejection
|
||||
|
||||
NUL_TEXTS = ["\x00", "\x00abc", "abc\x00def", "abc\x00"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", NUL_TEXTS)
|
||||
def test_basic_rejects_nul_username(username: str) -> None:
|
||||
raw = b64encode(f"{username}:synthetic-password".encode()).decode()
|
||||
assert basic_credentials(f"Basic {raw}") is None
|
||||
|
||||
|
||||
async def test_nul_username_is_rejected_before_credential_lookup() -> None:
|
||||
verify = AsyncMock(return_value=None)
|
||||
container = SimpleNamespace(get=AsyncMock(return_value=verify))
|
||||
scope: Scope = {
|
||||
"method": "POST",
|
||||
"path": LOGIN_PATH,
|
||||
"headers": [(b"authorization", b"Basic " + b64encode(b"abc\x00def:synthetic-password"))],
|
||||
"app": SimpleNamespace(state=SimpleNamespace(dishka_container=container)),
|
||||
}
|
||||
assert await guard(scope) == Rejection(
|
||||
401, "unauthorized", (("www-authenticate", BASIC_CHALLENGE),)
|
||||
)
|
||||
container.get.assert_awaited_once_with(VerifyCredentials)
|
||||
verify.assert_not_awaited()
|
||||
assert "user" not in scope["state"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
@pytest.mark.parametrize(
|
||||
("kind", "error"),
|
||||
[
|
||||
(DisplayName, InvalidUserData),
|
||||
(ChatTitle, InvalidChatData),
|
||||
(MessageText, InvalidMessageText),
|
||||
],
|
||||
)
|
||||
def test_text_values_reject_nul(
|
||||
kind: type[DisplayName | ChatTitle | MessageText], error: type[DomainError], raw: str
|
||||
) -> None:
|
||||
with pytest.raises(error):
|
||||
kind(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", [DisplayName, ChatTitle, MessageText])
|
||||
def test_text_values_preserve_unicode_and_whitespace(
|
||||
kind: type[DisplayName | ChatTitle | MessageText],
|
||||
) -> None:
|
||||
raw = " Привет\tмир\n👋 "
|
||||
assert kind(raw).value == raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("member", [False, True])
|
||||
async def test_nul_message_checks_access_without_writing(member: bool) -> None:
|
||||
chats = AsyncMock(spec=ChatDirectory)
|
||||
chats.chat_for_member.return_value = Mock() if member else None
|
||||
log = AsyncMock(spec=MessageLog)
|
||||
log.post.return_value = None
|
||||
uow = Mock(spec=MessagingUnitOfWork)
|
||||
clock = Mock(spec=Clock)
|
||||
clock.now.return_value = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
handler = PostMessageHandler(
|
||||
uow, log, chats, clock, Mock(spec=IdGenerator), ttl=timedelta(days=1)
|
||||
)
|
||||
command = PostMessage(uuid4(), uuid4(), "abc\x00def", "same-key", b"fingerprint")
|
||||
with pytest.raises(InvalidMessageText if member else ChatNotFound):
|
||||
await handler(command)
|
||||
chats.chat_for_member.assert_awaited_once_with(command.chat_id, command.sender_id)
|
||||
log.post.assert_not_awaited()
|
||||
uow.record.assert_not_called()
|
||||
@@ -0,0 +1,93 @@
|
||||
import json
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments.domain.jobs import Job, RetryPolicy
|
||||
from messenger.attachments.domain.variants import fit, variant_key
|
||||
from messenger.attachments.entrypoints.schemas import JobMessage
|
||||
from messenger.attachments.infrastructure.jitter import RandomJitter
|
||||
|
||||
SCHEMA = json.loads(
|
||||
(Path(__file__).resolve().parents[2] / "contracts" / "jobs.schema.json").read_text()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("size", "fitted"),
|
||||
[
|
||||
((320, 200), (256, 160)),
|
||||
((300, 200), (256, 170)),
|
||||
((801, 601), (256, 192)),
|
||||
((17, 1000), (4, 256)),
|
||||
((3000, 2), (256, 1)),
|
||||
((2, 3000), (1, 256)),
|
||||
((64, 64), (64, 64)),
|
||||
((256, 100), (256, 100)),
|
||||
((257, 257), (256, 256)),
|
||||
],
|
||||
)
|
||||
def test_thumbnail_fits_the_box_rounding_down(
|
||||
size: tuple[int, int], fitted: tuple[int, int]
|
||||
) -> None:
|
||||
assert fit(*size, 256) == fitted
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("spread", "share"), [(0.0, 0.5), (0.5, 0.75), (0.999, 0.9995)])
|
||||
def test_retry_delay_has_equal_jitter_up_to_the_cap(spread: float, share: float) -> None:
|
||||
policy = RetryPolicy(max_attempts=5, base_seconds=2, cap_seconds=10)
|
||||
delays = [policy.delay(attempt, spread) for attempt in range(1, 6)]
|
||||
ceilings = [2, 4, 8, 10]
|
||||
assert delays[:4] == [timedelta(seconds=ceiling * share) for ceiling in ceilings]
|
||||
assert delays[4] is None
|
||||
assert policy.exhausted(5)
|
||||
assert not policy.exhausted(4)
|
||||
|
||||
|
||||
def test_jitter_spreads_retries_between_half_and_full_delay() -> None:
|
||||
policy, jitter = RetryPolicy(5, 2, 60), RandomJitter()
|
||||
delays = {policy.delay(3, jitter.spread()) for _ in range(200)}
|
||||
assert all(timedelta(seconds=4) <= delay < timedelta(seconds=8) for delay in delays if delay)
|
||||
assert len(delays) > 150
|
||||
|
||||
|
||||
def test_job_message_follows_the_contract_schema() -> None:
|
||||
job = Job(uuid4(), uuid4(), 1, 3, datetime(2026, 9, 1, 12, 0, tzinfo=UTC))
|
||||
payload = job.payload()
|
||||
assert set(SCHEMA["required"]) <= set(payload) <= set(SCHEMA["properties"])
|
||||
assert payload["schema_version"] == SCHEMA["properties"]["schema_version"]["const"]
|
||||
assert payload["type"] == SCHEMA["properties"]["type"]["const"]
|
||||
assert payload["created_at"] == "2026-09-01T12:00:00.000000Z"
|
||||
assert JobMessage.model_validate_json(json.dumps(payload)).job() == job
|
||||
assert job.retried(4).payload()["job_id"] == payload["job_id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("example", SCHEMA["examples"])
|
||||
def test_contract_examples_are_accepted(example: dict[str, object]) -> None:
|
||||
assert JobMessage.model_validate_json(json.dumps(example)).attempt == example["attempt"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
{"schema_version": 2},
|
||||
{"type": "attachment.process.v2"},
|
||||
{"attempt": 0},
|
||||
{"pipeline_version": 0},
|
||||
{"filename": "a.png"},
|
||||
{"traceparent": "01-xyz"},
|
||||
{"created_at": "2026-09-01T12:00:00"},
|
||||
],
|
||||
)
|
||||
def test_messages_off_the_schema_are_rejected(change: dict[str, object]) -> None:
|
||||
message = {**SCHEMA["examples"][0], **change}
|
||||
with pytest.raises(ValueError, match="validation error"):
|
||||
JobMessage.model_validate_json(json.dumps(message))
|
||||
|
||||
|
||||
def test_variant_keys_carry_version_and_content_hash() -> None:
|
||||
attachment = uuid4()
|
||||
key = variant_key(attachment, 2, "thumbnail", "ab" * 32, "jpg")
|
||||
assert key == f"variants/{attachment}/2/thumbnail-{'ab' * 8}.jpg"
|
||||
@@ -0,0 +1,110 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import weakref
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageFile
|
||||
from PIL._util import DeferredError
|
||||
|
||||
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
|
||||
from png_trns_fixtures import boundary_png, png_with_trns
|
||||
|
||||
CASES = [(2, (1,)), (4, (5,)), (16, (12345,)), (16, (12345, 23456, 34567))]
|
||||
LIMITS = RenderLimits(10_485_760, 40_000_000)
|
||||
SAMPLE = Path(__file__).parents[2] / "tests/fixtures/sample.png"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("depth,key", CASES)
|
||||
def test_live_pixel_buffers_are_bounded(
|
||||
monkeypatch: pytest.MonkeyPatch, depth: int, key: tuple[int, ...]
|
||||
) -> None:
|
||||
size = (1025, 769)
|
||||
data, reference = png_with_trns(depth, key, size=size)
|
||||
expected = render_variants(reference, LIMITS)
|
||||
references: dict[int, weakref.ReferenceType[Image.Image]] = {}
|
||||
peak = 0
|
||||
original_new = Image.Image._new
|
||||
original_load = ImageFile.ImageFile.load_prepare
|
||||
|
||||
def record(image: Image.Image) -> None:
|
||||
nonlocal peak
|
||||
references[id(image)] = weakref.ref(image)
|
||||
buffers = {}
|
||||
for ref in references.values():
|
||||
current = ref()
|
||||
if current is None or current._im is None or isinstance(current._im, DeferredError):
|
||||
continue
|
||||
stride = 1 if current.mode in {"1", "L", "P"} else 4
|
||||
if current.mode.startswith("I;16"):
|
||||
stride = 2
|
||||
buffers[id(current.im)] = current.width * current.height * stride
|
||||
peak = max(peak, sum(buffers.values()))
|
||||
|
||||
def allocated(image: Image.Image, core: Image.core.ImagingCore) -> Image.Image:
|
||||
result = original_new(image, core)
|
||||
record(result)
|
||||
return result
|
||||
|
||||
def loaded(image: ImageFile.ImageFile) -> None:
|
||||
original_load(image)
|
||||
record(image)
|
||||
|
||||
monkeypatch.setattr(Image.Image, "_new", allocated)
|
||||
monkeypatch.setattr(ImageFile.ImageFile, "load_prepare", loaded)
|
||||
assert render_variants(data, LIMITS) == expected
|
||||
assert peak < size[0] * size[1] * 8 + 2**20, peak
|
||||
print(json.dumps({"depth": depth, "key": key, "pixel_buffer_peak_bytes": peak}))
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="RLIMIT_AS проверяется в Linux")
|
||||
def test_boundary_pngs_fit_worker_address_space(tmp_path: Path) -> None:
|
||||
script = """
|
||||
import json
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import sys
|
||||
|
||||
import messenger.worker
|
||||
from PIL import Image
|
||||
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
|
||||
|
||||
resource.setrlimit(resource.RLIMIT_AS, (448 << 20, 448 << 20))
|
||||
limits = RenderLimits(10_485_760, 40_000_000)
|
||||
for version in (1, 2):
|
||||
signal.alarm(30)
|
||||
variants = render_variants(Path(sys.argv[1]).read_bytes(), limits, version)
|
||||
signal.alarm(0)
|
||||
assert [(v.name, v.width, v.height) for v in variants] == [
|
||||
("thumbnail", 256, 160), ("crop", 128, 128), ("optimized", 1280, 800)
|
||||
]
|
||||
for variant in variants:
|
||||
with Image.open(BytesIO(variant.data)) as image:
|
||||
assert image.getpixel((5, image.height // 2)) == (255, 255, 255)
|
||||
assert image.getpixel((image.width - 6, image.height // 2)) != (255, 255, 255)
|
||||
assert len(render_variants(Path(sys.argv[2]).read_bytes(), limits)) == 3
|
||||
print(json.dumps({
|
||||
"versions": [1, 2], "max_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||
}))
|
||||
"""
|
||||
for name, (depth, key) in zip(("gray2", "gray4", "gray16", "rgb16"), CASES, strict=True):
|
||||
fixture = tmp_path / f"{name}-40mp.png"
|
||||
fixture.write_bytes(boundary_png(depth, key))
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
script,
|
||||
str(fixture),
|
||||
str(SAMPLE),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=65,
|
||||
check=True,
|
||||
)
|
||||
assert json.loads(result.stdout)["versions"] == [1, 2]
|
||||
print(name, result.stdout.strip())
|
||||
@@ -0,0 +1,67 @@
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from messenger.attachments.domain.values import ImageKind
|
||||
from messenger.attachments.infrastructure.images import (
|
||||
PillowImageInspector,
|
||||
RenderLimits,
|
||||
render_variants,
|
||||
)
|
||||
from png_trns_fixtures import png_with_trns
|
||||
|
||||
LIMITS = RenderLimits(10_485_760, 40_000_000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [1, 2])
|
||||
@pytest.mark.parametrize("depth,transparent", [(2, (1,)), (4, (5,)), (16, (12345, 23456, 34567))])
|
||||
async def test_review_samples_have_white_transparency(
|
||||
version: int, depth: int, transparent: tuple[int, ...]
|
||||
) -> None:
|
||||
data, reference = png_with_trns(depth, transparent)
|
||||
info = await PillowImageInspector(LIMITS.max_pixels, 1).inspect(data, ImageKind.PNG)
|
||||
assert (info.width, info.height) == (64, 64)
|
||||
variants = render_variants(data, LIMITS, version)
|
||||
for variant in variants:
|
||||
with Image.open(BytesIO(variant.data)) as image:
|
||||
assert image.getpixel((5, image.height // 2)) == (255, 255, 255), variant.name
|
||||
assert variants == render_variants(reference, LIMITS, version)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [1, 2])
|
||||
@pytest.mark.parametrize(
|
||||
"depth,key",
|
||||
[(depth, key) for depth in (1, 2, 4) for key in range(1 << depth)]
|
||||
+ [(8, 0), (8, 85), (8, 255), (16, 0), (16, 12345), (16, 65535)],
|
||||
)
|
||||
def test_grayscale_keys_preserve_opaque_neighbors(version: int, depth: int, key: int) -> None:
|
||||
data, reference = png_with_trns(depth, (key,))
|
||||
assert render_variants(data, LIMITS, version) == render_variants(reference, LIMITS, version)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [1, 2])
|
||||
@pytest.mark.parametrize("interlace", [0, 1])
|
||||
@pytest.mark.parametrize("filtering", range(5))
|
||||
@pytest.mark.parametrize("depth,transparent", [(2, (1,)), (4, (5,)), (16, (12345, 23456, 34567))])
|
||||
async def test_png_filters_and_adam7_preserve_exact_samples(
|
||||
version: int, interlace: int, filtering: int, depth: int, transparent: tuple[int, ...]
|
||||
) -> None:
|
||||
data, reference = png_with_trns(
|
||||
depth, transparent, size=(65, 63), interlace=interlace, filtering=filtering
|
||||
)
|
||||
info = await PillowImageInspector(LIMITS.max_pixels, 1).inspect(data, ImageKind.PNG)
|
||||
assert (info.width, info.height) == (65, 63)
|
||||
assert render_variants(data, LIMITS, version) == render_variants(reference, LIMITS, version)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [1, 2])
|
||||
@pytest.mark.parametrize("size", [(1, 1), (1, 9), (9, 1), (65, 63)])
|
||||
@pytest.mark.parametrize("transparent", [(0, 0, 0), (123, 234, 45), (65535, 65535, 65535)])
|
||||
def test_rgb16_small_passes_orientation_and_key_extremes(
|
||||
version: int, size: tuple[int, int], transparent: tuple[int, ...]
|
||||
) -> None:
|
||||
data, reference = png_with_trns(
|
||||
16, transparent, size=size, interlace=1, filtering=4, orientation=6
|
||||
)
|
||||
assert render_variants(data, LIMITS, version) == render_variants(reference, LIMITS, version)
|
||||
@@ -0,0 +1,83 @@
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from starlette.types import Scope
|
||||
|
||||
from fakes import NullLogger, RecordingPublisher
|
||||
from messenger.attachments.application.bus import AttachmentsCommandBus
|
||||
from messenger.attachments.application.commands import UploadAttachment
|
||||
from messenger.attachments.application.handlers import UploadAttachmentHandler, UploadSlots
|
||||
from messenger.attachments.application.ports import (
|
||||
AttachmentRepository,
|
||||
AttachmentsUnitOfWork,
|
||||
ChatMembership,
|
||||
ObjectStorage,
|
||||
)
|
||||
from messenger.attachments.entrypoints.errors import ERROR_CODES
|
||||
from messenger.attachments.entrypoints.http import uploads_router
|
||||
from messenger.attachments.infrastructure.images import PillowImageInspector
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
from messenger.shared.entrypoints.errors import install
|
||||
from messenger.shared.entrypoints.pipeline import RequestPipeline
|
||||
from pictures import BROKEN_PNG, DUPLICATE_IHDR_PNG
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data", [BROKEN_PNG, DUPLICATE_IHDR_PNG], ids=["bad-zlib", "duplicate-ihdr"]
|
||||
)
|
||||
async def test_broken_png_returns_415_before_any_storage_write(data: bytes) -> None:
|
||||
uow = Mock(spec=AttachmentsUnitOfWork)
|
||||
uow.attachments = AsyncMock(spec=AttachmentRepository)
|
||||
uow.transaction.return_value = AsyncMock()
|
||||
uow.collect_new_events.return_value = []
|
||||
storage = AsyncMock(spec=ObjectStorage)
|
||||
membership = AsyncMock(spec=ChatMembership)
|
||||
membership.is_member.return_value = True
|
||||
logger = NullLogger()
|
||||
publisher = RecordingPublisher()
|
||||
handler = UploadAttachmentHandler(
|
||||
uow,
|
||||
membership,
|
||||
PillowImageInspector(40_000_000, 1),
|
||||
storage,
|
||||
clock=Mock(spec=Clock, now=Mock(return_value=datetime(2026, 11, 6, tzinfo=UTC))),
|
||||
ids=Mock(spec=IdGenerator, new_id=Mock(side_effect=uuid4)),
|
||||
limit=10_485_760,
|
||||
slots=UploadSlots(1),
|
||||
logger=logger,
|
||||
)
|
||||
bus = AttachmentsCommandBus({UploadAttachment: handler}, uow, publisher)
|
||||
container = SimpleNamespace(get=AsyncMock(return_value=bus))
|
||||
owner, chat = uuid4(), uuid4()
|
||||
|
||||
async def guard(scope: Scope) -> None:
|
||||
scope["state"].update(actor=owner, dishka_container=container)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(uploads_router)
|
||||
install(app, logger, ERROR_CODES, lambda _: "Bearer", "offline-test")
|
||||
transport = ASGITransport(
|
||||
app=RequestPipeline(app, logger, 10_485_760, 5, guard, "offline-test")
|
||||
)
|
||||
async with AsyncClient(transport=transport, base_url="http://testserver") as http:
|
||||
response = await http.post(
|
||||
f"/api/v1/chats/{chat}/attachments?filename=broken.png",
|
||||
headers={"Content-Type": "image/png", "X-Request-Id": "png-regression"},
|
||||
content=data,
|
||||
)
|
||||
assert response.status_code == 415, response.text
|
||||
assert response.json()["error"]["code"] == "unsupported_media_type"
|
||||
assert response.json()["error"]["request_id"] == "png-regression"
|
||||
assert response.headers["X-Request-Id"] == "png-regression"
|
||||
assert response.headers["X-Instance-Id"] == "offline-test"
|
||||
membership.is_member.assert_awaited_once_with(chat, owner)
|
||||
uow.transaction.assert_not_called()
|
||||
uow.commit.assert_not_called()
|
||||
assert uow.attachments.mock_calls == []
|
||||
assert storage.mock_calls == []
|
||||
assert publisher.events == []
|
||||
@@ -0,0 +1,83 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"grade4_probe", Path(__file__).resolve().parents[2] / "scripts/probe.py"
|
||||
)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
probe = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(probe)
|
||||
ARGS = SimpleNamespace(
|
||||
label="old", command=[], expect="replace", max_failed_ratio=0.01, max_recovery=10
|
||||
)
|
||||
|
||||
|
||||
def result_of(probes: list[tuple]) -> dict:
|
||||
result = probe.summarize(
|
||||
ARGS, probes, [(99, 2), (101, 2)], {"start": 100, "end": 101, "exit": 0, "load_end": 120}, 2
|
||||
)
|
||||
result["k6"] = {"exit": 0, "failed_ratio": 0, "requests": 100, "dropped_iterations": 0}
|
||||
result["history"] = {"exact_match": True, "unique": True}
|
||||
return result
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attempts", "recovery", "passed"),
|
||||
[
|
||||
([(100, 503, 20, "old")], None, False),
|
||||
([(100, 503, 20, "old"), (109, 201, 2000, "new")], 11, False),
|
||||
([(100, 503, 20, "old"), (101, 201, 500, "new")], 1.5, True),
|
||||
([(101, 201, 500, "new")], 0, True),
|
||||
([], 0, False),
|
||||
],
|
||||
)
|
||||
def test_recovery_requires_completed_success(attempts: list, recovery: float, passed: bool) -> None:
|
||||
result = result_of([(99, 201, 1, "old"), *attempts])
|
||||
assert result["probe"]["recovery_s"] == recovery
|
||||
assert probe.verdict(ARGS, result)["write_recovery_ok"] is passed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value", "check"),
|
||||
[("requests", 0, "load_delivered"), ("dropped_iterations", 1, "load_delivered")],
|
||||
)
|
||||
def test_incomplete_load_fails(field: str, value: int, check: str) -> None:
|
||||
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
|
||||
result["k6"][field] = value
|
||||
assert not probe.verdict(ARGS, result)[check]
|
||||
|
||||
|
||||
def test_missing_lb_sample_fails() -> None:
|
||||
result = result_of([(99, 201, 1, "old"), (102, 201, 1, "new")])
|
||||
result["lb_samples_missing"] = 1
|
||||
assert not probe.verdict(ARGS, result)["lb_observed"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("corruption", ["none", "missing", "duplicate", "changed", "http", "cycle"])
|
||||
def test_full_history_matches_confirmed_bodies(
|
||||
monkeypatch: pytest.MonkeyPatch, corruption: str
|
||||
) -> None:
|
||||
messages = [{"id": str(n), "text": "original"} for n in range(101)]
|
||||
stored = list(reversed(messages))
|
||||
if corruption == "missing":
|
||||
stored.pop()
|
||||
if corruption == "duplicate":
|
||||
stored.append(stored[0])
|
||||
if corruption == "changed":
|
||||
stored[0] = dict(stored[0], text="changed")
|
||||
pages = iter(
|
||||
[
|
||||
(200, "", {"items": stored[:100], "next_cursor": "next"}),
|
||||
(
|
||||
503 if corruption == "http" else 200,
|
||||
"",
|
||||
{"items": stored[100:], "next_cursor": "next" if corruption == "cycle" else None},
|
||||
),
|
||||
]
|
||||
)
|
||||
monkeypatch.setattr(probe, "call", lambda *_a, **_kw: next(pages))
|
||||
result = probe.history_check({"auth": {}}, "chat", messages)
|
||||
assert (result["exact_match"] and result["unique"]) is (corruption == "none")
|
||||
@@ -0,0 +1,69 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def track(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
script = Path(__file__).resolve().parents[2] / "scripts/reconcile_track.py"
|
||||
spec = importlib.util.spec_from_file_location("reconcile_measurements", script)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("disturbed", "quiet", "accepted", "discarded"),
|
||||
[
|
||||
([False], True, True, 0),
|
||||
([True, False], True, True, 1),
|
||||
([True, True], True, False, 2),
|
||||
([True], False, False, 1),
|
||||
],
|
||||
)
|
||||
def test_only_clean_measurements_are_accepted(
|
||||
track: ModuleType,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
*,
|
||||
disturbed: list[bool],
|
||||
quiet: bool,
|
||||
accepted: bool,
|
||||
discarded: int,
|
||||
) -> None:
|
||||
reports = [{"cost": {"cpu_seconds": 1}, "attempt": i} for i in range(len(disturbed))]
|
||||
monkeypatch.setattr(track, "sample", lambda: None)
|
||||
monkeypatch.setattr(track, "reconcile", Mock(side_effect=reports))
|
||||
monkeypatch.setattr(track, "screen", Mock(side_effect=[{"disturbed": d} for d in disturbed]))
|
||||
monkeypatch.setattr(track, "wait_quiet", lambda *_: quiet)
|
||||
chosen, rejected = track.measure([], {}, SimpleNamespace(retries=1), set())
|
||||
assert (chosen is not None) == accepted
|
||||
assert len(rejected) == discarded
|
||||
assert all(r["screen"]["disturbed"] for r in rejected)
|
||||
if chosen is not None:
|
||||
assert not chosen["screen"]["disturbed"]
|
||||
assert chosen not in rejected
|
||||
|
||||
|
||||
def test_existing_series_is_preserved_before_docker_access(
|
||||
track: ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
monkeypatch.setenv("RECONCILE_EVIDENCE_DIR", str(tmp_path))
|
||||
folder = tmp_path / "cost"
|
||||
folder.mkdir()
|
||||
raw = folder / "n1000-shallow-1.json"
|
||||
raw.write_text("previous evidence")
|
||||
query = Mock(side_effect=AssertionError("must not access the stand"))
|
||||
monkeypatch.setattr(track, "psql", query)
|
||||
with pytest.raises(FileExistsError):
|
||||
track.cost(SimpleNamespace(sizes=[1000]))
|
||||
assert raw.read_text() == "previous evidence"
|
||||
query.assert_not_called()
|
||||
|
||||
|
||||
def test_quiet_deadline_is_not_success(track: ModuleType, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(track.time, "monotonic", lambda: 10)
|
||||
assert not track.wait_quiet(SimpleNamespace(quiet_timeout=0), set())
|
||||
@@ -0,0 +1,99 @@
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import ImageTooDemanding
|
||||
from messenger.attachments.infrastructure.images import (
|
||||
ProcessVariantRenderer,
|
||||
RenderLimits,
|
||||
render_variants,
|
||||
)
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from pictures import SAMPLE
|
||||
|
||||
LIMITS = RenderLimits(max_bytes=10_485_760, max_pixels=40_000_000)
|
||||
HOG_BYTES = 512 << 20
|
||||
|
||||
|
||||
def misbehaving(data: bytes, limits: RenderLimits, pipeline_version: int) -> list[Rendition]:
|
||||
if data == b"slow":
|
||||
time.sleep(30)
|
||||
if data == b"crash":
|
||||
os._exit(1)
|
||||
if data == b"oom":
|
||||
raise MemoryError
|
||||
if data == b"hog":
|
||||
bytearray(HOG_BYTES)
|
||||
return render_variants(data, limits, pipeline_version)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def renderer() -> AsyncIterator[ProcessVariantRenderer]:
|
||||
pool = ProcessVariantRenderer(
|
||||
LIMITS,
|
||||
concurrency=1,
|
||||
timeout=3.0,
|
||||
memory_bytes=256 << 20,
|
||||
tasks_per_child=10,
|
||||
render=misbehaving,
|
||||
)
|
||||
yield pool
|
||||
pool.close()
|
||||
|
||||
|
||||
async def test_renders_in_a_separate_process(renderer: ProcessVariantRenderer) -> None:
|
||||
assert await renderer.render(SAMPLE, 1) == render_variants(SAMPLE, LIMITS)
|
||||
|
||||
|
||||
async def test_timeout_kills_the_render_and_frees_the_slot(
|
||||
renderer: ProcessVariantRenderer,
|
||||
) -> None:
|
||||
started = time.monotonic()
|
||||
with pytest.raises(ImageTooDemanding):
|
||||
await renderer.render(b"slow", 1)
|
||||
assert time.monotonic() - started < 10
|
||||
assert len(await renderer.render(SAMPLE, 1)) == 3
|
||||
|
||||
|
||||
async def test_crashed_render_process_is_a_transient_error(
|
||||
renderer: ProcessVariantRenderer,
|
||||
) -> None:
|
||||
with pytest.raises(Unavailable):
|
||||
await renderer.render(b"crash", 1)
|
||||
assert len(await renderer.render(SAMPLE, 1)) == 3
|
||||
|
||||
|
||||
async def test_memory_error_is_a_permanent_error(renderer: ProcessVariantRenderer) -> None:
|
||||
with pytest.raises(ImageTooDemanding):
|
||||
await renderer.render(b"oom", 1)
|
||||
assert len(await renderer.render(SAMPLE, 1)) == 3
|
||||
|
||||
|
||||
async def test_cancelled_render_does_not_block_the_slot(renderer: ProcessVariantRenderer) -> None:
|
||||
slow = asyncio.create_task(renderer.render(b"slow", 1))
|
||||
await asyncio.sleep(1)
|
||||
slow.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await slow
|
||||
assert len(await asyncio.wait_for(renderer.render(SAMPLE, 1), 10)) == 3
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="RLIMIT_AS применяется только в Linux")
|
||||
async def test_address_space_limit_applies_to_the_render_process(
|
||||
renderer: ProcessVariantRenderer,
|
||||
) -> None:
|
||||
with pytest.raises(ImageTooDemanding):
|
||||
await renderer.render(b"hog", 1)
|
||||
|
||||
|
||||
async def test_process_uses_the_requested_recipe(renderer: ProcessVariantRenderer) -> None:
|
||||
first = await renderer.render(SAMPLE, 1)
|
||||
second = await renderer.render(SAMPLE, 2)
|
||||
assert second == render_variants(SAMPLE, LIMITS, 2)
|
||||
assert first != second
|
||||
assert await renderer.render(SAMPLE, 2) == second
|
||||
@@ -0,0 +1,162 @@
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import ImageTooDemanding, UnreadableImage
|
||||
from messenger.attachments.domain.values import ImageKind
|
||||
from messenger.attachments.infrastructure.images import (
|
||||
PillowImageInspector,
|
||||
RenderLimits,
|
||||
render_variants,
|
||||
)
|
||||
from pictures import SAMPLE
|
||||
|
||||
LIMITS = RenderLimits(max_bytes=10_485_760, max_pixels=40_000_000)
|
||||
FORMATS = {
|
||||
"thumbnail": ("image/jpeg", "jpg", "JPEG"),
|
||||
"crop": ("image/jpeg", "jpg", "JPEG"),
|
||||
"optimized": ("image/webp", "webp", "WEBP"),
|
||||
}
|
||||
|
||||
|
||||
def encoded(image: Image.Image, kind: str = "PNG", **options: object) -> bytes:
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, kind, **options)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def rendered(data: bytes, version: int = 1) -> dict[str, Image.Image]:
|
||||
renditions: list[Rendition] = render_variants(data, LIMITS, version)
|
||||
assert [rendition.name for rendition in renditions] == ["thumbnail", "crop", "optimized"]
|
||||
images = {}
|
||||
for rendition in renditions:
|
||||
content_type, extension, kind = FORMATS[rendition.name]
|
||||
assert (rendition.content_type, rendition.extension) == (content_type, extension)
|
||||
image = Image.open(BytesIO(rendition.data))
|
||||
assert image.format == kind
|
||||
assert image.size == (rendition.width, rendition.height)
|
||||
assert not image.getexif()
|
||||
assert not {"icc_profile", "exif", "xmp"} & set(image.info)
|
||||
images[rendition.name] = image
|
||||
return images
|
||||
|
||||
|
||||
def sizes(data: bytes) -> tuple[tuple[int, int], ...]:
|
||||
images = rendered(data)
|
||||
return tuple(images[name].size for name in ("thumbnail", "crop", "optimized"))
|
||||
|
||||
|
||||
def test_fixture_gives_three_variants() -> None:
|
||||
assert sizes(SAMPLE) == ((256, 160), (128, 128), (320, 200))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "size", "thumbnail", "optimized"),
|
||||
[
|
||||
("L", (17, 1000), (4, 256), (17, 1000)),
|
||||
("RGB", (64, 64), (64, 64), (64, 64)),
|
||||
("RGB", (3000, 2), (256, 1), (1280, 1)),
|
||||
("I;16", (300, 200), (256, 170), (300, 200)),
|
||||
("CMYK", (801, 601), (256, 192), (801, 601)),
|
||||
("RGB", (4000, 3000), (256, 192), (1280, 960)),
|
||||
],
|
||||
)
|
||||
def test_sizes_round_down_never_upscale_and_crop_is_square(
|
||||
mode: str, size: tuple[int, int], thumbnail: tuple[int, int], optimized: tuple[int, int]
|
||||
) -> None:
|
||||
kind = "JPEG" if mode == "CMYK" or size == (4000, 3000) else "PNG"
|
||||
assert sizes(encoded(Image.new(mode, size), kind)) == (thumbnail, (128, 128), optimized)
|
||||
|
||||
|
||||
def test_crop_takes_the_centre() -> None:
|
||||
image = Image.new("RGB", (300, 100), (255, 0, 0))
|
||||
image.paste((0, 0, 255), (100, 0, 200, 100))
|
||||
crop = rendered(encoded(image))["crop"].convert("RGB")
|
||||
pixels = [crop.getpixel((x, 64)) for x in (2, 64, 125)]
|
||||
assert all(isinstance(p, tuple) and p[0] < 60 and p[2] > 200 for p in pixels)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["RGBA", "LA"])
|
||||
def test_transparency_is_composed_on_white(mode: str) -> None:
|
||||
transparent = Image.new(mode, (300, 300), (0,) * len(mode))
|
||||
for image in rendered(encoded(transparent)).values():
|
||||
assert image.convert("RGB").getpixel((5, 5)) == (255, 255, 255)
|
||||
|
||||
|
||||
def test_palette_transparency_is_composed_on_white() -> None:
|
||||
palette = Image.new("P", (200, 100))
|
||||
image = rendered(encoded(palette, transparency=0))["thumbnail"]
|
||||
assert image.size == (200, 100)
|
||||
assert image.convert("RGB").getpixel((5, 5)) == (255, 255, 255)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [1, 2])
|
||||
@pytest.mark.parametrize(
|
||||
("mode", "transparent", "opaque", "expected"),
|
||||
[
|
||||
("RGB", (255, 0, 0), (32, 96, 160), (32, 96, 160)),
|
||||
("L", 0, 96, (96, 96, 96)),
|
||||
("1", 0, 255, (255, 255, 255)),
|
||||
("1", 255, 0, (0, 0, 0)),
|
||||
("I;16", 12345, 12346, (48, 48, 48)),
|
||||
],
|
||||
)
|
||||
async def test_png_trns_is_white_without_changing_opaque_pixels(
|
||||
version: int,
|
||||
mode: str,
|
||||
transparent: int | tuple[int, int, int],
|
||||
opaque: int | tuple[int, int, int],
|
||||
expected: tuple[int, int, int],
|
||||
) -> None:
|
||||
source = Image.new(mode, (64, 64), transparent)
|
||||
source.paste(Image.new(mode, (32, 64), opaque), (32, 0))
|
||||
assert source.getpixel((58, 32)) == opaque
|
||||
data = encoded(source, transparency=transparent)
|
||||
info = await PillowImageInspector(LIMITS.max_pixels, 1).inspect(data, ImageKind.PNG)
|
||||
assert (info.width, info.height) == (64, 64)
|
||||
for image in rendered(data, version).values():
|
||||
assert image.getpixel((5, image.height // 2)) == (255, 255, 255)
|
||||
pixel = image.getpixel((image.width - 6, image.height // 2))
|
||||
assert isinstance(pixel, tuple)
|
||||
assert all(abs(a - b) <= 3 for a, b in zip(pixel, expected, strict=True))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("orientation", "thumbnail", "optimized"),
|
||||
[(6, (128, 256), (200, 400)), (3, (256, 128), (400, 200))],
|
||||
)
|
||||
def test_exif_orientation_is_applied_before_sizing(
|
||||
orientation: int, thumbnail: tuple[int, int], optimized: tuple[int, int]
|
||||
) -> None:
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = orientation
|
||||
data = encoded(
|
||||
Image.new("RGB", (400, 200), (10, 200, 10)), "JPEG", exif=exif, icc_profile=b"x" * 64
|
||||
)
|
||||
assert sizes(data) == (thumbnail, (128, 128), optimized)
|
||||
|
||||
|
||||
def test_same_bytes_give_same_variants() -> None:
|
||||
assert render_variants(SAMPLE, LIMITS) == render_variants(SAMPLE, LIMITS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data",
|
||||
[b"", b"garbage", SAMPLE[: len(SAMPLE) // 2], b"GIF89a" + bytes(20)],
|
||||
ids=["empty", "garbage", "truncated", "gif"],
|
||||
)
|
||||
def test_undecodable_data_is_a_permanent_error(data: bytes) -> None:
|
||||
with pytest.raises(UnreadableImage):
|
||||
render_variants(data, LIMITS)
|
||||
|
||||
|
||||
def test_pixel_limit_is_checked_before_decoding() -> None:
|
||||
with pytest.raises(UnreadableImage):
|
||||
render_variants(SAMPLE, RenderLimits(LIMITS.max_bytes, 320 * 200 - 1))
|
||||
|
||||
|
||||
def test_byte_limit_is_checked_before_decoding() -> None:
|
||||
with pytest.raises(ImageTooDemanding):
|
||||
render_variants(SAMPLE, RenderLimits(len(SAMPLE) - 1, LIMITS.max_pixels))
|
||||
@@ -0,0 +1,80 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def scaling(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
scripts = Path(__file__).resolve().parents[2] / "scripts"
|
||||
monkeypatch.syspath_prepend(str(scripts))
|
||||
spec = importlib.util.spec_from_file_location("scaling", scripts / "scaling.py")
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_retry_preserves_previous_raw_data(scaling: ModuleType, tmp_path: Path) -> None:
|
||||
base = {"variant": "base", "config": "1x1"}
|
||||
first = scaling.attempt_folder(tmp_path, base, 100, 1)
|
||||
(first / "k6.txt").write_text("failed attempt")
|
||||
second = scaling.attempt_folder(tmp_path, base, 100, 1)
|
||||
assert first != second
|
||||
assert (first / "k6.txt").read_text() == "failed attempt"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("recover", [False, True])
|
||||
def test_disturbed_runs_never_enter_summary(
|
||||
scaling: ModuleType, monkeypatch: pytest.MonkeyPatch, recover: bool
|
||||
) -> None:
|
||||
args = SimpleNamespace(
|
||||
base_env={}, out="unused", retries=1, pause=0, rates="100", rejected=Mock()
|
||||
)
|
||||
rejected = {"raw_dir": "attempt1", "disturbed": True, "saturated": False}
|
||||
accepted = {"raw_dir": "attempt2", "disturbed": False, "saturated": False}
|
||||
monkeypatch.setattr(scaling, "layout", lambda *_: ({}, {}))
|
||||
monkeypatch.setattr(scaling, "apply", lambda *_: {})
|
||||
monkeypatch.setattr(scaling, "deployment", lambda *_: [])
|
||||
monkeypatch.setattr(scaling, "wait_quiet", lambda *_: None)
|
||||
monkeypatch.setattr(
|
||||
scaling, "step", Mock(side_effect=[rejected, accepted if recover else rejected])
|
||||
)
|
||||
output = Mock()
|
||||
if recover:
|
||||
scaling.block(args, output, "1x1", "base", [1])
|
||||
output.writerows.assert_called_once_with([accepted])
|
||||
args.rejected.writerow.assert_called_once_with(rejected)
|
||||
else:
|
||||
with pytest.raises(SystemExit, match="exhausted retries"):
|
||||
scaling.block(args, output, "1x1", "base", [1])
|
||||
output.writerows.assert_not_called()
|
||||
assert args.rejected.writerow.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fixed", "expected"),
|
||||
[
|
||||
(True, [("4x1", [2]), ("8x0.5", [2]), ("4x1", [3]), ("8x0.5", [3])]),
|
||||
(False, [("4x1", [2, 3]), ("8x0.5", [2, 3])]),
|
||||
],
|
||||
)
|
||||
def test_series_order(
|
||||
scaling: ModuleType,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
fixed: bool,
|
||||
expected: list[tuple[str, list[int]]],
|
||||
) -> None:
|
||||
args = SimpleNamespace(
|
||||
first_repeat=2,
|
||||
repeats=2,
|
||||
configs="4x1,8x0.5",
|
||||
variants=["pinned"],
|
||||
rates="3040,4560" if fixed else None,
|
||||
)
|
||||
block = Mock()
|
||||
monkeypatch.setattr(scaling, "block", block)
|
||||
scaling.series(args, Mock())
|
||||
assert [(call.args[2], list(call.args[4])) for call in block.call_args_list] == expected
|
||||
@@ -0,0 +1,161 @@
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import cast
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import ConnectionError as CacheConnectionError
|
||||
|
||||
from fakes import NullLogger
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.identity.infrastructure.valkey import (
|
||||
FILL,
|
||||
REVOKE,
|
||||
REVOKED,
|
||||
CachedSessionDirectory,
|
||||
key_of,
|
||||
milliseconds,
|
||||
)
|
||||
|
||||
NOW = datetime(2030, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
class CacheModel:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
self.expires: dict[str, int] = {}
|
||||
|
||||
async def get(self, key: str) -> str | None:
|
||||
return self.values.get(key)
|
||||
|
||||
async def set(self, key: str, value: str, *, pxat: int, nx: bool = False) -> bool:
|
||||
if nx and key in self.values:
|
||||
return False
|
||||
self.values[key], self.expires[key] = value, pxat
|
||||
return True
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
self.values.pop(key, None)
|
||||
self.expires.pop(key, None)
|
||||
|
||||
async def eval(self, script: str, count: int, key: str, marker: str, *args: str | int) -> bool:
|
||||
assert count == 2
|
||||
if script == REVOKE:
|
||||
value, until = args
|
||||
assert isinstance(value, str) and isinstance(until, int)
|
||||
await self.set(key, value, pxat=until)
|
||||
await self.delete(marker)
|
||||
return True
|
||||
assert script == FILL
|
||||
nonce, value, until = args
|
||||
assert isinstance(value, str) and isinstance(until, int)
|
||||
if await self.get(marker) != nonce:
|
||||
return False
|
||||
await self.delete(marker)
|
||||
return bool(value) and await self.set(key, value, pxat=until, nx=True)
|
||||
|
||||
|
||||
def directory(origin: AsyncMock, cache: CacheModel, ttl: int = 300) -> CachedSessionDirectory:
|
||||
return CachedSessionDirectory(
|
||||
origin, cast(Redis, cache), NullLogger(), limit=timedelta(seconds=ttl), cooldown=1
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session() -> Session:
|
||||
return Session.issue(user_id=uuid4(), issued_at=NOW, ttl=timedelta(seconds=30))[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ttl", [10, 300])
|
||||
async def test_cache_hit_keeps_absolute_ttl_without_reading_origin(
|
||||
session: Session, ttl: int
|
||||
) -> None:
|
||||
origin, cache = AsyncMock(), CacheModel()
|
||||
origin.find.return_value = session
|
||||
cached = directory(origin, cache, ttl)
|
||||
assert await cached.find(session.token_hash, NOW) == session
|
||||
assert await directory(origin, cache, ttl).find(session.token_hash, NOW) == session
|
||||
origin.find.assert_awaited_once()
|
||||
assert cache.expires == {
|
||||
key_of(session.token_hash): milliseconds(
|
||||
min(session.expires_at, NOW + timedelta(seconds=ttl))
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
|
||||
async def test_delayed_fill_cannot_revive_logged_out_session(session: Session, loss: str) -> None:
|
||||
origin, cache = AsyncMock(), CacheModel()
|
||||
origin.find.return_value = session
|
||||
entered, released = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def stale_find(token_hash: bytes, now: datetime) -> Session:
|
||||
entered.set()
|
||||
await released.wait()
|
||||
return session
|
||||
|
||||
slow = AsyncMock()
|
||||
slow.find.side_effect = stale_find
|
||||
async with asyncio.TaskGroup() as group:
|
||||
reader = group.create_task(directory(slow, cache).find(session.token_hash, NOW))
|
||||
await asyncio.wait_for(entered.wait(), 1)
|
||||
try:
|
||||
await directory(origin, cache).revoke(session)
|
||||
origin.find.return_value = None
|
||||
key = key_of(session.token_hash)
|
||||
if loss == "flushall":
|
||||
cache.values.clear()
|
||||
elif loss in {"evict", "replacement"}:
|
||||
await cache.delete(key)
|
||||
if loss == "replacement":
|
||||
await cache.set(f"{key}:fill", uuid4().hex, pxat=milliseconds(session.expires_at))
|
||||
finally:
|
||||
released.set()
|
||||
assert reader.result() == session
|
||||
assert await directory(origin, cache).find(session.token_hash, NOW) is None
|
||||
assert await cache.get(key) in {None, REVOKED}
|
||||
|
||||
|
||||
async def test_failed_reservation_never_fills_from_stale_database_result(session: Session) -> None:
|
||||
cache = CacheModel()
|
||||
origin = AsyncMock()
|
||||
key = key_of(session.token_hash)
|
||||
await cache.set(f"{key}:fill", "another-reader", pxat=milliseconds(session.expires_at))
|
||||
|
||||
async def find(token_hash: bytes, now: datetime) -> Session:
|
||||
cache.values.clear()
|
||||
return session
|
||||
|
||||
origin.find.side_effect = find
|
||||
assert await directory(origin, cache).find(session.token_hash, NOW) == session
|
||||
assert await cache.get(key) is None
|
||||
|
||||
|
||||
async def test_missing_session_releases_only_its_own_reservation(session: Session) -> None:
|
||||
origin, cache = AsyncMock(), CacheModel()
|
||||
origin.find.return_value = None
|
||||
assert await directory(origin, cache).find(session.token_hash, NOW) is None
|
||||
assert cache.values == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failed_operation", ["get", "set"])
|
||||
async def test_cache_recovery_during_database_read_does_not_allow_unreserved_fill(
|
||||
session: Session, failed_operation: str
|
||||
) -> None:
|
||||
origin, cache = AsyncMock(), AsyncMock()
|
||||
cache.get.return_value = None
|
||||
getattr(cache, failed_operation).side_effect = CacheConnectionError("offline")
|
||||
cached = CachedSessionDirectory(
|
||||
origin, cache, NullLogger(), limit=timedelta(seconds=300), cooldown=1
|
||||
)
|
||||
|
||||
async def find(token_hash: bytes, now: datetime) -> Session:
|
||||
cached._resume_at = 0.0
|
||||
return session
|
||||
|
||||
origin.find.side_effect = find
|
||||
assert await cached.find(session.token_hash, NOW) == session
|
||||
assert cache.set.await_count == (failed_operation == "set")
|
||||
cache.eval.assert_not_awaited()
|
||||
@@ -0,0 +1,115 @@
|
||||
import json
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from opentelemetry import context, trace
|
||||
from opentelemetry.sdk._logs import LoggerProvider
|
||||
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from opentelemetry.sdk.trace.sampling import Decision, ParentBased
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from fakes import NullLogger
|
||||
from messenger.messaging.domain.events import MessagePosted
|
||||
from messenger.shared.application.messagebus import EventBus
|
||||
from messenger.shared.config import PlatformSettings
|
||||
from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLogger
|
||||
from messenger.shared.infrastructure.telemetry import OtlpLogHandler, ServerRoots, start_telemetry
|
||||
|
||||
UNUSED_DSN = "postgresql://unused@127.0.0.1:1/unused"
|
||||
|
||||
|
||||
def traced() -> tuple[trace.Tracer, InMemorySpanExporter]:
|
||||
exporter = InMemorySpanExporter()
|
||||
provider = TracerProvider(shutdown_on_exit=False)
|
||||
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
||||
return provider.get_tracer("test"), exporter
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"switches",
|
||||
[{"otel_sdk_disabled": True, "otel_exporter_otlp_endpoint": "http://otel-collector:4318"}, {}],
|
||||
)
|
||||
def test_disabled_or_unaddressed_sdk_starts_nothing(switches: dict[str, Any]) -> None:
|
||||
settings = PlatformSettings.model_validate({"database_url": UNUSED_DSN, **switches})
|
||||
assert start_telemetry(settings, PLATFORM_FIELDS, "messenger-api") is None
|
||||
assert not isinstance(trace.get_tracer_provider(), TracerProvider)
|
||||
|
||||
|
||||
def test_only_server_side_spans_open_a_trace() -> None:
|
||||
sampler = ParentBased(ServerRoots())
|
||||
roots = {kind: sampler.should_sample(None, 1, "root", kind).decision for kind in SpanKind}
|
||||
assert roots == {
|
||||
SpanKind.SERVER: Decision.RECORD_AND_SAMPLE,
|
||||
SpanKind.CONSUMER: Decision.RECORD_AND_SAMPLE,
|
||||
SpanKind.PRODUCER: Decision.RECORD_AND_SAMPLE,
|
||||
SpanKind.CLIENT: Decision.DROP,
|
||||
SpanKind.INTERNAL: Decision.DROP,
|
||||
}
|
||||
tracer, _ = traced()
|
||||
with tracer.start_as_current_span("POST /api/v1/users", kind=SpanKind.SERVER):
|
||||
child = sampler.should_sample(context.get_current(), 1, "SELECT", SpanKind.CLIENT)
|
||||
assert child.decision is Decision.RECORD_AND_SAMPLE
|
||||
|
||||
|
||||
def test_log_record_carries_the_span_and_only_allowed_fields(
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
exporter = InMemoryLogRecordExporter()
|
||||
provider = LoggerProvider(shutdown_on_exit=False)
|
||||
provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))
|
||||
logger = StructlogLogger(level="INFO", allowed_fields=PLATFORM_FIELDS)
|
||||
handler = OtlpLogHandler(provider.get_logger("test"), PLATFORM_FIELDS)
|
||||
logging.getLogger().addHandler(handler)
|
||||
tracer, _ = traced()
|
||||
try:
|
||||
with tracer.start_as_current_span("request", kind=SpanKind.SERVER) as span:
|
||||
logger.info("request.handled", request_id="r-1", route="/x", password="hunter2")
|
||||
logger.info("service.started")
|
||||
finally:
|
||||
logging.getLogger().removeHandler(handler)
|
||||
expected = span.get_span_context()
|
||||
request, started = (item.log_record for item in exporter.get_finished_logs())
|
||||
assert request.body == "request.handled"
|
||||
assert request.severity_text == "INFO"
|
||||
assert (request.trace_id, request.span_id) == (expected.trace_id, expected.span_id)
|
||||
assert dict(request.attributes or {}) == {
|
||||
"request_id": "r-1",
|
||||
"route": "/x",
|
||||
"event": "request.handled",
|
||||
}
|
||||
assert started.body == "service.started"
|
||||
assert started.trace_id == 0
|
||||
line = json.loads(capsys.readouterr().out.splitlines()[0])
|
||||
assert line["trace_id"] == trace.format_trace_id(expected.trace_id)
|
||||
assert line["span_id"] == trace.format_span_id(expected.span_id)
|
||||
assert "password" not in line
|
||||
|
||||
|
||||
async def test_deferred_subscriber_runs_in_the_context_of_the_event() -> None:
|
||||
bus = EventBus(NullLogger())
|
||||
seen: list[int] = []
|
||||
|
||||
async def remember(_event: MessagePosted) -> None:
|
||||
seen.append(trace.get_current_span().get_span_context().trace_id)
|
||||
|
||||
bus.subscribe(MessagePosted, remember)
|
||||
bus.start()
|
||||
tracer, _ = traced()
|
||||
event = MessagePosted(
|
||||
message_id=uuid4(),
|
||||
chat_id=uuid4(),
|
||||
sender_id=uuid4(),
|
||||
text_length=1,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
with tracer.start_as_current_span("request", kind=SpanKind.SERVER) as span:
|
||||
await bus.emit(event)
|
||||
await bus.emit(event)
|
||||
await bus.stop()
|
||||
assert seen == [span.get_span_context().trace_id, 0]
|
||||
@@ -0,0 +1,61 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from messenger.shared.infrastructure.postgres import PING_TIMEOUT_SECONDS
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
DEFAULT = re.compile(r"\$\{\w+:?-([^}]*)\}")
|
||||
UNITS = {"ms": 0.001, "s": 1.0, "": 1.0}
|
||||
|
||||
|
||||
def seconds(value: object) -> float:
|
||||
found = re.fullmatch(r"([\d.]+)(ms|s|)", str(value))
|
||||
assert found is not None, value
|
||||
return float(found[1]) * UNITS[found[2]]
|
||||
|
||||
|
||||
def services() -> dict[str, Any]:
|
||||
return yaml.safe_load(DEFAULT.sub(r"\1", (ROOT / "compose.yaml").read_text()))["services"]
|
||||
|
||||
|
||||
def balancer() -> dict[str, float]:
|
||||
text = (ROOT / "infra/haproxy/haproxy.cfg").read_text()
|
||||
found = {
|
||||
f"timeout {name}": seconds(value)
|
||||
for name, value in re.findall(r"timeout ([\w-]+) (\S+)\n", text)
|
||||
}
|
||||
found["hard-stop-after"] = seconds(re.findall(r"hard-stop-after (\S+)", text)[0])
|
||||
check = re.findall(r"default-server .*", text)[0]
|
||||
for key in ("inter", "fastinter", "fall", "rise"):
|
||||
found[key] = seconds(re.findall(rf"\b{key} (\S+)", check)[0])
|
||||
return found
|
||||
|
||||
|
||||
def test_timeouts_shrink_inwards_and_shutdown_fits_the_stop_budget() -> None:
|
||||
lb, stand = balancer(), services()
|
||||
api = {k: seconds(v) for k, v in stand["api"]["environment"].items() if k.endswith("SECONDS")}
|
||||
hook = seconds(
|
||||
re.findall(r"STOP_TIMEOUT:-(\d+)", (ROOT / "scripts/stop-one.sh").read_text())[0]
|
||||
)
|
||||
grace = seconds(stand["api"]["stop_grace_period"])
|
||||
detection = lb["inter"] + (lb["fall"] - 1) * lb["fastinter"]
|
||||
hung = detection + lb["fall"] * lb["timeout check"]
|
||||
database = api["DB_ACQUIRE_TIMEOUT_SECONDS"] + api["DB_COMMAND_TIMEOUT_SECONDS"]
|
||||
drain, shutdown = api["DRAIN_SECONDS"], api["SHUTDOWN_TIMEOUT_SECONDS"]
|
||||
print(
|
||||
f"обнаружение {detection} с (зависание {hung} с), окно {drain} с,"
|
||||
f" дообработка {shutdown - drain - 1} с, остановка {shutdown} с, хук {hook} с,"
|
||||
f" stop_grace_period {grace} с; LB server {lb['timeout server']} с >"
|
||||
f" запрос {api['REQUEST_TIMEOUT_SECONDS']} с > БД {database} с;"
|
||||
f" readiness {2 * PING_TIMEOUT_SECONDS} с < check {lb['timeout check']} с"
|
||||
)
|
||||
assert lb["timeout server"] > api["REQUEST_TIMEOUT_SECONDS"] > database
|
||||
assert lb["timeout check"] > 2 * PING_TIMEOUT_SECONDS
|
||||
assert drain > detection
|
||||
assert shutdown - drain - 1 >= database
|
||||
assert shutdown < hook < grace < 10
|
||||
assert lb["hard-stop-after"] < seconds(stand["lb"]["stop_grace_period"])
|
||||
assert (detection, hung) == (1.5, 3.5)
|
||||
@@ -0,0 +1,63 @@
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, Mock, call
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments.application.commands import ProcessJob
|
||||
from messenger.attachments.domain.jobs import Job, Outcome
|
||||
from messenger.attachments.entrypoints.worker import REQUEUE_DELAY_SECONDS, handle_job
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
|
||||
def test_infrastructure_requeues_preserve_the_message_and_dead_letter_rejections() -> None:
|
||||
path = Path(__file__).resolve().parents[2] / "infra/rabbitmq/definitions.json"
|
||||
definitions = json.loads(path.read_text())
|
||||
policy = next(p for p in definitions["policies"] if p["name"] == "attachments-process")
|
||||
queue = next(q for q in definitions["queues"] if q["name"] == "attachments.process")
|
||||
assert policy["definition"]["delivery-limit"] == -1
|
||||
assert "x-delivery-limit" not in queue["arguments"]
|
||||
assert policy["definition"]["dead-letter-exchange"] == "attachments.dlx"
|
||||
assert policy["definition"]["dead-letter-strategy"] == "at-least-once"
|
||||
|
||||
|
||||
async def test_database_outage_never_acks_and_recovery_keeps_job_and_attempt(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
job = Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC))
|
||||
message = AsyncMock(body=json.dumps(job.payload()).encode())
|
||||
bus, logger, sleep = AsyncMock(), Mock(), AsyncMock()
|
||||
monkeypatch.setattr("messenger.attachments.entrypoints.worker.asyncio.sleep", sleep)
|
||||
bus.execute.side_effect = [Unavailable("database unavailable")] * 12 + [Outcome.DONE]
|
||||
for _ in range(12):
|
||||
await handle_job(message, bus, logger, Mock())
|
||||
message.ack.assert_not_awaited()
|
||||
message.reject.assert_not_awaited()
|
||||
assert message.nack.await_args_list == [call(requeue=True)] * 12
|
||||
assert sleep.await_args_list == [call(REQUEUE_DELAY_SECONDS)] * 12
|
||||
await handle_job(message, bus, logger, Mock())
|
||||
message.ack.assert_awaited_once_with()
|
||||
assert bus.execute.await_args_list == [call(ProcessJob(job))] * 13
|
||||
|
||||
|
||||
async def test_invalid_message_is_dead_lettered_without_calling_the_bus() -> None:
|
||||
message, bus = AsyncMock(body=b"{}"), AsyncMock()
|
||||
await handle_job(message, bus, Mock(), Mock())
|
||||
message.reject.assert_awaited_once_with(requeue=False)
|
||||
message.ack.assert_not_awaited()
|
||||
message.nack.assert_not_awaited()
|
||||
bus.execute.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_cancelled_handler_leaves_delivery_unacknowledged() -> None:
|
||||
job = Job(uuid4(), uuid4(), 1, 1, datetime.now(UTC))
|
||||
message, bus = AsyncMock(body=json.dumps(job.payload()).encode()), AsyncMock()
|
||||
bus.execute.side_effect = asyncio.CancelledError
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await handle_job(message, bus, Mock(), Mock())
|
||||
message.ack.assert_not_awaited()
|
||||
message.nack.assert_not_awaited()
|
||||
message.reject.assert_not_awaited()
|
||||
Reference in New Issue
Block a user