ЛР 4 — БВТ2304 — ivanstorozhev — на 3

Байты вложения лежат в общем S3, метаданные — в PostgreSQL, поэтому остановка загрузившей реплики не мешает другой отдать тот же файл. Idempotency-Key не даёт повторной отправке создать второе сообщение.

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 3
Трек 5, если заявлен: не заявлен

Что реализовано и что перенесено: из lab3 перенесены Spring Boot API, PostgreSQL, Redis-кэш сессий, Argon2id, Liquibase через одноразовый сервис migrate, HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh и scripts/restart.sh. Добавлены приватный SeaweedFS, таблица attachments, связь сообщения с вложениями и скачивание оригинала через API. Ключ объекта назначает сервер, имя файла только отображается.

Команды запуска из чистого clone:
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
curl -fsS http://127.0.0.1:8080/health/ready
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
docker compose --env-file .env start api

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md
make check — PASS: offline skeleton structure, local refs and Python syntax.
make test — PASS: lab4 public API scenario.
make test-persistence ACTION_SCRIPT=scripts/restart.sh — PASS: persistence preserved confirmed data and existing session.
make test-failover ACTION_SCRIPT=scripts/stop-one.sh — PASS: две реплики до отказа, восстановление записи за 1.665 с, 119 успешных записей и 1 ошибка перехода.
mvn -q test в backend/ — 16 тестов без ошибок, включая PNG по содержимому, подмену MIME, опасное имя файла и чужое вложение.
Анонимный GET объекта в сети стенда — HTTP 403.

Ограничения / известные ошибки: трек 5 и полный уровень 4 не делались. Один Docker-хост, единственные PostgreSQL, Redis, SeaweedFS и HAProxy остаются точками отказа. Если процесс умер после PUT и до COMMIT, объект может остаться без строки в БД. Ключ S3 один, с правами Admin. Пик памяти при параллельных загрузках не измерялся. Пока HAProxy не снял backend, часть запросов на останавливаемую реплику завершается ошибкой соединения; повтор с тем же Idempotency-Key безопасен для отправки сообщения.

Источники и использование ИИ: контракт contracts/openapi.json и contracts/README.md; код lab3; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Liquibase, Actuator, MapStruct 1.6.3, OpenAPI Generator 7.17.0, AWS SDK for Java 2.31.50, Bouncy Castle, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, SeaweedFS 4.52, Testcontainers. Реализация собрана в Cursor.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
This commit is contained in:
ivanstorozhev
2026-11-05 22:02:47 +03:00
parent ec540a1a72
commit 0450ba42ad
84 changed files with 4789 additions and 22 deletions
@@ -0,0 +1,41 @@
databaseChangeLog:
- changeSet:
id: 001-users
author: lab2
changes:
- createTable:
tableName: users
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
primaryKeyName: users_pkey
- column:
name: username
type: varchar(32)
constraints:
nullable: false
unique: true
uniqueConstraintName: users_username_key
- column:
name: display_name
type: varchar(100)
constraints:
nullable: false
- column:
name: password_hash
type: varchar(255)
constraints:
nullable: false
- column:
name: created_at
type: timestamp with time zone
constraints:
nullable: false
- sql:
sql: alter table users add constraint users_username_pattern check (username ~ '^[a-z0-9_]{3,32}$')
- sql:
sql: alter table users add constraint users_display_name_text check (char_length(btrim(display_name)) > 0)
@@ -0,0 +1,47 @@
databaseChangeLog:
- changeSet:
id: 002-sessions
author: lab2
changes:
- createTable:
tableName: sessions
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
primaryKeyName: sessions_pkey
- column:
name: token_hash
type: varchar(64)
constraints:
nullable: false
unique: true
uniqueConstraintName: sessions_token_hash_key
- column:
name: user_id
type: uuid
constraints:
nullable: false
- column:
name: expires_at
type: timestamp with time zone
constraints:
nullable: false
- column:
name: revoked_at
type: timestamp with time zone
- column:
name: created_at
type: timestamp with time zone
constraints:
nullable: false
- addForeignKeyConstraint:
baseTableName: sessions
baseColumnNames: user_id
referencedTableName: users
referencedColumnNames: id
constraintName: sessions_user_fk
onDelete: RESTRICT
@@ -0,0 +1,77 @@
databaseChangeLog:
- changeSet:
id: 003-chats
author: lab2
changes:
- createTable:
tableName: chats
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
primaryKeyName: chats_pkey
- column:
name: title
type: varchar(100)
constraints:
nullable: false
- column:
name: created_at
type: timestamp with time zone
constraints:
nullable: false
- sql:
sql: alter table chats add constraint chats_title_text check (char_length(btrim(title)) > 0)
- createTable:
tableName: chat_members
columns:
- column:
name: chat_id
type: uuid
constraints:
nullable: false
- column:
name: user_id
type: uuid
constraints:
nullable: false
- column:
name: ordinal
type: int
constraints:
nullable: false
- addPrimaryKey:
tableName: chat_members
columnNames: chat_id, user_id
constraintName: chat_members_pkey
- addForeignKeyConstraint:
baseTableName: chat_members
baseColumnNames: chat_id
referencedTableName: chats
referencedColumnNames: id
constraintName: chat_members_chat_fk
onDelete: RESTRICT
- addForeignKeyConstraint:
baseTableName: chat_members
baseColumnNames: user_id
referencedTableName: users
referencedColumnNames: id
constraintName: chat_members_user_fk
onDelete: RESTRICT
- createIndex:
indexName: chat_members_user_idx
tableName: chat_members
columns:
- column:
name: user_id
- createIndex:
indexName: chats_history_idx
tableName: chats
columns:
- column:
name: created_at
- column:
name: id
@@ -0,0 +1,61 @@
databaseChangeLog:
- changeSet:
id: 004-messages
author: lab2
changes:
- createTable:
tableName: messages
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
primaryKeyName: messages_pkey
- column:
name: chat_id
type: uuid
constraints:
nullable: false
- column:
name: sender_id
type: uuid
constraints:
nullable: false
- column:
name: text
type: varchar(4000)
constraints:
nullable: false
- column:
name: created_at
type: timestamp with time zone
constraints:
nullable: false
- addForeignKeyConstraint:
baseTableName: messages
baseColumnNames: chat_id
referencedTableName: chats
referencedColumnNames: id
constraintName: messages_chat_fk
onDelete: RESTRICT
- addForeignKeyConstraint:
baseTableName: messages
baseColumnNames: sender_id
referencedTableName: users
referencedColumnNames: id
constraintName: messages_sender_fk
onDelete: RESTRICT
- sql:
sql: alter table messages add constraint messages_text_not_blank check (char_length(btrim(text)) > 0 and char_length(text) <= 4000)
- createIndex:
indexName: messages_history_idx
tableName: messages
columns:
- column:
name: chat_id
- column:
name: created_at
- column:
name: id
@@ -0,0 +1,73 @@
databaseChangeLog:
- changeSet:
id: 005-idempotency
author: lab3
changes:
- createTable:
tableName: idempotency_records
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
primaryKeyName: idempotency_records_pkey
- column:
name: user_id
type: uuid
constraints:
nullable: false
- column:
name: http_method
type: varchar(8)
constraints:
nullable: false
- column:
name: path
type: varchar(256)
constraints:
nullable: false
- column:
name: idempotency_key
type: varchar(128)
constraints:
nullable: false
- column:
name: request_hash
type: varchar(64)
constraints:
nullable: false
- column:
name: message_id
type: uuid
constraints:
nullable: false
- column:
name: created_at
type: timestamp with time zone
constraints:
nullable: false
- column:
name: expires_at
type: timestamp with time zone
constraints:
nullable: false
- addUniqueConstraint:
tableName: idempotency_records
columnNames: user_id, http_method, path, idempotency_key
constraintName: idempotency_scope_uq
- addForeignKeyConstraint:
baseTableName: idempotency_records
baseColumnNames: user_id
referencedTableName: users
referencedColumnNames: id
constraintName: idempotency_user_fk
onDelete: RESTRICT
- addForeignKeyConstraint:
baseTableName: idempotency_records
baseColumnNames: message_id
referencedTableName: messages
referencedColumnNames: id
constraintName: idempotency_message_fk
onDelete: RESTRICT
@@ -0,0 +1,127 @@
databaseChangeLog:
- changeSet:
id: 006-attachments
author: lab4
changes:
- sql:
sql: alter table messages drop constraint messages_text_not_blank
- createTable:
tableName: attachments
columns:
- column:
name: id
type: uuid
constraints:
primaryKey: true
nullable: false
primaryKeyName: attachments_pkey
- column:
name: chat_id
type: uuid
constraints:
nullable: false
- column:
name: owner_id
type: uuid
constraints:
nullable: false
- column:
name: filename
type: varchar(255)
constraints:
nullable: false
- column:
name: content_type
type: varchar(32)
constraints:
nullable: false
- column:
name: size_bytes
type: bigint
constraints:
nullable: false
- column:
name: sha256
type: varchar(64)
constraints:
nullable: false
- column:
name: object_key
type: varchar(80)
constraints:
nullable: false
- column:
name: status
type: varchar(16)
constraints:
nullable: false
- column:
name: created_at
type: timestamp with time zone
constraints:
nullable: false
- column:
name: updated_at
type: timestamp with time zone
constraints:
nullable: false
- addUniqueConstraint:
tableName: attachments
columnNames: object_key
constraintName: attachments_object_key_uq
- addForeignKeyConstraint:
baseTableName: attachments
baseColumnNames: chat_id
referencedTableName: chats
referencedColumnNames: id
constraintName: attachments_chat_fk
onDelete: RESTRICT
- addForeignKeyConstraint:
baseTableName: attachments
baseColumnNames: owner_id
referencedTableName: users
referencedColumnNames: id
constraintName: attachments_owner_fk
onDelete: RESTRICT
- createIndex:
indexName: attachments_chat_idx
tableName: attachments
columns:
- column:
name: chat_id
- createTable:
tableName: message_attachments
columns:
- column:
name: message_id
type: uuid
constraints:
nullable: false
- column:
name: sort_order
type: int
constraints:
nullable: false
- column:
name: attachment_id
type: uuid
constraints:
nullable: false
- addPrimaryKey:
tableName: message_attachments
columnNames: message_id, sort_order
constraintName: message_attachments_pkey
- addForeignKeyConstraint:
baseTableName: message_attachments
baseColumnNames: message_id
referencedTableName: messages
referencedColumnNames: id
constraintName: message_attachments_message_fk
onDelete: RESTRICT
- addForeignKeyConstraint:
baseTableName: message_attachments
baseColumnNames: attachment_id
referencedTableName: attachments
referencedColumnNames: id
constraintName: message_attachments_attachment_fk
onDelete: RESTRICT
@@ -0,0 +1,19 @@
databaseChangeLog:
- include:
file: 001-users.yaml
relativeToChangelogFile: true
- include:
file: 002-sessions.yaml
relativeToChangelogFile: true
- include:
file: 003-chats.yaml
relativeToChangelogFile: true
- include:
file: 004-messages.yaml
relativeToChangelogFile: true
- include:
file: 005-idempotency.yaml
relativeToChangelogFile: true
- include:
file: 006-attachments.yaml
relativeToChangelogFile: true