Реализовал уровень 4: Redis-кэш, проверки отказов и индекс истории
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user