Files
mtusi2026lab5/migrations/0002_idempotency_keys.sql
Alexey BodanyukandClaude Opus 5.5 5112be83cc перенос: реализация lab4 без изменений (API, миграции 0001-0004, HAProxy, Valkey, SeaweedFS, тесты)
Скопировано из mtusi2026lab4 (ветка solution/bvt2302-bodanyuk, commit 17c33cd) через
git archive: исходники, миграции, собственные тесты, Dockerfile, compose, конфигурации
infra/, скрипты и bench/. README, COURSE, contracts/, tests/ и отчёт lab4 не копировались.
Makefile и .env.example — версии lab4 (skeleton-часть совпадает с lab5, строки broker
добавляются в следующих коммитах).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 15:19:00 +03:00

26 lines
1.6 KiB
SQL

-- 0002 (lab 3): shared idempotency of POST /chats/{chat_id}/messages.
-- Additive only (new table), so the lab 2 API keeps working while this runs: it is safe
-- to apply before a rolling update of the API replicas (see REPORT.md, "Миграции").
--
-- Scope of a key (contracts/README.md): current user + HTTP method + chat path + key.
-- The method (POST) and the path template are fixed for this table, so the scope
-- is (user_id, chat_id, key). The key row, the message and the result are written in
-- ONE transaction (repo.post_message): there is no "pending" state that a crash could
-- leave behind, and the stored result is the message row itself.
CREATE TABLE idempotency_keys (
user_id uuid NOT NULL REFERENCES users (id),
chat_id uuid NOT NULL REFERENCES chats (id),
key text NOT NULL,
request_hash bytea NOT NULL, -- SHA-256 of the canonical JSON body
-- Inserted before the message in the same transaction, hence checked at COMMIT.
message_id uuid NOT NULL REFERENCES messages (id) DEFERRABLE INITIALLY DEFERRED,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, chat_id, key),
CONSTRAINT idempotency_keys_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
CONSTRAINT idempotency_keys_hash_len CHECK (octet_length(request_hash) = 32),
CONSTRAINT idempotency_keys_message_key UNIQUE (message_id)
);
-- Housekeeping of keys older than IDEMPOTENCY_TTL_SECONDS (>= 24 h).
CREATE INDEX idempotency_keys_created_at ON idempotency_keys (created_at);