#!/usr/bin/env python3 """Cross-replica idempotency, key isolation, sessions and pagination.""" from concurrent.futures import ThreadPoolExecutor import json from pathlib import Path 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, arguments, check, run def main(): args = arguments(__doc__) c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() path = '/api/v1/chats/%s/messages' % chat['id'] observed = {c.call('GET', '/api/v1/users/me', actor=alice)['headers']['X-Instance-Id'] for _ in range(20)} check(len(observed) >= 2, 'one session must work through at least two replicas') key = uuid.uuid4().hex barrier = threading.Barrier(12) def worker(_): local = Client(args.base_url, args.ca_file) barrier.wait() return local.message(alice, chat, 'Один ключ — одно сообщение 👋', key=key) with ThreadPoolExecutor(max_workers=12) as pool: replies = list(pool.map(worker, range(12))) instances = {r['headers']['X-Instance-Id'] for r in replies} check(len(instances) >= 2, 'parallel key replay did not reach both replicas') first = replies[0]['json'] check(all(r['json'] == first and r['status'] == 201 for r in replies), 'replays differ') page = c.call('GET', path, actor=alice, schema='MessagePage')['json'] check(page['items'] == [first], 'parallel replay stored duplicate messages') c.call('POST', path, 409, actor=alice, body={'text': 'другое'}, headers={'Idempotency-Key': key}) for bad in (None, '', 'bad key', 'x' * 129, 'bad/key'): c.call('POST', path, 400, actor=alice, body={'text': 'invalid'}, headers={} if bad is None else {'Idempotency-Key': bad}) c.call('POST', path, 404, actor=eve, body={'text': first['text']}, headers={'Idempotency-Key': key}) other_user = c.message(bob, chat, first['text'], key=key)['json'] check(other_user['id'] != first['id'], 'different user key was aliased') second_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json'] other_chat = c.message(alice, second_chat, first['text'], key=key)['json'] check(other_chat['id'] != first['id'], 'different chat key was aliased') for index in range(5): c.message(alice, chat, 'page-%d' % index) result, cursor, page_instances = [], None, set() while True: url = path + '?limit=1' + (('&cursor=' + quote(cursor, safe='')) if cursor else '') reply = c.call('GET', url, actor=alice, schema='MessagePage') page_instances.add(reply['headers']['X-Instance-Id']) result.extend(reply['json']['items']) cursor = reply['json']['next_cursor'] if cursor is None: break check(len(result) == len({m['id'] for m in result}) == 7, 'pagination lost/duplicated messages') check(len(page_instances) >= 2, 'cursor did not cross replicas') # Revocation is observed on every API, even with an existing Redis entry. c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) for _ in range(8): c.call('GET', '/api/v1/users/me', 401, actor=alice) c.call('POST', path, 401, actor=alice, body={'text': first['text']}, headers={'Idempotency-Key': key}) print(json.dumps({'parallel_requests': 12, 'parallel_replicas': sorted(instances), 'unique_parallel_messages': 1, 'pagination_messages': 7, 'pagination_replicas': sorted(page_instances)}, ensure_ascii=False)) print('PASS: cross-replica idempotency, isolation, pagination and logout') if __name__ == '__main__': run(main)