forked from mtusi2026/mtusi2026lab3
101 lines
5.5 KiB
Python
101 lines
5.5 KiB
Python
"""Black-box cross-replica idempotency tests. All HTTP goes through the LB."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
from urllib.parse import urlsplit
|
|
import uuid
|
|
from client import Client, arguments, check, run
|
|
|
|
|
|
def configure(p):
|
|
p.add_argument('--restart-script', help='Optional full-stack restart, preserving volumes')
|
|
|
|
|
|
def main():
|
|
args = arguments('Shared idempotency and previous-lab behavior', configure)
|
|
c = Client(args.base_url, args.ca_file, timeout=8)
|
|
alice, bob, outsider, chat = c.bootstrap()
|
|
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
|
key = uuid.uuid4().hex
|
|
barrier = threading.Barrier(16)
|
|
|
|
def send(i):
|
|
local = Client(args.base_url, args.ca_file, timeout=8)
|
|
barrier.wait(timeout=10)
|
|
# Reordered keys, explicit [] and omission must be equivalent.
|
|
body = {'attachment_ids': [], 'text': 'Одна параллельная запись'} if i % 2 else {'text': 'Одна параллельная запись'}
|
|
return local.call('POST', path, 201, actor=alice, body=body,
|
|
headers={'Idempotency-Key': key}, schema='Message')
|
|
|
|
with ThreadPoolExecutor(max_workers=16) as pool:
|
|
replies = list(pool.map(send, range(16)))
|
|
original = replies[0]['json']
|
|
check(all(r['json'] == original for r in replies), 'concurrent replay changed the Message')
|
|
instances = sorted({r['headers']['X-Instance-Id'] for r in replies})
|
|
check(len(instances) >= 2, 'race did not reach two API processes')
|
|
page = c.call('GET', path, actor=alice, schema='MessagePage')['json']
|
|
check(page['items'] == [original], 'concurrent repeat inserted duplicate messages')
|
|
print(json.dumps({'parallel_requests': 16, 'instances': instances, 'messages_created': 1}))
|
|
|
|
c.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
|
|
for invalid in ('', 'with space', 'a' * 129, 'with/slash', 'bad,key'):
|
|
c.call('POST', path, 400, actor=alice, body={'text': 'bad key'}, headers={'Idempotency-Key': invalid})
|
|
c.call('POST', path, 400, actor=alice, body={'text': 'missing'})
|
|
c.call('POST', path, 404, actor=outsider, body={'text': original['text']}, headers={'Idempotency-Key': key})
|
|
|
|
# The same key belongs independently to another user or chat.
|
|
other = c.message(bob, chat, 'Другой отправитель', key=key)['json']
|
|
check(other['id'] != original['id'], 'key incorrectly shared between users')
|
|
second_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
|
|
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]})['json']
|
|
separate = c.message(alice, second_chat, original['text'], key=key)['json']
|
|
check(separate['id'] != original['id'], 'key incorrectly shared between chats')
|
|
|
|
# Send a complete POST and close the connection without reading its outcome.
|
|
# Retry the exact key/body through the LB, regardless of which API committed.
|
|
uncertain_key = uuid.uuid4().hex
|
|
body = json.dumps({'text': 'Неизвестный клиенту результат'}, ensure_ascii=False).encode()
|
|
url = urlsplit(args.base_url)
|
|
check(url.scheme == 'http', 'local lost-response scenario expects http')
|
|
raw = (f'POST {path} HTTP/1.1\r\nHost: {url.netloc}\r\n'
|
|
f'Authorization: Bearer {alice["token"]}\r\nIdempotency-Key: {uncertain_key}\r\n'
|
|
f'Content-Type: application/json\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n').encode() + body
|
|
with socket.create_connection((url.hostname, url.port or 80), timeout=5) as conn:
|
|
conn.sendall(raw)
|
|
conn.shutdown(socket.SHUT_WR)
|
|
replayed = c.message(alice, chat, 'Неизвестный клиенту результат', key=uncertain_key)['json']
|
|
repeated = c.message(alice, chat, 'Неизвестный клиенту результат', key=uncertain_key)['json']
|
|
check(replayed == repeated, 'uncertain write cannot be retried')
|
|
messages = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
|
|
check(sum(m['text'] == replayed['text'] for m in messages) == 1, 'uncertain result created a duplicate')
|
|
|
|
if args.restart_script:
|
|
script = Path(args.restart_script).resolve()
|
|
subprocess.run([str(script)], check=True, timeout=90, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
deadline = time.monotonic() + 60
|
|
while True:
|
|
try:
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
break
|
|
except AssertionError:
|
|
check(time.monotonic() < deadline, 'LB did not recover')
|
|
time.sleep(0.25)
|
|
recovered = [c.message(alice, chat, original['text'], key=key) for _ in range(12)]
|
|
check(all(r['json'] == original for r in recovered), 'restart lost idempotency record')
|
|
check(len({r['headers']['X-Instance-Id'] for r in recovered}) >= 2, 'both APIs did not recover')
|
|
print('PASS: same session and exact Message replay after full-stack restart')
|
|
|
|
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
|
for _ in range(6):
|
|
c.call('POST', path, 401, actor=alice, body={'text': original['text']}, headers={'Idempotency-Key': key})
|
|
print('PASS: concurrent replay, normalized JSON, key scope, conflict, invalid key, access, uncertain response and logout')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|