выполненная лаб2

This commit is contained in:
2026-10-22 17:11:47 +03:00
parent 65003b6119
commit 508340638d
39 changed files with 3547 additions and 33 deletions
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
from pathlib import Path
import secrets
p=Path('secrets'); p.mkdir(mode=0o700,exist_ok=True)
password=p/'db_password'
if not password.exists(): password.write_text(secrets.token_hex(24))
for name,value in {'database_url':'postgresql://messenger:'+password.read_text().strip()+'@postgres:5432/messenger','cache_url':'redis://redis:6379/0'}.items():
target=p/name
if not target.exists(): target.write_text(value)
for target in p.iterdir(): target.chmod(0o600)
if not Path('.env').exists(): Path('.env').write_text('SESSION_TTL_SECONDS=3600\n')
print('Local configuration created; secrets were not printed.')
+4
View File
@@ -0,0 +1,4 @@
import json, subprocess, sys
ids=subprocess.check_output(['docker','compose','ps','-q',*(sys.argv[1:] or ['api','postgres','redis'])],text=True).split()
rows=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
print(json.dumps([{'name':r['Name'],'id':r['Id'],'started_at':r['State']['StartedAt'],'volumes':[{'name':m.get('Name'),'destination':m['Destination']} for m in r['Mounts'] if m['Type']=='volume']} for r in rows],indent=2))
+20
View File
@@ -0,0 +1,20 @@
import sys,base64,uuid
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,check
c=Client()
a,b,e,chat=c.bootstrap()
path='/api/v1/chats/'+chat['id']
results={'contract_extra':{}}
# Full UTF-8 password range, including a colon; malformed JSON and invalid limits.
unicode_name='utf_'+uuid.uuid4().hex[:16]
unicode_password='🔑'*120+':пароль!'
check(len(unicode_password)==128,'password fixture length')
c.call('POST','/api/v1/users',201,body={'username':unicode_name,'display_name':'UTF-8','password':unicode_password},schema='User')
credential=base64.b64encode((unicode_name+':'+unicode_password).encode()).decode()
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
c.call('POST','/api/v1/users',400,raw=b'{',headers={'Content-Type':'application/json'})
c.call('GET',path+'/messages?limit='+('9'*100),400,actor=a)
results['contract_extra']['utf8_128_password_with_colon']=True
print('PASS: 128-codepoint UTF-8 password with colon; malformed JSON and oversized limit rejected')
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Integration experiments. No credentials or bearer tokens are written to evidence."""
import concurrent.futures as cf
import json, os, pathlib, subprocess, sys, time, uuid, base64
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
root=pathlib.Path(__file__).resolve().parents[1]
os.chdir(root)
evidence=root/'evidence'; evidence.mkdir(exist_ok=True)
results={}
def dc(*args,input=None):
return subprocess.run(['docker','compose',*args],input=input,text=True,capture_output=True,check=True).stdout
def sql(query,db='messenger'):
return dc('exec','-T','postgres','psql','-U','messenger','-d',db,'-At','-v','ON_ERROR_STOP=1','-c',query).strip()
def ready():
start=time.monotonic()
while time.monotonic()-start<90:
try:
Client(timeout=5).call('GET','/health/ready',schema='Health')
return round(time.monotonic()-start,3)
except Exception: time.sleep(.5)
raise RuntimeError('Readiness timeout')
def save(): (evidence/'experiments.json').write_text(json.dumps(results,ensure_ascii=False,indent=2))
c=Client(); a,b,e,chat=c.bootstrap(); path='/api/v1/chats/'+chat['id']
# Race: one insert wins, unique index rejects the others.
d={'username':'race_'+uuid.uuid4().hex[:16],'display_name':'Гонка','password':'race-password-12345'}
def register(_): return Client().call('POST','/api/v1/users',[201,409],body=d)['status']
with cf.ThreadPoolExecutor(max_workers=8) as executor: statuses=list(executor.map(register,range(8)))
check(statuses.count(201)==1 and statuses.count(409)==7,'registration race')
results['registration_race']={'concurrency':8,'statuses':statuses}
# Trigger a failure AFTER the chat insert; a database trigger is test-only and always removed.
name='rollback_'+uuid.uuid4().hex[:8]
sql("CREATE FUNCTION lab_reject_member() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected'; END $$; CREATE TRIGGER lab_reject_member BEFORE INSERT ON members FOR EACH ROW EXECUTE FUNCTION lab_reject_member()")
try:
c.call('POST','/api/v1/chats',503,actor=a,body={'title':name,'member_ids':[a['id'],b['id']]})
check(sql("SELECT count(*) FROM chats WHERE title='"+name+"'")=='0','partial chat survived')
finally: sql('DROP TRIGGER lab_reject_member ON members; DROP FUNCTION lab_reject_member()')
results['rollback']={'failure':'trigger rejects membership after chat INSERT','remaining_chats':0}
# Negative API and access cases, resource-bound cursor and immediate visibility.
for payload in [{'text':'ok','sender_id':e['id']},{'text':34},{'text':' '}]:
c.call('POST',path+'/messages',400,actor=a,body=payload)
first=c.message(a,chat,'read-after-write 👋')['json']
c.message(b,chat,'second')
page=c.call('GET',path+'/messages?limit=1',actor=b,schema='MessagePage')['json']
check(page['items'][0]==first,'read after write')
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']),400,actor=a)
c.call('GET',path+'/messages?cursor='+quote(base64.urlsafe_b64encode(json.dumps([chat['id'],123,a['id']]).encode()).decode()),400,actor=a)
results['contract_extra']={'malformed_cursor_rejected':True,'read_after_write':True,'foreign_cursor_rejected':True,'strict_json':True}
# Redis: warm cache, real hits, outage fallback, restart, cold-cache recovery.
c.call('GET','/api/v1/users/me',actor=a,schema='User')
before=dc('exec','-T','redis','redis-cli','INFO','stats')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
after=dc('exec','-T','redis','redis-cli','INFO','stats')
def hits(info): return int(next(x.split(':')[1] for x in info.splitlines() if x.startswith('keyspace_hits:')))
check(hits(after)>hits(before),'Redis unused')
start=time.monotonic(); dc('stop','redis')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
c.call('GET','/api/v1/users/me',401)
c.message(a,chat,'redis unavailable')
results['redis_outage']={'cache_hits_delta':hits(after)-hits(before),'fallback_request_ms':None,'anonymous_status':401}
t=time.monotonic(); c.call('GET','/api/v1/users/me',actor=a,schema='User'); results['redis_outage']['fallback_request_ms']=round((time.monotonic()-t)*1000,2)
dc('start','redis'); dc('exec','-T','redis','redis-cli','FLUSHDB')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
results['redis_outage']['recovered']=True
# DB outage is bounded and fails closed; process stays alive.
dc('stop','postgres'); start=time.monotonic()
c.call('GET','/health/live',schema='Health')
c.call('GET','/health/ready',503)
c.call('GET','/api/v1/users/me',503,actor=a)
c.call('GET','/api/v1/users/me',401)
results['postgres_outage']={'ready_status':503,'authenticated_status':503,'anonymous_status':401,'checks_seconds':round(time.monotonic()-start,3)}
dc('start','postgres'); results['postgres_outage']['recovery_seconds']=ready()
c.call('GET','/api/v1/users/me',actor=a,schema='User')
save()
# Short-lived sessions on a recreated API, then restore ordinary TTL unconditionally.
try:
env=dict(os.environ,SESSION_TTL_SECONDS='2')
subprocess.run(['docker','compose','up','-d','--no-deps','--force-recreate','api'],env=env,check=True,capture_output=True)
ready(); short=Client().user('expiry'); time.sleep(2.2)
Client().call('GET','/api/v1/users/me',401,actor=short)
results['expiry']={'ttl_seconds':2,'wait_seconds':2.2,'status':401}
finally:
env=dict(os.environ,SESSION_TTL_SECONDS='3600')
subprocess.run(['docker','compose','up','-d','--no-deps','--force-recreate','api'],env=env,check=True,capture_output=True)
ready()
# Dedicated database to avoid destructive benchmark operations on the app tables.
if sql("SELECT count(*) FROM pg_database WHERE datname='research'")=='0': sql('CREATE DATABASE research')
source=(root/'scripts/research.py').read_text()
research=json.loads(dc('exec','-T','api','python','-',input=source))
(evidence/'research.json').write_text(json.dumps(research,ensure_ascii=False,indent=2))
# Restore on another PostgreSQL instance with an independent persistent volume.
dc('--profile','research','up','-d','--wait','postgres_restore')
def restored_sql(query):
return dc('exec','-T','postgres_restore','psql','-U','messenger','-d','research_restored','-At','-v','ON_ERROR_STOP=1','-c',query).strip()
restored_sql('DROP SCHEMA public CASCADE; CREATE SCHEMA public')
start=time.monotonic()
dc('exec','-T','postgres','pg_dump','-U','messenger','-d','research','-Fc','-f','/tmp/research.dump')
backup_seconds=time.monotonic()-start
backup_dir=root/'backups'; backup_dir.mkdir(exist_ok=True)
start=time.monotonic()
dc('cp','postgres:/tmp/research.dump',str(backup_dir/'research.dump'))
dc('cp',str(backup_dir/'research.dump'),'postgres_restore:/tmp/research.dump')
copy_seconds=time.monotonic()-start
start=time.monotonic(); dc('exec','-T','postgres_restore','pg_restore','-U','messenger','-d','research_restored','--exit-on-error','/tmp/research.dump')
restore_seconds=time.monotonic()-start
query="SELECT count(*),md5(string_agg(id::text||':'||chat_id::text||':'||sender_id::text||':'||created_at::text||':'||text,'|' ORDER BY id)) FROM messages"
original=sql(query,'research'); restored=restored_sql(query); check(original==restored,'restored data differs')
samples="SELECT id,chat_id,sender_id,created_at,text FROM messages WHERE id IN (SELECT md5(n::text)::uuid FROM unnest(ARRAY[1,50000,100000,110000,120000]) n) ORDER BY id"
check(sql(samples,'research')==restored_sql(samples),'sample mismatch')
results['backup_restore']={'backup_seconds':round(backup_seconds,3),'copy_seconds':round(copy_seconds,3),'restore_seconds':round(restore_seconds,3),'source':original,'restored':restored,'samples_equal':True,'target':'postgres_restore / research_restored / restoredata','rows':120000}
results['restored_table_counts']={}
for table in ['users','chats','members','messages','sessions']:
original_count=sql('SELECT count(*) FROM '+table,'research')
restored_count=restored_sql('SELECT count(*) FROM '+table)
check(original_count==restored_count,'table count mismatch: '+table)
results['restored_table_counts'][table]={'source':int(original_count),'restored':int(restored_count)}
(evidence/'restore-storage.json').write_text(subprocess.check_output(['python3','scripts/container_state.py','postgres','postgres_restore'],text=True))
results['resources']=dc('stats','--no-stream','--format','json')
results['versions']=dc('version')
save(); print('PASS: registration race, rollback, strict contract, Redis/DB failure, expiry, 120000-row plans, backup/restore; evidence saved without tokens.')
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
import json, pathlib, platform, subprocess, time
root=pathlib.Path(__file__).resolve().parents[1]
samples=[]
for n in range(1,4):
process=subprocess.Popen(['python3','tests/load.py','--duration','10','--concurrency','4','--output',f'evidence/load-{n}.json'],cwd=root,stdout=subprocess.DEVNULL)
while process.poll() is None:
result=subprocess.run(['docker','compose','stats','--no-stream','--format','json'],capture_output=True,text=True,check=True)
samples.append({'run':n,'elapsed_epoch':time.time(),'containers':[json.loads(line) for line in result.stdout.splitlines() if line.strip()]})
if process.returncode: raise SystemExit(process.returncode)
(root/'evidence/load-resources.json').write_text(json.dumps({'host':platform.platform(),'machine':platform.machine(),'samples':samples},indent=2))
print('PASS: three 10-second runs, concurrency 4; HTTP metrics and container resource samples saved.')
+45
View File
@@ -0,0 +1,45 @@
"""Run only in an isolated research database, created by experiments.py."""
import json, time, uuid, statistics, os
from pathlib import Path
import psycopg
from app.migrate import setting
url=setting('DATABASE_URL').rsplit('/',1)[0]+'/research'
summary={'dataset':{'messages':120000,'chat_sizes':[100000,15000,5000]},'plans':{},'write':{}}
with psycopg.connect(url,autocommit=True) as c:
c.execute('DROP SCHEMA public CASCADE; CREATE SCHEMA public')
c.execute(Path('migrations/001_initial.sql').read_text())
c.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (md5('user')::uuid,'bench_user','Benchmark','synthetic-not-a-login')")
c.execute("INSERT INTO chats(id,title) SELECT md5('chat'||n)::uuid,'Benchmark '||n FROM generate_series(1,3) n")
c.execute("INSERT INTO members SELECT id,md5('user')::uuid FROM chats")
c.execute("INSERT INTO messages(id,chat_id,sender_id,created_at,text) SELECT md5(n::text)::uuid,md5('chat'||CASE WHEN n<=100000 THEN 1 WHEN n<=115000 THEN 2 ELSE 3 END)::uuid,md5('user')::uuid, '2026-01-01'::timestamptz+n*interval '1 millisecond',repeat('x',100) FROM generate_series(1,120000) n")
c.execute('DROP INDEX messages_history')
c.execute('ANALYZE messages')
for variant,ddl in [('chat_only','CREATE INDEX candidate ON messages(chat_id)'),('composite','CREATE INDEX candidate ON messages(chat_id,created_at,id)')]:
c.execute(ddl); c.execute('ANALYZE messages')
plans={}
for chat,offset in [(1,90000),(2,110000),(3,119000)]:
for kind in ['keyset','offset']:
q="SELECT * FROM messages WHERE chat_id=md5('chat'||%s::text)::uuid"
params=[chat]
if kind=='keyset': q+=" AND (created_at,id)>('2026-01-01'::timestamptz+%s*interval '1 millisecond',md5(%s::text)::uuid)"; params += [offset,offset]
q+=' ORDER BY created_at,id LIMIT 50'
if kind=='offset': q+=' OFFSET %s'; params += [offset-({1:0,2:100000,3:115000}[chat])]
for _ in range(2): c.execute(q,params).fetchall()
runs=[c.execute('EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON) '+q,params).fetchone()[0][0] for _ in range(5)]
plans[str(chat)+'_'+kind]={'execution_ms':[r['Execution Time'] for r in runs],'plan':runs[-1]}
summary['plans'][variant]=plans
summary['write'][variant]={'index_bytes':c.execute("SELECT pg_relation_size('candidate')").fetchone()[0],'runs':[]}
for rep in range(5):
with c.transaction():
start=time.perf_counter()
c.execute("INSERT INTO messages(id,chat_id,sender_id,created_at,text) SELECT md5(n::text)::uuid,md5('chat1')::uuid,md5('user')::uuid,'2027-01-01'::timestamptz,repeat('w',100) FROM generate_series(200001,205000) n")
elapsed=(time.perf_counter()-start)*1000
summary['write'][variant]['runs'].append({'insert_5000_ms':elapsed})
c.execute("DELETE FROM messages WHERE created_at>='2027-01-01'")
c.execute('DROP INDEX candidate')
c.execute('CREATE INDEX candidate ON messages(chat_id,created_at,id)')
summary['count']=c.execute('SELECT count(*) FROM messages').fetchone()[0]
summary['samples']=c.execute("SELECT id::text,chat_id::text,sender_id::text,created_at::text,text FROM messages WHERE id IN (SELECT md5(n::text)::uuid FROM unnest(ARRAY[1,50000,100000,110000,120000]) n) ORDER BY id").fetchall()
summary['postgres_version']=c.execute('SELECT version()').fetchone()[0]
print(json.dumps(summary,ensure_ascii=False,indent=2))
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p evidence
python3 scripts/container_state.py > evidence/restart-before.json
docker compose restart api postgres redis >/dev/null
python3 scripts/container_state.py > evidence/restart-after.json