feat: база из лабораторной 3 перенесена в лабу 4

This commit is contained in:
2026-11-10 16:24:08 +03:00
parent ec540a1a72
commit fc3ab1ca38
27 changed files with 1273 additions and 1374 deletions
+79 -199
View File
@@ -1,217 +1,97 @@
"""HTTP helpers for public black-box tests; Python 3.9+, standard library only."""
import base64
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import re
import ssl
import time
import urllib.error
import urllib.request
#!/usr/bin/env python3
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
LAB = json.loads((ROOT / 'lab.json').read_text())['number']
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text())
import requests
BASE = "http://localhost:8080"
LOGIN = "test"
PASSWORD = "test123"
TIMEOUT = 5
failures = []
class Failure(AssertionError):
pass
def check(condition, message):
if not condition:
raise Failure(message)
if condition:
print("PASS:", message)
return True
failures.append(message)
print("FAIL:", message)
return False
def timestamp(value):
check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z')
try:
return dt.datetime.fromisoformat(value[:-1] + '+00:00')
except ValueError as exc:
raise Failure('invalid RFC3339 timestamp') from exc
def validate(value, schema, where='response'):
"""Validate the JSON Schema subset used by the supplied contract, not arbitrary OpenAPI."""
if '$ref' in schema:
target = SPEC
for part in schema['$ref'].split('/')[1:]:
target = target[part]
return validate(value, target, where)
kinds = schema.get('type', [])
if isinstance(kinds, str):
kinds = [kinds]
matches = {'null':value is None, 'boolean':isinstance(value,bool), 'integer':isinstance(value,int) and not isinstance(value,bool), 'number':isinstance(value,(int,float)) and not isinstance(value,bool), 'string':isinstance(value,str), 'array':isinstance(value,list), 'object':isinstance(value,dict)}
if kinds:
check(any(matches.get(k,False) for k in kinds), where + ': incorrect type')
if 'enum' in schema:
check(value in schema['enum'], where + ': invalid enum')
if 'const' in schema:
check(value == schema['const'], where + ': invalid const')
if isinstance(value,dict):
props = schema.get('properties',{})
check(all(k in value for k in schema.get('required',[])), where + ': missing required fields')
if schema.get('additionalProperties') is False:
check(not set(value).difference(props), where + ': unexpected fields')
for key, sub in props.items():
if key in value:
validate(value[key], sub, where + '.' + key)
if isinstance(value,list):
check(len(value) >= schema.get('minItems',0), where + ': too few items')
check(len(value) <= schema.get('maxItems',float('inf')), where + ': too many items')
if schema.get('uniqueItems'):
encoded = [json.dumps(x,sort_keys=True) for x in value]
check(len(encoded)==len(set(encoded)), where + ': duplicate items')
if 'items' in schema:
for item in value:
validate(item, schema['items'], where + '[]')
if isinstance(value,str):
check(len(value) >= schema.get('minLength',0), where + ': too short')
check(len(value) <= schema.get('maxLength',float('inf')), where + ': too long')
if 'pattern' in schema:
check(re.search(schema['pattern'], value) is not None, where + ': pattern mismatch')
if schema.get('format') == 'uuid':
try:
uuid.UUID(value)
except ValueError as exc:
raise Failure(where + ': invalid UUID') from exc
if schema.get('format') == 'date-time':
timestamp(value)
if isinstance(value,(int,float)) and not isinstance(value,bool):
check(value >= schema.get('minimum',-float('inf')), where + ': below minimum')
check(value <= schema.get('maximum',float('inf')), where + ': above maximum')
if 'anyOf' in schema:
for alternative in schema['anyOf']:
try:
validate(value, alternative, where)
break
except Failure:
pass
else:
raise Failure(where + ': no anyOf branch matches')
def shape(value, name):
validate(value, SPEC['components']['schemas'][name])
return value
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
def login():
response = requests.post(
BASE + "/api/auth/login",
json={"login": LOGIN, "password": PASSWORD},
timeout=TIMEOUT,
)
if not check(response.status_code == 200, "login returns 200 (got %d)" % response.status_code):
print(response.text)
return None
token = response.json().get("token")
check(bool(token), "login returns a token")
return token
class Client:
def __init__(self, base_url=None, ca_file=None, timeout=10):
self.base = (base_url or os.environ.get('BASE_URL') or ('https://localhost:8443' if LAB==7 else 'http://localhost:8080')).rstrip('/')
check(self.base.startswith(('http://','https://')), 'BASE_URL must be HTTP(S)')
check(LAB != 7 or self.base.startswith('https://'), 'lab7 requires HTTPS')
self.timeout = timeout
context = ssl.create_default_context(cafile=ca_file or os.environ.get('CA_FILE') or None)
self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=context))
def call(self, method, path, expected=200, body=None, actor=None, headers=None, raw=None, schema=None):
h = {'Accept':'application/json'}
if actor:
h['X-User-Id' if LAB==1 else 'Authorization'] = actor['id'] if LAB==1 else 'Bearer ' + actor['token']
if body is not None:
raw = json.dumps(body,ensure_ascii=False).encode('utf-8')
h['Content-Type'] = 'application/json'
h.update(headers or {})
req = urllib.request.Request(self.base + path, data=raw, headers=h, method=method)
start = time.monotonic()
try:
response = self.opener.open(req, timeout=self.timeout)
except urllib.error.HTTPError as error:
response = error
except (urllib.error.URLError,TimeoutError,OSError) as exc:
# Do not print URL query, headers, request body, or credentials.
raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None
with response:
status = response.code
rh = response.headers
data = response.read(16*1024*1024 + 1)
check(len(data) <= 16*1024*1024, 'response exceeds test safety limit')
allowed = [expected] if isinstance(expected,int) else expected
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id')
if LAB>=3:
check(bool(rh.get('X-Instance-Id')), 'missing X-Instance-Id')
payload = None
if schema or status>=400:
check(rh.get_content_type()=='application/json', 'expected application/json')
try:
payload = json.loads(data)
except (ValueError,UnicodeError):
raise Failure('invalid response JSON') from None
shape(payload, 'Error' if status>=400 else schema)
if status>=400:
check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header')
if status==401 and LAB>=2:
scheme = 'Basic' if path=='/api/v1/auth/sessions' else 'Bearer'
check(rh.get('WWW-Authenticate','').lower().startswith(scheme.lower()), 'incorrect WWW-Authenticate challenge')
if status==204:
check(not data, '204 must not contain body')
return {'status':status,'headers':rh,'json':payload,'bytes':data,'elapsed':time.monotonic()-start}
def main():
token = login()
if token is None:
return 1
def user(self, label):
username = 'u_' + label + '_' + uuid.uuid4().hex[:12]
password = 'T3st-' + uuid.uuid4().hex
body = {'username':username,'display_name':'Студент ' + label}
if LAB>=2:
body['password'] = password
user = self.call('POST','/api/v1/users',201,body=body,schema='User')['json']
check(user['username']==username,'username changed')
actor = {'id':user['id'],'user':user,'registration':body}
if LAB>=2:
credential = base64.b64encode((username+':'+password).encode()).decode()
session = self.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json']
check(session['user']==user,'session user mismatch')
check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),'session already expired')
actor['token'] = session['token']
return actor
auth = {"Authorization": "Bearer " + token}
def bootstrap(self):
self.call('GET','/health/live',schema='Health')
self.call('GET','/health/ready',schema='Health')
alice, bob, eve = (self.user(label) for label in ('alice','bob','eve'))
chat = self.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Контрактный тест','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
check(set(chat['member_ids'])=={alice['id'],bob['id']},'chat member mismatch')
return alice,bob,eve,chat
response = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT)
check(response.status_code == 200, "GET /api/messages returns 200")
instance = response.headers.get("X-Instance-Id")
check(bool(instance), "response carries X-Instance-Id (%s)" % instance)
check(isinstance(response.json(), list), "GET /api/messages returns a JSON array")
def message(self, actor, chat, text, key=None, attachments=None):
body = {'text':text}
if attachments is not None:
body['attachment_ids'] = attachments
headers = {'Idempotency-Key':key or uuid.uuid4().hex} if LAB>=3 else {}
return self.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=actor,body=body,headers=headers,schema='Message')
key = "key-" + uuid.uuid4().hex[:12]
body = {"recipient": LOGIN, "body": "hello " + uuid.uuid4().hex[:8]}
def attachment(self, actor, chat):
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
att = self.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',201 if LAB==4 else 202,actor=actor,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')['json']
check(att['status']==('ready' if LAB==4 else 'queued'),'incorrect upload status')
check(att['chat_id']==chat['id'] and att['owner_id']==actor['id'],'attachment ownership mismatch')
check(att['sha256']==hashlib.sha256(content).hexdigest() and att['size_bytes']==len(content),'original checksum/size mismatch')
return att,content
first = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": key}),
json=body,
timeout=TIMEOUT,
)
check(first.status_code == 201, "first POST returns 201 (got %d)" % first.status_code)
def wait_ready(self, actor, att, wait_seconds=60):
deadline = time.monotonic()+wait_seconds
while time.monotonic()<deadline:
att = self.call('GET','/api/v1/attachments/'+att['id'],actor=actor,schema='Attachment')['json']
check(att['status']!='failed','attachment reached failed')
if att['status']=='ready':
return att
time.sleep(0.3)
raise Failure('attachment did not become ready within test deadline')
second = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": key}),
json=body,
timeout=TIMEOUT,
)
check(second.status_code in (200, 201), "replayed POST returns 2xx (got %d)" % second.status_code)
def arguments(description, configure=None):
import argparse
p = argparse.ArgumentParser(description=description)
p.add_argument('--base-url', default=None)
p.add_argument('--ca-file', default=None)
if configure:
configure(p)
return p.parse_args()
first_id = first.json().get("id")
second_id = second.json().get("id")
check(first_id is not None, "first POST returns message id")
check(first_id == second_id, "replay returns the same id (%s vs %s)" % (first_id, second_id))
def run(main):
missing_key = requests.post(BASE + "/api/messages", headers=auth, json=body, timeout=TIMEOUT)
check(missing_key.status_code == 400, "POST without Idempotency-Key returns 400 (got %d)" % missing_key.status_code)
unauthorized = requests.get(BASE + "/api/messages", timeout=TIMEOUT)
check(unauthorized.status_code == 401, "GET without token returns 401 (got %d)" % unauthorized.status_code)
messages = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT).json()
matching = [m for m in messages if m.get("body") == body["body"]]
check(len(matching) == 1, "history contains exactly one copy of the message (got %d)" % len(matching))
if failures:
print("\n%d check(s) failed" % len(failures))
return 1
print("\nAll API checks passed")
return 0
if __name__ == "__main__":
try:
main()
except (Failure,ValueError,OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
sys.exit(main())
except requests.RequestException as exc:
print("request failed:", exc)
sys.exit(1)
+157 -51
View File
@@ -1,58 +1,164 @@
#!/usr/bin/env python3
"""Small closed-loop HTTP write benchmark; not an open-loop capacity proof."""
from concurrent.futures import ThreadPoolExecutor
import json
import math
from pathlib import Path
import subprocess
import sys
import threading
import time
from client import Client, Failure, LAB, arguments, check, run
from pathlib import Path
import requests
BASE = "http://localhost:8080"
LOGIN = "test"
PASSWORD = "test123"
TIMEOUT = 5
REPO_ROOT = Path(__file__).resolve().parents[1]
RECOVERY_BUDGET = 10.0
failures = []
def check(condition, message):
if condition:
print("PASS:", message)
return True
failures.append(message)
print("FAIL:", message)
return False
def login():
response = requests.post(
BASE + "/api/auth/login",
json={"login": LOGIN, "password": PASSWORD},
timeout=TIMEOUT,
)
response.raise_for_status()
return response.json()["token"]
def fetch(token):
response = requests.get(
BASE + "/api/messages",
headers={"Authorization": "Bearer " + token},
timeout=TIMEOUT,
)
response.raise_for_status()
return response.headers.get("X-Instance-Id", "")
def round_robin(token, count):
instances = []
lock = threading.Lock()
def worker():
try:
instance = fetch(token)
except requests.RequestException:
return
with lock:
instances.append(instance)
threads = [threading.Thread(target=worker) for _ in range(count)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return instances
def compose(*args):
return subprocess.run(
["docker", "compose", *args],
cwd=REPO_ROOT,
capture_output=True,
text=True,
check=False,
)
def main():
def configure(p):
p.add_argument('--duration',type=float,default=30)
p.add_argument('--concurrency',type=int,default=4)
p.add_argument('--output',default=None,help='Optional JSON metrics, no session tokens')
args = arguments('Synthetic POST message load, closed loop; creates users/messages',configure)
check(1<=args.duration<=3600,'duration must be 1..3600 seconds')
check(1<=args.concurrency<=128,'concurrency must be 1..128')
c = Client(args.base_url,args.ca_file)
alice,bob,eve,chat = c.bootstrap()
barrier = threading.Barrier(args.concurrency)
def worker(worker_id):
local = Client(args.base_url,args.ca_file,timeout=5)
barrier.wait()
deadline = time.monotonic()+args.duration
latencies,errors = [],0
index = 0
while time.monotonic()<deadline:
start = time.monotonic()
try:
local.message(alice,chat,'load-%s-%s' % (worker_id,index))
latencies.append(time.monotonic()-start)
except Failure:
errors += 1
index += 1
return latencies,errors
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
results = list(pool.map(worker,range(args.concurrency)))
elapsed = time.monotonic()-started
latencies = sorted(x for values,_ in results for x in values)
errors = sum(n for _,n in results)
total = len(latencies)+errors
def percentile(p):
return round(1000*latencies[max(0,math.ceil(p*len(latencies))-1)],3) if latencies else None
report = {'lab':LAB,'workload':'closed-loop POST messages; no automatic retries','requested_duration_seconds':args.duration,'elapsed_seconds':round(elapsed,3),'concurrency':args.concurrency,'successful_requests':len(latencies),'failed_requests':errors,'error_ratio':round(errors/total,6) if total else None,'successful_rps':round(len(latencies)/elapsed,3),'successful_latency_ms':{'p50':percentile(.50),'p95':percentile(.95),'p99':percentile(.99)},'note':'Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.'}
text = json.dumps(report,ensure_ascii=False,indent=2)
if args.output:
dest = Path(args.output)
dest.parent.mkdir(parents=True,exist_ok=True)
dest.write_text(text+'\n')
print(text)
check(bool(latencies),'no successful writes')
# Errors are reported, not treated as a universal load-test threshold.
token = login()
auth = {"Authorization": "Bearer " + token}
if __name__=='__main__':
run(main)
probe = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": "load-" + str(time.time_ns())}),
json={"recipient": LOGIN, "body": "before failover"},
timeout=TIMEOUT,
)
check(probe.status_code == 201, "message written before failover (got %d)" % probe.status_code)
probe_id = probe.json().get("id")
instances = round_robin(token, 20)
check(len(set(instances)) >= 2, "requests reached at least two replicas: %s" % sorted(set(instances)))
print("\n=== Stopping api1 ===")
stop = compose("stop", "api1")
check(stop.returncode == 0, "docker compose stop api1 succeeded")
started = time.monotonic()
recovered_at = None
served_after = []
transient_errors = 0
while time.monotonic() - started < RECOVERY_BUDGET + 5:
try:
instance = fetch(token)
except requests.RequestException:
transient_errors += 1
time.sleep(0.2)
continue
if recovered_at is None:
recovered_at = time.monotonic() - started
served_after.append(instance)
if len(served_after) >= 5:
break
time.sleep(0.1)
check(
recovered_at is not None and recovered_at <= RECOVERY_BUDGET,
"reads recovered within %.0fs (%.2fs, %d transient errors)"
% (RECOVERY_BUDGET, recovered_at if recovered_at is not None else -1, transient_errors),
)
check(bool(served_after), "requests still served while api1 is down")
check(all(x == "api2" for x in served_after), "api1 left rotation, served by: %s" % sorted(set(served_after)))
write = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": "load-fail-" + str(time.time_ns())}),
json={"recipient": LOGIN, "body": "written during failover"},
timeout=TIMEOUT,
)
check(write.status_code == 201, "write works while api1 is down (got %d)" % write.status_code)
print("\n=== Starting api1 back ===")
start = compose("start", "api1")
check(start.returncode == 0, "docker compose start api1 succeeded")
deadline = time.monotonic() + 30
back = set()
while time.monotonic() < deadline:
back = set(round_robin(token, 10))
if "api1" in back:
break
time.sleep(1)
check("api1" in back, "api1 is back in rotation: %s" % sorted(back))
history = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT)
check(history.status_code == 200, "history readable after failover (got %d)" % history.status_code)
ids = [m.get("id") for m in history.json()]
check(probe_id in ids, "message written before failover survived")
check(len(ids) == len(set(ids)), "no duplicate messages in history")
if failures:
print("\n%d check(s) failed" % len(failures))
return 1
print("\nFailover scenario passed")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except requests.RequestException as exc:
print("request failed:", exc)
sys.exit(1)