192 lines
7.5 KiB
Python
192 lines
7.5 KiB
Python
import base64
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def call(method, path, body=None, token=None, raw=None, headers=None, timeout=10):
|
|
all_headers = {}
|
|
if token:
|
|
all_headers['Authorization'] = 'Bearer ' + token
|
|
if body is not None:
|
|
raw = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
if raw is not None:
|
|
all_headers['Content-Type'] = 'application/json'
|
|
all_headers.update(headers or {})
|
|
if method == 'POST' and path.split('?')[0].endswith('/messages') and 'Idempotency-Key' not in all_headers:
|
|
all_headers['Idempotency-Key'] = uuid.uuid4().hex
|
|
all_headers = {name: value for name, value in all_headers.items() if value is not None}
|
|
request = urllib.request.Request(BASE_URL + path, data=raw, headers=all_headers, method=method)
|
|
try:
|
|
response = urllib.request.urlopen(request, timeout=timeout)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
data = response.read()
|
|
is_json = response.headers.get_content_type() == 'application/json'
|
|
return response.status, response.headers, json.loads(data) if data and is_json else None
|
|
|
|
|
|
def basic(username, password):
|
|
return {'Authorization': 'Basic ' + base64.b64encode((username + ':' + password).encode('utf-8')).decode()}
|
|
|
|
|
|
def register(label='user', password=None):
|
|
username = (label + '_' + uuid.uuid4().hex[:12])[:32]
|
|
password = password or 'Pw-' + uuid.uuid4().hex
|
|
status, _, user = call('POST', '/api/v1/users', {'username': username, 'display_name': label, 'password': password})
|
|
assert status == 201, status
|
|
return user, password
|
|
|
|
|
|
def login(username, password):
|
|
status, _, session = call('POST', '/api/v1/auth/sessions', headers=basic(username, password))
|
|
assert status == 201, status
|
|
return session
|
|
|
|
|
|
def new_user(label='user'):
|
|
user, password = register(label)
|
|
session = login(user['username'], password)
|
|
return dict(user, password=password, token=session['token'])
|
|
|
|
|
|
def new_chat(owner, *others, title='Тестовый чат'):
|
|
members = [owner['id']] + [u['id'] for u in others]
|
|
status, _, chat = call('POST', '/api/v1/chats', {'title': title, 'member_ids': members}, owner['token'])
|
|
assert status == 201, status
|
|
return chat
|
|
|
|
|
|
def read_all_messages(chat_id, token, limit):
|
|
items, cursor, pages = [], None, 0
|
|
while True:
|
|
query = '?limit=%d' % limit + ('&cursor=' + urllib.parse.quote(cursor, safe='') if cursor else '')
|
|
status, _, page = call('GET', '/api/v1/chats/%s/messages%s' % (chat_id, query), token=token)
|
|
assert status == 200, status
|
|
items += page['items']
|
|
pages += 1
|
|
cursor = page['next_cursor']
|
|
if cursor is None:
|
|
return items, pages
|
|
|
|
|
|
def compose(*args, env=None, check=True):
|
|
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT, capture_output=True, text=True,
|
|
encoding='utf-8', env=env)
|
|
if check and result.returncode != 0:
|
|
raise RuntimeError('docker compose %s failed: %s' % (' '.join(args), result.stderr.strip()))
|
|
return result.stdout.strip()
|
|
|
|
|
|
def sql(query, db='messenger', service='postgres'):
|
|
return compose('exec', '-T', service, 'psql', '-U', 'messenger', '-d', db, '-X', '-tA', '-v', 'ON_ERROR_STOP=1',
|
|
'-c', query)
|
|
|
|
|
|
def wait_ready(seconds=90):
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if call('GET', '/health/ready', timeout=2)[0] == 200:
|
|
return time.monotonic()
|
|
except OSError:
|
|
pass
|
|
time.sleep(0.3)
|
|
raise AssertionError('API is not ready after %ds' % seconds)
|
|
|
|
|
|
def api_containers():
|
|
return compose('ps', '-q', 'api').split()
|
|
|
|
|
|
def wait_in_rotation(container, seconds=60):
|
|
deadline = time.monotonic() + seconds
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if call('GET', '/health/ready', timeout=2)[1].get('X-Instance-Id') == container[:12]:
|
|
return time.monotonic()
|
|
except OSError:
|
|
pass
|
|
time.sleep(0.1)
|
|
raise AssertionError('container %s did not enter LB rotation' % container[:12])
|
|
|
|
|
|
class Load:
|
|
"""Отправляет сообщения в несколько потоков; неудачный POST повторяет с тем же Idempotency-Key."""
|
|
|
|
def __init__(self, token, chat_id, workers=4):
|
|
self.token, self.path, self.workers = token, '/api/v1/chats/%s/messages' % chat_id, workers
|
|
self.records, self.confirmed, self.uncertain = [], [], 0
|
|
self.stopped = threading.Event()
|
|
self.threads = []
|
|
|
|
def start(self):
|
|
self.threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(self.workers)]
|
|
for thread in self.threads:
|
|
thread.start()
|
|
return self
|
|
|
|
def stop(self):
|
|
self.stopped.set()
|
|
for thread in self.threads:
|
|
thread.join()
|
|
|
|
def worker(self, n):
|
|
sent = 0
|
|
while not self.stopped.is_set():
|
|
key, text = uuid.uuid4().hex, 'load %d-%d %s' % (n, sent, uuid.uuid4().hex[:6])
|
|
sent += 1
|
|
while True:
|
|
started = time.monotonic()
|
|
try:
|
|
status, headers, body = call('POST', self.path, {'text': text}, self.token,
|
|
headers={'Idempotency-Key': key}, timeout=5)
|
|
instance = headers.get('X-Instance-Id')
|
|
except OSError as error:
|
|
status, instance, body = type(error).__name__, None, None
|
|
self.records.append((started, time.monotonic(), status, instance))
|
|
if status == 201:
|
|
self.confirmed.append(body)
|
|
break
|
|
if self.stopped.is_set():
|
|
self.uncertain += 1
|
|
break
|
|
time.sleep(0.05)
|
|
|
|
def window(self, start, end):
|
|
rows = [r for r in self.records if start <= r[0] < end]
|
|
ok = [r for r in rows if r[2] == 201]
|
|
latencies = sorted((r[1] - r[0]) * 1000 for r in ok)
|
|
p = lambda q: round(latencies[min(len(latencies) - 1, int(len(latencies) * q))], 1) if latencies else None
|
|
return {'seconds': round(end - start, 2), 'ok': len(ok), 'errors': len(rows) - len(ok),
|
|
'rps': round(len(ok) / (end - start), 1) if end > start else 0,
|
|
'p50_ms': p(0.5), 'p95_ms': p(0.95), 'p99_ms': p(0.99),
|
|
'error_kinds': sorted({str(r[2]) for r in rows if r[2] != 201})}
|
|
|
|
def verify(self, token):
|
|
stored, cursor = [], None
|
|
while True:
|
|
query = '?limit=100' + ('&cursor=' + urllib.parse.quote(cursor, safe='') if cursor else '')
|
|
page = call('GET', self.path + query, token=token)[2]
|
|
stored += page['items']
|
|
cursor = page['next_cursor']
|
|
if cursor is None:
|
|
break
|
|
ids = [m['id'] for m in stored]
|
|
texts = [m['text'] for m in stored]
|
|
return {'confirmed': len(self.confirmed), 'stored': len(stored),
|
|
'lost': len({m['id'] for m in self.confirmed} - set(ids)),
|
|
'duplicate_ids': len(ids) - len(set(ids)), 'duplicate_texts': len(texts) - len(set(texts)),
|
|
'uncertain_at_stop': self.uncertain}
|