Реализовать lab2: PostgreSQL и постоянные Bearer-сессии
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
"""Run against a separate API with SESSION_TTL_SECONDS=2."""
|
||||
import sys,time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,run
|
||||
|
||||
def main():
|
||||
c=Client('http://localhost:8081')
|
||||
a=c.user('expiry')
|
||||
c.call('GET','/api/v1/users/me',actor=a,schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET','/api/v1/users/me',401,actor=a)
|
||||
print('PASS: a real short-lived session authenticates before expiry and returns 401 after expiry')
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Real Docker restart evidence plus repeated migrations, expiry, DB failure."""
|
||||
import json,subprocess,sys,time,urllib.request,urllib.error
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,check,run
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args,cwd=ROOT,text=True).strip()
|
||||
|
||||
def snapshot():
|
||||
for service in ('api','db','cache'):
|
||||
container=command('docker','compose','ps','-q',service)
|
||||
value=command('docker','inspect','--format','{{.Id}} {{.State.StartedAt}} {{.RestartCount}}',container)
|
||||
print(service,value,flush=True)
|
||||
print('DB postmaster:',command('docker','compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc','select pg_postmaster_start_time()'),flush=True)
|
||||
|
||||
def wait_ready(url):
|
||||
for _ in range(90):
|
||||
try:
|
||||
if urllib.request.urlopen(url,timeout=2).status==200: return
|
||||
except (OSError,urllib.error.URLError): pass
|
||||
time.sleep(1)
|
||||
raise AssertionError('Readiness timeout')
|
||||
|
||||
def main():
|
||||
print('Before full restart:',flush=True); snapshot()
|
||||
subprocess.run(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh'],cwd=ROOT,check=True)
|
||||
print('After full restart:',flush=True); snapshot()
|
||||
sql='select (select count(*) from users),(select count(*) from chats),(select count(*) from messages),(select count(*) from sessions),(select count(*) from schema_migrations)'
|
||||
def counts(): return command('docker','compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',sql)
|
||||
before=counts()
|
||||
for _ in range(2):
|
||||
print(command('docker','compose','exec','-T','api','python','src/migrate.py'),flush=True)
|
||||
check(before==counts(),'Migration rerun changed counts')
|
||||
print('PASS: two migration reruns; users/chats/messages/sessions/migrations counts unchanged:',before,flush=True)
|
||||
# Separate short-TTL process, same database, isolated port; no change to normal API TTL.
|
||||
subprocess.run(['docker','compose','run','-d','--no-deps','--name','lab2-expiry','-e','SESSION_TTL_SECONDS=2','-p','127.0.0.1:8081:8080','api'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
|
||||
try:
|
||||
wait_ready('http://localhost:8081/health/ready')
|
||||
subprocess.run([sys.executable,'student-tests/expiry.py'],cwd=ROOT,check=True)
|
||||
finally:
|
||||
subprocess.run(['docker','rm','-f','lab2-expiry'],check=True,stdout=subprocess.DEVNULL)
|
||||
c=Client(timeout=10)
|
||||
actor=c.user('db_failure')
|
||||
subprocess.run(['docker','compose','stop','db'],cwd=ROOT,check=True)
|
||||
try:
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('GET','/api/v1/users/me',503,actor=actor)
|
||||
print('PASS: DB down: live=200, ready=503, authenticated request=503; no anonymous fallback',flush=True)
|
||||
finally:
|
||||
subprocess.run(['docker','compose','start','db'],cwd=ROOT,check=True)
|
||||
wait_ready('http://localhost:8080/health/ready')
|
||||
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
print('PASS: DB recovered; same session works',flush=True)
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Adapted from Karpova lab1 archive: password + Basic/Bearer transition only."""
|
||||
"""100 concurrent message writes from 10 client identities."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
|
||||
def call(method, path, *, body=None, actor=None):
|
||||
headers = {"Accept": "application/json", "Content-Type": "application/json"}
|
||||
if actor:
|
||||
headers["Authorization"] = "Bearer " + actor["token"]
|
||||
raw = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
|
||||
request = Request(BASE_URL + path, data=raw, headers=headers, method=method)
|
||||
try:
|
||||
response = urlopen(request, timeout=10)
|
||||
status = response.status
|
||||
data = response.read()
|
||||
except HTTPError as error:
|
||||
status = error.code
|
||||
data = error.read()
|
||||
payload = json.loads(data) if data else None
|
||||
return status, payload
|
||||
|
||||
|
||||
def create_user(label):
|
||||
status, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={
|
||||
"username": "c_" + label + "_" + uuid.uuid4().hex[:8],
|
||||
"display_name": "Client " + label, "password": "Synthetic-lab1-port-123",
|
||||
},
|
||||
)
|
||||
assert status == 201, (status, payload)
|
||||
basic = base64.b64encode((payload['username']+':Synthetic-lab1-port-123').encode()).decode()
|
||||
req = Request(BASE_URL+'/api/v1/auth/sessions', method='POST', headers={'Authorization':'Basic '+basic})
|
||||
with urlopen(req, timeout=10) as response:
|
||||
payload['token'] = json.load(response)['token']
|
||||
return payload
|
||||
|
||||
|
||||
def main():
|
||||
clients = [create_user(str(i)) for i in range(10)]
|
||||
status, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
actor=clients[0],
|
||||
body={"title": "Concurrent test", "member_ids": [x["id"] for x in clients]},
|
||||
)
|
||||
assert status == 201, (status, chat)
|
||||
|
||||
def send(client_index):
|
||||
actor = clients[client_index]
|
||||
status, payload = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
actor=actor,
|
||||
body={"text": f"concurrent-client-{client_index}-message-{uuid.uuid4().hex}"},
|
||||
)
|
||||
return status, payload
|
||||
|
||||
results = []
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures = [pool.submit(send, i % 10) for i in range(100)]
|
||||
for future in as_completed(futures):
|
||||
results.append(future.result())
|
||||
|
||||
statuses = [status for status, _ in results]
|
||||
assert all(status == 201 for status in statuses), f"unexpected statuses: {statuses}"
|
||||
|
||||
status, page = call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||||
actor=clients[0],
|
||||
)
|
||||
assert status == 200, (status, page)
|
||||
ids = [item["id"] for item in page["items"]]
|
||||
assert len(ids) == 100, f"expected 100 messages, got {len(ids)}"
|
||||
assert len(set(ids)) == 100, "message IDs are not unique"
|
||||
assert page["next_cursor"] is None, "100 messages should fit one page"
|
||||
|
||||
print("PASS: 10 concurrent clients -> 100 successful messages -> 100 unique messages")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Adapted from Karpova lab1 archive: password + Basic/Bearer transition only."""
|
||||
"""Student tests for MTUSI Lab1 level 4 requirements."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
|
||||
def call(method, path, *, body=None, actor=None, raw=None, content_type=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if actor:
|
||||
headers["Authorization"] = "Bearer " + actor["token"]
|
||||
if body is not None:
|
||||
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
content_type = "application/json"
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
req = Request(BASE_URL + path, data=raw, headers=headers, method=method)
|
||||
try:
|
||||
response = urlopen(req, timeout=5)
|
||||
status = response.status
|
||||
data = response.read()
|
||||
headers = response.headers
|
||||
except HTTPError as error:
|
||||
status = error.code
|
||||
data = error.read()
|
||||
headers = error.headers
|
||||
payload = None
|
||||
if headers.get_content_type() == "application/json" and data:
|
||||
payload = json.loads(data)
|
||||
return status, headers, payload
|
||||
|
||||
|
||||
def expect(status, actual, label):
|
||||
assert actual == status, f"{label}: expected {status}, got {actual}"
|
||||
|
||||
|
||||
def create_user(label, username=None):
|
||||
username = username or ("t_" + label + "_" + uuid.uuid4().hex[:10])
|
||||
status, headers, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={"username": username, "display_name": "Тест " + label, "password": "Synthetic-lab1-port-123"},
|
||||
)
|
||||
expect(201, status, "create user")
|
||||
basic = base64.b64encode((payload['username']+':Synthetic-lab1-port-123').encode()).decode()
|
||||
req = Request(BASE_URL+'/api/v1/auth/sessions', method='POST', headers={'Authorization':'Basic '+basic})
|
||||
with urlopen(req, timeout=10) as response:
|
||||
payload['token'] = json.load(response)['token']
|
||||
return payload
|
||||
|
||||
|
||||
def main():
|
||||
# 1) malformed JSON must be 400, not FastAPI's default 422.
|
||||
status, headers, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
raw=b'{"username":',
|
||||
content_type="application/json",
|
||||
)
|
||||
expect(400, status, "malformed JSON")
|
||||
assert payload["error"]["code"] == "invalid_request"
|
||||
assert headers.get("X-Request-Id") == payload["error"]["request_id"]
|
||||
|
||||
# 2) Duplicate username must be 409.
|
||||
username = "dup_" + uuid.uuid4().hex[:8]
|
||||
create_user("one", username=username)
|
||||
status, _, payload = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={"username": username, "display_name": "Дубликат", "password": "Synthetic-lab1-port-123"},
|
||||
)
|
||||
expect(409, status, "duplicate username")
|
||||
assert payload["error"]["code"] == "conflict"
|
||||
|
||||
alice = create_user("alice")
|
||||
bob = create_user("bob")
|
||||
eve = create_user("eve")
|
||||
|
||||
# 3) Create a private chat for Alice + Bob. Eve must not see it.
|
||||
status, _, chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
actor=alice,
|
||||
body={"title": "Private test", "member_ids": [alice["id"], bob["id"]]},
|
||||
)
|
||||
expect(201, status, "create chat")
|
||||
|
||||
status, _, _ = call("GET", f"/api/v1/chats/{chat['id']}", actor=eve)
|
||||
expect(404, status, "outsider chat access")
|
||||
|
||||
# 4) Blank message must be 400.
|
||||
status, _, payload = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
actor=alice,
|
||||
body={"text": " "},
|
||||
)
|
||||
expect(400, status, "blank message")
|
||||
assert payload["error"]["code"] == "invalid_request"
|
||||
|
||||
# 5) Send 3 messages and walk multiple pages using cursor.
|
||||
message_ids = []
|
||||
for i in range(3):
|
||||
status, _, message = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
actor=alice if i % 2 == 0 else bob,
|
||||
body={"text": f"page-{i} Привет 👋"},
|
||||
)
|
||||
expect(201, status, "create message")
|
||||
message_ids.append(message["id"])
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=1"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
status, _, payload = call("GET", path, actor=bob)
|
||||
expect(200, status, "message page")
|
||||
seen.extend(x["id"] for x in payload["items"])
|
||||
cursor = payload["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
|
||||
assert len(seen) == 3, f"pagination returned {len(seen)} messages"
|
||||
assert len(set(seen)) == 3, "pagination duplicated a message"
|
||||
assert set(seen) == set(message_ids), "pagination lost a message"
|
||||
|
||||
# A messages cursor from another resource is invalid.
|
||||
status, _, payload = call("GET", "/api/v1/chats?limit=1", actor=bob)
|
||||
expect(200, status, "chat list")
|
||||
bad_cursor = payload["next_cursor"]
|
||||
if bad_cursor is None:
|
||||
# Create enough chats to get a cursor.
|
||||
for i in range(2):
|
||||
call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
actor=bob,
|
||||
body={"title": f"Extra {i}", "member_ids": [bob["id"]]},
|
||||
)
|
||||
status, _, payload = call("GET", "/api/v1/chats?limit=1", actor=bob)
|
||||
expect(200, status, "chat list second try")
|
||||
bad_cursor = payload["next_cursor"]
|
||||
status, _, err = call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={quote(bad_cursor, safe='')}",
|
||||
actor=bob,
|
||||
)
|
||||
expect(400, status, "cursor from another resource")
|
||||
assert err["error"]["code"] == "invalid_request"
|
||||
|
||||
print("PASS: own negative, access-control and multi-page tests")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Exercise Redis cache, safe fallback and real post-insert transactional rollback."""
|
||||
import json,subprocess,sys,time,uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,check,run
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def cmd(*args):
|
||||
return subprocess.check_output(args,cwd=ROOT,text=True).strip()
|
||||
|
||||
def sql(statement):
|
||||
return cmd('docker','compose','exec','-T','db','psql','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger','-Atc',statement)
|
||||
|
||||
def redis(*args):
|
||||
return cmd('docker','compose','exec','-T','cache','redis-cli','--raw',*args)
|
||||
|
||||
def main():
|
||||
c=Client(timeout=10); actor=c.user('cache')
|
||||
key='profile:v1:'+actor['id']
|
||||
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
cached=json.loads(redis('GET',key))
|
||||
check(cached==actor['user'],'profile not actually cached')
|
||||
remaining=int(redis('TTL',key)); check(0<remaining<=60,'profile cache TTL missing')
|
||||
def hits():
|
||||
return int(next(line.split(':')[1] for line in redis('INFO','stats').splitlines() if line.startswith('keyspace_hits:')))
|
||||
before=hits()
|
||||
for _ in range(3): c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
check(hits()>=before+3,'API did not read Redis')
|
||||
print('PASS: actual cached public profile, TTL <=60 seconds, at least 3 Redis cache hits',flush=True)
|
||||
subprocess.run(['docker','compose','stop','cache'],cwd=ROOT,check=True)
|
||||
try:
|
||||
start=time.monotonic()
|
||||
result=c.call('GET','/api/v1/users/me',actor=actor,schema='User')['json']
|
||||
elapsed=time.monotonic()-start
|
||||
print('Cache outage diagnostic: profile_matches=%s elapsed_seconds=%.3f'%(result==actor['user'],elapsed),flush=True)
|
||||
check(result==actor['user'] and elapsed<3,'cache fallback incorrect or unbounded')
|
||||
c.call('GET','/api/v1/users/me',401)
|
||||
c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Bearer random-invalid-token'})
|
||||
c.call('GET','/health/ready',schema='Health')
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=actor)
|
||||
c.call('GET','/api/v1/users/me',401,actor=actor)
|
||||
print('PASS: Redis down: PostgreSQL fallback %.3fs, ready=200, invalid/absent/revoked sessions=401'%elapsed,flush=True)
|
||||
finally:
|
||||
subprocess.run(['docker','compose','start','cache'],cwd=ROOT,check=True)
|
||||
for _ in range(30):
|
||||
try:
|
||||
if redis('PING')=='PONG': break
|
||||
except subprocess.CalledProcessError: pass
|
||||
time.sleep(1)
|
||||
check(redis('EXISTS',key)=='0','cache unexpectedly persisted test key')
|
||||
actor=c.user('cache_recovery')
|
||||
for _ in range(5):
|
||||
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
if redis('EXISTS','profile:v1:'+actor['id'])=='1': break
|
||||
time.sleep(1)
|
||||
check(redis('EXISTS','profile:v1:'+actor['id'])=='1','cache did not recover')
|
||||
print('PASS: ephemeral Redis restart: cache is rebuilt; no session source of truth lost',flush=True)
|
||||
# Inject a scoped storage failure on member INSERT, after the chat INSERT.
|
||||
title='rollback_'+uuid.uuid4().hex
|
||||
function='lab2_test_'+uuid.uuid4().hex
|
||||
trigger=function+'_trigger'
|
||||
sql("CREATE FUNCTION "+function+"() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF EXISTS (SELECT 1 FROM chats WHERE id=NEW.chat_id AND title='"+title+"') THEN RAISE EXCEPTION 'synthetic member insert failure' USING ERRCODE='23514'; END IF; RETURN NEW; END $$; CREATE TRIGGER "+trigger+" BEFORE INSERT ON members FOR EACH ROW EXECUTE FUNCTION "+function+"();")
|
||||
try:
|
||||
c.call('POST','/api/v1/chats',503,actor=actor,body={'title':title,'member_ids':[actor['id']]})
|
||||
check(sql("SELECT count(*) FROM chats WHERE title='"+title+"'")=='0','partial chat survived failed member INSERT')
|
||||
check(sql('SELECT count(*) FROM members m LEFT JOIN chats c ON c.id=m.chat_id WHERE c.id IS NULL')=='0','orphan membership')
|
||||
print('PASS: injected failure AFTER chat INSERT: HTTP 503, transaction rolled back chat and members',flush=True)
|
||||
finally:
|
||||
sql('DROP TRIGGER '+trigger+' ON members; DROP FUNCTION '+function+'();')
|
||||
c.call('POST','/api/v1/chats',201,actor=actor,body={'title':'after rollback','member_ids':[actor['id']]},schema='Chat')
|
||||
print('PASS: same API remains usable after rollback',flush=True)
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Track 2: isolated 120k-row study, actual pg_dump/restore and content verification."""
|
||||
import datetime,json,subprocess,time,uuid
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def worker(mode,database,host=None):
|
||||
r=subprocess.run(['docker','compose','exec','-T','api','python','-',mode,database]+([host] if host else []),cwd=ROOT,input=(ROOT/'student-tests/research_worker.py').read_text(),stdout=subprocess.PIPE,text=True,check=True)
|
||||
return json.loads(r.stdout)
|
||||
|
||||
def main():
|
||||
suffix=uuid.uuid4().hex[:10]; source='lab2_study_'+suffix; restored=source+'_restored'
|
||||
print('Fresh isolated databases:',source,restored,flush=True)
|
||||
prepared=worker('prepare',source)
|
||||
print('Seeded',prepared['messages'],'synthetic messages:',prepared['distribution'],flush=True)
|
||||
result=worker('benchmark',source)
|
||||
dump='/tmp/'+source+'.dump'
|
||||
recovery='lab2-recovery-'+suffix; volume=recovery+'-data'
|
||||
container=subprocess.check_output(['docker','compose','ps','-q','api'],cwd=ROOT,text=True).strip()
|
||||
network=next(iter(json.loads(subprocess.check_output(['docker','inspect','--format','{{json .NetworkSettings.Networks}}',container],text=True))))
|
||||
subprocess.run(['docker','volume','create',volume],check=True,stdout=subprocess.DEVNULL)
|
||||
started=False
|
||||
def db(*args):
|
||||
subprocess.run(['docker','compose','exec','-T','db',*args],cwd=ROOT,check=True)
|
||||
try:
|
||||
start=time.perf_counter();db('pg_dump','-U','messenger','-d',source,'-Fc','-f',dump); backup_s=time.perf_counter()-start
|
||||
start=time.perf_counter()
|
||||
subprocess.run(['docker','run','-d','--name',recovery,'--network',network,
|
||||
'-e','POSTGRES_DB='+restored,'-e','POSTGRES_USER=messenger',
|
||||
'-e','POSTGRES_PASSWORD_FILE=/run/secrets/db_password',
|
||||
'--mount','type=bind,src='+str(ROOT/'secrets/db_password')+',dst=/run/secrets/db_password,readonly',
|
||||
'--mount','type=volume,src='+volume+',dst=/var/lib/postgresql/data',
|
||||
'postgres:17.6-bookworm'],check=True,stdout=subprocess.DEVNULL)
|
||||
started=True
|
||||
for _ in range(60):
|
||||
probe=subprocess.run(['docker','exec',recovery,'pg_isready','-U','messenger','-d',restored],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
if probe.returncode==0:
|
||||
break
|
||||
time.sleep(1)
|
||||
# Wait until final server accepts TCP inside the default network.
|
||||
for _ in range(60):
|
||||
probe=subprocess.run(['docker','exec',recovery,'pg_isready','-h','127.0.0.1','-U','messenger','-d',restored],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
if probe.returncode==0: break
|
||||
time.sleep(1)
|
||||
else: raise RuntimeError('Restoration server did not become ready')
|
||||
producer=subprocess.Popen(['docker','compose','exec','-T','db','cat',dump],cwd=ROOT,stdout=subprocess.PIPE)
|
||||
try:
|
||||
consumer=subprocess.run(['docker','exec','-i',recovery,'pg_restore','-U','messenger','-d',restored,'--exit-on-error','--no-owner'],stdin=producer.stdout)
|
||||
producer.stdout.close()
|
||||
code=producer.wait()
|
||||
if code or consumer.returncode: raise RuntimeError('Backup stream or restore failed')
|
||||
finally:
|
||||
if producer.poll() is None: producer.kill();producer.wait()
|
||||
restore_s=time.perf_counter()-start
|
||||
start=time.perf_counter();actual=worker('verify',restored,recovery);verify_s=time.perf_counter()-start
|
||||
expected=result.pop('fingerprint')
|
||||
if actual!=expected: raise AssertionError('Restored counts, full message digest or samples differ')
|
||||
size=int(subprocess.check_output(['docker','compose','exec','-T','db','stat','-c','%s',dump],cwd=ROOT,text=True))
|
||||
result['backup_restore']={'backup_s':backup_s,'fresh_container_bootstrap_and_restore_s':restore_s,'verification_s':verify_s,'dump_bytes':size,'expected':expected,'restored':actual,'identical':True,'source_database':source,'restored_database':restored,'new_volume':volume,'recovery_container':recovery,'limitation':'logical snapshot; no PITR or concurrent writes; separate PostgreSQL instance and fresh named volume on the same physical Docker host'}
|
||||
result['utc']=datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
(ROOT/'evidence/query-study.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')
|
||||
print('PASS: 2 indexes, 3 rounds, 3 query profiles, 20 measured reads/profile, real 5000-row writes with rollback',flush=True)
|
||||
print('PASS: pg_dump -> NEW PostgreSQL container + NEW volume -> table counts + ALL 120000 messages SHA256 + selected messages match',flush=True)
|
||||
print('Backup %.3fs; restore %.3fs; verification %.3fs; dump %d bytes'%(backup_s,restore_s,verify_s,size),flush=True)
|
||||
for variant in ['global','chat_first']:
|
||||
rows=[r for r in result['results'] if r['variant']==variant]
|
||||
print(variant,'5000-row insert ms:',[round(r['insert_5000_ms'],3) for r in rows],flush=True)
|
||||
for scenario in ['hot-middle','medium-first','tiny-first']:
|
||||
print(variant,scenario,'median ms per round:',[round(q['median_ms'],3) for r in rows for q in r['queries'] if q['scenario']==scenario],flush=True)
|
||||
finally:
|
||||
# Only objects created by this run; main messenger database and named volume are never removed.
|
||||
db('rm','-f',dump)
|
||||
if started: subprocess.run(['docker','rm','-f',recovery],check=True,stdout=subprocess.DEVNULL)
|
||||
print('Research source database and recovered volume retained for inspection; recovery process stopped; no dump/credentials included in evidence.',flush=True)
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Executed inside API container by research.py, only in fresh research databases."""
|
||||
import hashlib,json,os,statistics,sys,time,uuid
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
mode,dbname=sys.argv[1:3]
|
||||
if not dbname.startswith('lab2_study_') or not dbname.replace('_','').isalnum():
|
||||
raise ValueError('Expected isolated study database name')
|
||||
base=Path(os.environ['DATABASE_URL_FILE']).read_text().strip()
|
||||
dsn=make_conninfo(base,dbname=dbname, **({"host":sys.argv[3]} if len(sys.argv)>3 else {}))
|
||||
|
||||
def fingerprint(conn):
|
||||
counts={t:conn.execute('SELECT count(*) AS n FROM '+t).fetchone()['n'] for t in ['users','chats','members','messages','sessions','schema_migrations']}
|
||||
digest=hashlib.sha256()
|
||||
with conn.cursor(name='verify_messages') as cur:
|
||||
cur.execute('SELECT id,chat_id,sender_id,text,created_at FROM messages ORDER BY id')
|
||||
for row in cur:
|
||||
digest.update(json.dumps(row,sort_keys=True,default=str,ensure_ascii=False).encode()+b'\n')
|
||||
samples=conn.execute("SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE id IN (md5('message-1')::uuid,md5('message-100000')::uuid,md5('message-120000')::uuid) ORDER BY id").fetchall()
|
||||
return {'counts':counts,'messages_sha256':digest.hexdigest(),'samples':samples}
|
||||
|
||||
if mode=='prepare':
|
||||
with psycopg.connect(base,autocommit=True) as admin:
|
||||
from psycopg import sql
|
||||
admin.execute(sql.SQL('CREATE DATABASE {}').format(sql.Identifier(dbname)))
|
||||
with psycopg.connect(dsn,row_factory=dict_row) as conn:
|
||||
conn.execute('CREATE TABLE schema_migrations(version text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
|
||||
for path in sorted(Path('/app/migrations').glob('*.sql')):
|
||||
conn.execute(path.read_text());conn.execute('INSERT INTO schema_migrations(version) VALUES(%s)',(path.name,))
|
||||
conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES(md5('research-user')::uuid,'research_user','Synthetic benchmark user','not-a-login-account')")
|
||||
conn.execute("INSERT INTO chats(id,title) SELECT md5('chat-'||n)::uuid,'Synthetic chat '||n FROM generate_series(0,101) n")
|
||||
conn.execute("INSERT INTO members(chat_id,user_id) SELECT id,md5('research-user')::uuid FROM chats")
|
||||
conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT md5('message-'||n)::uuid,
|
||||
md5('chat-'||(CASE WHEN n<=100000 THEN 0 WHEN n<=119000 THEN 1 ELSE 2+(n-119001)%100 END))::uuid,
|
||||
md5('research-user')::uuid,'synthetic-'||n||'-'||repeat('x',64+n%512),
|
||||
timestamptz '2026-01-01 00:00:00+00'+ n * interval '1 microsecond'
|
||||
FROM generate_series(1,120000) n""")
|
||||
conn.execute('ANALYZE messages')
|
||||
print(json.dumps({'created':dbname,'messages':120000,'distribution':'100000 + 19000 + 100*10','synthetic_only':True}))
|
||||
elif mode=='benchmark':
|
||||
query='SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51'
|
||||
specs=[('hot-middle',0,'2026-01-01T00:00:00.050000Z'),('medium-first',1,'2026-01-01T00:00:00Z'),('tiny-first',101,'2026-01-01T00:00:00Z')]
|
||||
output={'messages':120000,'warmup':3,'measured_reads':20,'rounds':3,'write_batch':5000,'results':[],'query':query}
|
||||
with psycopg.connect(dsn,row_factory=dict_row) as conn:
|
||||
for round_no in range(3):
|
||||
# Alternate order to reduce systematic warmup/order bias.
|
||||
variants=['global','chat_first'] if round_no%2==0 else ['chat_first','global']
|
||||
for variant in variants:
|
||||
conn.execute('DROP INDEX IF EXISTS messages_history');conn.execute('DROP INDEX IF EXISTS messages_global')
|
||||
definition=('CREATE INDEX messages_history ON messages(chat_id,created_at,id)' if variant=='chat_first' else 'CREATE INDEX messages_global ON messages(created_at,id)')
|
||||
start=time.perf_counter();conn.execute(definition);conn.commit();build_ms=(time.perf_counter()-start)*1000
|
||||
conn.execute('ANALYZE messages');conn.commit()
|
||||
record={'round':round_no+1,'variant':variant,'definition':definition,'index_build_ms':build_ms,'queries':[]}
|
||||
for name,chat_no,stamp in specs:
|
||||
args=(str(uuid.UUID(hashlib.md5(('chat-'+str(chat_no)).encode()).hexdigest())),stamp,str(uuid.UUID(int=0)))
|
||||
for _ in range(3):conn.execute(query,args).fetchall()
|
||||
times=[]
|
||||
for _ in range(20):
|
||||
start=time.perf_counter();rows=conn.execute(query,args).fetchall();times.append((time.perf_counter()-start)*1000)
|
||||
plan=conn.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '+query,args).fetchone()['QUERY PLAN'][0]
|
||||
record['queries'].append({'scenario':name,'rows':len(rows),'median_ms':statistics.median(times),'p95_ms':sorted(times)[18],'raw_ms':times,'explain':plan})
|
||||
conn.commit()
|
||||
# Real inserts, full constraints/index maintenance, then rollback to keep all variants at 120k rows.
|
||||
start=time.perf_counter()
|
||||
conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT md5('write-cost-'||n)::uuid,md5('chat-0')::uuid,md5('research-user')::uuid,
|
||||
'synthetic-write-'||n,timestamptz '2026-01-02 00:00:00+00'+n*interval '1 microsecond'
|
||||
FROM generate_series(1,5000) n""")
|
||||
record['insert_5000_ms']=(time.perf_counter()-start)*1000
|
||||
conn.rollback()
|
||||
# Clean up dead tuples from rollback, without changing measured data volume.
|
||||
with psycopg.connect(dsn,autocommit=True) as vacuum: vacuum.execute('VACUUM ANALYZE messages')
|
||||
record['index_bytes']=conn.execute("SELECT pg_relation_size(%s) AS bytes",('messages_history' if variant=='chat_first' else 'messages_global',)).fetchone()['bytes']
|
||||
conn.commit();output['results'].append(record)
|
||||
conn.execute('DROP INDEX IF EXISTS messages_global');conn.execute('DROP INDEX IF EXISTS messages_history')
|
||||
conn.execute('CREATE INDEX messages_history ON messages(chat_id,created_at,id)');conn.commit()
|
||||
output['fingerprint']=fingerprint(conn)
|
||||
print(json.dumps(output,default=str,ensure_ascii=False))
|
||||
elif mode=='verify':
|
||||
with psycopg.connect(dsn,row_factory=dict_row) as conn:
|
||||
print(json.dumps(fingerprint(conn),default=str,ensure_ascii=False))
|
||||
else: raise ValueError('Unknown study mode')
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Sequential required functional checks; failures preserve nonzero status."""
|
||||
import subprocess,sys
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
commands=[
|
||||
['make','check'],['make','test'],
|
||||
[sys.executable,'student-tests/security.py'],
|
||||
[sys.executable,'student-tests/lab1_own_tests.py'],
|
||||
[sys.executable,'student-tests/lab1_concurrency.py'],
|
||||
[sys.executable,'student-tests/level4.py'],
|
||||
[sys.executable,'student-tests/infrastructure.py'],
|
||||
]
|
||||
for command in commands:
|
||||
print('RUN: '+' '.join(command),flush=True)
|
||||
subprocess.run(command,cwd=root,check=True)
|
||||
print('PASS: all required functional checks completed',flush=True)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Additional API checks; tokens and passwords are never printed."""
|
||||
import sys
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
c=Client()
|
||||
a,b,e,room=c.bootstrap()
|
||||
path='/api/v1/chats/'+room['id']
|
||||
for data in [ {'text':' '}, {'text':'ok','sender_id':e['id']}, {'text':123}, {'text':'x'*4001} ]:
|
||||
c.call('POST',path+'/messages',400,actor=a,body=data)
|
||||
c.call('POST',path+'/messages',400,actor=a,raw=b'{broken',headers={'Content-Type':'application/json'})
|
||||
c.call('GET',path+'/messages?cursor=broken',400,actor=a)
|
||||
c.message(a,room,'page 1'); c.message(a,room,'page 2')
|
||||
page=c.call('GET',path+'/messages?limit=1',actor=a,schema='MessagePage')['json']
|
||||
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json']
|
||||
from urllib.parse import quote
|
||||
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(page['next_cursor'],safe=''),400,actor=a)
|
||||
before=c.call('GET','/api/v1/chats?limit=100',actor=a,schema='ChatPage')['json']
|
||||
c.call('POST','/api/v1/chats',400,actor=a,body={'title':'must not exist','member_ids':[a['id'],str(uuid.uuid4())]})
|
||||
after=c.call('GET','/api/v1/chats?limit=100',actor=a,schema='ChatPage')['json']
|
||||
check(before==after,'invalid chat left state behind')
|
||||
body={'username':'race_'+uuid.uuid4().hex[:12],'display_name':'Race','password':'Synthetic-password-123'}
|
||||
def register(_):
|
||||
return Client().call('POST','/api/v1/users',[201,409],body=body)['status']
|
||||
with ThreadPoolExecutor(max_workers=4) as executor:
|
||||
codes=sorted(executor.map(register,range(4)))
|
||||
check(codes==[201,409,409,409],'registration race was not atomic')
|
||||
print('PASS: malformed JSON, strict fields/types, whitespace, limits, cursor resource binding, invalid chat atomicity, concurrent username uniqueness')
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
Reference in New Issue
Block a user