ЛР 5 — БВТ2304 — Черников — на 4

This commit is contained in:
2026-11-11 23:56:28 +03:00
parent 276dbdad8a
commit 0b399073d6
77 changed files with 6838 additions and 27 deletions
+46
View File
@@ -0,0 +1,46 @@
-- Схема мессенджера: пользователи, чаты, участники, сообщения.
-- Ограничения повторяют правила контракта, чтобы база не приняла неверные данные,
-- даже если ошибка будет в коде приложения.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL, -- Argon2id, сам пароль не хранится
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_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100)
);
-- Участники задаются при создании чата и потом не меняются.
-- position хранит порядок member_ids из запроса на создание.
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id),
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)
);
-- Список чатов пользователя ищется по user_id.
CREATE INDEX chat_members_user_id_idx ON chat_members (user_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000),
-- Отправитель обязан состоять в чате: это проверяет и база, а не только код.
CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id)
REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,8 @@
-- Индекс для чтения истории чата. Приложение выполняет запрос
-- SELECT ... FROM messages
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- Колонки индекса идут в том же порядке, поэтому страница читается диапазоном индекса
-- без сортировки и без просмотра всей истории чата. План на 10 000+ сообщениях —
-- в evidence/explain.txt (scripts/explain_history.py).
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
+20
View File
@@ -0,0 +1,20 @@
-- Идемпотентность отправки сообщения (с lab3).
-- Область ключа: пользователь + метод + путь чата + значение Idempotency-Key.
-- Строка ключа и сообщение создаются в одной транзакции: повтор запроса с тем же ключом
-- либо находит готовый результат, либо (если первая попытка не зафиксирована) создаёт его заново,
-- но никогда не создаёт второе сообщение.
-- Миграция только добавляет таблицу: версия API из lab2 продолжает работать с этой схемой.
CREATE TABLE idempotency_keys (
user_id uuid NOT NULL REFERENCES users (id),
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash text NOT NULL, -- sha256 разобранного тела: другое тело с тем же ключом — 409
message_id uuid NOT NULL REFERENCES messages (id),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT idempotency_keys_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$')
);
-- Удаление ключей старше срока хранения (IDEMPOTENCY_TTL_SECONDS, не меньше 24 часов).
CREATE INDEX idempotency_keys_created_at_idx ON idempotency_keys (created_at);
+27
View File
@@ -0,0 +1,27 @@
-- Байты только в S3; ключ не зависит от filename и не отдаётся клиенту.
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
owner_id uuid NOT NULL,
object_key text NOT NULL UNIQUE,
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members (chat_id, user_id),
UNIQUE (id, chat_id)
);
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
ALTER TABLE messages DROP CONSTRAINT messages_text_length;
ALTER TABLE messages ADD CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 0 AND 4000);
-- Массив хранит порядок attachment_ids и возвращается вместе с сообщением/повтором.
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id),
attachment_id uuid NOT NULL,
chat_id uuid NOT NULL,
PRIMARY KEY (message_id, attachment_id),
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id)
);
+91
View File
@@ -0,0 +1,91 @@
-- PostgreSQL owns the logical job and its publication intent. The broker is a
-- durable delivery mechanism; it is never the only copy of accepted work.
ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1);
ALTER TABLE attachments ADD COLUMN error_code text
CHECK (error_code IS NULL OR error_code ~ '^[a-z][a-z0-9_]{0,63}$');
ALTER TABLE attachments ADD COLUMN staging_key text;
UPDATE attachments SET staging_key = object_key;
ALTER TABLE attachments ALTER COLUMN staging_key SET NOT NULL;
ALTER TABLE attachments ADD COLUMN staging_cleanup_pending boolean NOT NULL DEFAULT false;
ALTER TABLE attachments ADD COLUMN staging_deleted_at timestamptz;
ALTER TABLE attachments ADD CONSTRAINT attachments_result_state CHECK (
(status <> 'ready' OR error_code IS NULL) AND
(status <> 'failed' OR error_code IS NOT NULL) AND
(NOT staging_cleanup_pending OR status = 'ready')
);
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments (id),
pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version >= 1),
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
-- attempt is monotonic, including an explicit replay; its retry budget is separate.
attempt integer NOT NULL DEFAULT 0 CHECK (attempt >= 0),
run_attempts integer NOT NULL DEFAULT 0 CHECK (run_attempts >= 0 AND run_attempts <= attempt),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
worker_id text,
lease_token uuid,
lease_until timestamptz,
error_code text CHECK (error_code IS NULL OR error_code ~ '^[a-z][a-z0-9_]{0,63}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
CHECK ((status = 'processing') = (worker_id IS NOT NULL AND lease_token IS NOT NULL AND lease_until IS NOT NULL))
);
CREATE INDEX attachment_jobs_expired_idx ON attachment_jobs (lease_until) WHERE status = 'processing';
CREATE INDEX attachment_jobs_failed_idx ON attachment_jobs (updated_at) WHERE status = 'failed';
CREATE TABLE attachment_outbox (
id uuid PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (id),
attempt integer NOT NULL CHECK (attempt >= 1),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
published_at timestamptz,
worker_id text,
lease_token uuid,
lease_until timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
UNIQUE (job_id, attempt),
CHECK ((lease_token IS NULL) = (lease_until IS NULL)),
CHECK ((lease_token IS NULL) = (worker_id IS NULL))
);
CREATE INDEX attachment_outbox_pending_idx ON attachment_outbox (available_at, created_at)
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 CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
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 ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (attachment_id, pipeline_version, name)
);
CREATE INDEX attachment_staging_cleanup_idx ON attachments (updated_at) WHERE staging_cleanup_pending;
CREATE TABLE job_audit (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs (id),
action text NOT NULL,
actor text NOT NULL CHECK (char_length(actor) BETWEEN 1 AND 120),
reason text NOT NULL CHECK (char_length(reason) BETWEEN 1 AND 500),
details jsonb NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
-- Explicit operator fault hooks are persisted and consumed once across restarts.
CREATE TABLE job_faults (
job_id uuid NOT NULL REFERENCES attachment_jobs (id),
action text NOT NULL CHECK (action IN ('crash_after_objects', 'crash_after_ready', 'transient', 'permanent', 'stall_processing')),
remaining integer NOT NULL CHECK (remaining BETWEEN 0 AND 100),
PRIMARY KEY (job_id, action)
);
-- An upgrade from lab4 also schedules its existing originals for the new pipeline.
INSERT INTO attachment_jobs (id, attachment_id) SELECT gen_random_uuid(), id FROM attachments;
INSERT INTO attachment_outbox (id, job_id, attempt) SELECT gen_random_uuid(), id, 1 FROM attachment_jobs;