forked from mtusi2026/mtusi2026lab6
Реализовать наблюдаемость мессенджера и проверить её под нагрузкой
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from psycopg import sql
|
||||
from psycopg.conninfo import make_conninfo
|
||||
|
||||
from messenger.app import create_app
|
||||
from messenger.migrate import migrate
|
||||
from messenger.settings import Settings
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PASSWORD = "Учебный:пароль😀-12345"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def settings():
|
||||
password = (ROOT / "secrets/postgres_password").read_text().strip()
|
||||
admin = make_conninfo(
|
||||
host="127.0.0.1", port=55467, user="messenger", password=password, dbname="messenger"
|
||||
)
|
||||
database = "student_tests_" + uuid4().hex
|
||||
with psycopg.connect(admin, autocommit=True) as conn:
|
||||
conn.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(database)))
|
||||
config = Settings(
|
||||
make_conninfo(admin, dbname=database),
|
||||
"redis://127.0.0.1:56386/1",
|
||||
broker_url="redis://127.0.0.1:56387/1",
|
||||
s3_bucket="messenger-attachments-tests",
|
||||
s3_access_key=(ROOT / "secrets/s3_test_access_key_id").read_text().strip(),
|
||||
s3_secret_key=(ROOT / "secrets/s3_test_secret_access_key").read_text().strip(),
|
||||
)
|
||||
migrate(config.database_url, ROOT / "migrations")
|
||||
with pytest.MonkeyPatch.context() as environment:
|
||||
environment.setenv("S3_ENDPOINT", config.s3_endpoint)
|
||||
environment.setenv("S3_BUCKET", config.s3_bucket)
|
||||
environment.setenv("S3_ACCESS_KEY_ID_FILE", str(ROOT / "secrets/s3_test_access_key_id"))
|
||||
environment.setenv(
|
||||
"S3_SECRET_ACCESS_KEY_FILE", str(ROOT / "secrets/s3_test_secret_access_key")
|
||||
)
|
||||
yield config
|
||||
with psycopg.connect(admin, autocommit=True) as conn:
|
||||
conn.execute(sql.SQL("DROP DATABASE {} WITH (FORCE)").format(sql.Identifier(database)))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(settings):
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
conn.execute("TRUNCATE users,chats,chat_members,messages,sessions CASCADE")
|
||||
with TestClient(create_app(settings), raise_server_exceptions=False) as client:
|
||||
client.app.state.cache.client.flushdb()
|
||||
yield client
|
||||
|
||||
|
||||
def basic(username, password=PASSWORD):
|
||||
return {
|
||||
"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode()).decode()
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def actors(client):
|
||||
result = []
|
||||
for name in ("alice", "bob", "eve"):
|
||||
r = client.post(
|
||||
"/api/v1/users", json={"username": name, "display_name": name, "password": PASSWORD}
|
||||
)
|
||||
assert r.status_code == 201
|
||||
session = client.post("/api/v1/auth/sessions", headers=basic(name))
|
||||
assert session.status_code == 201
|
||||
result.append({**r.json(), "token": session.json()["token"]})
|
||||
return result
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def room(client, actors):
|
||||
response = client.post(
|
||||
"/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + actors[0]["token"]},
|
||||
json={"title": "Чат 👋", "member_ids": [u["id"] for u in actors[:2]]},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
@@ -0,0 +1,299 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from conftest import PASSWORD, ROOT, basic
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from messenger.app import create_app
|
||||
from messenger.auth import basic_credentials
|
||||
from messenger.migrate import migrate
|
||||
|
||||
|
||||
def headers(actor):
|
||||
return {"Authorization": "Bearer " + actor["token"], "Idempotency-Key": uuid4().hex}
|
||||
|
||||
|
||||
def error(response, status, code):
|
||||
assert response.status_code == status, response.text
|
||||
body = response.json()["error"]
|
||||
assert set(body) == {"code", "message", "request_id"}
|
||||
assert body["code"] == code
|
||||
assert body["request_id"] == response.headers["X-Request-Id"]
|
||||
assert len(response.headers.get_list("X-Request-Id")) == 1
|
||||
if status == 401:
|
||||
assert response.headers["WWW-Authenticate"].startswith(("Basic", "Bearer"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", ["{", "null", "[]", '"text"', '{"username":'])
|
||||
def test_malformed_json(client, body):
|
||||
error(
|
||||
client.post("/api/v1/users", content=body, headers={"Content-Type": "application/json"}),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
{"username": "ab"},
|
||||
{"username": "a" * 33},
|
||||
{"username": "Upper"},
|
||||
{"username": "кириллица"},
|
||||
{"username": "valid\n"},
|
||||
{"username": 123},
|
||||
{"username": True},
|
||||
{"display_name": 123},
|
||||
{"display_name": None},
|
||||
{"display_name": " \n\t"},
|
||||
{"display_name": "😀" * 101},
|
||||
{"display_name": "\ud800"},
|
||||
{"password": "short"},
|
||||
{"password": "😀" * 129},
|
||||
{"password": 123},
|
||||
{"password": " " * 12},
|
||||
{"password": "\ud800" * 12},
|
||||
{"extra": True},
|
||||
],
|
||||
)
|
||||
def test_strict_registration(client, change):
|
||||
data = {"username": "valid", "display_name": "Имя", "password": PASSWORD, **change}
|
||||
response = client.post(
|
||||
"/api/v1/users", content=json.dumps(data), headers={"Content-Type": "application/json"}
|
||||
)
|
||||
error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_unicode_password_hash_and_authentication(client, settings, actors):
|
||||
for u in actors:
|
||||
assert "password" not in u and "password_hash" not in u
|
||||
assert re.fullmatch(r"[A-Za-z0-9_-]{43}", u["token"])
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
encoded = conn.execute("SELECT password_hash FROM users WHERE username='alice'").fetchone()[
|
||||
0
|
||||
]
|
||||
assert encoded.startswith("$argon2id$") and PASSWORD not in encoded
|
||||
assert (
|
||||
conn.execute("SELECT octet_length(token_hash) FROM sessions LIMIT 1").fetchone()[0]
|
||||
== 32
|
||||
)
|
||||
bad = client.post("/api/v1/auth/sessions", headers=basic("alice", "wrong-password"))
|
||||
absent = client.post("/api/v1/auth/sessions", headers=basic("unknown", "wrong-password"))
|
||||
error(bad, 401, "unauthorized")
|
||||
error(absent, 401, "unauthorized")
|
||||
assert bad.json()["error"]["message"] == absent.json()["error"]["message"]
|
||||
assert bad.headers["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"'
|
||||
for value in (
|
||||
{},
|
||||
basic("alice"),
|
||||
{"X-User-Id": actors[0]["id"]},
|
||||
{"Authorization": "Bearer unknown"},
|
||||
):
|
||||
error(client.get("/api/v1/users/me", headers=value), 401, "unauthorized")
|
||||
actual = client.get(
|
||||
"/api/v1/users/me", headers={**headers(actors[0]), "X-User-Id": actors[2]["id"]}
|
||||
).json()
|
||||
assert actual["id"] == actors[0]["id"]
|
||||
error(
|
||||
client.post("/api/v1/auth/sessions", headers=basic("alice"), json={}),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [None, "Bearer a", "Basic !", "Basic YWxpY2U=", "Basic /w=="])
|
||||
def test_invalid_basic(value):
|
||||
with pytest.raises(Exception) as caught:
|
||||
basic_credentials(value)
|
||||
assert caught.value.status == 401
|
||||
|
||||
|
||||
def test_registration_race(client, settings):
|
||||
def register(_):
|
||||
return client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "same", "display_name": "Алиса", "password": PASSWORD},
|
||||
).status_code
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
assert sorted(pool.map(register, range(10))) == [201] + [409] * 9
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
assert conn.execute("SELECT count(*) FROM users WHERE username='same'").fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_acl_validation_and_transaction_rollback(client, actors, room, settings):
|
||||
path = "/api/v1/chats/" + room["id"]
|
||||
for suffix in ("", "/messages"):
|
||||
error(client.get(path + suffix, headers=headers(actors[2])), 404, "not_found")
|
||||
error(client.get("/api/v1/chats/not-a-uuid"), 401, "unauthorized")
|
||||
error(
|
||||
client.get("/api/v1/chats/not-a-uuid", headers=headers(actors[0])), 400, "invalid_request"
|
||||
)
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
before = conn.execute("SELECT count(*) FROM chats").fetchone()[0]
|
||||
for members in ([actors[0]["id"], str(uuid4())], [actors[0]["id"]] * 2, [actors[1]["id"]], []):
|
||||
error(
|
||||
client.post(
|
||||
"/api/v1/chats",
|
||||
headers=headers(actors[0]),
|
||||
json={"title": "rollback", "member_ids": members},
|
||||
),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
assert conn.execute("SELECT count(*) FROM chats").fetchone()[0] == before
|
||||
assert conn.execute("SELECT count(*) FROM chat_members").fetchone()[0] == 2
|
||||
for body in (
|
||||
{"text": ""},
|
||||
{"text": " \t"},
|
||||
{"text": "😀" * 4001},
|
||||
{"text": 123},
|
||||
{"text": None},
|
||||
{"text": "ok", "sender_id": actors[1]["id"]},
|
||||
):
|
||||
error(
|
||||
client.post(path + "/messages", headers=headers(actors[0]), json=body),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
for query in (
|
||||
"limit=0",
|
||||
"limit=101",
|
||||
"limit=true",
|
||||
"limit=1.0",
|
||||
"limit=1&limit=2",
|
||||
"cursor=",
|
||||
"cursor=bad!",
|
||||
"cursor=e30",
|
||||
"cursor=x&cursor=y",
|
||||
):
|
||||
error(
|
||||
client.get(path + "/messages?" + query, headers=headers(actors[0])),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
def test_concurrent_messages_and_keyset_ties(client, actors, room, settings):
|
||||
path = f"/api/v1/chats/{room['id']}/messages"
|
||||
|
||||
def send(i):
|
||||
r = client.post(path, headers=headers(actors[i % 2]), json={"text": f"m{i} 😀"})
|
||||
assert r.status_code == 201
|
||||
return r.json()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
sent = list(pool.map(send, range(100)))
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
conn.execute(
|
||||
"UPDATE messages SET created_at='2026-10-17T12:00:00Z' WHERE chat_id=%s", (room["id"],)
|
||||
)
|
||||
for m in sent:
|
||||
m["created_at"] = "2026-10-17T12:00:00.000000Z"
|
||||
found, cursor = [], None
|
||||
while True:
|
||||
query = {"limit": 17 if cursor else 1}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
response = client.get(path, params=query, headers=headers(actors[1]))
|
||||
assert response.status_code == 200
|
||||
page = response.json()
|
||||
found.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
assert len(found) == len({x["id"] for x in found}) == 100
|
||||
assert found == sorted(sent, key=lambda x: (x["created_at"], x["id"]))
|
||||
first_cursor = client.get(path + "?limit=1", headers=headers(actors[0])).json()["next_cursor"]
|
||||
error(
|
||||
client.get("/api/v1/chats", params={"cursor": first_cursor}, headers=headers(actors[0])),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
def test_cache_hit_flush_and_revocation(client, actors, monkeypatch):
|
||||
user = actors[0]
|
||||
url = "/api/v1/users/me"
|
||||
assert client.get(url, headers=headers(user)).status_code == 200
|
||||
repository = client.app.state.repository
|
||||
original = repository.get_user
|
||||
|
||||
def must_be_cached(*args):
|
||||
raise AssertionError("cache hit should avoid fetching immutable user again")
|
||||
|
||||
monkeypatch.setattr(repository, "get_user", must_be_cached)
|
||||
assert client.get(url, headers=headers(user)).status_code == 200
|
||||
monkeypatch.setattr(repository, "get_user", original)
|
||||
cache = client.app.state.cache.client
|
||||
digest = hashlib.sha256(user["token"].encode()).digest()
|
||||
key = client.app.state.cache.key(digest)
|
||||
assert 0 < cache.ttl(key) <= 3600
|
||||
stale = cache.get(key)
|
||||
cache.flushdb()
|
||||
assert client.get(url, headers=headers(user)).status_code == 200
|
||||
assert client.delete("/api/v1/auth/sessions/current", headers=headers(user)).status_code == 204
|
||||
cache.set(key, stale, ex=3600) # A resurrected stale cache entry must not resurrect a session.
|
||||
error(client.get(url, headers=headers(user)), 401, "unauthorized")
|
||||
error(
|
||||
client.delete("/api/v1/auth/sessions/current", headers=headers(user)), 401, "unauthorized"
|
||||
)
|
||||
|
||||
|
||||
def test_expiry_and_api_restart(client, actors, settings, monkeypatch, tmp_path):
|
||||
database_file, cache_file = tmp_path / "database_url", tmp_path / "cache_url"
|
||||
database_file.write_text(settings.database_url)
|
||||
cache_file.write_text(settings.cache_url)
|
||||
monkeypatch.setenv("DATABASE_URL_FILE", str(database_file))
|
||||
monkeypatch.setenv("CACHE_URL_FILE", str(cache_file))
|
||||
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
|
||||
with TestClient(create_app()) as short:
|
||||
response = short.post("/api/v1/auth/sessions", headers=basic("alice"))
|
||||
assert response.status_code == 201
|
||||
token = {"Authorization": "Bearer " + response.json()["token"]}
|
||||
assert short.get("/api/v1/users/me", headers=token).status_code == 200
|
||||
with TestClient(create_app(settings)) as restarted:
|
||||
assert restarted.get("/api/v1/users/me", headers=token).status_code == 200
|
||||
time.sleep(2.1)
|
||||
error(restarted.get("/api/v1/users/me", headers=token), 401, "unauthorized")
|
||||
|
||||
|
||||
def test_migrations_idempotent_and_detect_change(client, settings, tmp_path):
|
||||
migrate(settings.database_url, ROOT / "migrations")
|
||||
modified = tmp_path / "001_initial.sql"
|
||||
modified.write_text((ROOT / "migrations/001_initial.sql").read_text() + "\n-- changed")
|
||||
with pytest.raises(RuntimeError, match="checksum changed"):
|
||||
migrate(settings.database_url, tmp_path)
|
||||
|
||||
|
||||
def test_logs_and_safe_errors(client, monkeypatch, caplog):
|
||||
canary = "PRIVATE_BODY_CANARY_123"
|
||||
with caplog.at_level("INFO", logger="messenger"):
|
||||
r = client.post(
|
||||
"/api/v1/users",
|
||||
json={"username": "logging", "display_name": canary, "password": PASSWORD},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
assert canary not in caplog.text and PASSWORD not in caplog.text
|
||||
|
||||
def broken(*args):
|
||||
raise RuntimeError(canary)
|
||||
|
||||
monkeypatch.setattr(client.app.state.authentication, "register", broken)
|
||||
response = client.post(
|
||||
"/api/v1/users", json={"username": "broken", "display_name": "x", "password": PASSWORD}
|
||||
)
|
||||
error(response, 500, "internal_error")
|
||||
assert canary not in response.text and canary not in caplog.text
|
||||
error(
|
||||
client.post("/api/v1/users", content="{}", headers={"Content-Type": "text/plain"}),
|
||||
415,
|
||||
"unsupported_media_type",
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import replace
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from test_api import error, headers
|
||||
|
||||
from messenger.app import create_app
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [None, "", "a b", "/", "a" * 129])
|
||||
def test_message_key_required(client, actors, room, key):
|
||||
h = {"Authorization": "Bearer " + actors[0]["token"]}
|
||||
if key is not None:
|
||||
h["Idempotency-Key"] = key
|
||||
error(
|
||||
client.post(
|
||||
f"/api/v1/chats/{room['id']}/messages", headers=h, json={"text": "key validation"}
|
||||
),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
def test_replay_scope_conflict_and_fresh_authorization(client, actors, room):
|
||||
path = f"/api/v1/chats/{room['id']}/messages"
|
||||
key = "Scope.Key:123"
|
||||
h = {**headers(actors[0]), "Idempotency-Key": key}
|
||||
first = client.post(path, headers=h, json={"text": "exact whitespace \n"})
|
||||
assert first.status_code == 201
|
||||
repeat = client.post(
|
||||
path,
|
||||
headers={**h, "Content-Type": "application/json"},
|
||||
content=json.dumps({"text": "exact whitespace \n"}, indent=3),
|
||||
)
|
||||
assert repeat.status_code == 201 and repeat.json() == first.json()
|
||||
error(client.post(path, headers=h, json={"text": "different"}), 409, "conflict")
|
||||
outsider = {**headers(actors[2]), "Idempotency-Key": key}
|
||||
error(
|
||||
client.post(path, headers=outsider, json={"text": "exact whitespace \n"}), 404, "not_found"
|
||||
)
|
||||
other_user = {**headers(actors[1]), "Idempotency-Key": key}
|
||||
own = client.post(path, headers=other_user, json={"text": "another author"})
|
||||
assert own.status_code == 201 and own.json()["id"] != first.json()["id"]
|
||||
chat = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=headers(actors[0]),
|
||||
json={"title": "another", "member_ids": [actors[0]["id"]]},
|
||||
).json()
|
||||
other_chat = client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", headers=h, json={"text": "different chat"}
|
||||
)
|
||||
assert other_chat.status_code == 201 and other_chat.json()["id"] != first.json()["id"]
|
||||
assert client.delete("/api/v1/auth/sessions/current", headers=h).status_code == 204
|
||||
error(client.post(path, headers=h, json={"text": "exact whitespace \n"}), 401, "unauthorized")
|
||||
|
||||
|
||||
def test_concurrent_replay_across_independent_apps(client, actors, room, settings):
|
||||
path = f"/api/v1/chats/{room['id']}/messages"
|
||||
h = {**headers(actors[0]), "Idempotency-Key": uuid4().hex}
|
||||
with TestClient(create_app(settings)) as second:
|
||||
assert second.app.state.instance_id != client.app.state.instance_id
|
||||
|
||||
def send(i):
|
||||
c = client if i % 2 else second
|
||||
r = c.post(path, headers=h, json={"text": "same concurrent body"})
|
||||
assert r.status_code == 201
|
||||
return r.json(), r.headers["X-Instance-Id"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
results = list(pool.map(send, range(30)))
|
||||
assert len({item[0]["id"] for item in results}) == 1
|
||||
assert len({item[1] for item in results}) == 2
|
||||
assert len(client.get(path, headers=headers(actors[1])).json()["items"]) == 1
|
||||
|
||||
|
||||
def test_side_effect_and_result_rollback_together(client, actors, room, settings, monkeypatch):
|
||||
repository = client.app.state.repository
|
||||
original = repository._save_request
|
||||
|
||||
def fail_after_message_insert(*args):
|
||||
raise RuntimeError("injected between message and result")
|
||||
|
||||
monkeypatch.setattr(repository, "_save_request", fail_after_message_insert)
|
||||
path = f"/api/v1/chats/{room['id']}/messages"
|
||||
h = {**headers(actors[0]), "Idempotency-Key": uuid4().hex}
|
||||
error(
|
||||
client.post(path, headers=h, json={"text": "retry after rollback"}), 500, "internal_error"
|
||||
)
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
assert conn.execute("SELECT count(*) FROM messages").fetchone()[0] == 0
|
||||
assert conn.execute("SELECT count(*) FROM message_requests").fetchone()[0] == 0
|
||||
monkeypatch.setattr(repository, "_save_request", original)
|
||||
result = client.post(path, headers=h, json={"text": "retry after rollback"})
|
||||
assert result.status_code == 201
|
||||
assert (
|
||||
client.post(path, headers=h, json={"text": "retry after rollback"}).json() == result.json()
|
||||
)
|
||||
|
||||
|
||||
def test_expired_key_can_be_reused_without_deleting_old_message(client, actors, room, settings):
|
||||
path = f"/api/v1/chats/{room['id']}/messages"
|
||||
h = {**headers(actors[0]), "Idempotency-Key": uuid4().hex}
|
||||
first = client.post(path, headers=h, json={"text": "old"}).json()
|
||||
with psycopg.connect(settings.database_url) as conn:
|
||||
conn.execute(
|
||||
"UPDATE message_requests SET created_at=clock_timestamp()-interval '2 days', "
|
||||
"expires_at=clock_timestamp()-interval '1 day'"
|
||||
)
|
||||
second = client.post(path, headers=h, json={"text": "new"})
|
||||
assert second.status_code == 201 and second.json()["id"] != first["id"]
|
||||
assert len(client.get(path, headers=headers(actors[0])).json()["items"]) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("optimized", [True, False])
|
||||
def test_read_modes_preserve_public_result(client, actors, room, settings, optimized):
|
||||
with TestClient(create_app(replace(settings, read_autocommit=optimized))) as c:
|
||||
c.get("/api/v1/users/me", headers=headers(actors[0]))
|
||||
pool = c.app.state.repository.pool
|
||||
before = pool.get_stats().get("requests_num", 0)
|
||||
response = c.get(f"/api/v1/chats/{room['id']}/messages", headers=headers(actors[0]))
|
||||
assert response.status_code == 200 and response.json()["items"] == []
|
||||
assert pool.get_stats()["requests_num"] - before == 3
|
||||
|
||||
|
||||
def test_instance_header_covers_health_errors_and_success(client):
|
||||
values = [
|
||||
client.get("/health/live"),
|
||||
client.get("/health/ready"),
|
||||
client.get("/api/v1/users/me"),
|
||||
client.get("/not-a-route"),
|
||||
]
|
||||
assert len({r.headers["X-Instance-Id"] for r in values}) == 1
|
||||
assert all(len(r.headers.get_list("X-Instance-Id")) == 1 for r in values)
|
||||
@@ -0,0 +1,357 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import zlib
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
import jsonschema
|
||||
import pytest
|
||||
from conftest import ROOT
|
||||
from PIL import Image
|
||||
from test_api import error, headers
|
||||
|
||||
from messenger.broker import GROUP, STREAM, Broker, Job
|
||||
from messenger.cleanup import collect
|
||||
from messenger.domain import DomainError
|
||||
from messenger.images import variants
|
||||
from messenger.pipeline import Pipeline
|
||||
from messenger.relay import publish_one
|
||||
from messenger.worker import handle
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def upload(client, actor, room, data=PNG, media="image/png", name="Фото.png"):
|
||||
return client.post(
|
||||
f"/api/v1/chats/{room['id']}/attachments?filename={quote(name, safe='')}",
|
||||
headers={**headers(actor), "Content-Type": media},
|
||||
content=data,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def broker(settings):
|
||||
b = Broker(settings)
|
||||
assert settings.broker_url.endswith("/1")
|
||||
b.client.flushdb()
|
||||
b.group()
|
||||
yield b
|
||||
b.client.flushdb()
|
||||
b.close()
|
||||
|
||||
|
||||
def process(client, settings, broker):
|
||||
db = client.app.state.repository
|
||||
assert publish_one(db, broker, settings)
|
||||
id, fields = broker.client.xreadgroup(GROUP, "unit", {STREAM: ">"}, count=1)[0][1][0]
|
||||
jsonschema.validate(
|
||||
json.loads(fields["job"]),
|
||||
json.loads((ROOT / "contracts/jobs.schema.json").read_text()),
|
||||
format_checker=jsonschema.FormatChecker(),
|
||||
)
|
||||
handle(db, broker, client.app.state.attachments.store, settings, id, fields["job"])
|
||||
|
||||
|
||||
def test_queued_message_ready_and_all_variants(client, actors, room, settings, broker):
|
||||
r = upload(client, actors[0], room)
|
||||
assert r.status_code == 202 and r.json()["status"] == "queued"
|
||||
a = r.json()
|
||||
assert not a["variants"] and a["sha256"] == hashlib.sha256(PNG).hexdigest()
|
||||
path = "/api/v1/attachments/" + a["id"]
|
||||
error(client.get(path + "/content", headers=headers(actors[0])), 409, "conflict")
|
||||
key = uuid4().hex
|
||||
msg = client.post(
|
||||
f"/api/v1/chats/{room['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
headers={**headers(actors[0]), "Idempotency-Key": key},
|
||||
)
|
||||
assert msg.status_code == 201
|
||||
for suffix in ("", "/content"):
|
||||
error(client.get(path + suffix, headers=headers(actors[2])), 404, "not_found")
|
||||
error(client.get(path + suffix), 401, "unauthorized")
|
||||
process(client, settings, broker)
|
||||
ready = client.get(path, headers=headers(actors[1])).json()
|
||||
assert ready["status"] == "ready" and ready["error_code"] is None
|
||||
assert {v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"}
|
||||
assert client.get(path + "/content", headers=headers(actors[1])).content == PNG
|
||||
for v in ready["variants"]:
|
||||
content = client.get(path + "/content?variant=" + v["name"], headers=headers(actors[1]))
|
||||
assert content.status_code == 200 and content.headers["content-type"] == v["content_type"]
|
||||
assert len(content.content) == v["size_bytes"]
|
||||
assert hashlib.sha256(content.content).hexdigest() == v["sha256"]
|
||||
with Image.open(io.BytesIO(content.content)) as image:
|
||||
assert image.size == (v["width"], v["height"])
|
||||
assert not image.getexif()
|
||||
with client.app.state.repository.connection() as conn:
|
||||
j = conn.execute(
|
||||
"SELECT * FROM attachment_jobs WHERE attachment_id=%s", (a["id"],)
|
||||
).fetchone()
|
||||
job = Job(
|
||||
schema_version=1,
|
||||
type="attachment.process.v1",
|
||||
job_id=str(j["job_id"]),
|
||||
attachment_id=a["id"],
|
||||
pipeline_version=1,
|
||||
attempt=1,
|
||||
created_at=a["created_at"],
|
||||
)
|
||||
sid = broker.publish(job)
|
||||
handle(
|
||||
client.app.state.repository,
|
||||
broker,
|
||||
client.app.state.attachments.store,
|
||||
settings,
|
||||
sid,
|
||||
job.model_dump_json(exclude_none=True),
|
||||
)
|
||||
assert client.get(path, headers=headers(actors[0])).json() == ready
|
||||
assert broker.client.xlen(STREAM) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", "../a.png", "a\\b.png", "a\x00.png", "\n.png", "x" * 256])
|
||||
def test_bad_filename(client, actors, room, name):
|
||||
error(upload(client, actors[0], room, name=name), 400, "invalid_request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data,media",
|
||||
[
|
||||
(b"", "image/png"),
|
||||
(b"bad", "image/png"),
|
||||
(PNG[:30], "image/png"),
|
||||
(PNG, "image/jpeg"),
|
||||
(PNG, "text/plain"),
|
||||
],
|
||||
)
|
||||
def test_bad_image(client, actors, room, data, media):
|
||||
error(upload(client, actors[0], room, data, media), 415, "unsupported_media_type")
|
||||
|
||||
|
||||
def test_upload_limits_and_pixel_bomb(client, actors, room):
|
||||
error(upload(client, actors[0], room, b"x" * (10485760 + 1)), 413, "payload_too_large")
|
||||
error(
|
||||
upload(client, actors[0], room, (b"x" * 1048576 for _ in range(11))),
|
||||
413,
|
||||
"payload_too_large",
|
||||
)
|
||||
data = bytearray(PNG)
|
||||
data[16:24] = struct.pack(">II", 10000, 10000)
|
||||
data[29:33] = struct.pack(">I", zlib.crc32(data[12:29]) & 0xFFFFFFFF)
|
||||
error(upload(client, actors[0], room, bytes(data)), 413, "payload_too_large")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size", [(320, 200), (17, 11), (1, 400), (400, 1), (1281, 713)])
|
||||
def test_transform_dimensions_alpha_and_exif(size):
|
||||
raw = io.BytesIO()
|
||||
Image.new("RGBA", size, (1, 2, 3, 0)).save(raw, "PNG")
|
||||
results = {name: (data, dims, media) for name, data, dims, media in variants(raw, 1)}
|
||||
scale = max(size)
|
||||
assert results["thumbnail"][1] == tuple(max(1, n * min(256, scale) // scale) for n in size)
|
||||
assert results["crop"][1] == (128, 128)
|
||||
assert max(results["optimized"][1]) <= 1280
|
||||
with Image.open(io.BytesIO(results["thumbnail"][0])) as image:
|
||||
assert image.getpixel((0, 0)) == (255, 255, 255)
|
||||
|
||||
|
||||
def test_exif_orientation_and_original_unchanged():
|
||||
raw = io.BytesIO()
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
Image.new("RGB", (320, 200), "red").save(raw, "JPEG", exif=exif)
|
||||
before = raw.getvalue()
|
||||
result = list(variants(raw, 1))
|
||||
assert result[0][2] == (160, 256) and raw.getvalue() == before
|
||||
for _, data, _, _ in result:
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
assert not image.getexif()
|
||||
|
||||
|
||||
def test_failed_retry_replay_and_ready_replay_rejected(
|
||||
client, actors, room, settings, broker, monkeypatch
|
||||
):
|
||||
a = upload(client, actors[0], room).json()
|
||||
store, db = client.app.state.attachments.store, client.app.state.repository
|
||||
original = store.put
|
||||
monkeypatch.setattr(
|
||||
store, "put", lambda *_: (_ for _ in ()).throw(DomainError(503, "unavailable", "test"))
|
||||
)
|
||||
process(client, replace(settings, job_max_attempts=1), broker)
|
||||
path = "/api/v1/attachments/" + a["id"]
|
||||
assert client.get(path, headers=headers(actors[0])).json()["error_code"] == "retry_exhausted"
|
||||
error(
|
||||
client.post(
|
||||
f"/api/v1/chats/{room['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
headers={**headers(actors[0]), "Idempotency-Key": uuid4().hex},
|
||||
),
|
||||
409,
|
||||
"conflict",
|
||||
)
|
||||
Pipeline(db, settings).replay(a["id"])
|
||||
monkeypatch.setattr(store, "put", original)
|
||||
process(client, settings, broker)
|
||||
assert client.get(path, headers=headers(actors[0])).json()["status"] == "ready"
|
||||
with pytest.raises(ValueError):
|
||||
Pipeline(db, settings).replay(a["id"])
|
||||
|
||||
|
||||
def test_invalid_envelope_quarantined(client, settings, broker):
|
||||
sid = broker.client.xadd(STREAM, {"job": '{"url":"http://untrusted.invalid/"}'})
|
||||
handle(
|
||||
client.app.state.repository,
|
||||
broker,
|
||||
client.app.state.attachments.store,
|
||||
settings,
|
||||
sid,
|
||||
'{"url":"http://untrusted.invalid/"}',
|
||||
)
|
||||
assert broker.client.xlen("invalid-jobs") == 1
|
||||
assert "url" not in json.dumps(broker.client.xrange("invalid-jobs"))
|
||||
|
||||
|
||||
def test_staging_failure_has_no_accepted_job(client, actors, room, monkeypatch):
|
||||
store = client.app.state.attachments.store
|
||||
monkeypatch.setattr(
|
||||
store, "put", lambda *_: (_ for _ in ()).throw(DomainError(503, "unavailable", "test"))
|
||||
)
|
||||
error(upload(client, actors[0], room), 503, "unavailable")
|
||||
with client.app.state.repository.connection() as conn:
|
||||
assert conn.execute("SELECT count(*) AS n FROM attachment_jobs").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_gc_minimum_retention(client):
|
||||
with pytest.raises(ValueError):
|
||||
collect(client.app.state.repository, client.app.state.attachments.store, 0, True)
|
||||
|
||||
|
||||
def test_gc_fences_paused_upload_before_job_commit(client, actors, room, settings, monkeypatch):
|
||||
db, store = client.app.state.repository, client.app.state.attachments.store
|
||||
p = Pipeline(db, settings)
|
||||
id = str(uuid4())
|
||||
key = "staging/" + id
|
||||
p.reserve(id, key)
|
||||
store.put(key, io.BytesIO(PNG), len(PNG), "image/png", hashlib.sha256(PNG).hexdigest())
|
||||
# Simulated S3 object age; actual private test-bucket deletion and DB locks are real.
|
||||
old = datetime.now(UTC) - timedelta(seconds=301)
|
||||
head = store.head(key)
|
||||
head["LastModified"] = old
|
||||
objects = [{"Key": key, "ETag": head["ETag"], "Size": len(PNG), "LastModified": old}]
|
||||
monkeypatch.setattr(store, "head", lambda _: head)
|
||||
monkeypatch.setattr(
|
||||
store.client,
|
||||
"get_paginator",
|
||||
lambda _: SimpleNamespace(paginate=lambda **_: [{"Contents": objects}]),
|
||||
)
|
||||
assert collect(db, store, 300, True)["protected"] == 1
|
||||
with db.connection(write=True) as conn:
|
||||
conn.execute(
|
||||
"UPDATE upload_reservations SET expires_at=clock_timestamp()-interval '1 second' "
|
||||
"WHERE id=%s",
|
||||
(id,),
|
||||
)
|
||||
assert collect(db, store, 300, False)["eligible"] == 1
|
||||
assert collect(db, store, 300, True)["deleted"] == 1
|
||||
with pytest.raises(DomainError) as expired:
|
||||
p.accept(
|
||||
id,
|
||||
room["id"],
|
||||
actors[0]["id"],
|
||||
"paused.png",
|
||||
"image/png",
|
||||
len(PNG),
|
||||
hashlib.sha256(PNG).hexdigest(),
|
||||
key,
|
||||
)
|
||||
assert expired.value.status == 503 and db.attachment(id) is None
|
||||
|
||||
|
||||
def test_version_fence_rejects_old_writer(client, actors, room, settings, broker):
|
||||
a = upload(client, actors[0], room).json()
|
||||
db, store = client.app.state.repository, client.app.state.attachments.store
|
||||
with db.connection() as conn:
|
||||
j = conn.execute(
|
||||
"SELECT * FROM attachment_jobs WHERE attachment_id=%s", (a["id"],)
|
||||
).fetchone()
|
||||
envelope = Job(
|
||||
schema_version=1,
|
||||
type="attachment.process.v1",
|
||||
job_id=str(j["job_id"]),
|
||||
attachment_id=a["id"],
|
||||
pipeline_version=1,
|
||||
attempt=1,
|
||||
created_at=a["created_at"],
|
||||
)
|
||||
pipeline = Pipeline(db, settings)
|
||||
outcome, old = pipeline.claim(envelope)
|
||||
assert outcome == "claimed"
|
||||
pipeline.replay(a["id"], new_version=True)
|
||||
process(client, settings, broker)
|
||||
current = db.attachment(a["id"])
|
||||
assert current["pipeline_version"] == 2 and current["storage_state"] == "ready"
|
||||
assert not pipeline.publish(old, "objects/old-result", [])
|
||||
handle(
|
||||
db,
|
||||
broker,
|
||||
store,
|
||||
settings,
|
||||
broker.publish(envelope),
|
||||
envelope.model_dump_json(exclude_none=True),
|
||||
)
|
||||
assert db.attachment(a["id"])["object_key"] == current["object_key"]
|
||||
|
||||
|
||||
def test_foreign_chat_attachment_is_not_linkable(client, actors, room):
|
||||
a = upload(client, actors[0], room).json()
|
||||
other = client.post(
|
||||
"/api/v1/chats",
|
||||
headers=headers(actors[0]),
|
||||
json={"title": "other", "member_ids": [actors[0]["id"]]},
|
||||
).json()
|
||||
error(
|
||||
client.post(
|
||||
f"/api/v1/chats/{other['id']}/messages",
|
||||
headers={**headers(actors[0]), "Idempotency-Key": uuid4().hex},
|
||||
json={"text": "", "attachment_ids": [a["id"]]},
|
||||
),
|
||||
404,
|
||||
"not_found",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"patch",
|
||||
[
|
||||
{"schema_version": True},
|
||||
{"traceparent": None},
|
||||
{"tracestate": None},
|
||||
{"url": "https://untrusted.invalid/"},
|
||||
{"job_id": "not-a-uuid"},
|
||||
{"pipeline_version": 0},
|
||||
{"attempt": 0},
|
||||
{"created_at": "2026-10-17T12:00:00"},
|
||||
{"traceparent": "invalid"},
|
||||
{"type": "download.anything"},
|
||||
],
|
||||
)
|
||||
def test_job_schema_rejects_invalid_carrier(client, settings, broker, patch):
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"type": "attachment.process.v1",
|
||||
"job_id": str(uuid4()),
|
||||
"attachment_id": str(uuid4()),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": "2026-10-17T12:00:00Z",
|
||||
**patch,
|
||||
}
|
||||
data = json.dumps(payload)
|
||||
sid = broker.client.xadd(STREAM, {"job": data})
|
||||
handle(
|
||||
client.app.state.repository, broker, client.app.state.attachments.store, settings, sid, data
|
||||
)
|
||||
assert broker.client.xrange("invalid-jobs")[0][1]["reason"] == "invalid_envelope"
|
||||
Reference in New Issue
Block a user