S3-вложения и сверка Postgresql с MinIO

This commit is contained in:
2026-11-13 19:15:04 +03:00
parent ec540a1a72
commit 79e94f9d2a
60 changed files with 6702 additions and 50 deletions
+50
View File
@@ -0,0 +1,50 @@
-- Пользователи, чаты, состав и сообщения. PostgreSQL — источник истины.
-- Сессии здесь не хранятся: их держит Redis с AOF.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_unique 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),
CONSTRAINT users_password_hash_present CHECK (char_length(password_hash) > 0)
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
-- Список чатов пользователя идёт по (created_at, id).
CREATE INDEX chats_list_idx ON chats (created_at, id);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id),
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonneg CHECK (position >= 0),
CONSTRAINT chat_members_position_unique UNIQUE (chat_id, position)
);
-- Обратный поиск: чаты конкретного пользователя.
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id),
sender_id uuid NOT NULL REFERENCES users (id),
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
-- Keyset-страница истории: WHERE chat_id = $1 AND (created_at, id) > cursor
-- ORDER BY created_at, id LIMIT n. Индекс покрывает фильтр и порядок,
-- поэтому страница не читает всю историю чата.
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
+18
View File
@@ -0,0 +1,18 @@
-- Общая идемпотентность POST сообщения. Область: пользователь + чат + ключ.
-- Строка пишется в той же транзакции, что и сообщение, поэтому 5xx не оставляет
-- «занятый» ключ без сообщения и не оставляет сообщение без ключа.
-- Повтор с тем же текстом читает message_id. Другой текст — конфликт на уровне API.
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users (id),
chat_id uuid NOT NULL REFERENCES chats (id),
idem_key text NOT NULL,
fingerprint text NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id),
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY (user_id, chat_id, idem_key),
CONSTRAINT message_idempotency_key_len CHECK (char_length(idem_key) BETWEEN 1 AND 128),
CONSTRAINT message_idempotency_fingerprint_present CHECK (char_length(fingerprint) > 0),
CONSTRAINT message_idempotency_expiry CHECK (expires_at > created_at)
);
+42
View File
@@ -0,0 +1,42 @@
-- Метаданные вложения живут в PostgreSQL, байты — в приватном bucket.
-- object_key назначает сервер. filename только для показа и не входит в ключ.
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) <= 4000);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id),
owner_id uuid NOT NULL REFERENCES users (id),
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 text NOT NULL,
object_key text NOT NULL,
width integer NOT NULL,
height integer NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_status CHECK (status = 'ready'),
CONSTRAINT attachments_dimensions CHECK (width >= 1 AND height >= 1),
CONSTRAINT attachments_object_key_unique UNIQUE (object_key)
);
CREATE INDEX attachments_chat_idx ON attachments (chat_id, created_at, id);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id),
attachment_id uuid NOT NULL REFERENCES attachments (id),
position integer NOT NULL,
PRIMARY KEY (message_id, position),
CONSTRAINT message_attachments_position_nonneg CHECK (position >= 0),
CONSTRAINT message_attachments_unique UNIQUE (message_id, attachment_id)
);
-- Сверка и проверка «файл уже прикреплён» не сканируют всю историю.
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
+7
View File
@@ -0,0 +1,7 @@
// хранит версионируемые SQL-файлы внутри бинарника.
package migrations
import "embed"
//go:embed *.sql
var FS embed.FS