Реализовал уровень 4: Redis-кэш, проверки отказов и индекс истории

This commit is contained in:
2026-10-09 14:19:48 +03:00
parent 6fba9410d5
commit 64f2a5b468
16 changed files with 321 additions and 8 deletions
+18
View File
@@ -0,0 +1,18 @@
"""Проверить индекс истории на 10 000 синтетических сообщений."""
import json
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
from support import sql
c=Client('http://localhost:8080')
a,b,_,chat=c.bootstrap()
sql("INSERT INTO messages (id,chat_id,sender_id,text,created_at) SELECT gen_random_uuid(),%s,%s,'Синтетическое ' || n, timestamptz '2026-01-01' + n * interval '1 microsecond' FROM generate_series(1,10000) n",[chat['id'],a['id']])
sql('ANALYZE messages')
marker=sql('SELECT created_at,id FROM messages WHERE chat_id=%s ORDER BY created_at,id OFFSET 8000 LIMIT 1',[chat['id']])[0]
query='SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51'
plan=sql('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '+query,[chat['id'],marker['created_at'],marker['id']])[0]['QUERY PLAN'][0]
check('messages_history_idx' in json.dumps(plan),'индекс истории не используется')
Path('evidence/explain_10000.json').write_text(json.dumps({'rows':10000,'query':query,'plan':plan},ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print('PASS: 10000 messages, indexed keyset pagination, execution ms:',plan['Execution Time'])
+21
View File
@@ -0,0 +1,21 @@
"""Административные запросы только к изолированному учебному стенду Compose."""
import json
import subprocess
def compose(*args):
result=subprocess.run(['docker','compose',*args],capture_output=True,text=True,encoding='utf-8',errors='replace',check=True)
return result.stdout.strip()
def sql(query, params=None):
source="""import json, psycopg
from psycopg.rows import dict_row
from src.config import setting
with psycopg.connect(setting('DATABASE_URL'),row_factory=dict_row) as conn:
cursor=conn.execute(%r, %r)
result=cursor.fetchall() if cursor.description else []
print(json.dumps(result,default=str))
""" % (query,params)
result=subprocess.run(['docker','compose','exec','-T','api','python','-'],input=source,capture_output=True,text=True,encoding='utf-8',check=True)
return json.loads(result.stdout)
+95
View File
@@ -0,0 +1,95 @@
"""Гонки, транзакции, короткий TTL и реальные отказы зависимостей."""
import concurrent.futures
import json
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
from support import compose, sql
def wait_ready(client):
deadline=time.monotonic()+45
while time.monotonic()<deadline:
try:
client.call('GET','/health/ready',schema='Health')
return
except Exception:
time.sleep(0.3)
raise AssertionError('сервер не восстановился')
def main():
c=Client('http://localhost:8080')
alice,bob,eve,chat=c.bootstrap()
registration=dict(alice['registration'],username='race_'+uuid.uuid4().hex[:16])
def register(i):
# Оба результата допустимы для отдельного участника гонки.
import urllib.request, urllib.error
req=urllib.request.Request(c.base+'/api/v1/users',data=json.dumps(registration).encode(),headers={'Content-Type':'application/json'},method='POST')
try:
with urllib.request.urlopen(req,timeout=10) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.code
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
codes=list(pool.map(register,range(8)))
check(codes.count(201)==1 and codes.count(409)==7,'гонка регистрации: '+str(codes))
before=sql('SELECT count(*) AS n FROM chats')[0]['n']
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'Rollback','member_ids':[alice['id'],str(uuid.uuid4())]})
check(sql('SELECT count(*) AS n FROM chats')[0]['n']==before,'чат не откатился')
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
cached=compose('exec','-T','redis','redis-cli','GET','profile:v1:'+alice['id'])
check(alice['id'] in cached,'Redis не используется')
ttl=int(compose('exec','-T','redis','redis-cli','TTL','profile:v1:'+alice['id']))
check(0<ttl<=60,'нет TTL кэша')
started=time.monotonic()
try:
compose('stop','redis')
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
redis_fallback=time.monotonic()-started
c.call('GET','/api/v1/users/me',401)
finally:
compose('start','redis')
# Потеря кэша не теряет сессии и публичные профили.
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
try:
compose('stop','db')
c.call('GET','/health/live',schema='Health')
started=time.monotonic()
c.call('GET','/health/ready',503)
c.call('GET','/api/v1/users/me',503,actor=alice)
db_failure=time.monotonic()-started
finally:
compose('start','db')
wait_ready(c)
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
# В отдельном процессе срок жизни 2 секунды; основной стенд не меняется.
name='lyakhonov-lab2-expiry-'+uuid.uuid4().hex[:6]
try:
compose('run','-d','--name',name,'-p','127.0.0.1:8082:8080','-e','SESSION_TTL_SECONDS=2','api')
short=Client('http://localhost:8082')
wait_ready(short)
a,_,_,_=short.bootstrap()
short.call('GET','/api/v1/users/me',actor=a,schema='User')
time.sleep(2.2)
response=short.call('GET','/api/v1/users/me',401,actor=a)
check('Bearer' in response['headers'].get('WWW-Authenticate',''),'нет Bearer challenge')
finally:
subprocess.run(['docker','rm','-f',name],check=True,capture_output=True)
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('GET','/api/v1/users/me',401,actor=alice)
result={'registration_codes':codes,'rollback':'PASS','profile_cache_ttl_seconds':ttl,
'redis_fallback':'PASS','redis_stop_and_request_seconds':round(redis_fallback,3),
'db_failure':'503, live=200, recovery with same session','two_db_error_requests_seconds':round(db_failure,3),
'expiry_seconds':2,'expiry':'401','logout':'401','passed':True}
Path('evidence/level4.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print('PASS: registration race, chat rollback, Redis TTL/fallback/restart, DB outage/recovery, expiry, logout')
if __name__=='__main__':
main()