Implement lab 7 transport security and worker containment

This commit is contained in:
Artyom
2026-11-13 23:58:00 +03:00
parent 20afc2c790
commit 170a76a6ce
543 changed files with 96442 additions and 65 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",
)
+116
View File
@@ -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"'
+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)
+178
View File
@@ -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)
+26
View File
@@ -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"
+279
View File
@@ -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
+75
View File
@@ -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
+95
View File
@@ -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"
+110
View File
@@ -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)
+83
View File
@@ -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 == []
+83
View File
@@ -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())
+99
View File
@@ -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
+162
View File
@@ -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))
+80
View File
@@ -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
+161
View File
@@ -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]
+61
View File
@@ -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()