Реализовать общую идемпотентность отправки сообщения

Ключ Idempotency-Key с TTL (минимум 86400 c), таблица message_requests и
advisory-лок на (пользователь, чат, ключ): конкурентные повторные запросы
возвращают одно и то же сообщение, конфликт по body -> 409. Добавлена
миграция 002 и сценарий проверки scripts/check_idempotency.py.
This commit is contained in:
2026-11-16 22:18:42 +00:00
parent 9698fae3be
commit 0e20efe781
7 changed files with 91 additions and 8 deletions
+44
View File
@@ -0,0 +1,44 @@
"""Concurrent HTTP contract check through LB, using one session on two replicas."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
key = uuid4().hex
path = '/api/v1/chats/' + chat['id'] + '/messages'
def send(_):
return Client(args.base_url).message(alice, chat, 'Одно сообщение 👋', key=key)
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(send, range(24)))
first = responses[0]['json']
check(all(r['json'] == first and r['status'] == 201 for r in responses), 'Concurrent replay differs')
instances = {r['headers']['X-Instance-Id'] for r in responses}
check(len(instances) >= 2, 'Concurrent requests did not reach both replicas')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
check(page['items'] == [first], 'Concurrent repeat created duplicate messages')
c.call('POST', path, 409, actor=alice, body={'text': 'Different'}, headers={'Idempotency-Key': key})
c.call('POST', path, 400, actor=alice, body={'text': 'Missing key'})
c.call('POST', path, 400, actor=alice, body={'text': 'Bad key'}, headers={'Idempotency-Key': 'bad key'})
c.call('POST', path, 404, actor=eve, body={'text': 'Одно сообщение 👋'}, headers={'Idempotency-Key': key})
other = c.message(bob, chat, 'Same key, different user', key=key)['json']
check(other['id'] != first['id'], 'User scope is not independent')
second_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Second', 'member_ids': [alice['id']]}, schema='Chat')['json']
check(c.message(alice, second_chat, 'Other chat', key=key)['json']['id'] != first['id'], 'Chat scope is not independent')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('POST', path, 401, actor=alice, body={'text': 'Одно сообщение 👋'}, headers={'Idempotency-Key': key})
print('PASS: 24 concurrent requests / 8 clients / %d replicas -> one message; conflict, scopes, access and logout verified.' % len(instances))
if __name__ == '__main__':
main()