ЛР 3: балансировка, общая идемпотентность и исследование масштабирования
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Internal diagnostic only: invoke while PostgreSQL is deliberately stopped.
|
||||
|
||||
Business acceptance and all load/failure tests use the LB; no host API port is exposed.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
|
||||
c = Client('http://api:8080', timeout=8)
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
c.call('GET', '/health/ready', 503)
|
||||
print('PASS: DB unavailable -> process live=200, readiness=503 with API error envelope.')
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional black-box checks; public tests/contracts remain untouched."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
key = uuid.uuid4().hex
|
||||
barrier = threading.Barrier(16)
|
||||
|
||||
def duplicate(index):
|
||||
local = Client()
|
||||
barrier.wait()
|
||||
body = {'text': 'Конкурентный повтор 👋'}
|
||||
if index % 2:
|
||||
body = {'attachment_ids': [], **body}
|
||||
return local.call('POST', path + '/messages', 201, actor=alice, body=body,
|
||||
headers={'Idempotency-Key': key}, schema='Message')
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(duplicate, range(16)))
|
||||
instances = {r['headers']['X-Instance-Id'] for r in responses}
|
||||
check(len(instances) >= 2, 'concurrent requests must reach >=2 actual replicas')
|
||||
check(all(r['json'] == responses[0]['json'] for r in responses), 'concurrent replay differs')
|
||||
page = c.call('GET', path + '/messages', actor=alice, schema='MessagePage')['json']
|
||||
check(len(page['items']) == 1, 'concurrent key created duplicate rows')
|
||||
c.call('POST', path + '/messages', 409, actor=alice, body={'text': 'different'},
|
||||
headers={'Idempotency-Key': key})
|
||||
# Scope includes both user and chat. Same key is independent in each.
|
||||
c.message(bob, chat, 'same key, another user', key=key)
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'another', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
c.message(alice, other, 'same key, another chat', key=key)
|
||||
c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'hidden'},
|
||||
headers={'Idempotency-Key': key})
|
||||
for bad in ({'text': 'ok', 'sender_id': eve['id']}, {'text': ' '}, {'text': 123},
|
||||
{'text': 'x' * 4001}, {'text': 'ok', 'attachment_ids': None},
|
||||
{'text': 'ok', 'attachment_ids': [str(uuid.uuid4())]}, {'text': '\x00'}):
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=bad,
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
for bad_key in ('', 'white space', 'a' * 129, 'slash/key'):
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body={'text': 'ok'},
|
||||
headers={'Idempotency-Key': bad_key})
|
||||
for raw in (b'{', b'[]', b'{"text":"a","text":"b"}', b'{"text":NaN}', b'\xff'):
|
||||
c.call('POST', path + '/messages', 400, actor=alice, raw=raw,
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex, 'Content-Type': 'application/json'})
|
||||
c.call('POST', path + '/messages', 415, actor=alice, raw=b'x',
|
||||
headers={'Idempotency-Key': key, 'Content-Type': 'text/plain'})
|
||||
c.call('POST', path + '/messages', 413, actor=alice, raw=b' ' * 65537,
|
||||
headers={'Idempotency-Key': key, 'Content-Type': 'application/json'})
|
||||
c.call('GET', '/api/v1/chats/not-a-uuid', 401)
|
||||
c.call('GET', '/api/v1/chats/not-a-uuid', 400, actor=alice)
|
||||
for members in ([alice['id'], alice['id']], [bob['id']], [alice['id'], str(uuid.uuid4())], [], 'bad'):
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'bad', 'member_ids': members})
|
||||
for query in ('limit=true', 'limit=-1', 'limit=101', 'limit=1&limit=2', 'cursor=garbage'):
|
||||
c.call('GET', path + '/messages?' + query, 400, actor=alice)
|
||||
cursor = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']['next_cursor']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=alice)
|
||||
c.call('GET', path + '/messages?cursor=' + quote(cursor + 'x'), 400, actor=alice)
|
||||
# Unicode password at the maximum length; colons are part of the password.
|
||||
username = 'u_' + uuid.uuid4().hex[:20]
|
||||
password = '🔑:' * 64
|
||||
user = c.call('POST', '/api/v1/users', 201,
|
||||
body={'username': username, 'display_name': '👋' * 100, 'password': password}, schema='User')['json']
|
||||
auth = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
session = c.call('POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + auth}, schema='Session')['json']
|
||||
unicode_actor = {'id': user['id'], 'token': session['token']}
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=unicode_actor)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=unicode_actor)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('POST', path + '/messages', 401, actor=alice, body={'text': 'Конкурентный повтор 👋'},
|
||||
headers={'Idempotency-Key': key})
|
||||
print(json.dumps({'result': 'PASS', 'concurrent_requests': 16,
|
||||
'observed_instances': sorted(instances), 'messages_for_shared_key': 1,
|
||||
'checks': 'scope, access, revocation, strict JSON, limits, signed cursors, Unicode KDF'},
|
||||
ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read AND write during a selected real API process failure, through LB only."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
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, Failure, check
|
||||
from resilience import history
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--target-hostname', required=True)
|
||||
args = parser.parse_args()
|
||||
c = Client(timeout=2)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
original = c.message(alice, chat, 'confirmed before selected failure')['json']
|
||||
target = None
|
||||
for _ in range(100):
|
||||
alias = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
|
||||
if alias.startswith(args.target_hostname + '-'):
|
||||
target = alias
|
||||
break
|
||||
check(target is not None, 'Selected target was not observed through LB')
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=target)
|
||||
start = time.monotonic()
|
||||
proc = subprocess.Popen(['scripts/stop-one.sh'], env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
records = {'read': [], 'write': []}
|
||||
errors = {'read': 0, 'write': 0}
|
||||
recover = {'read': None, 'write': None}
|
||||
confirmed, instances = [], []
|
||||
key = uuid.uuid4().hex
|
||||
try:
|
||||
while time.monotonic() - start < 15:
|
||||
check(proc.poll() in (None, 0), 'stop-one hook failed')
|
||||
for operation in ('read', 'write'):
|
||||
before = time.monotonic()
|
||||
try:
|
||||
if operation == 'read':
|
||||
r = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
|
||||
actor=bob, schema='MessagePage')
|
||||
check(original in r['json']['items'], 'Confirmed message unavailable during failure')
|
||||
else:
|
||||
r = c.message(alice, chat, 'during-' + key, key=key)
|
||||
confirmed.append(r['json'])
|
||||
key = uuid.uuid4().hex
|
||||
records[operation].append(1000 * (time.monotonic() - before))
|
||||
if proc.poll() == 0:
|
||||
if recover[operation] is None:
|
||||
recover[operation] = time.monotonic() - start
|
||||
instances.append(r['headers']['X-Instance-Id'])
|
||||
except Failure:
|
||||
errors[operation] += 1
|
||||
time.sleep(.15)
|
||||
check(proc.poll() == 0, 'Hook did not complete')
|
||||
check(all(v is not None and v <= 10 for v in recover.values()), 'Read/write recovery >10s')
|
||||
check(target not in instances[-10:], 'Stopped target still serving')
|
||||
stored = history(c, bob, chat)
|
||||
check(all(m in stored for m in [original, *confirmed]), 'Confirmed data lost')
|
||||
texts = [m['text'] for m in stored]
|
||||
check(len(texts) == len(set(texts)), 'Uncertain retries duplicated messages')
|
||||
elapsed = time.monotonic() - start
|
||||
metrics = {}
|
||||
for op, latencies in records.items():
|
||||
ordered = sorted(latencies)
|
||||
metrics[op] = {'successes': len(ordered), 'errors': errors[op],
|
||||
'successful_rps': round(len(ordered) / elapsed, 3),
|
||||
'first_recovery_seconds': round(recover[op], 3),
|
||||
'successful_latency_ms': {label: round(ordered[max(0, math.ceil(p * len(ordered)) - 1)], 3)
|
||||
for label, p in [('p50', .5), ('p95', .95), ('p99', .99)]}}
|
||||
print(json.dumps({'result': 'PASS', 'target_alias': target, 'duration_seconds': round(elapsed, 3),
|
||||
'metrics': metrics, 'preserved_confirmations': len(confirmed) + 1,
|
||||
'duplicate_texts': 0}, indent=2))
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run only against a separate 2-second SESSION_TTL_SECONDS configuration."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
|
||||
c = Client()
|
||||
user = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=user, schema='User')
|
||||
time.sleep(2.2)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=user)
|
||||
print('PASS: session works before expiry and returns 401 after configured 2-second TTL.')
|
||||
Reference in New Issue
Block a user