ЛР 6 — БПИ2302 — Нурлыгаянова — на 3

This commit is contained in:
Nurlygayanova Ekaterina
2026-11-13 11:32:45 +03:00
parent 470d9d6f1e
commit 69a190be0e
164 changed files with 25947 additions and 29 deletions
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Short live edge cases, no load or service restarts."""
import sys
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check, ROOT
c=Client('http://localhost:18086')
a,b,e,chat=c.bootstrap()
p='/api/v1/chats/'+chat['id']
count=0
def case(name,method,path,status,**kw):
global count
r=c.call(method,path,status,**kw)
count+=1
print('PASS:',name)
return r
for limit in ['0','101','-1','abc']:
case('invalid limit '+limit,'GET',p+'/messages?limit='+limit,400,actor=a)
case('invalid cursor','GET',p+'/messages?cursor=broken',400,actor=a)
case('invalid UUID','GET','/api/v1/chats/not-a-uuid',400,actor=a)
case('unknown UUID','GET','/api/v1/chats/'+str(uuid.uuid4()),404,actor=a)
case('bad bearer','GET','/api/v1/users/me',401,headers={'Authorization':'Bearer invalid'})
case('broken JSON','POST',p+'/messages',400,actor=a,raw=b'{',headers={'Content-Type':'application/json','Idempotency-Key':uuid.uuid4().hex})
for text in [' \t\n','x'*4001]:
case('empty/oversized text','POST',p+'/messages',400,actor=a,body={'text':text},headers={'Idempotency-Key':uuid.uuid4().hex})
case('4000 Unicode characters','POST',p+'/messages',201,actor=a,body={'text':'🙂'*4000},headers={'Idempotency-Key':uuid.uuid4().hex},schema='Message')
for label,filename,mime,data,status in [
('path filename','../x.png','image/png',(ROOT/'tests/fixtures/sample.png').read_bytes(),400),
('corrupt PNG','x.png','image/png',b'not an image',415),
('unsupported MIME','x.txt','text/plain',b'hello',415),
('upload over 10 MiB','x.png','image/png',b'x'*(10485760+1),413)]:
case(label,'POST',p+'/attachments?filename='+quote(filename,safe=''),status,actor=a,raw=data,headers={'Content-Type':mime})
case('outsider upload','POST',p+'/attachments?filename=x.png',404,actor=e,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'})
# Same idempotency key reaches two real API replicas concurrently.
key=uuid.uuid4().hex
with ThreadPoolExecutor(max_workers=8) as pool:
replies=list(pool.map(lambda _:Client('http://localhost:18086').message(a,chat,'same request',key=key),range(8)))
check(len({r['json']['id'] for r in replies})==1,'concurrent replay created duplicates')
check(len({r['headers']['X-Instance-Id'] for r in replies})==2,'did not reach both replicas')
print('PASS: 8 concurrent replays across both API replicas return one message')
count+=1
case('same key different body','POST',p+'/messages',409,actor=a,body={'text':'different'},headers={'Idempotency-Key':key})
att,_=c.attachment(a,chat)
case('duplicate attachment IDs','POST',p+'/messages',400,actor=a,body={'text':'','attachment_ids':[att['id'],att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json']
case('attachment from another chat','POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.wait_ready(a,att)
case('unknown variant','GET','/api/v1/attachments/'+att['id']+'/content?variant=unknown',400,actor=a)
case('outsider thumbnail','GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',404,actor=e)
page=c.call('GET',p+'/messages?limit=1',actor=a,schema='MessagePage')['json']
check(bool(page['next_cursor']),'missing cursor')
case('cursor from another chat','GET','/api/v1/chats/'+other['id']+'/messages?cursor='+quote(page['next_cursor'],safe=''),400,actor=a)
print('PASS:',count,'live corner cases')
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Run after persistence hook; query the IDs/timestamps captured BEFORE restart."""
import json
from observability import ROOT, eventually, logs, get, trace_exists
proof = json.loads((ROOT/'evidence'/'telemetry.json').read_text())
result = {}
for role in ['api','worker']:
tid = proof[role+'_trace_id']
eventually(lambda: trace_exists(tid))
eventually(lambda: logs('messenger-'+role,' | trace_id="'+tid+'"'))
result[role] = {'trace_id':tid,'old_trace_found':True,'old_log_found':True}
when = proof['metrics']['api_requests_total'][0]['value'][0]
old = eventually(lambda: get('http://localhost:19091','/api/v1/query',{'query':'api_requests_total','time':when})['data']['result'])
result['metrics'] = {'historical_query_timestamp':when,'series_found':len(old)}
(ROOT/'evidence'/'telemetry-history.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: pre-restart API/worker traces, correlated logs and metric history survived restart')
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Two bounded local faults. Always restore every service in finally blocks."""
import json
import subprocess
import time
from pathlib import Path
from observability import Client, check, logs, eventually, get, ROOT, trace_exists
report = []
def compose(*args):
subprocess.run(['docker','compose',*args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
def main():
c = Client('http://localhost:18086')
alice, bob, eve, chat = c.bootstrap()
start = time.time()
compose('stop','worker')
try:
att, _ = c.attachment(alice,chat)
time.sleep(5)
queued = c.call('GET','/api/v1/attachments/'+att['id'],actor=alice,schema='Attachment')['json']
check(queued['status']=='queued','job processed while worker stopped')
accepted_logs = eventually(lambda: logs('messenger-api',' | status="202"'))
report.append({'incident':'worker stopped','started_unix':start,'accepted_status':202,'after_5s':queued['status'],'api_observations':accepted_logs})
finally:
compose('up','-d','--no-deps','worker')
c.wait_ready(alice,att)
report[-1]['recovery_seconds'] = round(time.time()-start,3)
report[-1]['recovered_status'] = 'ready'
# Accept durable work before disabling S3; the worker then experiences real S3 errors.
compose('stop','worker')
att, _ = c.attachment(alice,chat)
start = time.time()
try:
compose('stop','s3')
compose('up','-d','--no-deps','worker')
error_logs = eventually(lambda: [r for r in logs('messenger-worker',' | event="s3.error"') if int(r['values'][0][0])/1e9 >= start], seconds=70)
tid = error_logs[0]['stream']['trace_id']
error_trace = eventually(lambda: trace_exists(tid))
report.append({'incident':'S3 stopped during background processing','started_unix':start,'observations':error_logs, 'error_trace':error_trace})
finally:
compose('up','-d','--no-deps','s3','worker')
# Wait for S3 health before issuing the control upload.
eventually(lambda: subprocess.run(['docker','compose','exec','-T','s3','wget','--quiet','--spider','http://127.0.0.1:9000/healthz'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode==0)
time.sleep(5)
att2, _ = c.attachment(alice,chat)
c.wait_ready(alice,att2)
report[-1]['recovery_seconds'] = round(time.time()-start,3)
report[-1]['control_upload_status'] = 'ready'
report[-1]['worker_errors'] = get('http://localhost:19091','/api/v1/query',{'query':'worker_jobs_total{outcome=~"retry|failed|error"}'})
(ROOT/'evidence'/'incidents.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
print('PASS: stopped worker retained queued job, S3 outage produced worker errors, both recovered; evidence/incidents.json')
if __name__ == '__main__':
main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Assert actual application signals in each backend; persist no credentials."""
import json
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
ROOT = Path(__file__).resolve().parents[1]
def get(base, path, params=None):
if params:
path += '?' + urllib.parse.urlencode(params)
with urllib.request.urlopen(base + path, timeout=15) as response:
return json.load(response)
def eventually(fn, seconds=90):
deadline = time.monotonic() + seconds
last = None
while time.monotonic() < deadline:
try:
value = fn()
if value:
return value
except Exception as exc:
last = type(exc).__name__
time.sleep(2)
raise AssertionError('signal did not arrive: ' + str(last))
def logs(service, suffix=''):
return get('http://localhost:3100', '/loki/api/v1/query_range', {
'query': '{service_name="'+service+'"}' + suffix,
'start': int((time.time()-600)*1e9), 'end': int(time.time()*1e9), 'limit': 100
})['data']['result']
def trace_exists(tid):
data = get('http://localhost:3200', '/api/traces/' + tid)
return data if data.get('batches') or data.get('resourceSpans') else None
def main():
c = Client('http://localhost:18086')
alice, bob, eve, chat = c.bootstrap()
response = c.message(alice, chat, 'telemetry synthetic check')
# Follow a controlled request by server-generated X-Trace-Id and X-Request-Id.
response = c.call('GET', '/api/v1/chats/'+chat['id']+'/messages', actor=alice)
headers = response['headers']
tid = headers.get('X-Trace-Id')
rid = headers.get('X-Request-Id')
check(bool(tid) and len(tid)==32, 'missing trace ID')
job_started = time.time()
att, _ = c.attachment(alice, chat)
c.wait_ready(alice, att)
api_logs = eventually(lambda: logs('messenger-api', ' | trace_id="'+tid+'"'))
api_trace = eventually(lambda: trace_exists(tid))
worker_logs = eventually(lambda: [row for row in logs('messenger-worker', ' | event="job.success"') if int(row['values'][0][0])/1e9 >= job_started])
values = worker_logs[0]['values']
# Native OTLP metadata carries trace_id without making it a metric label.
worker_tid = values[0][2].get('trace_id') if len(values[0]) > 2 else None
if not worker_tid:
worker_tid = worker_logs[0]['stream'].get('trace_id')
check(bool(worker_tid), 'worker log lacks trace ID')
worker_trace = eventually(lambda: trace_exists(worker_tid))
metric_names = ['api_requests_total','api_duration_seconds_bucket','worker_jobs_total','worker_duration_seconds_bucket']
metric_results = {}
for name in metric_names:
metric_results[name] = eventually(lambda: get('http://localhost:19091','/api/v1/query',{'query': name})['data']['result'])
for results in metric_results.values():
for result in results:
check(not (set(result['metric']) & {'user_id','chat_id','message_id','attachment_id','request_id','filename'}), 'high cardinality metric labels')
proof = {'api_trace_id':tid,'api_request_id':rid,'worker_trace_id':worker_tid,
'api_logs':api_logs,'worker_logs':worker_logs,'api_trace':api_trace,'worker_trace':worker_trace,
'metrics':metric_results}
(ROOT/'evidence'/'telemetry.json').write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n')
print('PASS: API trace + matching log, worker consumer trace + matching log, four real SDK metrics; evidence/telemetry.json')
if __name__ == '__main__':
main()