Carry over the lab 5 solution

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

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-29 03:51:58 +03:00
co-authored by Claude Opus 5.5
parent a0d3947710
commit 5ae3d77152
204 changed files with 18547 additions and 1 deletions
@@ -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",
)
+64
View File
@@ -0,0 +1,64 @@
from base64 import b64encode
import pytest
from messenger.identity.entrypoints.authentication import (
basic_credentials,
bearer_token,
challenge_for,
)
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
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"'
+56
View File
@@ -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)
+239
View File
@@ -0,0 +1,239 @@
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 (
ChatNotFound,
IdempotencyConflict,
InvalidAttachmentList,
InvalidChatData,
InvalidMessageText,
)
from messenger.messaging.domain.models import Chat, Receipt
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 make_chat(*members: object) -> Chat:
ids = [uuid4() for _ in members] if members else [uuid4()]
return Chat.create(
chat_id=uuid4(),
title="Чат",
member_ids=ids,
creator_id=ids[0],
created_at=MOMENT,
)
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_outsider_cannot_post() -> None:
chat = make_chat(1)
with pytest.raises(ChatNotFound):
chat.post(message_id=uuid4(), sender_id=uuid4(), text="привет", now=MOMENT)
def test_post_never_moves_history_back() -> None:
chat = make_chat(1)
sender = chat.member_ids[0]
first = chat.post(
message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT + timedelta(seconds=1)
)
second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=MOMENT)
assert second.created_at == first.created_at + timedelta(microseconds=1)
assert chat.last_message_at == second.created_at
def test_post_keeps_clock_when_it_is_ahead() -> None:
chat = make_chat(1)
sender = chat.member_ids[0]
first = chat.post(message_id=uuid4(), sender_id=sender, text="первое", now=MOMENT)
later = MOMENT + timedelta(seconds=5)
second = chat.post(message_id=uuid4(), sender_id=sender, text="второе", now=later)
assert first.created_at == MOMENT
assert second.created_at == later
def test_post_validates_membership_before_text() -> None:
chat = make_chat(1)
with pytest.raises(ChatNotFound):
chat.post(message_id=uuid4(), sender_id=uuid4(), text="", now=MOMENT)
def test_empty_text_needs_an_attachment() -> None:
chat = make_chat(1)
sender = chat.member_ids[0]
with pytest.raises(InvalidMessageText):
chat.post(message_id=uuid4(), sender_id=sender, text="", now=MOMENT)
ids = (uuid4(), uuid4())
message = chat.post(
message_id=uuid4(), sender_id=sender, text="", now=MOMENT, attachment_ids=ids
)
assert message.attachment_ids == ids
with pytest.raises(InvalidMessageText):
chat.post(message_id=uuid4(), sender_id=sender, text=" ", now=MOMENT, attachment_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:
chat = make_chat(1)
with pytest.raises(InvalidAttachmentList):
chat.post(
message_id=uuid4(),
sender_id=chat.member_ids[0],
text="x",
now=MOMENT,
attachment_ids=ids,
)
def test_membership_is_checked_before_attachments() -> None:
chat = make_chat(1)
with pytest.raises(ChatNotFound):
chat.post(
message_id=uuid4(),
sender_id=uuid4(),
text="",
now=MOMENT,
attachment_ids=[uuid4() for _ in range(11)],
)
def test_receipt_replays_only_the_same_request() -> None:
chat = make_chat(1)
message = chat.post(message_id=uuid4(), sender_id=chat.member_ids[0], text="раз", now=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_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,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"
+91
View File
@@ -0,0 +1,91 @@
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) -> 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)
@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)
+126
View File
@@ -0,0 +1,126 @@
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.infrastructure.images import 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) -> dict[str, Image.Image]:
renditions: list[Rendition] = render_variants(data, LIMITS)
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(
("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))
+60
View File
@@ -0,0 +1,60 @@
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} с, остановка {shutdown} с,"
f" хук {hook} с, 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 >= database
assert shutdown < hook < grace < 10
assert lb["hard-stop-after"] < seconds(stand["lb"]["stop_grace_period"])
assert (detection, hung) == (1.5, 3.5)