62 lines
2.9 KiB
Python
62 lines
2.9 KiB
Python
import base64, json, os, random, string, threading, time, urllib.error, urllib.request
|
|
|
|
BASE = os.getenv('MOCK_BASE_URL', 'http://lb:8080').rstrip('/')
|
|
RATE = float(os.getenv('MOCK_RATE', '2'))
|
|
WORKERS = int(os.getenv('MOCK_WORKERS', '2'))
|
|
TEXTS = ['Привет из mock-load', 'Проверка pipeline', 'Наблюдаемость работает', 'synthetic message']
|
|
|
|
def request(method, path, body=None, headers=None):
|
|
data = None if body is None else json.dumps(body, ensure_ascii=False).encode()
|
|
h = {'Content-Type': 'application/json'}
|
|
if headers: h.update(headers)
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=8) as r:
|
|
raw = r.read()
|
|
return r.status, json.loads(raw) if raw else {}
|
|
except Exception as e:
|
|
print(f'[mock] {method} {path}: {e}', flush=True)
|
|
return 0, {}
|
|
|
|
def create_actor(prefix):
|
|
suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
|
|
username = f'{prefix}_{suffix}'
|
|
password = 'MockOnly-' + suffix + '-123'
|
|
status, user = request('POST', '/api/v1/users', {'username': username, 'display_name': prefix, 'password': password})
|
|
if status not in (201, 409):
|
|
return None
|
|
token_raw = base64.b64encode(f'{username}:{password}'.encode()).decode()
|
|
status, session = request('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + token_raw})
|
|
token = session.get('token') or session.get('session_token')
|
|
uid = user.get('id')
|
|
return {'id': uid, 'token': token, 'username': username} if token else None
|
|
|
|
def setup():
|
|
a, b = create_actor('mock_a'), create_actor('mock_b')
|
|
if not a or not b: return None
|
|
status, chat = request('POST', '/api/v1/chats', {'title': 'mock activity', 'member_ids': [a['id'], b['id']]}, {'Authorization': 'Bearer ' + a['token']})
|
|
if status not in (201, 409) or not chat.get('id'): return None
|
|
return a, b, chat['id']
|
|
|
|
def worker(index, state):
|
|
a, b, chat = state
|
|
n = 0
|
|
while True:
|
|
actor = a if n % 2 == 0 else b
|
|
auth = {'Authorization': 'Bearer ' + actor['token']}
|
|
key = f'mock-{index}-{n}-{time.time_ns()}'
|
|
request('POST', f'/api/v1/chats/{chat}/messages', {'text': random.choice(TEXTS)}, {**auth, 'Idempotency-Key': key})
|
|
request('GET', f'/api/v1/chats/{chat}/messages?limit=20', headers=auth)
|
|
request('GET', '/health/ready')
|
|
n += 1
|
|
time.sleep(max(0.05, 1.0 / max(RATE, 0.1) / max(WORKERS, 1)))
|
|
|
|
while True:
|
|
state = setup()
|
|
if state:
|
|
print(f'[mock] started base={BASE} workers={WORKERS} rate={RATE}/s', flush=True)
|
|
for i in range(WORKERS): threading.Thread(target=worker, args=(i, state), daemon=True).start()
|
|
while True: time.sleep(3600)
|
|
print('[mock] setup failed; retrying in 5s', flush=True)
|
|
time.sleep(5)
|