forked from mtusi2026/mtusi2026lab4
Добавил загрузку картинок в S3 и проверку доступа к вложениям
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
"""Integration tests against real HTTP, PostgreSQL and Redis on the local stack."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
import redis
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client
|
||||
from ops import containers
|
||||
from app.config import secret
|
||||
|
||||
|
||||
class APITests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client(timeout=8)
|
||||
self.alice = self.c.user("student")
|
||||
self.bob = self.c.user("member")
|
||||
self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "Учебный чат", "member_ids": [self.alice["id"], self.bob["id"]]},
|
||||
schema="Chat")["json"]
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def scalar(self, query, params=()):
|
||||
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2) as conn:
|
||||
return conn.execute(query, params).fetchone()[0]
|
||||
|
||||
def history(self, limit=17):
|
||||
result, cursor = [], None
|
||||
for _ in range(100):
|
||||
path = self.path + "/messages?limit=" + str(limit)
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = self.c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
|
||||
result.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return result
|
||||
self.fail("Pagination did not terminate")
|
||||
|
||||
def test_registration_race(self):
|
||||
registration = {"username": "race_" + uuid4().hex[:16], "display_name": "Гонка",
|
||||
"password": "Synthetic-password-12345"}
|
||||
def register(_):
|
||||
return self.c.call("POST", "/api/v1/users", [201, 409], body=registration,
|
||||
schema="User")["status"]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
statuses = list(pool.map(register, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users WHERE username=%s",
|
||||
(registration["username"],)), 1)
|
||||
print("RACE: 10 requests, 1 created, 9 conflicts, 1 database row", flush=True)
|
||||
|
||||
def test_composite_chat_rollback(self):
|
||||
before = self.scalar("SELECT count(*) FROM chats")
|
||||
memberships = self.scalar("SELECT count(*) FROM chat_members")
|
||||
self.c.call("POST", "/api/v1/chats", 400, actor=self.alice,
|
||||
body={"title": "Rollback", "member_ids": [self.alice["id"], str(uuid4())]})
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chats"), before)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chat_members"), memberships)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chats c WHERE NOT EXISTS "
|
||||
"(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id)"), 0)
|
||||
print("ROLLBACK: invalid second member left no chat or membership rows", flush=True)
|
||||
|
||||
def test_concurrent_messages(self):
|
||||
def send(index):
|
||||
return self.c.message(self.alice, self.chat, "parallel-" + str(index))["json"]["id"]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
ids = list(pool.map(send, range(100)))
|
||||
messages = self.history()
|
||||
self.assertEqual(len(messages), 100)
|
||||
self.assertEqual(len(set(ids)), 100)
|
||||
self.assertEqual({row["id"] for row in messages}, set(ids))
|
||||
self.assertEqual({row["text"] for row in messages}, {"parallel-" + str(i) for i in range(100)})
|
||||
self.assertEqual(messages, sorted(messages, key=lambda row: (row["created_at"], row["id"])))
|
||||
print("CONCURRENCY: 10 clients, 100 confirmations, 100 unique messages", flush=True)
|
||||
|
||||
def test_validation_and_access(self):
|
||||
for payload in [b"{", b"null", b"[]", b"\xff", b'{"text":NaN}']:
|
||||
self.c.call("POST", self.path + "/messages", 400, actor=self.alice, raw=payload,
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": uuid4().hex})
|
||||
for body in [{"text": ""}, {"text": " \n\t"}, {"text": 123}, {"text": "x" * 4001},
|
||||
{"text": "hello", "sender_id": self.bob["id"]}]:
|
||||
self.c.call("POST", self.path + "/messages", 400, actor=self.alice, body=body,
|
||||
headers={"Idempotency-Key": uuid4().hex})
|
||||
outsider = self.c.user("outsider")
|
||||
for suffix in ("", "/messages"):
|
||||
self.c.call("GET", self.path + suffix, 404, actor=outsider)
|
||||
self.c.call("POST", self.path + "/messages", 404, actor=outsider, body={"text": "hidden"})
|
||||
for members in [[self.bob["id"]], [self.alice["id"], self.alice["id"]], ["bad"], []]:
|
||||
self.c.call("POST", "/api/v1/chats", 400, actor=self.alice,
|
||||
body={"title": "Invalid", "member_ids": members})
|
||||
self.c.call("GET", "/api/v1/chats/not-uuid", 400, actor=self.alice)
|
||||
for limit in ("0", "101", "1.1", "-1", "", "true"):
|
||||
self.c.call("GET", self.path + "/messages?limit=" + limit, 400, actor=self.alice)
|
||||
self.c.call("POST", "/api/v1/users", 409, body=self.alice["registration"])
|
||||
for raw in (b"{}", b'{"username":123}', b'{"username":"ab","display_name":"x","password":"123456789012"}'):
|
||||
self.c.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
|
||||
|
||||
def test_passwords_and_authentication(self):
|
||||
registration = {"username": "unicode_" + uuid4().hex[:12], "display_name": "Имя 🧪",
|
||||
"password": "я:🧪" + "密" * 125}
|
||||
user = self.c.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
|
||||
credential = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
|
||||
session = self.c.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": "Basic " + credential}, schema="Session")["json"]
|
||||
self.assertEqual(session["user"]["id"], user["id"])
|
||||
encoded = self.scalar("SELECT password_hash FROM users WHERE id=%s", (user["id"],))
|
||||
algorithm, n, r, p, salt, digest = encoded.split("$")
|
||||
self.assertEqual(algorithm, "scrypt")
|
||||
actual = hashlib.scrypt(registration["password"].encode(), salt=bytes.fromhex(salt),
|
||||
n=int(n), r=int(r), p=int(p), dklen=32, maxmem=64 * 1024 * 1024).hex()
|
||||
self.assertTrue(actual == digest)
|
||||
self.assertNotIn("password", user)
|
||||
for username in (registration["username"], "missing_" + uuid4().hex[:12]):
|
||||
bad = base64.b64encode((username + ":wrong-password-123").encode()).decode()
|
||||
response = self.c.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers={"Authorization": "Basic " + bad})
|
||||
self.assertEqual(response["headers"]["WWW-Authenticate"], 'Basic realm="messenger", charset="UTF-8"')
|
||||
self.assertEqual(response["json"]["error"]["message"], "Valid credentials required")
|
||||
self.c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Basic " + credential})
|
||||
self.c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
self.c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "x" * 43})
|
||||
actor = {"id": user["id"], "token": session["token"]}
|
||||
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
|
||||
self.c.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
self.c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=actor)
|
||||
|
||||
def test_cursor_binding_and_chat_pages(self):
|
||||
sent = [self.c.message(self.alice, self.chat, "page-" + str(i))["json"] for i in range(7)]
|
||||
self.assertEqual(self.history(limit=2), sent)
|
||||
page = self.c.call("GET", self.path + "/messages?limit=2", actor=self.alice, schema="MessagePage")["json"]
|
||||
cursor = page["next_cursor"]
|
||||
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "Other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
|
||||
self.c.call("GET", "/api/v1/chats/" + other["id"] + "/messages?cursor=" + quote(cursor), 400, actor=self.alice)
|
||||
for token in ("bad", "", cursor[:-3] + "xxx"):
|
||||
self.c.call("GET", self.path + "/messages?cursor=" + quote(token), 400, actor=self.alice)
|
||||
later = self.c.message(self.alice, self.chat, "later")["json"]
|
||||
continued = self.c.call("GET", self.path + "/messages?limit=100&cursor=" + quote(cursor),
|
||||
actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual(continued["items"], sent[2:] + [later])
|
||||
first = self.c.call("GET", "/api/v1/chats?limit=1", actor=self.alice, schema="ChatPage")["json"]
|
||||
second = self.c.call("GET", "/api/v1/chats?limit=100&cursor=" + quote(first["next_cursor"]),
|
||||
actor=self.alice, schema="ChatPage")["json"]
|
||||
self.assertEqual([row["id"] for row in first["items"] + second["items"]],
|
||||
[self.chat["id"], other["id"]])
|
||||
|
||||
def compose(self, *args):
|
||||
result = subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
|
||||
capture_output=True, text=True, timeout=45)
|
||||
if result.returncode:
|
||||
self.fail("Compose action failed: " + " ".join(args[:2]))
|
||||
|
||||
def wait_ready(self):
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
self.c.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except AssertionError:
|
||||
time.sleep(0.25)
|
||||
self.fail("Stack did not recover")
|
||||
|
||||
def test_dependency_failures(self):
|
||||
# With all backends unready, LB may generate its own 503. Diagnose
|
||||
# the application error contract on an internal replica explicitly.
|
||||
row = containers()[0]
|
||||
self.c = Client("http://" + row["Name"].lstrip("/") + ":8080", timeout=8)
|
||||
report = {}
|
||||
for service in ("redis", "postgres"):
|
||||
self.compose("stop", "--timeout", "2", service)
|
||||
try:
|
||||
self.c.call("GET", "/health/live", schema="Health")
|
||||
ready = self.c.call("GET", "/health/ready", 503)
|
||||
started = time.monotonic()
|
||||
response = self.c.call("GET", "/api/v1/users/me", 503, actor=self.alice)
|
||||
elapsed = time.monotonic() - started
|
||||
self.assertEqual(response["json"]["error"]["code"], "unavailable")
|
||||
self.assertLess(elapsed, 6)
|
||||
self.c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.alice["id"]})
|
||||
report[service] = {"ready_status": ready["status"], "protected_status": response["status"],
|
||||
"elapsed_seconds": round(elapsed, 3), "anonymous_status": 401}
|
||||
finally:
|
||||
self.compose("start", service)
|
||||
self.wait_ready()
|
||||
self.c.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
|
||||
self.c.message(self.alice, self.chat, "after-" + service)
|
||||
(ROOT / "evidence" / "failures.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print("FAILURES: Redis/PostgreSQL -> bounded 503, live 200, anonymous 401, recovery with old session", flush=True)
|
||||
|
||||
def test_redis_crash_durability(self):
|
||||
client = redis.Redis.from_url(secret("CACHE_URL"), decode_responses=True)
|
||||
try:
|
||||
self.assertEqual(client.config_get("appendonly")["appendonly"], "yes")
|
||||
self.assertEqual(client.config_get("appendfsync")["appendfsync"], "always")
|
||||
key = "session:" + hashlib.sha256(self.alice["token"].encode()).hexdigest()
|
||||
deadline_before = client.pexpiretime(key)
|
||||
self.compose("kill", "--signal", "SIGKILL", "redis")
|
||||
self.compose("start", "redis")
|
||||
self.wait_ready()
|
||||
self.c.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
|
||||
self.assertEqual(client.pexpiretime(key), deadline_before)
|
||||
finally:
|
||||
client.close()
|
||||
print("REDIS CRASH: old session survived SIGKILL/AOF replay, expiry deadline unchanged", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Grade 4 integration checks against real stores, including fault injection."""
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
from PIL import Image
|
||||
from botocore.exceptions import ClientError
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT/'tests'), str(ROOT/'scripts')]
|
||||
from client import Client
|
||||
from ops import compose, command, containers, summary
|
||||
from app.config import Settings
|
||||
from app.store import Store
|
||||
from app.attachments import Attachments, client, BUCKET
|
||||
|
||||
class AttachmentTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client(timeout=40)
|
||||
self.a,self.b,self.e,self.chat = self.c.bootstrap()
|
||||
self.path = '/api/v1/chats/'+self.chat['id']+'/attachments?filename=photo.png'
|
||||
self.png = (ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(self, raw=None, mime='image/png', expected=201, path=None):
|
||||
return self.c.call('POST', path or self.path, expected, actor=self.a,
|
||||
raw=self.png if raw is None else raw, headers={'Content-Type':mime},
|
||||
schema='Attachment' if expected==201 else None)
|
||||
|
||||
def sql(self, query, params=()):
|
||||
with psycopg.connect(Settings.load().database_url, autocommit=True) as conn:
|
||||
return conn.execute(query, params).fetchall() if query.lstrip().upper().startswith('SELECT') else conn.execute(query,params)
|
||||
|
||||
def test_validation_and_acl(self):
|
||||
self.upload(b'x'*(10*1024*1024+1),expected=413)
|
||||
self.upload(self.png[:30],expected=415)
|
||||
self.upload(mime='image/jpeg',expected=415)
|
||||
self.upload(path=self.path.replace('photo.png','..%2Fphoto.png'),expected=400)
|
||||
bomb=io.BytesIO(); Image.new('1',(8000,5001)).save(bomb,format='PNG')
|
||||
self.upload(bomb.getvalue(),expected=413)
|
||||
jpg=io.BytesIO(); Image.new('RGB',(64,32),'red').save(jpg,format='JPEG')
|
||||
self.upload(jpg.getvalue(),mime='image/jpeg')
|
||||
item=self.upload()['json']; p='/api/v1/attachments/'+item['id']
|
||||
for suffix in ('','/content'):
|
||||
self.c.call('GET',p+suffix,404,actor=self.e)
|
||||
self.c.call('GET',p,401)
|
||||
self.c.call('GET',p+'/content',actor=self.b)
|
||||
other=self.c.call('POST','/api/v1/chats',201,actor=self.a,body={
|
||||
'title':'Other','member_ids':[self.a['id']]},schema='Chat')['json']
|
||||
foreign=self.upload(path=self.path.replace(self.chat['id'],other['id']))['json']
|
||||
for aid in (foreign['id'],str(uuid4())):
|
||||
self.c.call(
|
||||
'POST','/api/v1/chats/'+self.chat['id']+'/messages',404,actor=self.a,
|
||||
body={'text':'foreign','attachment_ids':[aid]},headers={'Idempotency-Key':uuid4().hex})
|
||||
message=self.c.message(self.a,self.chat,'',attachments=[item['id']])
|
||||
self.assertEqual(message['json']['attachment_ids'],[item['id']])
|
||||
self.c.call('POST','/api/v1/chats/'+self.chat['id']+'/messages',400,actor=self.a,
|
||||
body={'text':' '},headers={'Idempotency-Key':uuid4().hex})
|
||||
|
||||
def test_private_bucket_and_bootstrap(self):
|
||||
item=self.upload()['json']
|
||||
import urllib.request, urllib.error
|
||||
key=self.sql('SELECT object_key FROM attachments WHERE id=%s',(item['id'],))[0][0]
|
||||
for path in ('attachments', 'attachments/'+key):
|
||||
try:
|
||||
urllib.request.urlopen('http://minio:9000/'+path,timeout=3)
|
||||
self.fail('Anonymous access succeeded')
|
||||
except urllib.error.HTTPError as error:
|
||||
self.assertEqual(error.code,403)
|
||||
s3=client()
|
||||
for operation in (lambda:s3.create_bucket(Bucket='forbidden'),
|
||||
lambda:s3.put_object(Bucket=BUCKET,Key='outside-prefix',Body=b'x')):
|
||||
with self.assertRaises(ClientError) as caught:
|
||||
operation()
|
||||
self.assertEqual(caught.exception.response['ResponseMetadata']['HTTPStatusCode'],403)
|
||||
bootstrap = containers('bucket-init', running=False)[0]['Id']
|
||||
command(['docker','start','-a',bootstrap]); command(['docker','start','-a',bootstrap])
|
||||
result=self.c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=self.b)
|
||||
self.assertEqual(result['bytes'],self.png)
|
||||
|
||||
def test_failed_commit_cleanup_and_abort(self):
|
||||
# A partial client body cannot reach PUT.
|
||||
before=self.sql('SELECT count(*) FROM attachments')[0][0]
|
||||
sock=socket.create_connection(('lb',8080),timeout=3)
|
||||
request=('POST '+self.path+' HTTP/1.1\r\nHost: lb\r\nAuthorization: Bearer '+self.a['token']+
|
||||
'\r\nContent-Type: image/png\r\nContent-Length: 10000\r\n\r\n').encode()+self.png[:20]
|
||||
sock.sendall(request); sock.close(); time.sleep(.3)
|
||||
self.assertEqual(before,self.sql('SELECT count(*) FROM attachments')[0][0])
|
||||
self.sql("""CREATE OR REPLACE FUNCTION lab4_fail_ready() RETURNS trigger LANGUAGE plpgsql AS
|
||||
$$ BEGIN IF NEW.status='ready' AND NEW.filename='fault.png' THEN
|
||||
RAISE EXCEPTION 'injected commit failure'; END IF; RETURN NEW; END $$""")
|
||||
self.sql('CREATE TRIGGER lab4_fail_ready BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_fail_ready()')
|
||||
try:
|
||||
self.upload(path=self.path.replace('photo.png','fault.png'),expected=503)
|
||||
finally:
|
||||
self.sql('DROP TRIGGER lab4_fail_ready ON attachments'); self.sql('DROP FUNCTION lab4_fail_ready()')
|
||||
aid,key=self.sql("SELECT id,object_key FROM attachments WHERE filename='fault.png' AND chat_id=%s",(self.chat['id'],))[0]
|
||||
s3=client(); s3.head_object(Bucket=BUCKET,Key=key)
|
||||
async def cleanup():
|
||||
store=Store(Settings.load()); await store.open()
|
||||
try: return await Attachments(store).cleanup()
|
||||
finally: await store.close()
|
||||
asyncio.run(cleanup())
|
||||
s3.head_object(Bucket=BUCKET,Key=key) # grace protects the fresh pending object
|
||||
self.sql("UPDATE attachments SET created_at=clock_timestamp()-interval '2 hours' WHERE id=%s",(aid,))
|
||||
self.assertGreaterEqual(asyncio.run(cleanup()),1)
|
||||
asyncio.run(cleanup()) # repeat is harmless
|
||||
self.assertFalse(self.sql('SELECT id FROM attachments WHERE id=%s',(aid,)))
|
||||
with self.assertRaises(ClientError): s3.head_object(Bucket=BUCKET,Key=key)
|
||||
self.upload() # ready original survives cleanup
|
||||
|
||||
def test_s3_outage(self):
|
||||
item=self.upload()['json']
|
||||
direct=Client('http://api:8080',timeout=10)
|
||||
compose('stop','minio')
|
||||
try:
|
||||
direct.call('GET','/health/live',schema='Health')
|
||||
direct.call('GET','/health/ready',503)
|
||||
direct.call('POST',self.path,503,actor=self.a,raw=self.png,headers={'Content-Type':'image/png'})
|
||||
direct.call('GET','/api/v1/attachments/'+item['id']+'/content',503,actor=self.a)
|
||||
finally:
|
||||
compose('start','minio')
|
||||
time.sleep(5)
|
||||
self.assertEqual(self.c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=self.b)['bytes'],self.png)
|
||||
|
||||
def test_ten_parallel_uploads_memory(self):
|
||||
# RGB random image is poorly compressible, roughly 8 MiB.
|
||||
image=Image.frombytes('RGB',(1700,1600),os.urandom(1700*1600*3))
|
||||
out=io.BytesIO(); image.save(out,format='PNG'); raw=out.getvalue()
|
||||
ids=[x['Id'] for x in containers()]
|
||||
barrier=threading.Barrier(11); stop=threading.Event(); samples=[]
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
rows=[]
|
||||
for cid in ids:
|
||||
value=command(['docker','exec',cid,'cat','/sys/fs/cgroup/memory.current'])
|
||||
rows.append(int(value))
|
||||
samples.append({'elapsed':round(time.monotonic()-start,3),'bytes':rows})
|
||||
stop.wait(.1)
|
||||
start=time.monotonic(); sampler=threading.Thread(target=sample); sampler.start()
|
||||
def upload(_):
|
||||
barrier.wait()
|
||||
t=time.monotonic(); item=self.upload(raw)['json']
|
||||
got=self.c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=self.b)['bytes']
|
||||
self.assertEqual(hashlib.sha256(got).hexdigest(),hashlib.sha256(raw).hexdigest())
|
||||
return time.monotonic()-t
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures=[pool.submit(upload,i) for i in range(10)]
|
||||
barrier.wait(); durations=[f.result() for f in futures]
|
||||
finally:
|
||||
stop.set(); sampler.join()
|
||||
result={'concurrency':10,'successful':len(durations),'size_bytes':len(raw),
|
||||
'duration_seconds':time.monotonic()-start,'upload_and_download_seconds':durations,
|
||||
'api_container_ids':ids,'memory_samples':samples,
|
||||
'sampled_peak_bytes':[max(s['bytes'][i] for s in samples) for i in range(len(ids))],
|
||||
'cgroup_memory_peak_bytes':[int(command(['docker','exec',cid,'cat','/sys/fs/cgroup/memory.peak'])) for cid in ids],
|
||||
'memory_limit_bytes':512*1024*1024,
|
||||
'note':'memory.current includes cache and runtime; memory.peak covers container lifetime, not only experiment'}
|
||||
(ROOT/'evidence/uploads-memory.json').write_text(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__': unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Cross-process idempotency, access and transaction boundaries."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client
|
||||
from ops import containers
|
||||
from app.config import secret
|
||||
|
||||
|
||||
class ReplicationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
|
||||
def sql(self, query, values=()):
|
||||
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2) as conn:
|
||||
cur = conn.execute(query, values)
|
||||
return cur.fetchall() if cur.description else None
|
||||
|
||||
def test_parallel_replay_across_real_replicas(self):
|
||||
replicas = containers()
|
||||
self.assertGreaterEqual(len(replicas), 2)
|
||||
clients = [Client("http://" + row["Name"].lstrip("/") + ":8080") for row in replicas]
|
||||
barrier = threading.Barrier(10)
|
||||
key = uuid4().hex
|
||||
def send(index):
|
||||
if index < 10:
|
||||
barrier.wait()
|
||||
return clients[index % len(clients)].message(self.alice, self.chat, "Один результат 🧪", key=key)
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(100)))
|
||||
self.assertEqual(len({r["json"]["id"] for r in responses}), 1)
|
||||
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
|
||||
self.assertTrue(all(r["json"] == responses[0]["json"] for r in responses))
|
||||
self.assertEqual(self.sql("SELECT count(*) FROM messages WHERE chat_id=%s", (self.chat["id"],))[0][0], 1)
|
||||
self.assertEqual(self.sql("SELECT count(*) FROM message_requests WHERE chat_id=%s", (self.chat["id"],))[0][0], 1)
|
||||
for _ in range(12):
|
||||
self.assertEqual(self.c.message(self.alice, self.chat, "Один результат 🧪", key=key)["json"], responses[0]["json"])
|
||||
report = {"requests": 100, "clients": 10, "real_containers": len(replicas),
|
||||
"observed_instances": len({r["headers"]["X-Instance-Id"] for r in responses}),
|
||||
"messages": 1, "replay_records": 1, "lb_replays": 12}
|
||||
(ROOT / "evidence" / "idempotency.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
def test_key_validation_scope_conflict_and_logout(self):
|
||||
for key in (None, "", "bad key", "bad/key", "a" * 129):
|
||||
headers = {} if key is None else {"Idempotency-Key": key}
|
||||
self.c.call("POST", self.path, 400, actor=self.alice, body={"text": "test"}, headers=headers)
|
||||
key = uuid4().hex
|
||||
first = self.c.message(self.alice, self.chat, "first", key=key)["json"]
|
||||
replay = self.c.call("POST", self.path, 201, actor=self.alice,
|
||||
raw=b'{\n "text" : "first"\n}', headers={"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
schema="Message")["json"]
|
||||
self.assertEqual(first, replay)
|
||||
self.c.call("POST", self.path, 409, actor=self.alice, body={"text": "changed"}, headers={"Idempotency-Key": key})
|
||||
second = self.c.message(self.bob, self.chat, "first", key=key)["json"]
|
||||
self.assertNotEqual(first["id"], second["id"])
|
||||
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "scope", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
|
||||
self.assertNotEqual(self.c.message(self.alice, other, "first", key=key)["json"]["id"], first["id"])
|
||||
self.c.call("POST", self.path, 404, actor=self.eve, body={"text": "first"}, headers={"Idempotency-Key": key})
|
||||
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
|
||||
self.c.call("POST", self.path, 401, actor=self.alice, body={"text": "first"}, headers={"Idempotency-Key": key})
|
||||
|
||||
def test_failed_transaction_does_not_save_message_or_replay(self):
|
||||
key = uuid4().hex
|
||||
# Fail after INSERT messages, at INSERT replay, to check the whole
|
||||
# transaction rather than merely validation before the first write.
|
||||
self.sql("""CREATE FUNCTION lab3_test_reject() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'synthetic transaction failure'; END $$""")
|
||||
self.sql("CREATE TRIGGER lab3_test_reject BEFORE INSERT ON message_requests "
|
||||
"FOR EACH ROW EXECUTE FUNCTION lab3_test_reject()")
|
||||
try:
|
||||
self.c.call("POST", self.path, 503, actor=self.alice, body={"text": "atomic"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.sql("SELECT count(*) FROM messages WHERE chat_id=%s", (self.chat["id"],))[0][0], 0)
|
||||
self.assertEqual(self.sql("SELECT count(*) FROM message_requests WHERE chat_id=%s", (self.chat["id"],))[0][0], 0)
|
||||
finally:
|
||||
self.sql("DROP TRIGGER lab3_test_reject ON message_requests")
|
||||
self.sql("DROP FUNCTION lab3_test_reject()")
|
||||
first = self.c.message(self.alice, self.chat, "atomic", key=key)["json"]
|
||||
self.assertEqual(self.c.message(self.alice, self.chat, "atomic", key=key)["json"], first)
|
||||
|
||||
def test_expired_key_and_same_session_on_all_instances(self):
|
||||
observed = set()
|
||||
for _ in range(30):
|
||||
response = self.c.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
|
||||
self.assertEqual(response["json"]["id"], self.alice["id"])
|
||||
observed.add(response["headers"]["X-Instance-Id"])
|
||||
self.assertGreaterEqual(len(observed), 2)
|
||||
key = uuid4().hex
|
||||
original = self.c.message(self.alice, self.chat, "before expiry", key=key)["json"]
|
||||
self.sql("UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second' "
|
||||
"WHERE user_id=%s AND chat_id=%s AND request_key=%s", (self.alice["id"], self.chat["id"], key))
|
||||
fresh = self.c.message(self.alice, self.chat, "after expiry", key=key)["json"]
|
||||
self.assertNotEqual(original["id"], fresh["id"])
|
||||
self.assertEqual(self.c.message(self.alice, self.chat, "after expiry", key=key)["json"], fresh)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user