"""Run inside API network: same session and simultaneous requests at distinct processes.""" from concurrent.futures import ThreadPoolExecutor import json from pathlib import Path import socket import sys import threading import uuid sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, check def main(): clients = [Client('http://' + ip + ':8080') for ip in sorted(set(socket.gethostbyname_ex('api')[2]))] check(len(clients) == 2, 'Expected two API addresses in Docker DNS') c = clients[0] alice, bob, eve, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/messages' key = uuid.uuid4().hex barrier = threading.Barrier(16) def send(n): barrier.wait(timeout=10) return clients[n % 2].call('POST', path, 201, actor=alice, body={'attachment_ids': [], 'text': 'Параллельный повтор'} if n % 2 else {'text': 'Параллельный повтор'}, headers={'Idempotency-Key': key}, schema='Message') with ThreadPoolExecutor(max_workers=16) as pool: responses = list(pool.map(send, range(16))) messages = [x['json'] for x in responses] instances = sorted({x['headers']['X-Instance-Id'] for x in responses}) check(len(instances) == 2, 'Requests did not reach distinct API processes') check(all(x == messages[0] for x in messages), 'Concurrent responses differ') history = clients[1].call('GET', path, actor=bob, schema='MessagePage')['json']['items'] check(history == [messages[0]], 'Concurrent requests created duplicates') clients[1].call('POST', path, 409, actor=alice, body={'text': 'Другой body'}, headers={'Idempotency-Key': key}) # Scope is user + chat; an independent user and another chat may reuse the key. other = clients[1].message(bob, chat, 'Другой пользователь', key=key)['json'] chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json'] third = clients[1].message(alice, chat2, 'Другой чат', key=key)['json'] check(len({messages[0]['id'], other['id'], third['id']}) == 3, 'Incorrect idempotency scope') for invalid in ('', 'contains space', 'x' * 129): c.call('POST', path, 400, actor=alice, body={'text': 'Invalid key'}, headers={'Idempotency-Key': invalid}) c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) clients[1].call('POST', path, 401, actor=alice, body={'text': 'Параллельный повтор'}, headers={'Idempotency-Key': key}) print(json.dumps(dict(result='PASS', parallel_requests=16, api_instances=instances, unique_messages=1, scope_conflict_logout='PASS'), ensure_ascii=False)) if __name__ == '__main__': main()