Files
2026-10-23 18:10:07 +03:00

81 lines
3.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Идемпотентность сообщений + балансировка через LB."""
import json
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import (
BASE_URL, Client, Failure, check, observe_instances, print_pass,
)
def main():
c = Client(BASE_URL)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
# 1) Через LB видно ≥2 реплики.
seen = observe_instances(c, alice, n=40)
check(len(seen) >= 2, 'менее двух X-Instance-Id через LB: %r' % seen)
print(' instances:', seen)
# 2) Replay с тем же ключом и телом → тот же Message.
key = 'idem-' + uuid.uuid4().hex
body = {'text': 'idem-' + uuid.uuid4().hex}
r1 = c.call('POST', path, 201, actor=alice, body=body,
headers={'Idempotency-Key': key}, schema='Message')
r2 = c.call('POST', path, 201, actor=alice, body=body,
headers={'Idempotency-Key': key}, schema='Message')
check(r1['json'] == r2['json'], 'replay дал другой ответ')
# 3) Тот же ключ, другое тело → 409.
c.call('POST', path, 409, actor=alice, body={'text': 'other'},
headers={'Idempotency-Key': key})
# 4) Без ключа → 400.
c.call('POST', path, 400, actor=alice, body={'text': 'no key'})
# 5) Невалидный ключ → 400.
c.call('POST', path, 400, actor=alice, body={'text': 'bad key'},
headers={'Idempotency-Key': 'has space'})
# 6) Разные пользователи с одним ключом независимы.
key_shared = 'shared-' + uuid.uuid4().hex
ra = c.message(alice, chat, 'alice-' + uuid.uuid4().hex, key=key_shared)
rb = c.message(bob, chat, 'bob-' + uuid.uuid4().hex, key=key_shared)
check(ra['json']['id'] != rb['json']['id'],
'одинаковый ключ у разных пользователей склеил сообщения')
# 7) Конкурентный повтор: 20 параллельных POST с одним ключом.
key_c = 'conc-' + uuid.uuid4().hex
text_c = 'conc-' + uuid.uuid4().hex
def send(_):
local = Client(BASE_URL, timeout=15)
r = local.call('POST', path, (201, 503), actor=alice,
body={'text': text_c},
headers={'Idempotency-Key': key_c})
payload = r['json']
if payload is None and r['status'] == 201:
try:
payload = json.loads(r['bytes'])
except ValueError:
pass
return {'status': r['status'], 'json': payload}
with ThreadPoolExecutor(max_workers=20) as pool:
results = list(pool.map(send, range(20)))
ok = [r for r in results if r['status'] == 201 and r['json']]
check(len(ok) >= 15, 'слишком много не-201 при конкурентном повторе: %d/20' % len(ok))
ids = {r['json']['id'] for r in ok}
check(len(ids) == 1, 'конкурентный повтор создал %d разных id: %r' % (len(ids), ids))
print(' concurrent: %d×201, один id' % len(ok))
print_pass('idempotency')
if __name__ == '__main__':
try:
main()
except Failure as e:
print('FAIL:', e)
raise SystemExit(1)