ЛР 3: Балансировка API и отказ реплики

This commit is contained in:
2026-12-02 00:16:41 +03:00
parent 0ab3a341aa
commit 25f666a3e8
22 changed files with 993 additions and 18 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);
+25
View File
@@ -0,0 +1,25 @@
# 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.
- `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 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 and chat membership are checked before replay.
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's data directory on the named `postgres_data` volume. The persistence hook restarts the API and database containers without removing that volume. Backups and destructive volume resets are deliberately separate operator actions.