docs: add lab5 report and evidence

This commit is contained in:
2026-11-16 17:57:34 +03:00
parent 484119a6a9
commit f47dae8846
16 changed files with 1296 additions and 15 deletions
+267
View File
@@ -0,0 +1,267 @@
# Стенд: сервисы, порты, лимиты, секреты, миграции, топология брокера
# date: 2026-11-16T13:59:25Z
# commit: 484119a
$ docker compose ps -a --format table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}
SERVICE NAME IMAGE STATUS PORTS
api messenger-lab5-api-1 mtusi-messenger-lab5-api:dev Up 14 seconds (healthy) 8080/tcp
api messenger-lab5-api-2 mtusi-messenger-lab5-api:dev Up 15 seconds (healthy) 8080/tcp
lb messenger-lab5-lb-1 haproxy:3.0.6-alpine Up 8 seconds 127.0.0.1:8080->8080/tcp
migrate messenger-lab5-migrate-1 mtusi-messenger-lab5-migrate:dev Exited (0) 15 seconds ago
postgres messenger-lab5-postgres-1 postgres:17.2-alpine Up 24 seconds (healthy) 5432/tcp
rabbitmq messenger-lab5-rabbitmq-1 rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 Up 24 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
reconciler messenger-lab5-reconciler-1 mtusi-messenger-lab5-api:dev Up 15 seconds 8080/tcp
redis messenger-lab5-redis-1 redis:7.4.1-alpine Up 24 seconds (healthy) 6379/tcp
relay messenger-lab5-relay-1 mtusi-messenger-lab5-api:dev Up 9 seconds 8080/tcp
s3 messenger-lab5-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 Up 24 seconds (healthy) 9000/tcp
s3-init messenger-lab5-s3-init-1 pgsty/mc:RELEASE.2026-10-26T00-00-00Z@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8 Exited (0) 15 seconds ago
secrets-init messenger-lab5-secrets-init-1 alpine:3.20.3 Exited (0) 25 seconds ago
tools messenger-lab5-tools-run-ce3cefcdf49a mtusi-messenger-lab5-tools:dev Up 5 seconds
worker messenger-lab5-worker-1 mtusi-messenger-lab5-api:dev Up 9 seconds 8080/tcp
## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)
$ sh -c docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' $(docker compose ps -aq)
/messenger-lab5-api-1 cpus=500000000 memory=268435456
/messenger-lab5-api-2 cpus=500000000 memory=268435456
/messenger-lab5-lb-1 cpus=250000000 memory=67108864
/messenger-lab5-migrate-1 cpus=500000000 memory=536870912
/messenger-lab5-postgres-1 cpus=1000000000 memory=536870912
/messenger-lab5-rabbitmq-1 cpus=500000000 memory=536870912
/messenger-lab5-reconciler-1 cpus=250000000 memory=134217728
/messenger-lab5-redis-1 cpus=250000000 memory=134217728
/messenger-lab5-relay-1 cpus=250000000 memory=134217728
/messenger-lab5-s3-1 cpus=500000000 memory=536870912
/messenger-lab5-s3-init-1 cpus=250000000 memory=268435456
/messenger-lab5-secrets-init-1 cpus=100000000 memory=33554432
/messenger-lab5-tools-run-ce3cefcdf49a cpus=1000000000 memory=268435456
/messenger-lab5-worker-1 cpus=1000000000 memory=805306368
## Секреты: каждый сервис видит только свои файлы (содержимое не выводится)
$ docker compose exec -T postgres ls /run/secrets
pg_password
$ docker compose exec -T redis ls /run/secrets
redis_password
$ docker compose exec -T s3 ls /run/secrets
s3_root_password
s3_root_user
$ docker compose exec -T api ls /run/secrets
cache_url
database_url
s3_access_key_id
s3_secret_access_key
$ docker compose exec -T reconciler ls /run/secrets
database_url
s3_access_key_id
s3_secret_access_key
$ docker compose exec -T relay ls /run/secrets
broker_url
database_url
$ docker compose exec -T worker ls /run/secrets
broker_url
database_url
s3_access_key_id
s3_secret_access_key
$ docker compose exec -T rabbitmq ls /etc/rabbitmq/conf.d
10-messenger.conf
$ docker compose exec -T lb sh -c ls /run/secrets 2>/dev/null || echo "no /run/secrets"
no /run/secrets
## Версии
$ docker compose exec -T lb haproxy -v
HAProxy version 3.0.6-c2c0090 2024/11/07 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2029.
Known bugs: http://www.haproxy.org/bugs/bugs-3.0.6.html
Running on: Linux 5.15.153.1-microsoft-standard-WSL2 #1 SMP Fri Mar 29 23:14:13 UTC 2024 x86_64
$ docker compose exec -T postgres postgres --version
postgres (PostgreSQL) 17.2
$ docker compose exec -T redis redis-server --version
Redis server v=7.4.1 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=a93ce81042b3a6d7
$ docker compose exec -T s3 minio --version
minio version RELEASE.2026-08-04T00-00-00Z (commit-id=d88f46ccee345a9c2fabe2d221d9a9e56bc11aec)
Runtime: go1.26.5 linux/amd64
License: GNU AGPLv3 - https://www.gnu.org/licenses/agpl-3.0.html
Copyright: 2015-2026 MinIO, Inc.
$ docker compose exec -T rabbitmq rabbitmqctl -q version
4.0.5
## Топология брокера: durable quorum-очереди, delivery-limit и DLQ
$ docker compose exec -T rabbitmq rabbitmqctl -q list_queues name type durable arguments messages
name type durable arguments messages
attachment.jobs quorum true [{"x-queue-type","quorum"},{"x-delivery-limit",20},{"x-dead-letter-exchange",[]},{"x-dead-letter-routing-key","attachment.jobs.dlq"}] 0
attachment.jobs.dlq quorum true [{"x-queue-type","quorum"}] 0
$ docker compose exec -T rabbitmq rabbitmqctl -q list_consumers queue_name prefetch_count ack_required
queue_name ack_required prefetch_count
attachment.jobs true 2
## Таблицы
$ docker compose exec -T postgres psql -U messenger -d messenger -c \d attachments -c \d attachment_variants -c \d attachment_jobs -c \d outbox -c \d job_events
Table "public.attachments"
Column | Type | Collation | Nullable | Default
--------------+-----------------------------+-----------+----------+-------------------
id | uuid | | not null |
chat_id | uuid | | not null |
owner_id | uuid | | not null |
filename | character varying(255) | | not null |
content_type | character varying(32) | | not null |
size_bytes | integer | | not null |
sha256 | character(64) | | not null |
object_key | character varying(128) | | not null |
created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
updated_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
staging_key | character varying(128) | | |
status | character varying(16) | | not null |
error_code | character varying(64) | | |
Indexes:
"attachments_pkey" PRIMARY KEY, btree (id)
"attachments_chat_id_idx" btree (chat_id)
"attachments_object_key_key" UNIQUE, btree (object_key)
"attachments_owner_id_idx" btree (owner_id)
"attachments_staging_key_key" UNIQUE, btree (staging_key)
Check constraints:
"attachments_content_type_allowed" CHECK (content_type::text = ANY (ARRAY['image/png'::character varying, 'image/jpeg'::character varying]::text[]))
"attachments_error_code_when_failed" CHECK ((status::text = 'failed'::text) = (error_code IS NOT NULL))
"attachments_filename_not_blank" CHECK (btrim(filename::text) <> ''::text)
"attachments_sha256_format" CHECK (sha256 ~ '^[a-f0-9]{64}$'::text)
"attachments_size_range" CHECK (size_bytes >= 1 AND size_bytes <= 10485760)
"attachments_status_allowed" CHECK (status::text = ANY (ARRAY['queued'::character varying, 'processing'::character varying, 'ready'::character varying, 'failed'::character varying]::text[]))
Foreign-key constraints:
"attachments_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON UPDATE CASCADE ON DELETE CASCADE
"attachments_owner_id_fkey" FOREIGN KEY (owner_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE RESTRICT
Referenced by:
TABLE "attachment_jobs" CONSTRAINT "attachment_jobs_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE
TABLE "attachment_variants" CONSTRAINT "attachment_variants_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE
TABLE "message_attachments" CONSTRAINT "message_attachments_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE
Table "public.attachment_variants"
Column | Type | Collation | Nullable | Default
------------------+-----------------------------+-----------+----------+-------------------
attachment_id | uuid | | not null |
pipeline_version | integer | | not null |
name | character varying(16) | | not null |
content_type | character varying(32) | | not null |
object_key | character varying(128) | | not null |
size_bytes | integer | | not null |
width | integer | | not null |
height | integer | | not null |
sha256 | character(64) | | not null |
created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
Indexes:
"attachment_variants_pkey" PRIMARY KEY, btree (attachment_id, pipeline_version, name)
"attachment_variants_object_key_key" UNIQUE, btree (object_key)
Check constraints:
"attachment_variants_content_type_allowed" CHECK (content_type::text = ANY (ARRAY['image/jpeg'::character varying, 'image/png'::character varying, 'image/webp'::character varying]::text[]))
"attachment_variants_name_allowed" CHECK (name::text = ANY (ARRAY['thumbnail'::character varying, 'crop'::character varying, 'optimized'::character varying]::text[]))
"attachment_variants_positive" CHECK (pipeline_version >= 1 AND size_bytes >= 1 AND width >= 1 AND height >= 1)
"attachment_variants_sha256_format" CHECK (sha256 ~ '^[a-f0-9]{64}$'::text)
Foreign-key constraints:
"attachment_variants_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE
Table "public.attachment_jobs"
Column | Type | Collation | Nullable | Default
------------------+-----------------------------+-----------+----------+-------------------
id | uuid | | not null |
attachment_id | uuid | | not null |
pipeline_version | integer | | not null |
status | character varying(16) | | not null |
attempt | integer | | not null |
max_attempts | integer | | not null |
next_attempt_at | timestamp(3) with time zone | | not null |
lease_owner | uuid | | |
lease_until | timestamp(3) with time zone | | |
error_code | character varying(64) | | |
last_error | character varying(200) | | |
created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
updated_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
finished_at | timestamp(3) with time zone | | |
Indexes:
"attachment_jobs_pkey" PRIMARY KEY, btree (id)
"attachment_jobs_attachment_id_pipeline_version_key" UNIQUE, btree (attachment_id, pipeline_version)
"attachment_jobs_status_lease_until_idx" btree (status, lease_until)
Check constraints:
"attachment_jobs_attempt_range" CHECK (pipeline_version >= 1 AND attempt >= 1 AND attempt <= max_attempts)
"attachment_jobs_error_code_when_failed" CHECK ((status::text = 'failed'::text) = (error_code IS NOT NULL))
"attachment_jobs_lease_when_processing" CHECK (status::text <> 'processing'::text OR lease_owner IS NOT NULL AND lease_until IS NOT NULL)
"attachment_jobs_status_allowed" CHECK (status::text = ANY (ARRAY['queued'::character varying, 'processing'::character varying, 'ready'::character varying, 'failed'::character varying]::text[]))
Foreign-key constraints:
"attachment_jobs_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE
Referenced by:
TABLE "job_events" CONSTRAINT "job_events_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE
TABLE "outbox" CONSTRAINT "outbox_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE
Table "public.outbox"
Column | Type | Collation | Nullable | Default
------------------+-----------------------------+-----------+----------+------------------------------------
id | bigint | | not null | nextval('outbox_id_seq'::regclass)
job_id | uuid | | not null |
payload | jsonb | | not null |
available_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
published_at | timestamp(3) with time zone | | |
publish_attempts | integer | | not null | 0
created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
Indexes:
"outbox_pkey" PRIMARY KEY, btree (id)
"outbox_job_id_idx" btree (job_id)
"outbox_published_at_available_at_idx" btree (published_at, available_at)
Foreign-key constraints:
"outbox_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE
Table "public.job_events"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+----------------------------------------
id | bigint | | not null | nextval('job_events_id_seq'::regclass)
job_id | uuid | | not null |
attempt | integer | | not null |
event | character varying(32) | | not null |
detail | character varying(200) | | |
created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP
Indexes:
"job_events_pkey" PRIMARY KEY, btree (id)
"job_events_job_id_idx" btree (job_id)
Foreign-key constraints:
"job_events_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE
## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет, схема совпадает с БД
$ docker compose run --rm migrate
Container messenger-lab5-secrets-init-1 Created
Container messenger-lab5-postgres-1 Running
Container messenger-lab5-secrets-init-1 Starting
Container messenger-lab5-secrets-init-1 Started
Container messenger-lab5-secrets-init-1 Waiting
Container messenger-lab5-secrets-init-1 Exited
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "messenger", schema "public" at "postgres:5432"
5 migrations found in prisma/migrations
No pending migrations to apply.
$ docker compose run --rm --no-deps migrate sh -c export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code
No difference detected.
$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at
migration_name | finished_at
---------------------------------+-------------------------------
20261021000000_init | 2026-11-16 13:59:09.682776+00
20261021010000_auth_sessions | 2026-11-16 13:59:09.695226+00
20261101000000_idempotency_keys | 2026-11-16 13:59:09.708431+00
20261105000000_attachments | 2026-11-16 13:59:09.722515+00
20261115000000_attachment_jobs | 2026-11-16 13:59:09.743001+00
(5 rows)
+17
View File
@@ -0,0 +1,17 @@
# make test-failover: stop-one.sh останавливает реплику, обслужившую тест
# date: 2026-11-16T14:01:02Z
# commit: 484119a
## до
/messenger-lab5-api-1 id=1e38f40634b0 running exit=0 finished=2026-11-16T14:00:57.875525905Z
/messenger-lab5-api-2 id=87ae39d58075 running exit=0 finished=2026-11-16T14:00:57.874930868Z
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 3.439}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
## после: остановленная реплика Exited (0) — штатное завершение по SIGTERM
/messenger-lab5-api-1 id=1e38f40634b0 exited exit=0 finished=2026-11-16T14:01:15.808115084Z
/messenger-lab5-api-2 id=87ae39d58075 running exit=0 finished=2026-11-16T14:00:57.874930868Z
+214
View File
@@ -0,0 +1,214 @@
# Фоновая обработка: сценарии защиты уровней 3 и 4 (scripts/job-scenario.py)
# date: 2026-11-16T14:01:41Z
# commit: 484119a
## restart
$ python3 scripts/job-scenario.py restart
[ 0.2s] user 82eeee3d-6dbd-4f88-89f7-f90af93592c1 chat 65981e2e-b48c-436f-8817-7adb465bc180
[ 0.2s] $ docker compose stop worker
[ 0.9s] POST attachment -> 202 status=queued id=eade9374-e447-4d1a-bcc1-b1bab3b3886b instance=87ae39d58075
[ 0.9s] content while queued -> 409
[ 1.0s] POST message with 1 attachment(s) -> 201 id=068bed4e-0750-4afe-94c3-409708601758
[ 1.0s] POST message with 0 attachment(s) -> 201 id=73f5328e-b50e-463a-9b44-52e094985702
[ 8.7s] queues: name type durable messages_ready messages_unacknowledged
attachment.jobs quorum true 1 0
attachment.jobs.dlq quorum true 0 0
[ 8.7s] $ docker compose restart api rabbitmq
[ 26.3s] queues after broker restart: name type durable messages_ready messages_unacknowledged
attachment.jobs quorum true 1 0
attachment.jobs.dlq quorum true 0 0
[ 26.3s] status after restarts: queued
[ 26.3s] $ docker compose start worker
[ 31.5s] GET attachment -> status=queued error_code=None
[ 32.5s] GET attachment -> status=ready error_code=None
[ 32.5s] original -> 200 sha256 matches upload: True
[ 32.5s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True
[ 32.6s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True
[ 32.6s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True
[ 32.7s] job: 27a4684d-3af8-4547-9610-07aba55b7657 | ready | 1 | 5 |
[ 32.9s] variants rows: 3
[ 33.1s] events: enqueued -> processing -> ready
## crash-after-store
$ python3 scripts/job-scenario.py crash-after-store
[ 0.1s] user 870efd23-431d-4c5d-bb6a-fb69fe407107 chat 36e1d058-a50b-468a-8286-41c65ee181ad
[ 0.1s] $ docker compose stop worker
[ 0.6s] $ docker compose run --no-deps -e WORKER_FAULT=exit-after-store -e JOB_LEASE_SECONDS=15 worker
[ 2.2s] POST attachment -> 202 status=queued id=052c555e-1e36-4ca6-aea6-cf7bfa933904 instance=1e38f40634b0
[ 3.0s] one-off: fault injection: worker killed after storing objects, before commit and ack
[ 3.1s] one-off process exit code 137 (137 = killed without ack)
[ 3.1s] status after crash: processing
[ 3.6s] lease: processing | 1 | t
[ 11.3s] queues (unacked message returned): name type durable messages_ready messages_unacknowledged
attachment.jobs quorum true 1 0
attachment.jobs.dlq quorum true 0 0
[ 11.3s] $ docker compose start worker
[ 15.8s] GET attachment -> status=processing error_code=None
[ 18.8s] GET attachment -> status=queued error_code=None
[ 19.8s] GET attachment -> status=processing error_code=None
[ 20.8s] GET attachment -> status=ready error_code=None
[ 20.8s] original -> 200 sha256 matches upload: True
[ 20.9s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True
[ 20.9s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True
[ 20.9s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True
[ 21.1s] job: 8922e0b2-1b70-4294-81f5-75dbb82b1006 | ready | 2 | 5 |
[ 21.3s] variants rows: 3
[ 21.5s] events: enqueued -> processing -> lease_expired -> processing -> ready
[ 21.9s] worker: job 8922e0b2-1b70-4294-81f5-75dbb82b1006: processing, not due or leased elsewhere, skipped
[ 21.9s] worker: job 8922e0b2-1b70-4294-81f5-75dbb82b1006 attempt 1 (redelivered): skipped
[ 21.9s] worker: job 8922e0b2-1b70-4294-81f5-75dbb82b1006 attempt 2: ready
[ 22.0s] relay: lease expired: 1, stale queued republished: 0
## crash-after-commit
$ python3 scripts/job-scenario.py crash-after-commit
[ 0.1s] user 892084ce-d560-4b81-8a41-29b037a7f501 chat 15fb5c7e-bb70-4945-8ddf-d26d1d3569d3
[ 0.1s] $ docker compose stop worker
[ 0.9s] $ docker compose run --no-deps -e WORKER_FAULT=exit-after-commit worker
[ 2.7s] POST attachment -> 202 status=queued id=377694eb-cef4-4db3-a1e4-af9053e26e70 instance=1e38f40634b0
[ 3.7s] one-off: fault injection: worker killed after commit, before ack
[ 3.8s] one-off process exit code 137 (137 = killed without ack)
[ 4.2s] status after crash: ready staging_key: staging/377694eb-cef4-4db3-a1e4-af9053e26e70
[ 12.2s] queues (unacked message returned): name type durable messages_ready messages_unacknowledged
attachment.jobs quorum true 1 0
attachment.jobs.dlq quorum true 0 0
[ 12.2s] $ docker compose start worker
[ 18.5s] staging_key after redelivery: NULL
[ 18.5s] original -> 200 sha256 matches upload: True
[ 18.5s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True
[ 18.5s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True
[ 18.5s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True
[ 18.7s] job: 4f105bfb-f45c-445f-9bf9-ffaae7c159e3 | ready | 1 | 5 |
[ 18.8s] variants rows: 3
[ 19.0s] events: enqueued -> processing -> ready
[ 19.3s] worker: job 4f105bfb-f45c-445f-9bf9-ffaae7c159e3: ready, not due or leased elsewhere, skipped
[ 19.3s] worker: job 4f105bfb-f45c-445f-9bf9-ffaae7c159e3 attempt 1 (redelivered): skipped
## outbox-gap
$ python3 scripts/job-scenario.py outbox-gap
[ 0.1s] user f6bbc6d7-414b-47ba-a108-ee447cc4e169 chat 9092c599-a754-4f16-8b09-34f630f34c5b
[ 0.1s] $ docker compose stop relay
[ 0.7s] POST attachment -> 202 status=queued id=f92b9390-13c8-472a-a730-b2cd64f31a79 instance=87ae39d58075
[ 1.0s] outbox after COMMIT: 8 | NOT PUBLISHED | 0
[ 8.7s] queues: name type durable messages_ready messages_unacknowledged
attachment.jobs quorum true 0 0
attachment.jobs.dlq quorum true 0 0
[ 8.7s] $ docker compose kill api
[ 9.3s] API killed (SIGKILL) after COMMIT, nothing was published
[ 9.3s] $ docker compose start api
[ 17.4s] status after API restart: queued
[ 17.4s] $ docker compose start relay
[ 22.0s] GET attachment -> status=queued error_code=None
[ 24.1s] GET attachment -> status=ready error_code=None
[ 24.2s] outbox after relay recovery: 8 | 2026-11-16 14:03:19.506+00 | 1
[ 24.2s] original -> 200 sha256 matches upload: True
[ 24.2s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True
[ 24.3s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True
[ 24.3s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True
[ 24.4s] job: 0ca33e89-2981-4966-93fd-1d591dd83973 | ready | 1 | 5 |
[ 24.6s] variants rows: 3
[ 24.8s] events: enqueued -> processing -> ready
## relay-crash
$ python3 scripts/job-scenario.py relay-crash
[ 0.1s] user a1d5a875-1b08-48c9-926a-b7c0089f274c chat 660bdc6f-b600-44d4-ad7e-cc888fbe1413
[ 0.1s] $ docker compose stop relay
[ 1.0s] $ docker compose run --no-deps -e RELAY_FAULT=exit-after-confirm relay
[ 3.0s] POST attachment -> 202 status=queued id=fb12fbe4-8102-43a9-92b5-bb331ecf9b9d instance=1e38f40634b0
[ 3.6s] one-off: published 1 job message(s), broker confirmed
[ 3.6s] one-off: fault injection: exit after broker confirm, before outbox is marked
[ 3.7s] one-off process exit code 137 (137 = killed without ack)
[ 4.1s] outbox after relay crash: 9 | NOT MARKED | 0
[ 4.1s] $ docker compose start relay
[ 8.8s] GET attachment -> status=ready error_code=None
[ 11.9s] outbox after relay restart: 9 | 2026-11-16 14:03:31.241+00 | 1
[ 12.0s] original -> 200 sha256 matches upload: True
[ 12.0s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True
[ 12.0s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True
[ 12.0s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True
[ 12.1s] job: 1ef3a3cd-134f-47b7-83e4-fc74dc77ae29 | ready | 1 | 5 |
[ 12.3s] variants rows: 3
[ 12.4s] events: enqueued -> processing -> ready
[ 12.6s] worker: job 1ef3a3cd-134f-47b7-83e4-fc74dc77ae29 attempt 1: ready
[ 12.6s] worker: job 1ef3a3cd-134f-47b7-83e4-fc74dc77ae29: ready, not due or leased elsewhere, skipped
[ 12.6s] worker: job 1ef3a3cd-134f-47b7-83e4-fc74dc77ae29 attempt 1: skipped
## retry-replay
$ python3 scripts/job-scenario.py retry-replay
[ 0.1s] user 766c68fb-94b6-4104-ac84-5166f401ee4f chat e9627c1d-9123-4962-9eed-d7a8282742b3
[ 0.1s] $ docker compose stop worker
[ 0.6s] POST attachment -> 202 status=queued id=5b6058ab-2875-47a3-9458-0f266742fd97 instance=1e38f40634b0
[ 0.6s] $ docker compose stop s3
[ 1.2s] $ docker start worker (without dependencies)
[ 1.6s] GET attachment -> status=queued error_code=None
[ 2.6s] GET attachment -> status=processing error_code=None
[ 3.6s] GET attachment -> status=queued error_code=None
[ 4.6s] GET attachment -> status=processing error_code=None
[ 5.6s] GET attachment -> status=queued error_code=None
[ 6.6s] GET attachment -> status=processing error_code=None
[ 7.6s] GET attachment -> status=queued error_code=None
[ 10.7s] GET attachment -> status=processing error_code=None
[ 11.7s] GET attachment -> status=queued error_code=None
[ 19.7s] GET attachment -> status=processing error_code=None
[ 20.7s] GET attachment -> status=failed error_code=retry_exhausted
[ 20.7s] POST message with 1 attachment(s) -> 409 id=None
[ 20.7s] failed attachment in a new message -> 409
[ 20.7s] retries:
[ 20.9s] 1 | enqueued | | 14:03:34.662
[ 20.9s] 1 | processing | | 14:03:36.116
[ 20.9s] 1 | retry_scheduled | temporary failure: ApiError; next attempt 2 in 533 ms | 14:03:37.143
[ 20.9s] 2 | processing | | 14:03:37.813
[ 20.9s] 2 | retry_scheduled | temporary failure: ApiError; next attempt 3 in 1378 ms | 14:03:38.824
[ 20.9s] 3 | processing | | 14:03:40.337
[ 20.9s] 3 | retry_scheduled | temporary failure: ApiError; next attempt 4 in 2625 ms | 14:03:41.346
[ 20.9s] 4 | processing | | 14:03:44.387
[ 20.9s] 4 | retry_scheduled | temporary failure: ApiError; next attempt 5 in 7110 ms | 14:03:45.394
[ 20.9s] 5 | processing | | 14:03:52.956
[ 20.9s] 5 | failed | retry_exhausted: temporary failure: ApiError | 14:03:53.967
[ 20.9s] $ replay.js --list
[ 21.2s] replay: {"job_id":"fdb3f527-6383-4917-a690-5a9c75bb3c09","attachment_id":"5b6058ab-2875-47a3-9458-0f266742fd97","error_code":"retry_exhausted","attempt":5,"last_error":"temporary failure: ApiError","finished_at":"2026-11-16T14:03:53.967Z"}
[ 21.2s] $ docker compose start s3
[ 23.3s] $ replay.js 5b6058ab-2875-47a3-9458-0f266742fd97
[ 23.7s] replay: {"id":"5b6058ab-2875-47a3-9458-0f266742fd97","job_id":"fdb3f527-6383-4917-a690-5a9c75bb3c09","result":"replayed"}
[ 23.7s] GET attachment -> status=queued error_code=None
[ 24.7s] GET attachment -> status=ready error_code=None
[ 24.7s] original -> 200 sha256 matches upload: True
[ 24.7s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True
[ 24.7s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True
[ 24.7s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True
[ 24.7s] $ replay.js 5b6058ab-2875-47a3-9458-0f266742fd97 (already ready)
[ 25.0s] replay: {"id":"5b6058ab-2875-47a3-9458-0f266742fd97","job_id":"fdb3f527-6383-4917-a690-5a9c75bb3c09","result":"already_ready"}
[ 25.2s] job: fdb3f527-6383-4917-a690-5a9c75bb3c09 | ready | 1 | 5 |
[ 25.3s] variants rows: 3
[ 25.5s] events: enqueued -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> failed -> replayed -> processing -> ready
## broker
$ python3 scripts/job-scenario.py broker
[ 1.8s] consumers: queue_name ack_required prefetch_count
attachment.jobs true 2
[ 2.0s] worker limits: cpus=1000000000 memory=805306368
[ 2.3s] malformed message published
[ 10.1s] queues: name type durable messages_ready messages_unacknowledged
attachment.jobs quorum true 0 0
attachment.jobs.dlq quorum true 1 0
[ 10.2s] worker: malformed job message moved to dead letter queue
## Итог по всем заданиям стенда
$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT status, count(*) FROM attachment_jobs GROUP BY status -c SELECT count(*) AS unpublished_outbox FROM outbox WHERE published_at IS NULL -c SELECT count(*) AS staging_left_on_ready FROM attachments WHERE status = 'ready' AND staging_key IS NOT NULL
status | count
--------+-------
ready | 9
(1 row)
unpublished_outbox
--------------------
0
(1 row)
staging_left_on_ready
-----------------------
0
(1 row)
## Последний проход reconciler
{"mode":"apply","grace_seconds":3600,"staging_expired":0,"scanned":0,"fresh_skipped":0,"referenced":0,"orphans":0,"deleted":0,"failed":0,"orphan_keys":[],"duration_ms":382}
+26
View File
@@ -0,0 +1,26 @@
# make test-persistence: restart.sh перезапускает postgres, redis, s3, rabbitmq, api, lb с сохранением volumes
# date: 2026-11-16T14:00:52Z
# commit: 484119a
## до
/messenger-lab5-api-1 running started=2026-11-16T13:59:10.816425606Z
/messenger-lab5-api-2 running started=2026-11-16T13:59:10.479356802Z
/messenger-lab5-lb-1 running started=2026-11-16T13:59:16.591296088Z
/messenger-lab5-postgres-1 running started=2026-11-16T13:59:00.844067952Z
/messenger-lab5-rabbitmq-1 running started=2026-11-16T13:59:00.836854706Z
/messenger-lab5-redis-1 running started=2026-11-16T13:59:00.841606284Z
/messenger-lab5-s3-1 running started=2026-11-16T13:59:00.820149618Z
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
## после
/messenger-lab5-api-1 running started=2026-11-16T14:00:58.355736385Z
/messenger-lab5-api-2 running started=2026-11-16T14:00:58.472999625Z
/messenger-lab5-lb-1 running started=2026-11-16T14:00:55.123503698Z
/messenger-lab5-postgres-1 running started=2026-11-16T14:00:54.940878738Z
/messenger-lab5-rabbitmq-1 running started=2026-11-16T14:00:56.122220193Z
/messenger-lab5-redis-1 running started=2026-11-16T14:00:54.826444235Z
/messenger-lab5-s3-1 running started=2026-11-16T14:00:54.598200795Z
+37
View File
@@ -0,0 +1,37 @@
# S3 (минимум lab4): идемпотентный bootstrap, приватность мимо API, права пользователя API
# date: 2026-11-16T14:01:31Z
# commit: 484119a
$ docker compose run --rm --no-deps -T s3-init
Bucket created successfully `root/messenger-attachments`.
Access permission for `root/messenger-attachments` is set to `private`
Created policy `messenger-api` successfully.
bucket messenger-attachments ready
$ docker compose run --rm --no-deps -T s3-init
Bucket created successfully `root/messenger-attachments`.
Access permission for `root/messenger-attachments` is set to `private`
Created policy `messenger-api` successfully.
bucket messenger-attachments ready
$ sh scripts/check-s3.sh
## S3 не опубликован наружу, консоль выключена
s3 ports=9000/tcp
MINIO_BROWSER=off
## Права пользователя API: только свой bucket
PUT в свой bucket -> allowed
GET из своего bucket -> allowed
создание другого bucket -> denied
GET из другого bucket -> denied
PUT в другой bucket -> denied
изменение политики bucket -> denied
администрирование пользователей -> denied
## Анонимный доступ напрямую к S3, мимо API
GET messenger-attachments/<object> -> 403
GET messenger-attachments/ -> 403
PUT messenger-attachments/anon.txt -> 403
PASS: bucket приватный, у API нет прав вне своего bucket
+22
View File
@@ -0,0 +1,22 @@
# Публичные проверки через LB; разные реплики обслуживают одну сессию
# date: 2026-11-16T14:00:47Z
# commit: 484119a
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
$ make test
python3 tests/smoke.py --base-url "http://lb:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
$ python3 scripts/probe.py instances 6
register -> 201
login -> 201 expires_at: 2026-11-16T15:00:52.043Z
GET /api/v1/users/me -> 200 X-Instance-Id: 87ae39d58075
GET /api/v1/users/me -> 200 X-Instance-Id: 1e38f40634b0
GET /api/v1/users/me -> 200 X-Instance-Id: 87ae39d58075
GET /api/v1/users/me -> 200 X-Instance-Id: 1e38f40634b0
GET /api/v1/users/me -> 200 X-Instance-Id: 87ae39d58075
GET /api/v1/users/me -> 200 X-Instance-Id: 1e38f40634b0
+349
View File
@@ -0,0 +1,349 @@
# Собственные e2e-тесты (PostgreSQL + Redis + MinIO из compose.test.yaml)
# date: 2026-11-16T13:59:44Z
# commit: 484119a
$ docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose
Network messenger-lab5-test_default Creating
Network messenger-lab5-test_default Created
Container messenger-lab5-test-postgres-1 Creating
Container messenger-lab5-test-s3-1 Creating
Container messenger-lab5-test-redis-1 Creating
Container messenger-lab5-test-redis-1 Created
Container messenger-lab5-test-postgres-1 Created
Container messenger-lab5-test-s3-1 Created
Container messenger-lab5-test-s3-1 Starting
Container messenger-lab5-test-postgres-1 Starting
Container messenger-lab5-test-redis-1 Starting
Container messenger-lab5-test-postgres-1 Started
Container messenger-lab5-test-s3-1 Started
Container messenger-lab5-test-redis-1 Started
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "messenger_test", schema "public" at "postgres:5432"
5 migrations found in prisma/migrations
Applying migration `20261021000000_init`
Applying migration `20261021010000_auth_sessions`
Applying migration `20261101000000_idempotency_keys`
Applying migration `20261105000000_attachments`
Applying migration `20261115000000_attachment_jobs`
The following migration(s) have been applied:
migrations/
└─ 20261021000000_init/
└─ migration.sql
└─ 20261021010000_auth_sessions/
└─ migration.sql
└─ 20261101000000_idempotency_keys/
└─ migration.sql
└─ 20261105000000_attachments/
└─ migration.sql
└─ 20261115000000_attachment_jobs/
└─ migration.sql
All migrations have been successfully applied.
[Nest] 101 - 11/16/2026, 2:00:26 PM  ERROR [S3Service] get staging/4b23a90d-13cf-4aee-8879-49e2ad11bdf3 failed: NoSuchKey
PASS test/api.e2e-spec.ts (16.705 s)
API мессенджера (e2e) — граничные случаи сверх публичного smoke
POST /api/v1/users
✓ отклоняет некорректный JSON с кодом 400 (82 ms)
✓ отклоняет тело с лишними полями (40 ms)
✓ отклоняет username с заглавными буквами (5 ms)
✓ отклоняет display_name из одних пробелов (4 ms)
✓ отклоняет дубликат username с кодом 409 (176 ms)
✓ никогда не возвращает поле пароля или его хэша (35 ms)
✓ отклоняет username короче 3 символов (3 ms)
✓ отклоняет username длиннее 32 символов (3 ms)
✓ отклоняет username с недопустимыми символами (дефис) (2 ms)
✓ принимает username ровно на границах длины 3 и 32 символа (59 ms)
✓ отклоняет display_name длиннее 100 Unicode code points (3 ms)
✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (30 ms)
✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (2 ms)
контроль доступа
✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (5 ms)
✓ возвращает 404 (не 403), когда чат запрашивает не его участник (229 ms)
✓ отклоняет создание чата, если вызывающий не входит в member_ids (162 ms)
✓ отклоняет создание чата с дублирующимися member_ids (117 ms)
✓ считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре (122 ms)
✓ принимает ровно 100 участников и отклоняет 101 (135 ms)
✓ отклоняет создание чата с неизвестным участником (85 ms)
✓ отклоняет создание чата с пустым/пробельным title (105 ms)
✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (71 ms)
✓ возвращает 404 для корректного по формату, но несуществующего chat_id (89 ms)
GET /api/v1/chats (пагинация)
✓ использует limit=50 по умолчанию, если limit не передан (75 ms)
✓ отклоняет нечисловой limit (68 ms)
✓ отклоняет limit=0 (101 ms)
✓ отклоняет повторённые limit и cursor (101 ms)
✓ отклоняет cursor, не являющийся корректным base64url JSON (111 ms)
✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (138 ms)
✓ обходит весь список чатов по страницам без пропусков и дублей (130 ms)
сообщения
✓ не принимает sender_id, переданный клиентом (154 ms)
✓ считает attachment_ids: [] равным отсутствию поля, неизвестный ID — 404, неверный тип — 400 (290 ms)
✓ отклоняет пустое сообщение (562 ms)
✓ отклоняет сообщение из одних пробелов (266 ms)
✓ отклоняет отправку в чат, где вызывающий не участник (202 ms)
✓ отклоняет limit=0 при чтении истории (141 ms)
✓ отклоняет limit=101 при чтении истории (148 ms)
✓ отклоняет нечисловой limit (145 ms)
✓ отклоняет текст сообщения длиннее 4000 Unicode code points (129 ms)
✓ принимает текст сообщения ровно из 4000 Unicode code points (135 ms)
✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (142 ms)
✓ отклоняет cursor, не являющийся корректным base64url JSON (143 ms)
✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (149 ms)
✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (65 ms)
✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (64 ms)
✓ отклоняет cursor, взятый из другого чата (239 ms)
✓ обходит всю историю по страницам без пропусков и дублей (324 ms)
X-Request-Id
✓ присутствует и уникален для независимых запросов (3 ms)
✓ совпадает с request_id внутри тела ошибки (3 ms)
[Nest] 101 - 11/16/2026, 2:00:32 PM  ERROR [S3Service] get staging/fa865a7e-c789-461e-a013-75a790fc46ba failed: NoSuchKey
[Nest] 101 - 11/16/2026, 2:00:32 PM  ERROR [S3Service] get staging/e8cbd67b-3c57-4ac3-a928-885e2d4abed8 failed: NoSuchKey
PASS test/jobs.e2e-spec.ts (17.62 s)
Фоновая обработка вложений (e2e)
до обработки
✓ queued: метаданные доступны, content любого варианта — 409, сообщение с вложением создаётся (191 ms)
результат worker
✓ ready: оригинал неизменен, thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP без увеличения (225 ms)
✓ маленький исходник не увеличивается в thumbnail/optimized, crop — увеличивается (188 ms)
✓ прозрачность компонуется на белый, EXIF orientation применяется (364 ms)
✓ worker ограничивает пиксели до распаковки: превышение — InvalidImageError (17 ms)
✓ размеры считаются целочисленно: 319×200 → 256×160, перебор совпадает с точной формулой (3109 ms)
✓ размеры округляются вниз, минимум 1 px (1 ms)
идемпотентность и повторная доставка
✓ повтор уже ready-задания — no-op: второго набора вариантов нет, объекты не меняются (115 ms)
✓ пока lease действует, второй обработчик того же job не запускается (93 ms)
✓ worker упал после записи объектов, до COMMIT/ack: lease истекает, повтор завершает тот же результат (171 ms)
✓ worker упал после COMMIT, до ack: повтор — no-op, staging убирается при повторной доставке (118 ms)
✓ сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз (103 ms)
✓ устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются (50 ms)
ошибки, повторы и replay
✓ временная ошибка S3: повтор с backoff, до срока задание не берётся, затем ready (176 ms)
✓ попытки исчерпаны — failed retry_exhausted; replay явно возвращает в очередь и доводит до ready (389 ms)
✓ lease истёк на последней попытке — failed retry_exhausted, а не вечный processing (128 ms)
✓ replay и очистка staging не теряют исходник ни при каком порядке (237 ms)
✓ replay задания в очереди не создаёт дубль (50 ms)
✓ нераспаковываемое изображение — постоянная ошибка: сразу failed invalid_image без повторов (112 ms)
✓ staging подменён — failed checksum_mismatch; staging пропал — failed staging_missing (234 ms)
✓ превышение времени обработки — временная ошибка с повтором (115 ms)
формат сообщения и backoff
✓ сообщение соответствует jobs.schema.json, лишние/неверные поля отклоняются (2 ms)
✓ backoff растёт экспоненциально с jitter и ограничен сверху
console.warn
An error was encountered in a non-retryable streaming request.
213 | private async guard<T>(action: string, run: () => Promise<T>): Promise<T> {
214 | try {
> 215 | return await run();
| ^
216 | } catch (error) {
217 | const reason = error instanceof Error ? error.name : 'unknown error';
218 | this.logger.error(`${action} failed: ${reason}`);
at ../node_modules/@smithy/middleware-retry/dist-cjs/index.js:329:125
at ../node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/index.js:263:18
at ../node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js:110:22
at ../node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js:138:14
at ../node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js:34:22
at S3Service.guard (../src/storage/s3.service.ts:215:11)
at S3Service.putFile (../src/storage/s3.service.ts:64:3)
at AttachmentsService.store (../src/attachments/attachments.service.ts:153:3)
at AttachmentsService.upload (../src/attachments/attachments.service.ts:75:11)
at AttachmentsController.upload (../src/attachments/attachments.controller.ts:36:22)
at ../node_modules/@nestjs/core/router/router-execution-context.js:46:28
at Object.<anonymous> (../node_modules/@nestjs/core/router/router-proxy.js:9:17)
[Nest] 107 - 11/16/2026, 2:00:32 PM  ERROR [S3Service] put staging/08d3b29a-19ff-4b20-a40c-ad52e30606d3 failed: Error
[Nest] 107 - 11/16/2026, 2:00:32 PM  ERROR [HttpExceptionFilter] POST /api/v1/chats/89c9a591-2904-4f34-ae01-893a3c1d04cc/attachments?filename=a.png -> 503: object storage unavailable
[Nest] 107 - 11/16/2026, 2:00:33 PM  ERROR [HttpExceptionFilter] POST /api/v1/chats/89c9a591-2904-4f34-ae01-893a3c1d04cc/attachments?filename=sample.png -> 500: Internal server error
[Nest] 107 - 11/16/2026, 2:00:33 PM  ERROR [AttachmentsService] metadata insert failed for staging/b4facc6e-0d5d-44c1-bb7c-fb0b27446329
[Nest] 107 - 11/16/2026, 2:00:33 PM  ERROR [HttpExceptionFilter] POST /api/v1/chats/89c9a591-2904-4f34-ae01-893a3c1d04cc/attachments?filename=sample.png -> 503: database unavailable
[Nest] 107 - 11/16/2026, 2:00:33 PM  ERROR [HttpExceptionFilter] POST /api/v1/chats/89c9a591-2904-4f34-ae01-893a3c1d04cc/attachments?filename=sample.png -> 503: database unavailable
PASS test/attachments.e2e-spec.ts (18.099 s)
Загрузка вложений (e2e)
успешная загрузка
✓ возвращает 202 Attachment queued по контракту, staging и задание сохранены до ответа (252 ms)
✓ принимает реальный JPEG (61 ms)
✓ игнорирует параметры и регистр Content-Type (31 ms)
✓ принимает файл ровно 10 MiB, filename ровно 255 символов и PNG с байтами после IEND (551 ms)
✓ принимает ровно 40 млн пикселей (3511 ms)
порядок проверок и доступ
✓ без токена — 401 раньше любых проверок содержимого (21 ms)
✓ посторонний и несуществующий чат — одинаковый 404, чужой файл не сохраняется (14 ms)
✓ неверный UUID чата — 400 (3 ms)
filename
✓ отсутствует — 400 (5 ms)
✓ пустой — 400 (4 ms)
✓ только пробелы — 400 (4 ms)
✓ 256 символов — 400 (5 ms)
✓ путь через / — 400 (4 ms)
✓ путь через \ — 400 (4 ms)
✓ NUL — 400 (4 ms)
✓ перевод строки — 400 (5 ms)
✓ DEL — 400 (6 ms)
✓ C1 U+0085 — 400 (4 ms)
✓ разделитель строк U+2028 — 400 (3 ms)
✓ повторённый параметр — 400 (5 ms)
тип содержимого
✓ Content-Type text/plain — 415 (4 ms)
✓ Content-Type application/json — 415 (32 ms)
✓ Content-Type application/octet-stream — 415 (4 ms)
✓ Content-Type multipart/form-data; boundary=x — 415 (4 ms)
✓ Content-Type image/gif — 415 (3 ms)
✓ Content-Type image/webp — 415 (3 ms)
✓ без Content-Type — 415 (4 ms)
✓ подмена MIME в обе стороны и чужие форматы — 415 (42 ms)
✓ пустое тело — 400 (12 ms)
повреждённые изображения
✓ PNG: первые 33 байта sample.png — 415 (5 ms)
✓ PNG: половина файла — 415 (5 ms)
✓ PNG: без последних 20 байт — 415 (7 ms)
✓ PNG: без IEND — 415 (5 ms)
✓ PNG: неверный CRC — 415 (9 ms)
✓ PNG: фильтр строки 5 — 415 (7 ms)
✓ PNG: фильтр строки 255 — 415 (14 ms)
✓ PNG: неверный фильтр в последней строке — 415 (17 ms)
✓ PNG: мусор в IDAT с верным CRC — 415 (9 ms)
✓ PNG: данных меньше, чем строк — 415 (10 ms)
✓ PNG: палитра на 257 записей — 415 (9 ms)
✓ JPEG: все повреждения — 415 (47 ms)
лимиты
✓ 10 MiB + 1 байт — 413 и без чтения объявленного тела (328 ms)
✓ превышение при chunked без Content-Length — 413 (401 ms)
✓ превышение лимита пикселей — 413 до декодирования (19 ms)
✓ оборванная загрузка не оставляет временных файлов и строк в БД (806 ms)
отказы
✓ S3 недоступен — 503 с заголовками, метаданные не создаются (175 ms)
✓ явный отказ транзакции после PUT удаляет объект staging (70 ms)
✓ необработанная ошибка PostgreSQL при INSERT — 503, объект не удаляется (91 ms)
✓ при неясном исходе COMMIT объект не удаляется (43 ms)
[Nest] 100 - 11/16/2026, 2:00:34 PM  ERROR [S3Service] get attachments/36942ee7-b7cb-4da2-8782-d6a65b8052db/original failed: Error
[Nest] 100 - 11/16/2026, 2:00:34 PM  ERROR [HttpExceptionFilter] GET /api/v1/attachments/36942ee7-b7cb-4da2-8782-d6a65b8052db/content -> 503: object storage unavailable
[Nest] 100 - 11/16/2026, 2:00:34 PM  ERROR [S3Service] get attachments/ad6f9273-c285-46c2-896c-6fcfd4b85570/original failed: NoSuchKey
[Nest] 100 - 11/16/2026, 2:00:34 PM  ERROR [HttpExceptionFilter] GET /api/v1/attachments/ad6f9273-c285-46c2-896c-6fcfd4b85570/content -> 500: Internal server error
[Nest] 101 - 11/16/2026, 2:00:34 PM  ERROR [HttpExceptionFilter] GET /health/ready -> 503: object storage unavailable
PASS test/reconciler.e2e-spec.ts
Сверка объектов S3 с метаданными (e2e)
✓ dry-run сообщает о сироте и ничего не удаляет, apply удаляет, повторный запуск ничего не делает (67 ms)
✓ не трогает свежий объект внутри grace period (20 ms)
✓ не трогает старый объект, на который есть метаданные (47 ms)
✓ при отказе PostgreSQL проход прерывается и ничего не удаляет (30 ms)
✓ сбой удаления считается и повторяется на следующем проходе (68 ms)
✓ обходит все страницы листинга (84 ms)
✓ реальная загрузка остаётся доступной после сверки всего bucket префикса вложений (187 ms)
✓ после grace period объекты вложения и staging в очереди не считаются сиротами (239 ms)
✓ staging failed-вложения удаляется после срока хранения (184 ms)
✓ объекты вариантов без строк у существующего вложения не удаляются: replay после сверки доводит до ready (416 ms)
✓ staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения (176 ms)
Готовность при отказе S3 (e2e)
✓ ready — 503 с заголовками за короткое время, live и core — 200 (74 ms)
✓ при рабочем S3 ready — 200 (73 ms)
PASS test/contract.e2e-spec.ts
Все ответы соответствуют контракту: коды, схемы, заголовки (e2e)
✓ health, пользователи и сессии (406 ms)
✓ чаты и сообщения (241 ms)
✓ вложения во всех состояниях (804 ms)
✓ каждая операция контракта вызвана хотя бы раз (1 ms)
PASS test/auth.e2e-spec.ts
Аутентификация и сессии (e2e)
регистрация
✓ требует password (25 ms)
✓ отклоняет password короче 12 code points (6 ms)
✓ хранит пароль как Argon2id-хеш, а не открытым текстом (130 ms)
POST /api/v1/auth/sessions
✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (121 ms)
✓ принимает пароль с двоеточием и не-ASCII символами (73 ms)
✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (128 ms)
✓ отклоняет JSON body при входе даже с верным Basic (69 ms)
✓ отвечает 401 без заголовка Authorization (2 ms)
защищённые endpoint
✓ не принимают Basic (104 ms)
✓ не принимают X-User-Id сам по себе (164 ms)
✓ игнорируют X-User-Id рядом с Bearer (236 ms)
✓ отвечают 401 на неизвестный токен (4 ms)
DELETE /api/v1/auth/sessions/current
✓ отзывает только текущий токен: 204, затем 401 на повтор (130 ms)
PASS test/attachment-access.e2e-spec.ts (6.765 s)
Скачивание и привязка вложений (e2e)
чтение
✓ участник получает метаданные и оригинал побайтно (257 ms)
✓ JPEG отдаётся с истинным Content-Type (215 ms)
✓ посторонний и неизвестный ID получают одинаковый 404 (200 ms)
✓ UUID nil корректного формата — 404, а не 400 (23 ms)
✓ UUID v7 корректного формата — 404, а не 400 (23 ms)
✓ без токена 401, неверный UUID 400 (103 ms)
✓ variant: original явно, отсутствующий 404, неизвестный и повторённый 400 (162 ms)
✓ нет доступа к S3 — метаданные 200, content 503 с заголовками (437 ms)
✓ объект пропал из S3 — 500 без внутренних деталей (215 ms)
attachment_ids в сообщениях
✓ text="" с вложением принимается, Message читается вторым участником (175 ms)
✓ порядок [B, A] сохраняется в ответе, истории и повторе; перестановка с тем же ключом — 409 (314 ms)
✓ отсутствующий attachment_ids и [] равны при повторе, изменение списка — 409 (176 ms)
✓ вложение другого чата и неизвестное — одинаковый 404, сообщение не создаётся (214 ms)
✓ смесь своего и чужого вложения — 404 (364 ms)
✓ посторонний не может отправить вложение в чужой чат (176 ms)
✓ любой участник может сослаться на вложение чата, вложение можно использовать повторно (222 ms)
✓ ровно 10 вложений принимается, 11 — 400 (784 ms)
✓ UUID в другом регистре — тот же ID и дубль (166 ms)
✓ text отсутствует — 400 (132 ms)
✓ text null — 400 (112 ms)
✓ attachment_ids null — 400 (169 ms)
✓ attachment_ids строка — 400 (86 ms)
✓ элемент не UUID — 400 (102 ms)
✓ элемент число — 400 (105 ms)
✓ дубликат — 400 (173 ms)
✓ пустой текст без вложений — 400 (241 ms)
✓ пробельный текст без вложений — 400 (217 ms)
[Nest] 107 - 11/16/2026, 2:00:40 PM  ERROR [HttpExceptionFilter] DELETE /api/v1/auth/sessions/current -> 503: session cache unavailable
PASS test/idempotency.e2e-spec.ts
Идемпотентность отправки и X-Instance-Id (e2e)
✓ требует Idempotency-Key правильного формата (157 ms)
✓ повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение (112 ms)
✓ тот же ключ с другим телом — 409, сообщение не создаётся (101 ms)
✓ 20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение (411 ms)
✓ область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим (265 ms)
✓ повтор заново проверяет сессию (160 ms)
✓ после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново (1762 ms)
✓ X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе (76 ms)
[Nest] 107 - 11/16/2026, 2:00:41 PM  ERROR [HttpExceptionFilter] DELETE /api/v1/auth/sessions/current -> 503: session cache unavailable
PASS test/concurrency.e2e-spec.ts
Безопасность при конкурентном доступе (e2e)
✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (1656 ms)
✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (310 ms)
[Nest] 107 - 11/16/2026, 2:00:41 PM  ERROR [HttpExceptionFilter] GET /health/ready -> 503: database unavailable
[Nest] 107 - 11/16/2026, 2:00:41 PM  ERROR [HttpExceptionFilter] GET /api/v1/chats -> 503: database unavailable
[Nest] 107 - 11/16/2026, 2:00:41 PM  ERROR [HttpExceptionFilter] GET /api/v1/chats -> 503: database unavailable
[Nest] 107 - 11/16/2026, 2:00:41 PM  ERROR [HttpExceptionFilter] POST /api/v1/users -> 503: database unavailable
[Nest] 107 - 11/16/2026, 2:00:41 PM  ERROR [HttpExceptionFilter] GET /api/v1/chats -> 500: Internal server error
PASS test/failures.e2e-spec.ts (5.415 s)
Уровень 4: expiry, отказы зависимостей, rollback (e2e)
✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (2726 ms)
✓ без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва (440 ms)
✓ logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше (676 ms)
✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (203 ms)
✓ неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id (105 ms)
✓ откатывает создание чата целиком, если один из участников не существует (258 ms)
PASS test/docs.e2e-spec.ts
Swagger UI и примеры (e2e)
✓ отдаёт Swagger UI и документ контракта со всеми путями (31 ms)
✓ каждый пример запроса и ответа проходит JSON Schema контракта (213 ms)
Test Suites: 11 passed, 11 total
Tests: 196 passed, 196 total
Snapshots: 0 total
Time: 29.417 s
Ran all test suites.