feat: перенос 5 лабы логики

This commit is contained in:
Enterxx2
2026-11-10 13:48:00 +03:00
parent 470d9d6f1e
commit 60a71dc839
182 changed files with 14717 additions and 8 deletions
+60
View File
@@ -0,0 +1,60 @@
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT uuidv7(),
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
-- Источник истины для сессий; токен хранится только как SHA-256
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32),
CONSTRAINT sessions_expiry_order CHECK (expires_at > created_at)
);
CREATE INDEX sessions_user_id_idx ON sessions (user_id);
CREATE TABLE chats (
id uuid PRIMARY KEY DEFAULT uuidv7(),
title text NOT NULL,
created_by uuid NOT NULL REFERENCES users (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
-- position сохраняет порядок member_ids из запроса создания
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position smallint NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_key UNIQUE (chat_id, position)
);
-- Список чатов пользователя: WHERE user_id = $1
CREATE INDEX chat_members_user_id_chat_id_idx ON chat_members (user_id, chat_id);
-- created_at назначает приложение под блокировкой чата (строго возрастает в чате)
CREATE TABLE messages (
id uuid PRIMARY KEY DEFAULT uuidv7(),
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000),
-- отправитель обязан быть участником этого чата
CONSTRAINT messages_sender_member_fkey FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE
);
-- Keyset-пагинация истории: WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4 — Index Scan без сортировки и полного прохода
CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id);
+18
View File
@@ -0,0 +1,18 @@
-- Idempotency-Key отправки сообщения (lab3). Область по контракту:
-- пользователь + метод + путь + ключ. Метод и путь фиксированы
-- (POST /api/v1/chats/{chat_id}/messages), поэтому ключ — (sender_id, chat_id, key).
-- Только добавление таблицы (expand): предыдущая версия API работает на новой схеме.
CREATE TABLE message_idempotency_keys (
sender_id uuid NOT NULL,
chat_id uuid NOT NULL,
idempotency_key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL,
PRIMARY KEY (sender_id, chat_id, idempotency_key),
CONSTRAINT message_idempotency_keys_key_format
CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'),
CONSTRAINT message_idempotency_keys_hash_len CHECK (octet_length(request_hash) = 32),
CONSTRAINT message_idempotency_keys_expiry_order CHECK (expires_at > created_at)
);
+69
View File
@@ -0,0 +1,69 @@
-- Вложения (lab4): метаданные в PostgreSQL, байты — в приватном bucket S3.
-- Только расширение схемы (expand): API lab3 продолжает работать на новой схеме.
-- Строка создаётся ДО записи объекта в S3 (status = pending) и удаляется только
-- ПОСЛЕ удаления объекта (через deleting). Поэтому у каждого объекта S3 есть
-- строка, и janitor находит незавершённые загрузки по БД, а не обходом bucket.
CREATE TABLE attachments (
id uuid PRIMARY KEY DEFAULT uuidv7(),
chat_id uuid NOT NULL,
owner_id uuid NOT NULL,
filename text NOT NULL,
content_type text NOT NULL,
size_bytes integer NOT NULL,
sha256 bytea NOT NULL,
-- назначает сервер (originals/<random>); filename в ключ не входит
object_key text NOT NULL,
status text NOT NULL DEFAULT 'pending',
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
-- цель составного FK из message_attachments: вложение того же чата
CONSTRAINT attachments_id_chat_id_key UNIQUE (id, chat_id),
-- загружать может только участник чата; без CASCADE: молча удалённая
-- строка оставила бы объект S3 неучтённым
CONSTRAINT attachments_owner_member_fkey FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members (chat_id, user_id),
CONSTRAINT attachments_status_check
CHECK (status IN ('pending', 'ready', 'deleting')),
CONSTRAINT attachments_content_type_check
CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size_bytes_range CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256_len CHECK (octet_length(sha256) = 32),
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255)
);
-- janitor: WHERE status <> 'ready' AND created_at < now() - grace;
-- готовых строк подавляющее большинство, в индекс они не попадают
CREATE INDEX attachments_unfinished_created_at_idx
ON attachments (created_at)
WHERE status <> 'ready';
-- Пустой текст допустим, если у сообщения есть вложения (проверяет API:
-- условие охватывает две таблицы). Ограничение только ослабляется.
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
ALTER TABLE messages
ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000);
-- цель составного FK из message_attachments: сообщение того же чата
ALTER TABLE messages ADD CONSTRAINT messages_id_chat_id_key UNIQUE (id, chat_id);
-- position сохраняет порядок attachment_ids из запроса
CREATE TABLE message_attachments (
message_id uuid NOT NULL,
chat_id uuid NOT NULL,
attachment_id uuid NOT NULL,
position smallint NOT NULL,
PRIMARY KEY (message_id, position),
CONSTRAINT message_attachments_attachment_key UNIQUE (message_id, attachment_id),
CONSTRAINT message_attachments_message_fkey FOREIGN KEY (message_id, chat_id)
REFERENCES messages (id, chat_id) ON DELETE CASCADE,
-- вложение принадлежит чату сообщения; используемое вложение не удалить
CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id)
REFERENCES attachments (id, chat_id),
CONSTRAINT message_attachments_position_range CHECK (position BETWEEN 0 AND 9)
);
-- Проверка FK при удалении вложения: без индекса — полный проход таблицы
CREATE INDEX message_attachments_attachment_id_idx
ON message_attachments (attachment_id);
+57
View File
@@ -0,0 +1,57 @@
-- Durable handoff: staging + queued/job/outbox фиксируются до ответа 202.
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
CHECK (status IN ('pending', 'queued', 'processing', 'ready', 'failed', 'deleting'));
ALTER TABLE attachments ADD COLUMN staging_key text;
ALTER TABLE attachments ADD COLUMN error_code text;
UPDATE attachments SET staging_key = object_key WHERE status IN ('pending', 'deleting');
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY DEFAULT uuidv7(),
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id),
pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version = 1),
attempt integer NOT NULL DEFAULT 1 CHECK (attempt > 0),
failures integer NOT NULL DEFAULT 0 CHECK (failures >= 0),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_token uuid,
lease_until timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs (lease_until)
WHERE lease_until IS NOT NULL;
CREATE TABLE attachment_outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
attempt integer NOT NULL CHECK (attempt > 0),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
claim_token uuid,
claim_until timestamptz,
UNIQUE (job_id, attempt)
);
CREATE INDEX attachment_outbox_pending_idx ON attachment_outbox (available_at, id)
WHERE published_at IS NULL;
CREATE TABLE attachment_variants (
attachment_id uuid NOT NULL REFERENCES attachments(id),
pipeline_version integer NOT NULL CHECK (pipeline_version = 1),
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
object_key text NOT NULL UNIQUE,
content_type text NOT NULL,
size_bytes integer NOT NULL CHECK (size_bytes > 0),
width integer NOT NULL CHECK (width > 0),
height integer NOT NULL CHECK (height > 0),
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
PRIMARY KEY (attachment_id, pipeline_version, name)
);
-- failed + error_code в attachments — устойчивый реестр ошибок вместо DLQ.
CREATE TABLE attachment_replays (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
attempt integer NOT NULL,
operator text NOT NULL CHECK (char_length(operator) BETWEEN 1 AND 128),
reason text NOT NULL CHECK (char_length(reason) BETWEEN 1 AND 512),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
+2
View File
@@ -0,0 +1,2 @@
-- Сохраняем безопасную причину временной ошибки после retry_exhausted.
ALTER TABLE attachment_jobs ADD COLUMN last_error_code text;