Carry over the lab 3 fixes made after 61c0c28

Bring the system changes of lab 3 from 61c0c28..72a1e57 onto the lab 4
code, resolving each conflict by meaning and keeping everything lab 4
added:

- a message is posted with one SQL statement under the chat row lock,
  and the attachment links go into the same statement; a foreign key
  violation on the attachment link still answers 404 and leaves nothing
  behind. Text and the attachment list are checked before the write, an
  outsider gets 404 for both, as before the carry over;
- the request pipeline counts the body bytes actually received against
  the limit of the route, so a chunked body over 1 MiB gets 413 and the
  upload route keeps its MAX_UPLOAD_BYTES limit;
- a request cancelled at shutdown gets 503 unavailable in the contract
  format, the worker waits a second less than the rest of the shutdown
  budget, SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks 7 s;
- readiness sits behind a Readiness port with the draining flag in
  shared infrastructure, and the drain window is logged through Logger;
- logout revokes through SessionRevocations and withdraws the mark when
  PostgreSQL rejects the delete; an empty cursor is 400;
- EventBus.project is gone, the sweep test subscribes and waits on a
  queue; domain tests check attachment_list instead of Chat.post;
- make up waits for every replica in the balancer, BASE_URL follows the
  lb port, the image is tagged by the compose project, retry-check and
  faults-evidence are added, detection runs three times, failover-each
  and rolling-update record the stand usage, CI checks numeric uids.
  down also takes the tools and reconcile profiles of lab 4.

Track 1 tooling of lab 3 (scaling.py, its samplers, tools/ and the CPU
pinning of api, lb, valkey and k6) stays out; stand-usage.sh queries the
database size itself instead of the track 1 sampler.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 06:25:23 +03:00
co-authored by Claude Opus 5.5
parent 7ac1a4a11b
commit e927afdb09
56 changed files with 932 additions and 397 deletions
+38 -1
View File
@@ -1,8 +1,10 @@
import time
from uuid import uuid4
import asyncpg
from httpx import AsyncClient
from conftest import actor, keyed, make_chat, register
from conftest import DATABASE, actor, keyed, make_chat, register
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
@@ -82,3 +84,38 @@ async def test_403_is_never_used(client: AsyncClient) -> None:
]
for path in paths:
assert (await client.get(path, headers=actor(eve))).status_code != 403
async def test_request_shape_is_checked_before_access(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
for chat_id in (chat["id"], uuid4()):
path = f"/api/v1/chats/{chat_id}/messages"
unkeyed = await client.post(path, json={"text": "чужое"}, headers=actor(eve))
extra = await client.post(path, json={"text": "x", "a": 1}, headers=keyed(eve))
assert unkeyed.status_code == extra.status_code == 400
assert unkeyed.json()["error"]["code"] == extra.json()["error"]["code"] == "invalid_request"
blank = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": " "}, headers=keyed(eve)
)
assert blank.status_code == 404
async def test_outsider_does_not_wait_for_members_lock(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
holder = await asyncpg.connect(DATABASE["url"])
try:
async with holder.transaction():
await holder.execute("SELECT 1 FROM chats WHERE id = $1 FOR UPDATE", chat["id"])
started = time.perf_counter()
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "чужое"}, headers=keyed(eve)
)
elapsed = time.perf_counter() - started
finally:
await holder.close()
assert response.status_code == 404
assert elapsed < 0.5
+1 -14
View File
@@ -33,20 +33,6 @@ def test_identity_does_not_know_about_messaging() -> None:
assert not {k: v for k, v in offenders.items() if v}
def test_messaging_touches_identity_only_through_events() -> None:
allowed = f"{IDENTITY}.domain.events"
offenders: dict[str, list[str]] = {}
for path in modules_under("messaging"):
borrowed = [
module
for module in imports_of(path)
if module.startswith(IDENTITY) and module != allowed
]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_attachments_and_other_zones_do_not_import_each_other() -> None:
offenders: dict[str, list[str]] = {}
for zone, foreign in (
@@ -125,6 +111,7 @@ def test_shared_core_holds_only_platform() -> None:
"ids.py",
"logging.py",
"postgres.py",
"readiness.py",
}
+32 -4
View File
@@ -3,12 +3,15 @@ import time
from datetime import datetime
from hashlib import sha256
import pytest
from redis.asyncio import Redis
from conftest import actor, bearer, register, resolve, running_app, scalar
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import PostgresSessionRepository
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
BEARER = 'Bearer realm="messenger"'
@@ -53,6 +56,29 @@ async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -
await cache.aclose()
async def test_logout_rejected_by_database_changes_nothing(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch
) -> None:
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
raise Unavailable("PostgreSQL недоступен")
cache = Redis.from_url(valkey["url"])
logout = "/api/v1/auth/sessions/current"
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
with monkeypatch.context() as patch:
patch.setattr(PostgresSessionRepository, "remove", broken)
failed = await http.delete(logout, headers=actor(alice))
assert failed.status_code == 503
assert failed.json()["error"]["code"] == "unavailable"
assert await cache.get(key_of(token_of(alice))) is None
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await http.delete(logout, headers=actor(alice))).status_code == 204
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
await cache.aclose()
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
@@ -69,9 +95,6 @@ async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, s
await released.wait()
return stale[-1]
async def invalidate(self, session: Session) -> None:
await origin.invalidate(session)
directory._origin = SlowOrigin()
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await entered.wait()
@@ -106,6 +129,10 @@ async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
elapsed = time.perf_counter() - started
ready = await http.get("/health/ready")
chat = await make_chat(http, alice)
posted = await http.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без кэша"}, headers=keyed(alice)
)
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
still = await http.get("/api/v1/users/me", headers=actor(alice))
assert me.json() == alice
@@ -113,6 +140,7 @@ async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
assert stranger.headers["WWW-Authenticate"] == BEARER
assert elapsed < 1
assert ready.status_code == 200
assert posted.status_code == 201
assert logout.status_code == 503
assert logout.json()["error"]["code"] == "unavailable"
assert still.status_code == 200
+19
View File
@@ -1,10 +1,13 @@
import asyncio
from datetime import UTC, datetime, timedelta
from urllib.parse import quote
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register
from messenger.shared.infrastructure.clock import MonotonicUtcClock
CLIENTS = 10
PER_CLIENT = 10
@@ -60,6 +63,22 @@ async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
async def test_history_follows_the_clock_but_never_moves_back(
monkeypatch: pytest.MonkeyPatch, client: AsyncClient
) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
base = datetime.now(UTC) + timedelta(minutes=10)
stamps = []
for moment in (base, base - timedelta(minutes=5), base + timedelta(seconds=5)):
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self, moment=moment: moment)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": "часы"}, headers=keyed(alice)
)
stamps.append(datetime.fromisoformat(response.json()["created_at"]))
assert stamps == [base, base + timedelta(microseconds=1), base + timedelta(seconds=5)]
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
+24 -4
View File
@@ -9,10 +9,10 @@ import time
import httpx
from conftest import DATABASE, new_user
from messenger.shared.entrypoints.health import DRAINING
from messenger.shared.infrastructure.readiness import DRAINING
DRAIN = 1.5
SHUTDOWN = 4
DRAIN = 1.0
SHUTDOWN = 3
GUNICORN = (
"-m",
"gunicorn",
@@ -49,6 +49,17 @@ def status(port: int, path: str) -> int:
return 0
def answer_of(connection: socket.socket) -> tuple[str, dict[str, str], dict]:
data = b""
while chunk := connection.recv(4096):
data += chunk
connection.close()
head, _, body = data.partition(b"\r\n\r\n")
status, *lines = head.decode("latin-1").split("\r\n")
headers = dict(line.lower().split(": ", 1) for line in lines)
return status, headers, json.loads(body) if body else {}
def begin_registration(port: int) -> tuple[socket.socket, bytes]:
body = json.dumps(new_user("drain")).encode()
head = (
@@ -60,7 +71,7 @@ def begin_registration(port: int) -> tuple[socket.socket, bytes]:
return connection, body[8:]
def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> None:
port = free_port()
settings = {
"HOST": "127.0.0.1",
@@ -86,6 +97,7 @@ def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
assert time.monotonic() < deadline, "gunicorn не стал готов"
time.sleep(0.2)
pending, rest = begin_registration(port)
stuck, _ = begin_registration(port)
sent = time.monotonic()
server.send_signal(signal.SIGTERM)
time.sleep(0.3)
@@ -98,13 +110,21 @@ def test_sigterm_leaves_rotation_then_closes_and_exits() -> None:
pending.close()
code = server.wait(timeout=SHUTDOWN + 2)
exited = time.monotonic() - sent
cancelled, headers, error = answer_of(stuck)
finally:
if server.poll() is None:
server.kill()
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
print(f" content-type {headers.get('content-type')}, тело {error}")
assert during == (503, 200)
assert answer == "HTTP/1.1 201 Created"
assert cancelled == "HTTP/1.1 503 Service Unavailable"
assert headers["content-type"] == "application/json"
assert headers["x-instance-id"]
assert error["error"]["code"] == "unavailable"
assert error["error"]["request_id"] == headers["x-request-id"]
assert DRAIN - 0.2 <= closed < SHUTDOWN
assert exited < SHUTDOWN
assert code == 0
-12
View File
@@ -77,18 +77,6 @@ async def test_queue_overflow_drops_events_without_raising() -> None:
assert bus.pending <= 16
async def test_projection_runs_before_publish_returns() -> None:
bus = EventBus(NullLogger())
seen: list[str] = []
async def projection(_event: MessagePosted) -> None:
seen.append("projected")
bus.project(MessagePosted, projection)
await InMemoryEventPublisher(bus).publish([posted()])
assert seen == ["projected"]
async def test_publication_does_not_delay_response() -> None:
app = create_app(**split_settings(log_level="CRITICAL"))
async with (
+28 -1
View File
@@ -1,10 +1,20 @@
import json
import time
from collections.abc import AsyncIterator
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import PASSWORD, actor, keyed, make_chat, register, running_app, split_settings
from conftest import (
PASSWORD,
actor,
keyed,
make_chat,
new_user,
register,
running_app,
split_settings,
)
from messenger.main import create_app
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
@@ -100,6 +110,23 @@ async def test_body_limit_returns_413() -> None:
assert response.json()["error"]["code"] == "payload_too_large"
async def test_chunked_body_is_limited_too() -> None:
async def chunks(body: bytes) -> AsyncIterator[bytes]:
for start in range(0, len(body), 1000):
yield body[start : start + 1000]
user = json.dumps(new_user("chunked")).encode()
async with running_app(max_body_bytes=4096) as http:
large = await http.post("/api/v1/users", content=chunks(b"x" * 5000))
small = await http.post(
"/api/v1/users", content=chunks(user), headers={"Content-Type": "application/json"}
)
assert "content-length" not in large.request.headers
assert large.status_code == 413
assert large.json()["error"]["code"] == "payload_too_large"
assert small.status_code == 201
async def test_ready_turns_unavailable_without_database() -> None:
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
started = time.perf_counter()
+6 -5
View File
@@ -102,14 +102,15 @@ async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20"])
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20", ""])
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", headers=actor(alice)
)
assert response.status_code == 400
await fill(client, chat, alice, 1)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit=1&cursor={cursor}", headers=actor(alice))
assert response.status_code == 400, f"{path}?cursor={cursor} → {response.status_code}"
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
+12 -10
View File
@@ -29,16 +29,19 @@ def sweeper(http: AsyncClient) -> UploadSweeper:
return APPS[id(http)].state.sweeper
async def discarded(http: AsyncClient) -> list[AttachmentDiscarded]:
seen: list[AttachmentDiscarded] = []
async def keep(event: AttachmentDiscarded) -> None:
seen.append(event)
(await resolve(http, EventBus)).project(AttachmentDiscarded, keep)
async def discarded(http: AsyncClient) -> asyncio.Queue[AttachmentDiscarded]:
seen: asyncio.Queue[AttachmentDiscarded] = asyncio.Queue()
(await resolve(http, EventBus)).subscribe(AttachmentDiscarded, seen.put)
return seen
async def delivered(seen: asyncio.Queue[AttachmentDiscarded], count: int) -> list[str]:
async with asyncio.timeout(2):
events = [await seen.get() for _ in range(count)]
assert seen.empty()
return sorted(f"{event.reason} {event.attachment_id}" for event in events)
async def intent(http: AsyncClient, user: dict[str, Any], chat: dict[str, Any]) -> str:
store = await storage(http)
store.failing = True
@@ -79,7 +82,7 @@ async def test_commit_failure_after_put_is_compensated(client: AsyncClient) -> N
assert response.json()["error"]["code"] == "unavailable"
assert await scalar("SELECT count(*) FROM attachments WHERE filename = $1", name) == 0
assert set(store.objects) == before
assert [event.reason for event in seen] == ["compensation"]
assert [event.split()[0] for event in await delivered(seen, 1)] == ["compensation"]
async def test_lost_intent_gives_503_and_no_object(client: AsyncClient) -> None:
@@ -142,8 +145,7 @@ async def test_parallel_sweeps_share_the_work(client: AsyncClient) -> None:
seen = await discarded(client)
first, second = await asyncio.gather(sweeper(client).sweep(), sweeper(client).sweep())
assert first + second == 5
assert sorted(str(event.attachment_id) for event in seen) == sorted(pending)
assert {event.reason for event in seen} == {"abandoned"}
assert await delivered(seen, 5) == sorted(f"abandoned {item}" for item in pending)
assert await sweeper(client).sweep() == 0
objects = (await storage(client)).objects
assert not any(f"attachments/{attachment_id}" in objects for attachment_id in pending)