ЛР 3 — БВТ2301 — Майорова — на 5

This commit is contained in:
2026-10-27 11:26:09 +03:00
parent 0ab3a341aa
commit 8da1770331
55 changed files with 64041 additions and 35 deletions
+243
View File
@@ -0,0 +1,243 @@
"""Repeatable LB-only 80% history reads / 20% unique message writes, closed loop."""
import argparse
import collections
import concurrent.futures
import http.client
import json
import os
from pathlib import Path
import platform
import resource
import statistics
import subprocess
import sys
import threading
import time
import uuid
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
def command(args, env=None):
return subprocess.check_output(args, text=True, env=env).strip()
def containers():
ids = command(['docker', 'compose', 'ps', '-q']).split()
result = {}
for cid in ids:
role = command(['docker', 'inspect', '--format', '{{index .Config.Labels "com.docker.compose.service"}}', cid])
result[cid] = role
return result
def telemetry(done, result):
roles = containers()
while not done.is_set():
started = time.monotonic()
raw = command(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *roles])
sample = []
for line in raw.splitlines():
value = json.loads(line)
role = next((role for cid, role in roles.items() if cid.startswith(value['ID'])), '?')
sample.append({'service': role, 'container': value['ID'], 'cpu_percent': float(value['CPUPerc'].rstrip('%')), 'memory': value['MemUsage']})
waits = command(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', "SELECT coalesce(json_agg(s), '[]') FROM (SELECT state, wait_event_type, wait_event, count(*) AS connections FROM pg_stat_activity WHERE 1=1 AND datname = 'messenger' AND pid <> pg_backend_pid() GROUP BY state, wait_event_type, wait_event) s"])
result.append({'t_monotonic': started, 'containers': sample, 'postgres_activity': json.loads(waits)})
done.wait(.1)
def fixture():
# An overloaded LB needs time to mark recovered backends UP before seeding.
c = Client(timeout=2)
for attempt in range(120):
try:
c.call('GET', '/health/ready', schema='Health')
break
except Exception:
time.sleep(.25)
else:
raise AssertionError('LB did not recover before fixture')
time.sleep(1)
actor = c.user('bench')
chats = [c.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': 'synthetic-benchmark', 'member_ids': [actor['id']]}, schema='Chat')['json'] for _ in range(8)]
# Seed outside the measurement with the same 800-message fixture each run.
payload = json.dumps({'user': actor['id'], 'chats': [v['id'] for v in chats]})
code = """import json, sys, uuid, psycopg
sys.path.insert(0, '/app/src')
from postgres import setting
p = json.loads(sys.stdin.read())
with psycopg.connect(setting('DATABASE_URL')) as conn:
for chat in p['chats']:
conn.execute(\"INSERT INTO messages (id, chat_id, sender_id, text, created_at) SELECT gen_random_uuid(), %s::uuid, %s::uuid, convert_to(repeat('x', 64), 'UTF8'), TIMESTAMPTZ '2026-01-01 00:00:00Z' + n * INTERVAL '1 microsecond' FROM generate_series(1, 100) n\", (chat, p['user']))
print('Seeded 800 synthetic messages.')
"""
subprocess.run(['docker', 'compose', 'exec', '-T', 'api', 'python', '-c', code], input=payload, text=True, check=True, stdout=subprocess.DEVNULL)
return actor, chats
def percentile(values, fraction):
return values[max(0, int(len(values) * fraction + .999999) - 1)] if values else None
def measure(actor, chats, concurrency, duration):
parsed = urlsplit(os.environ.get('BASE_URL', 'http://127.0.0.1:18087'))
assert parsed.scheme == 'http', 'local synthetic stand only'
gate = threading.Barrier(concurrency + 1)
deadline = [0.0]
def worker(index):
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=3)
headers = {'Authorization': 'Bearer ' + actor['token'], 'Content-Type': 'application/json'}
times, errors, seen = [], collections.Counter(), collections.Counter()
reads = writes = 0
step = index
gate.wait()
try:
while time.monotonic() < deadline[0]:
chat = chats[(step // 5 + index) % len(chats)]
path = '/api/v1/chats/' + chat['id'] + '/messages'
write = step % 5 == 0
body = '{"text":"' + 'x' * 64 + '"}' if write else None
request_headers = dict(headers)
if write:
request_headers['Idempotency-Key'] = uuid.uuid4().hex
else:
path += '?limit=50'
start = time.monotonic()
try:
connection.request('POST' if write else 'GET', path, body=body, headers=request_headers)
response = connection.getresponse()
raw = response.read()
if response.status == (201 if write else 200):
payload = json.loads(raw)
assert ('id' in payload) if write else (len(payload['items']) == 50)
times.append((time.monotonic() - start) * 1000)
seen[response.getheader('X-Instance-Id')] += 1
writes += int(write)
reads += int(not write)
else:
errors['http_' + str(response.status)] += 1
except (OSError, http.client.HTTPException) as exc:
errors[type(exc).__name__] += 1
connection.close()
step += 1
finally:
connection.close()
return times, errors, seen, reads, writes
cpu_before = resource.getrusage(resource.RUSAGE_SELF)
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
futures = [executor.submit(worker, i) for i in range(concurrency)]
started = time.monotonic()
deadline[0] = started + duration
gate.wait()
rows = [f.result() for f in futures]
elapsed = time.monotonic() - started
cpu_after = resource.getrusage(resource.RUSAGE_SELF)
times = sorted(t for row in rows for t in row[0])
errors, instances = collections.Counter(), collections.Counter()
for row in rows:
errors.update(row[1]); instances.update(row[2])
count = len(times)
return {'duration_seconds': elapsed, 'configured_seconds': duration, 'concurrency': concurrency, 'successes': count, 'reads': sum(v[3] for v in rows), 'writes': sum(v[4] for v in rows), 'successful_rps': count / elapsed, 'errors': dict(errors), 'error_fraction': sum(errors.values()) / max(1, count + sum(errors.values())), 'p50_ms': percentile(times, .5), 'p95_ms': percentile(times, .95), 'p99_ms': percentile(times, .99), 'instances': dict(instances), 'generator_cpu_percent': ((cpu_after.ru_utime + cpu_after.ru_stime) - (cpu_before.ru_utime + cpu_before.ru_stime)) / elapsed * 100}
def pool_snapshot():
result = {}
for cid in command(['docker', 'compose', 'ps', '-q', 'api']).split():
command(['docker', 'kill', '--signal=USR1', cid])
logs = subprocess.check_output(['docker', 'logs', '--tail', '10', cid], text=True, stderr=subprocess.STDOUT)
lines = [line for line in logs.splitlines() if 'pool_stats instance=' in line]
assert lines, 'pool diagnostics signal missing'
stats = json.loads(lines[-1].split('stats=', 1)[1])
code = "from pathlib import Path; import json; print(json.dumps(dict(line.split() for line in Path('/sys/fs/cgroup/cpu.stat').read_text().splitlines())))"
stats['cgroup_cpu'] = json.loads(command(['docker', 'exec', cid, 'python', '-c', code]))
result[cid[:12]] = stats
return result
def trial(concurrency, duration):
actor, chats = fixture()
measure(actor, chats, concurrency, 2)
before = pool_snapshot()
samples = []
done = threading.Event()
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
probe = executor.submit(telemetry, done, samples)
try:
result = measure(actor, chats, concurrency, duration)
finally:
done.set()
probe.result()
result['pool_before'] = before
result['pool_after'] = pool_snapshot()
result['telemetry'] = samples
result['fixture'] = {'chats': 8, 'messages_before_warmup': 800, 'text_code_points': 64, 'history_limit': 50, 'warmup_seconds': 2, 'write_ratio_target': .2}
return result
def configure(replicas, cpu, memory, mode, pool=8, database_cpu=1):
env = dict(os.environ, API_REPLICAS=str(replicas), API_CPUS=str(cpu), API_MEMORY=str(memory) + 'm', DB_ACCESS_MODE=mode, DB_POOL_MAX=str(pool), POSTGRES_CPUS=str(database_cpu))
subprocess.run(['docker', 'compose', 'up', '-d', '--wait', '--no-deps', 'postgres'], env=env, check=True, stdout=subprocess.DEVNULL)
# Independent runs use a distinct new fixture; application replicas are recreated.
subprocess.run(['docker', 'compose', 'up', '-d', '--wait', '--no-deps', '--scale', 'api=' + str(replicas), 'api'], env=env, check=True, stdout=subprocess.DEVNULL)
c = Client(timeout=1)
deadline = time.monotonic() + 30
observed = set()
while time.monotonic() < deadline:
try:
observed.add(c.call('GET', '/health/ready', schema='Health')['headers']['X-Instance-Id'])
if len(observed) >= replicas:
break
except Exception:
pass
time.sleep(.1)
assert len(observed) == replicas
time.sleep(2)
return env
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--duration', type=float, default=8)
parser.add_argument('--repeats', type=int, default=3)
parser.add_argument('--pilot', action='store_true')
parser.add_argument('--resume', action='store_true')
args = parser.parse_args()
output = ROOT / 'evidence/scaling.json'
result = {'runtime': platform.python_version(), 'host': platform.platform(), 'docker': json.loads(command(['docker', 'info', '--format', '{"cpus":{{.NCPU}},"memory":{{.MemTotal}},"os":"{{.OperatingSystem}}"}'])), 'runs': []}
configs = [('fixed', n, 1 / n, 512 // n, 'optimized', 16) for n in (1, 2, 4)]
configs += [('growing', n, .5, 256, 'optimized', 16) for n in (1, 2, 4)]
configs += [('improvement', 2, .5, 256, 'baseline', 16)]
configs += [('saturation', 4, .5, 256, 'optimized', n) for n in (1, 4, 32, 64)]
configs = [(*row, 8) for row in configs]
configs += [('pool_limit', 1, 1, 512, 'optimized', 32, n) for n in (1, 8)]
configs += [('pool_isolated', 1, 1, 512, 'optimized', 16, n) for n in (1,8)]
configs = [(*row, 1) for row in configs]
configs += [('database_limit', n, .5, 256, 'optimized', 16, 8, .1) for n in (1,2,4)]
if args.resume:
result = json.loads(output.read_text())
if args.pilot:
configs = [('pilot', 2, .5, 256, 'optimized', 16, 8, 1)]
try:
for series, replicas, cpu, memory, mode, concurrency, pool, database_cpu in configs:
completed = [v for v in result['runs'] if v['series'] == series and v['replicas'] == replicas and v['concurrency'] == concurrency and v['db_pool_max'] == pool]
if len(completed) >= args.repeats:
continue
configure(replicas, cpu, memory, mode, pool, database_cpu)
for repeat in range(args.repeats):
if any(v['series'] == series and v['replicas'] == replicas and v['concurrency'] == concurrency and v['db_pool_max'] == pool and v['repeat'] == repeat + 1 for v in result['runs']):
continue
row = trial(concurrency, args.duration)
row.update(series=series, replicas=replicas, api_cpu_each=cpu, api_memory_mib_each=memory, mode=mode, repeat=repeat + 1, db_pool_max=pool, postgres_cpu=database_cpu)
result['runs'].append(row)
output.write_text(json.dumps(result, indent=2))
print(json.dumps({k: row[k] for k in ('series', 'replicas', 'mode', 'repeat', 'concurrency', 'successful_rps', 'p95_ms', 'errors', 'generator_cpu_percent')}), flush=True)
finally:
configure(2, 1, 256, 'optimized')
print('Research complete; default two-replica stand restored.')
if __name__ == '__main__':
main()
+53
View File
@@ -0,0 +1,53 @@
"""Cache fallback and mandatory database readiness, using the LB only."""
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
def compose(*args):
subprocess.run(['docker', 'compose', *args], check=True, stdout=subprocess.DEVNULL)
def main():
c = Client()
actor, _, _, chat = c.bootstrap()
sent = c.message(actor, chat, 'dependency-proof')['json']
try:
compose('stop', 'redis')
for _ in range(4):
assert c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'] == actor['user']
c.call('GET', '/health/ready', schema='Health')
print('PASS: Redis outage falls back to PostgreSQL; session still checked.', flush=True)
finally:
compose('up', '-d', '--wait', 'redis')
try:
compose('stop', 'postgres')
started = time.monotonic()
for _ in range(30):
try:
urllib.request.urlopen(c.base + '/health/ready', timeout=3)
except urllib.error.HTTPError as exc:
assert exc.code == 503
break
time.sleep(.2)
else:
raise AssertionError('Database outage did not affect readiness')
print('PASS: database outage makes LB readiness unavailable in %.3f seconds.' % (time.monotonic() - started), flush=True)
finally:
compose('up', '-d', '--wait', 'postgres')
subprocess.run([sys.executable, str(ROOT / 'scripts/wait_ready.py')], check=True)
assert c.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'] == actor['user']
found = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']['items']
assert sent in found
print('PASS: session and confirmed message preserved after database recovery.')
if __name__ == '__main__':
main()
+69
View File
@@ -0,0 +1,69 @@
"""Transaction rollback, lost reply, expiry and restart evidence on synthetic data only."""
import http.client
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
from resilience import history
def sql(statement):
return subprocess.check_output(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-Atc', statement], text=True).strip()
def main():
c = Client()
actor, reader, _, chat = c.bootstrap()
key = uuid.uuid4().hex
first = c.message(actor, chat, 'persist-key\x00👩', key=key)['json']
duration = float(sql("SELECT extract(epoch FROM expires_at - clock_timestamp()) FROM idempotency_keys WHERE 1=1 AND key = '" + key + "'"))
assert 86300 < duration <= 86400
subprocess.run([str(ROOT / 'scripts/restart.sh')], check=True, stdout=subprocess.DEVNULL)
subprocess.run([sys.executable, str(ROOT / 'scripts/wait_ready.py')], check=True)
assert c.message(actor, chat, 'persist-key\x00👩', key=key)['json'] == first
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor, body={'text': 'different'}, headers={'Idempotency-Key': key})
print('PASS: original session and same idempotency result survive full stack restart; retention >=24h.', flush=True)
failed_key = uuid.uuid4().hex
marker = 'rollback-' + uuid.uuid4().hex
# Inject only for this synthetic message; both the claim and write must roll back.
sql("CREATE FUNCTION synthetic_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.text = convert_to('" + marker + "', 'UTF8') THEN RAISE EXCEPTION 'synthetic failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER synthetic_failure BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION synthetic_failure();")
try:
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=actor, body={'text': marker}, headers={'Idempotency-Key': failed_key})
assert sql("SELECT count(*) FROM idempotency_keys WHERE 1=1 AND key = '" + failed_key + "'") == '0'
finally:
sql('DROP TRIGGER synthetic_failure ON messages; DROP FUNCTION synthetic_failure();')
c.message(actor, chat, marker, key=failed_key)
print('PASS: synthetic failure leaves no idempotency result; same key succeeds after recovery.', flush=True)
parsed = urlsplit(c.base)
lost_key = uuid.uuid4().hex
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=2)
connection.request('POST', '/api/v1/chats/' + chat['id'] + '/messages', body=json.dumps({'text': 'lost-reply-' + lost_key}), headers={'Authorization': 'Bearer ' + actor['token'], 'Content-Type': 'application/json', 'Idempotency-Key': lost_key})
connection.close() # Deliberately do not read the server's response.
time.sleep(.2)
restored = c.message(actor, chat, 'lost-reply-' + lost_key, key=lost_key)['json']
assert c.message(actor, chat, 'lost-reply-' + lost_key, key=lost_key)['json'] == restored
found = history(c, reader, chat)
assert sum(v['text'] == restored['text'] for v in found) == 1
print('PASS: retry after intentionally unread HTTP reply creates no duplicate.', flush=True)
sql("UPDATE idempotency_keys SET expires_at = clock_timestamp() - INTERVAL '1 second' WHERE 1=1 AND key = '" + key + "'")
renewed = c.message(actor, chat, 'new operation after expiry', key=key)['json']
assert renewed['id'] != first['id']
assert c.message(actor, chat, 'new operation after expiry', key=key)['json'] == renewed
found = history(c, reader, chat)
assert first in found and renewed in found
print('PASS: simulated expired key can be reused; original message remains in history.', flush=True)
if __name__ == '__main__':
main()
+134
View File
@@ -0,0 +1,134 @@
"""Real container failures/replacements while readers and writers use only the LB."""
import concurrent.futures
import json
import os
from pathlib import Path
import statistics
import subprocess
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure
from resilience import history
from stop_one import instance
def docker(*args):
return subprocess.check_output(['docker', *args], text=True).strip()
def wait_instances(expected):
deadline = time.monotonic() + 30
observed = set()
c = Client(timeout=1)
while time.monotonic() < deadline:
try:
observed.add(c.call('GET', '/health/ready', schema='Health')['headers']['X-Instance-Id'])
if len(observed) >= expected:
return observed
except Failure:
pass
time.sleep(0.1)
raise AssertionError('Not enough ready instances through LB')
def phase(actor, reader, chat, action, duration=12):
started = time.monotonic()
stop = threading.Event()
replies, failures, confirmed = [], [], {}
action_time = [None]
def worker(index):
c = Client(timeout=2)
key = uuid.uuid4().hex
content = 'fault-' + key
while not stop.is_set():
before = time.monotonic()
try:
if index < 2:
response = c.message(actor, chat, content, key=key)
confirmed[response['json']['id']] = response['json']
key = uuid.uuid4().hex
content = 'fault-' + key
else:
response = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=50', actor=reader, schema='MessagePage')
replies.append({'t': time.monotonic() - started, 'latency_ms': (time.monotonic() - before) * 1000, 'write': index < 2, 'instance': response['headers']['X-Instance-Id']})
except Failure:
failures.append({'t': time.monotonic() - started, 'write': index < 2})
# An uncertain POST keeps its original body/key until confirmation.
stop.wait(0.02)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(worker, i) for i in range(4)]
time.sleep(2)
action_time[0] = time.monotonic() - started
try:
action_record = action()
action_completed = time.monotonic() - started
except BaseException:
stop.set()
raise
remaining = duration - (time.monotonic() - started)
if remaining > 0:
stop.wait(remaining)
stop.set()
for future in futures:
future.result()
measurement_elapsed = time.monotonic() - started
found = history(Client(), reader, chat)
by_id = {v['id']: v for v in found}
assert all(by_id.get(k) == v for k, v in confirmed.items()), 'acknowledged message lost'
contents = [v['text'] for v in found]
assert len(contents) == len(set(contents)), 'uncertain retry duplicated a message'
target = action_record.get('instance', action_record.get('old_instance'))
recovered = [v['t'] - action_time[0] for v in replies if v['write'] and v['t'] >= action_completed and v['instance'] != target]
assert all(v['instance'] != target for v in replies[-5:]), 'removed instance still serves final replies'
assert recovered and min(recovered) <= 10, 'write recovery exceeded 10 seconds'
times = sorted(v['latency_ms'] for v in replies)
return {'duration': round(measurement_elapsed, 3), 'action_at': action_time[0], 'action_completed_at': action_completed, 'action': action_record, 'successful_rps': len(replies) / measurement_elapsed, 'successful_requests': len(replies), 'errors': len(failures), 'write_recovery_seconds': min(recovered), 'p50_ms': statistics.median(times), 'p95_ms': times[int(.95 * (len(times)-1))], 'p99_ms': times[int(.99 * (len(times)-1))], 'confirmed_messages_verified': len(confirmed), 'samples': replies, 'failed_samples': failures}
def main():
c = Client()
actor, reader, _, chat = c.bootstrap()
originals = docker('compose', 'ps', '-q', 'api').splitlines()
assert len(originals) == 2
wait_instances(2)
results = []
for container in originals:
alias = instance(container)
def stop_one():
env = dict(os.environ, TARGET_INSTANCE_ID=alias)
subprocess.run([str(ROOT / 'scripts/stop-one.sh')], env=env, check=True, stdout=subprocess.DEVNULL)
assert docker('inspect', '--format', '{{.State.Running}}', container) == 'false'
return {'container': container, 'instance': alias, 'running_after': False}
result = phase(actor, reader, chat, stop_one)
result['kind'] = 'stop'
results.append(result)
subprocess.run(['docker', 'compose', 'up', '-d', '--wait', '--no-deps', 'api'], check=True, stdout=subprocess.DEVNULL)
wait_instances(2)
print('PASS: stopped actual replica', container[:12], 'under read/write load; existing session/data preserved.', flush=True)
for container in originals:
old_alias = instance(container)
def replace():
docker('stop', '--time', '8', container)
docker('rm', container)
subprocess.run(['docker', 'compose', 'up', '-d', '--wait', '--no-deps', '--no-recreate', 'api'], check=True, stdout=subprocess.DEVNULL)
new_ids = docker('compose', 'ps', '-q', 'api').splitlines()
assert container not in new_ids and len(new_ids) == 2
new_aliases = wait_instances(2)
assert old_alias not in new_aliases
return {'old_container': container, 'old_instance': old_alias, 'new_containers': new_ids, 'observed_instances': sorted(new_aliases)}
result = phase(actor, reader, chat, replace, duration=18)
result['kind'] = 'rolling_replace'
results.append(result)
print('PASS: replaced actual replica', container[:12], 'under load; DNS rediscovery verified.', flush=True)
(ROOT / 'evidence/faults.json').write_text(json.dumps(results, indent=2))
print('PASS: each API stopped and then replaced sequentially; all confirmations and original sessions verified.')
if __name__ == '__main__':
main()
+95
View File
@@ -0,0 +1,95 @@
"""Render saved measurements, never fabricated or smoothed values."""
from collections import defaultdict
import json
import os
from pathlib import Path
import statistics
os.environ.setdefault('MPLCONFIGDIR', '/tmp/mtusi-lab3-matplotlib')
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT = Path(__file__).resolve().parents[1]
data = json.loads((ROOT / 'evidence/scaling.json').read_text())['runs']
plt.rcParams.update({'font.size': 10, 'axes.grid': True, 'grid.alpha': .2})
def values(series, replicas=None, concurrency=None, pool=None):
return [r for r in data if r['series'] == series and (replicas is None or r['replicas'] == replicas) and (concurrency is None or r['concurrency'] == concurrency) and (pool is None or r['db_pool_max'] == pool)]
def point(rows, metric):
v = [r[metric] for r in rows]
return statistics.median(v), min(v), max(v)
def curve(axis, xs, groups, metric, label, color):
p = [point(g, metric) for g in groups]
axis.errorbar(xs, [v[0] for v in p], yerr=[[v[0]-v[1] for v in p], [v[2]-v[0] for v in p]], marker='o', capsize=4, label=label, color=color)
fig, axes = plt.subplots(2, 2, figsize=(12, 8), layout='constrained')
for series, label, color in [('fixed', 'Всего API: 1 CPU / 512 MiB', '#c64a46'), ('growing', 'Каждая API: 0,5 CPU / 256 MiB', '#138a83')]:
groups = [values(series, n) for n in (1, 2, 4)]
curve(axes[0,0], [1,2,4], groups, 'successful_rps', label, color)
curve(axes[0,1], [1,2,4], groups, 'p99_ms', label, color)
for axis in axes[0]:
axis.set_xlabel('Число API-реплик'); axis.set_xticks([1,2,4]); axis.legend(fontsize=8)
axes[0,0].set_ylabel('Успешные запросы / с'); axes[0,0].set_title('Пропускная способность: 16 клиентов')
axes[0,1].set_ylabel('p99 успешных ответов, мс'); axes[0,1].set_title('Задержки: 16 клиентов')
xs = [1,4,16,32,64]
groups = [values('growing',4) if n == 16 else values('saturation',4,n) for n in xs]
curve(axes[1,0], xs, groups, 'successful_rps', '4 API × 0,5 CPU / 256 MiB', '#405bb5')
axes[1,0].set_xscale('log', base=2); axes[1,0].set_xticks(xs, labels=[str(x) for x in xs]); axes[1,0].set_xlabel('Одновременные клиенты'); axes[1,0].set_ylabel('Успешные запросы / с'); axes[1,0].set_title('Рост конкуренции'); axes[1,0].legend(fontsize=8)
groups = [values('improvement',2), values('fixed',2)]
p = [point(g,'successful_rps') for g in groups]
axes[1,1].bar(['Проверки из lab2', 'Без лишних SQL'], [v[0] for v in p], color=['#c64a46','#138a83'], yerr=[[v[0]-v[1] for v in p],[v[2]-v[0] for v in p]], capsize=5)
axes[1,1].set_ylabel('Успешные запросы / с'); axes[1,1].set_title('Улучшение: 2 API, всего 1 CPU / 512 MiB')
fig.suptitle('ЛР 3: цена масштабирования • 80% чтение / 20% запись\nМедианы трёх прогонов по 8 с; усы — min/max; прогрев 2 с', fontsize=13)
fig.savefig(ROOT / 'evidence/scaling.png', dpi=160)
fig.savefig(ROOT / 'evidence/scaling.svg')
plt.close(fig)
fig, axes = plt.subplots(1,2,figsize=(10,3.8),layout='constrained')
for series,label,color in [('growing','PostgreSQL: 1 CPU','#138a83'),('database_limit','PostgreSQL: 0,1 CPU','#c64a46')]:
groups = [values(series,n) for n in (1,2,4)]
curve(axes[0],[1,2,4],groups,'successful_rps',label,color)
cpu = []
for group in groups:
readings = [c['cpu_percent'] for row in group for sample in row['telemetry'] for c in sample['containers'] if c['service']=='postgres']
cpu.append(statistics.median(readings))
axes[1].plot([1,2,4],cpu,marker='o',label=label,color=color)
for axis in axes:
axis.set_xlabel('Число API-реплик');axis.set_xticks([1,2,4]);axis.legend(fontsize=8)
axes[0].set_ylabel('Успешные запросы / с');axes[1].set_ylabel('CPU PostgreSQL, % одного ядра')
axes[1].axhline(10,color='#c64a46',linestyle='--',alpha=.5)
fig.suptitle('Насыщение общей БД • каждая API: 0,5 CPU / 256 MiB\n16 клиентов, тот же профиль; PostgreSQL ограничен явно')
fig.savefig(ROOT / 'evidence/bottleneck.png',dpi=160)
plt.close(fig)
fig, axes = plt.subplots(1,2,figsize=(9,3.8),layout='constrained')
groups = [values('pool_isolated',pool=n) for n in (1,8)]
for axis, metric, ylabel in zip(axes, ['successful_rps','p99_ms'], ['Успешные запросы / с','p99 успешных ответов, мс']):
p = [point(g,metric) for g in groups]
axis.bar(['Пул 1', 'Пул 8'], [v[0] for v in p], color=['#c64a46','#138a83'], yerr=[[v[0]-v[1] for v in p],[v[2]-v[0] for v in p]], capsize=5)
axis.set_ylabel(ylabel)
fig.suptitle('Ограничение пула: 1 API, 1 CPU / 512 MiB, 16 клиентов\nМедианы трёх прогонов; остальные параметры одинаковы')
fig.savefig(ROOT / 'evidence/pool.png', dpi=160)
plt.close(fig)
faults = json.loads((ROOT / 'evidence/faults.json').read_text())
fig, axes = plt.subplots(2,2,figsize=(12,6.5),layout='constrained')
for i,(axis,run) in enumerate(zip(axes.flat,faults)):
successes, errors = defaultdict(int), defaultdict(int)
for sample in run['samples']:successes[int(sample['t'])] += 1
for sample in run['failed_samples']:errors[int(sample['t'])] += 1
x = range(int(run['duration']) + 1)
axis.plot(x,[successes[t] for t in x],label='Успешные чтения + записи',color='#138a83')
axis.plot(x,[errors[t] for t in x],label='Ошибки',color='#c64a46')
axis.axvline(run['action_at'],linestyle='--',color='#444',label='Начало воздействия')
axis.set_title(('Остановка' if run['kind']=='stop' else 'Замена') + ' реплики ' + str(i%2+1))
axis.set_xlabel('Время от начала прогона, с');axis.set_ylabel('Запросы за секунду');axis.legend(fontsize=7)
fig.suptitle('Последовательные отказы и замены реальных контейнеров через LB')
fig.savefig(ROOT / 'evidence/faults.png', dpi=160)
print('Saved scaling.png/.svg, pool.png and faults.png.')
+177
View File
@@ -0,0 +1,177 @@
"""Extra black-box tests, without changing the course's public tests."""
import concurrent.futures
from pathlib import Path
import sys
import unittest
from urllib.parse import quote
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client as PublicClient, LAB
class Client(PublicClient):
def call(self, method, path, *args, headers=None, **kwargs):
headers = dict(headers or {})
if method == 'POST' and path.endswith('/messages'):
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
return super().call(method, path, *args, headers=headers, **kwargs)
class APIContract(unittest.TestCase):
def setUp(self):
self.client = Client()
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = '/api/v1/chats/' + self.chat['id']
def test_malformed_json_and_extra_fields(self):
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
def test_unicode_limits(self):
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
self.assertEqual(result['text'], '👩' * 4000)
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
def test_unicode_nul_round_trip(self):
import base64
value = 'A\x00B\\u0000👩'
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
self.assertEqual(user['display_name'], value)
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
self.assertEqual(session['user'], user)
actor = {'id': user['id'], 'token': session['token']}
# Exercise the database path and then the Redis profile cache.
for _ in range(2):
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
self.assertEqual(chat['title'], value)
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
for content in contents:
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
self.assertEqual([message['text'] for message in history['items']], contents)
def test_foreign_chat(self):
for suffix in ('', '/messages'):
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
def test_registration_race(self):
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
statuses = list(executor.map(register, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
def test_invalid_chat_creation(self):
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
for member_ids in members:
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
def test_cursor_scope_and_validation(self):
for i in range(3):
self.client.message(self.alice, self.chat, str(i))
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
def test_concurrent_messages_and_pagination(self):
def send(i):
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
sent = list(executor.map(send, range(100)))
found = []
cursor = None
while True:
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
found.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
break
self.assertEqual(len(found), 100)
self.assertEqual(len({v['id'] for v in found}), 100)
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
def test_idempotency_concurrent_replicas(self):
key = uuid.uuid4().hex
def send(_):
return Client().message(self.alice, self.chat, 'Один раз\x00👩', key=key)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
replies = list(executor.map(send, range(32)))
self.assertGreaterEqual(len({v['headers']['X-Instance-Id'] for v in replies}), 2)
self.assertTrue(all(v['json'] == replies[0]['json'] for v in replies))
page = self.client.call('GET', self.path + '/messages', actor=self.bob, schema='MessagePage')['json']
self.assertEqual(page['items'], [replies[0]['json']])
self.client.call('POST', self.path + '/messages', 409, actor=self.alice, body={'text': 'different'}, headers={'Idempotency-Key': key})
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=self.alice)
self.client.call('POST', self.path + '/messages', 401, actor=self.alice, body={'text': 'Один раз\x00👩'}, headers={'Idempotency-Key': key})
def test_protocol_error_headers(self):
self.client.call('TRACE', '/api/v1/users/me', 400, actor=self.alice)
def test_idempotency_scope(self):
key = uuid.uuid4().hex
one = self.client.message(self.alice, self.chat, 'same', key=key)['json']
two = self.client.message(self.bob, self.chat, 'same', key=key)['json']
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'scope', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
three = self.client.message(self.alice, other, 'same', key=key)['json']
self.assertEqual(len({one['id'], two['id'], three['id']}), 3)
def test_idempotency_semantic_body(self):
key = uuid.uuid4().hex
one = self.client.message(self.alice, self.chat, 'semantic', key=key)['json']
two = self.client.call('POST', self.path + '/messages', 201, actor=self.alice, body={'attachment_ids': [], 'text': 'semantic'}, headers={'Idempotency-Key': key}, schema='Message')['json']
self.assertEqual(one, two)
def test_idempotency_invalid_keys(self):
for key in (None, '', 'x' * 129, 'space key', 'bad,key', 'slash/key'):
headers = {} if key is None else {'Idempotency-Key': key}
PublicClient().call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': 'valid'}, headers=headers)
for raw in (b'{"text":true}', b'{"text":"ok","extra":1}', b'{"text":"ok","attachment_ids":false}'):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
def test_idempotency_conflicting_race(self):
key = uuid.uuid4().hex
def send(i):
return Client().call('POST', self.path + '/messages', [201, 409], actor=self.alice, body={'text': str(i % 2)}, headers={'Idempotency-Key': key}, schema=None)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
replies = list(executor.map(send, range(32)))
self.assertEqual(sum(v['status'] == 201 for v in replies), 16)
self.assertEqual(sum(v['status'] == 409 for v in replies), 16)
page = self.client.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
self.assertEqual(len(page['items']), 1)
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
def test_unicode_password_basic_and_logout(self):
import base64
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
self.client.call('POST', '/api/v1/users', 201, body=registration)
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
headers = {'Authorization': 'Basic ' + encoded}
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
actor = {'id': session['user']['id'], 'token': session['token']}
self.client.call('GET', '/api/v1/users/me', actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
if __name__ == '__main__':
unittest.main(verbosity=2)