forked from mtusi2026/mtusi2026lab3
solution
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
"""Общая идемпотентность PostgreSQL: конкурентные реплики, rollback, expiry."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
import pytest
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.main import create_app
|
||||
from app.models import MessageRequest
|
||||
from conftest import assert_error, make_settings, run_sql
|
||||
|
||||
|
||||
def message_path(chat):
|
||||
return "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
|
||||
def headers(person, key):
|
||||
return {"Authorization": "Bearer " + person.token, "Idempotency-Key": key}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [None, "", "a b", "a?b", "x" * 129, "a,b", "a/b"])
|
||||
def test_key_is_required_and_validated(client, alice, chat, key):
|
||||
h = {"Authorization": "Bearer " + alice.token}
|
||||
if key is not None:
|
||||
h["Idempotency-Key"] = key
|
||||
assert_error(client.post(message_path(chat), json={"text": "hello"}, headers=h), 400, "invalid_request")
|
||||
assert not run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
|
||||
|
||||
|
||||
def test_duplicate_headers_are_invalid(client, alice, chat):
|
||||
h = [("Authorization", "Bearer " + alice.token), ("Idempotency-Key", "a"), ("Idempotency-Key", "b")]
|
||||
assert_error(client.post(message_path(chat), json={"text": "hi"}, headers=h), 400, "invalid_request")
|
||||
|
||||
|
||||
def test_replay_and_conflict_preserve_original_result(client, alice, chat):
|
||||
h = headers(alice, uuid.uuid4().hex)
|
||||
first = client.post(message_path(chat), json={"text": "original"}, headers=h)
|
||||
replay = client.post(message_path(chat), json={"attachment_ids": [], "text": "original"}, headers=h)
|
||||
assert first.status_code == replay.status_code == 201
|
||||
assert first.json() == replay.json()
|
||||
assert_error(client.post(message_path(chat), json={"text": "changed"}, headers=h), 409, "conflict")
|
||||
again = client.post(message_path(chat), json={"text": "original"}, headers=h)
|
||||
assert again.status_code == 201 and again.json() == first.json()
|
||||
rows = run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
|
||||
assert [str(row["id"]) for row in rows] == [first.json()["id"]]
|
||||
|
||||
|
||||
def test_parallel_same_key_across_two_applications(client, alice, chat):
|
||||
h = headers(alice, uuid.uuid4().hex)
|
||||
barrier = threading.Barrier(8)
|
||||
with TestClient(create_app(make_settings()), raise_server_exceptions=False) as other:
|
||||
def send(n):
|
||||
barrier.wait()
|
||||
return (client if n % 2 else other).post(message_path(chat), json={"text": "one"}, headers=h)
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
replies = list(pool.map(send, range(8)))
|
||||
assert all(reply.status_code == 201 for reply in replies)
|
||||
assert len({reply.json()["id"] for reply in replies}) == 1
|
||||
assert len({reply.headers["X-Instance-Id"] for reply in replies}) == 2
|
||||
assert len(run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))) == 1
|
||||
|
||||
|
||||
def test_key_scope_includes_user_and_chat(client, alice, bob, chat, make_chat):
|
||||
other = make_chat(alice, bob)
|
||||
key = uuid.uuid4().hex
|
||||
replies = [client.post(message_path(room), json={"text": "hi"}, headers=headers(person, key))
|
||||
for person, room in [(alice, chat), (bob, chat), (alice, other)]]
|
||||
assert all(reply.status_code == 201 for reply in replies)
|
||||
assert len({reply.json()["id"] for reply in replies}) == 3
|
||||
|
||||
|
||||
def test_expired_result_allows_new_message(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
h = headers(alice, key)
|
||||
first = client.post(message_path(chat), json={"text": "old"}, headers=h)
|
||||
run_sql("UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=$1 AND chat_id=$2 AND key=$3",
|
||||
uuid.UUID(alice.id), uuid.UUID(chat["id"]), key)
|
||||
second = client.post(message_path(chat), json={"text": "new"}, headers=h)
|
||||
assert first.status_code == second.status_code == 201
|
||||
assert first.json()["id"] != second.json()["id"]
|
||||
|
||||
|
||||
def test_failure_between_message_and_result_rolls_back(client, alice, chat, monkeypatch):
|
||||
key = uuid.uuid4().hex
|
||||
h = headers(alice, key)
|
||||
real = AsyncSession.execute
|
||||
async def fail_result(self, statement, *args, **kwargs):
|
||||
if getattr(getattr(statement, "table", None), "name", None) == MessageRequest.__tablename__:
|
||||
raise OperationalError("", {}, Exception("injected result failure"))
|
||||
return await real(self, statement, *args, **kwargs)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(AsyncSession, "execute", fail_result)
|
||||
assert_error(client.post(message_path(chat), json={"text": "once"}, headers=h), 503, "unavailable")
|
||||
assert not run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
|
||||
assert not run_sql("SELECT message_id FROM message_requests WHERE chat_id=$1", uuid.UUID(chat["id"]))
|
||||
assert client.post(message_path(chat), json={"text": "once"}, headers=h).status_code == 201
|
||||
|
||||
|
||||
def test_committed_but_lost_response_is_safe_to_retry(client, alice, chat, monkeypatch):
|
||||
from app import routes
|
||||
key = uuid.uuid4().hex
|
||||
h = headers(alice, key)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(routes, "message_out", lambda row: (_ for _ in ()).throw(RuntimeError("lost after commit")))
|
||||
assert_error(client.post(message_path(chat), json={"text": "one"}, headers=h), 500, "internal_error")
|
||||
replay = client.post(message_path(chat), json={"text": "one"}, headers=h)
|
||||
assert replay.status_code == 201
|
||||
rows = run_sql("SELECT id FROM messages WHERE chat_id=$1", uuid.UUID(chat["id"]))
|
||||
assert [str(row["id"]) for row in rows] == [replay.json()["id"]]
|
||||
|
||||
|
||||
def test_replay_rechecks_session_and_chat_access(client, alice, eve, chat):
|
||||
key = uuid.uuid4().hex
|
||||
h = headers(alice, key)
|
||||
assert client.post(message_path(chat), json={"text": "one"}, headers=h).status_code == 201
|
||||
assert_error(client.post(message_path(chat), json={"text": "one"}, headers=headers(eve, key)), 404, "not_found")
|
||||
assert client.delete("/api/v1/auth/sessions/current", headers=alice.headers).status_code == 204
|
||||
assert_error(client.post(message_path(chat), json={"text": "one"}, headers=h), 401, "unauthorized")
|
||||
Reference in New Issue
Block a user