From a18e7b320b65248aa22171b722c6544ed8ac162d Mon Sep 17 00:00:00 2001 From: Artyom Date: Wed, 28 Oct 2026 11:33:11 +0300 Subject: [PATCH] Add the idempotency key table as an additive migration Migration 0002 stores one row per accepted message key: the chat, the sender, the key, the SHA-256 fingerprint of the request and the message. The primary key (chat_id, user_id, key) is the key scope of the contract, the composite foreign key keeps the row inside the messaging tables, as messages already do, and CHECK constraints repeat the key format and the fingerprint length. Nothing existing changes, so the lab 2 code keeps running on the new schema. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../add-lab3-load-balanced-replicas/tasks.md | 4 ++-- .../migrations/0002_idempotency_keys.sql | 10 ++++++++++ student-tests/api/test_migrations.py | 18 ++++++++++++++++-- 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 src/messenger/migrations/0002_idempotency_keys.sql diff --git a/openspec/changes/add-lab3-load-balanced-replicas/tasks.md b/openspec/changes/add-lab3-load-balanced-replicas/tasks.md index 1469c856..6f5be321 100644 --- a/openspec/changes/add-lab3-load-balanced-replicas/tasks.md +++ b/openspec/changes/add-lab3-load-balanced-replicas/tasks.md @@ -11,8 +11,8 @@ ## 3. Схема -- [ ] 3.1 Миграция `0002_idempotency_keys.sql`: PK `(chat_id, user_id, key)`, FK на `chat_members` и `messages`, `CHECK` формата ключа и длины отпечатка -- [ ] 3.2 Проверка группы: тест миграций — версии `0001`, `0002`, повтор без изменений, ключ без участника отклоняется FK +- [x] 3.1 Миграция `0002_idempotency_keys.sql`: PK `(chat_id, user_id, key)`, FK на `chat_members` и `messages`, `CHECK` формата ключа и длины отпечатка +- [x] 3.2 Проверка группы: тест миграций — версии `0001`, `0002`, повтор без изменений, ключ без участника отклоняется FK ## 4. Идемпотентная отправка (зона `messaging`) diff --git a/src/messenger/migrations/0002_idempotency_keys.sql b/src/messenger/migrations/0002_idempotency_keys.sql new file mode 100644 index 00000000..a556f0fd --- /dev/null +++ b/src/messenger/migrations/0002_idempotency_keys.sql @@ -0,0 +1,10 @@ +CREATE TABLE idempotency_keys ( + chat_id uuid NOT NULL, + user_id uuid NOT NULL, + key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32), + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL, + PRIMARY KEY (chat_id, user_id, key), + FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id) +); diff --git a/student-tests/api/test_migrations.py b/student-tests/api/test_migrations.py index 73d2a405..12d9a351 100644 --- a/student-tests/api/test_migrations.py +++ b/student-tests/api/test_migrations.py @@ -7,7 +7,7 @@ from messenger.migrate import MigrationChangedError, migrate, migrations COUNTS = """ SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions), (SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members), - (SELECT count(*) FROM messages) + (SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys) """ @@ -22,7 +22,7 @@ async def counts() -> list[int]: async def test_migrations_are_ordered_and_versioned() -> None: versions = [version for version, _ in migrations()] assert versions == sorted(versions) - assert versions[0] == "0001_init" + assert versions[:2] == ["0001_init", "0002_idempotency_keys"] applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations") assert applied == versions @@ -61,3 +61,17 @@ async def test_sender_must_be_member_even_bypassing_api() -> None: ) finally: await connection.close() + + +async def test_key_needs_a_member_and_a_message() -> None: + connection = await asyncpg.connect(DATABASE["url"]) + try: + with pytest.raises(asyncpg.ForeignKeyViolationError): + await connection.execute( + "INSERT INTO idempotency_keys " + "(chat_id, user_id, key, fingerprint, message_id, created_at) " + "VALUES (gen_random_uuid(), gen_random_uuid(), 'k-1', " + "sha256('x'), gen_random_uuid(), now())" + ) + finally: + await connection.close()