Реализована лабораторная 4: MinIO и вложения

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-12-02 03:04:36 +03:00
co-authored by Copilot
parent ec540a1a72
commit dd484c90b4
28 changed files with 1718 additions and 34 deletions
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+5
View File
@@ -0,0 +1,5 @@
CREATE TABLE chats (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
member_position SMALLINT NOT NULL CHECK (member_position BETWEEN 0 AND 99),
PRIMARY KEY (chat_id, user_id),
UNIQUE (chat_id, member_position)
);
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text TEXT NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000 AND btrim(text) <> ''),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+6
View File
@@ -0,0 +1,6 @@
CREATE TABLE sessions (
token_hash CHAR(64) PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > created_at)
);
@@ -0,0 +1 @@
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
@@ -0,0 +1 @@
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
+1
View File
@@ -0,0 +1 @@
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
+1
View File
@@ -0,0 +1 @@
CREATE INDEX chats_order_idx ON chats (created_at, id);
+17
View File
@@ -0,0 +1,17 @@
CREATE TABLE idempotency_records (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
http_method TEXT NOT NULL CHECK (http_method = 'POST'),
request_path TEXT NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
response_status SMALLINT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (user_id, http_method, request_path, idempotency_key),
CHECK ((response_status IS NULL) = (response_body IS NULL)),
CHECK (response_status IS NULL OR response_status = 201)
);
CREATE INDEX idempotency_records_expiry_idx
ON idempotency_records (expires_at);
+48
View File
@@ -0,0 +1,48 @@
ALTER TABLE messages
DROP CONSTRAINT messages_text_check;
ALTER TABLE messages
ADD CONSTRAINT messages_text_check
CHECK (char_length(text) BETWEEN 0 AND 4000 AND (text = '' OR btrim(text) <> ''));
ALTER TABLE messages
ADD CONSTRAINT messages_chat_id_id_unique UNIQUE (chat_id, id);
CREATE TABLE attachments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL,
owner_id UUID NOT NULL,
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 BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 CHAR(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
object_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
variants JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(variants) = 'array'),
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (chat_id, id),
CHECK (error_code IS NULL),
FOREIGN KEY (chat_id, owner_id)
REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE
);
CREATE INDEX attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
CREATE TABLE message_attachments (
chat_id UUID NOT NULL,
message_id UUID NOT NULL,
attachment_id UUID NOT NULL,
position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position),
FOREIGN KEY (chat_id, message_id)
REFERENCES messages(chat_id, id) ON DELETE CASCADE,
FOREIGN KEY (chat_id, attachment_id)
REFERENCES attachments(chat_id, id) ON DELETE CASCADE
);
CREATE INDEX message_attachments_chat_attachment_idx
ON message_attachments (chat_id, attachment_id);
+29
View File
@@ -0,0 +1,29 @@
# PostgreSQL schema and transactions
## Tables and invariants
- `users`: UUID primary key, unique constrained username, display name, Argon2 password hash, server timestamp.
- `chats`: UUID primary key and title.
- `chat_members`: composite `(chat_id, user_id)` primary key, foreign keys to both parent tables, unique stable member position per chat. The `(user_id, chat_id)` index supports listing a user's chats.
- `messages`: UUID primary key and foreign keys to chat and sender. `(chat_id, created_at, id)` supports the API's ascending keyset history query.
- `sessions`: SHA-256 digest of a random opaque token as primary key, user foreign key, creation and expiry timestamps. Raw tokens are returned only once and are never stored.
- `idempotency_records`: unique per user, method, request path, and key; stores the request hash and committed response for 24 hours. Expired records are removed when a message is submitted.
- `attachments`: PostgreSQL metadata for a chat-scoped image; `object_key` points to the object in the private MinIO bucket and is never exposed by the API.
- `message_attachments`: ordered message-to-attachment links with composite foreign keys that prevent linking a file from another chat.
- `schema_migrations`: migration filename and application timestamp; created by the migration runner.
All timestamps are `TIMESTAMPTZ`. PostgreSQL owns generated UUIDs and creation timestamps. Named migrations run once in lexicographic order; an advisory transaction lock serializes startup migration attempts.
## Transaction boundaries
Each HTTP request uses one pooled PostgreSQL connection and one transaction. A successful response is written only after that transaction commits. Creating a chat and inserting every member is one transaction, so a failed member insert rolls back both the chat and any earlier member rows. Registration relies on the unique username constraint as the final arbiter of concurrent registrations; the losing request returns `409`.
Creating a message, linking its attachments, and recording its idempotency result share one transaction. PostgreSQL's composite primary key serializes concurrent requests across API replicas. Matching bodies replay the original status and message; a different body returns `409`. Authentication, chat membership, and attachment scope are checked before replay. Upload writes bytes to S3 first, then inserts metadata in PostgreSQL; a failed DB transaction triggers a best-effort object delete compensation.
The original file is authoritative in MinIO; PostgreSQL stores its chat/owner ACL, object key, checksum, type, and size. Bucket bootstrap is idempotent and creates a private bucket. The API currently uses the local MinIO root credentials, acceptable only for this grade-3 isolated lab topology; use a scoped service account for a stronger deployment.
Message history uses `WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4`, matching `messages_chat_history_idx`. Cursors include their resource scope and the last row's timestamp and UUID.
## Durability
Compose mounts PostgreSQL and MinIO data directories on named `postgres_data` and `minio_data` volumes. The persistence hook restarts the API, database, and MinIO without removing those volumes. Backups and destructive volume resets are deliberately separate operator actions.