ЛР 4: S3-хранилище (SeaweedFS) и вложения

This commit is contained in:
kalibr456
2026-10-21 21:25:10 +03:00
parent ec540a1a72
commit 5c3a31db2e
81 changed files with 6847 additions and 25 deletions
+67
View File
@@ -0,0 +1,67 @@
# attachments: lab4: files, limits, damaged images, MIME, filenames, access, attachment_ids
# date: 2026-10-21 21:03:05, commit: 2dbed80
# command: python.exe student-tests/test_attachments.py
# exit code: 0, 4.0 s
sample.png: 111817 bytes, sha256 99ea7533c441..., downloaded by the other member, same bytes
sample.jpg: 1492 bytes, sha256 c310b9a1c208..., downloaded by the other member, same bytes
progressive.jpg: 1081 bytes, sha256 913df01aec84..., downloaded by the other member, same bytes
interlaced.png: 79 bytes, sha256 38149222f78f..., downloaded by the other member, same bytes
1x1.png: 67 bytes, sha256 eaa4a94ea300..., downloaded by the other member, same bytes
PASS: PNG, JPEG, progressive JPEG, interlaced PNG and 1x1 PNG are stored and returned byte for byte
exactly 10485760 bytes (10 MiB) -> 201
10485761 bytes (10 MiB + 1) with Content-Length -> 413 before reading the body
PASS: the 10 MiB limit is exact
12 MiB without Content-Length (chunked) -> 413 as soon as the 10 MiB limit is passed
PASS: oversized streamed body is cut off, the API keeps working
8000x5000 = 40 000 000 pixels (38957 bytes compressed) -> 201 5ffe6847
8001x5000 = 40 005 000 pixels (38962 bytes) -> 413
header claims 100000x100000 in 65 bytes -> 413 from the header, nothing is decoded
PASS: pixel limit is checked before decompression
PNG cut in half (55908 bytes, image/png) -> 415
PNG without IEND (111805 bytes, image/png) -> 415
PNG with a flipped byte in IDAT (CRC mismatch) (111817 bytes, image/png) -> 415
PNG with garbage after IEND (111824 bytes, image/png) -> 415
PNG signature only (8 bytes, image/png) -> 415
PNG with less pixel data than the header says (68 bytes, image/png) -> 415
JPEG cut in half (746 bytes, image/jpeg) -> 415
JPEG header only (20 bytes, image/jpeg) -> 415
random bytes (1600 bytes, image/png) -> 415
plain text (28 bytes, image/jpeg) -> 415
empty body -> 400
PASS: damaged and foreign files are rejected with 415, never 500
PNG bytes sent as image/jpeg -> 415
JPEG bytes sent as image/png -> 415
GIF bytes sent as image/png -> 415
PNG sent as image/gif -> 415
PNG sent as text/html -> 415
PNG sent as application/octet-stream -> 415
PNG sent as multipart/form-data -> 415
PNG sent as 'IMAGE/PNG; charset=binary' -> 201, stored as image/png
PASS: the type is taken from the content; a declared type that does not match is refused
13 dangerous or invalid names (path, slashes, NUL, control characters, empty, 256 chars) -> 400
no filename -> 400
Unicode, 255 chars, leading dots, %20 and ? are kept as display names only
PASS: filename never becomes a path; dangerous names are refused
outsider -> 404 for metadata and bytes (same as a non-existent id); no token -> 401; bad UUID -> 400
upload into someone else's / unknown chat -> 404, without token -> 401
variant=thumbnail -> 400 (not in the lab4 contract), variant=original -> 200
PASS: only chat members can see an attachment
text='' with 2 attachments -> 201, order kept; any member may attach a file uploaded by another member
history returns attachment_ids for every message, [] for a message without files; reuse is allowed
attachment of another chat (author is a member of both) -> 404
own + foreign attachment -> 404
unknown attachment_id -> 404
outsider referencing an attachment of the chat -> 404
duplicate ids -> 400
11 ids -> 400
bad UUID -> 400
empty text without attachments -> 400
whitespace text without attachments -> 400
PASS: only attachments of the same chat can be linked; rejected requests change nothing
same key + same attachments -> same 201; other attachments -> 409; missing field == []
PASS: Idempotency-Key covers attachment_ids
sent 1.1 MB of a declared 5 MB body and closed the connection
the API keeps serving uploads; nothing of the aborted request is visible (DB/S3 side is checked by test_consistency.py)
PASS: an interrupted upload is dropped
11 passed, 0 failed
+18
View File
@@ -0,0 +1,18 @@
# balancing: balancing, shared sessions/data/files, X-Instance-Id
# date: 2026-10-21 21:08:50, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_balancing.py
# exit code: 0, 1.9 s
20 x GET /users/me with one token -> replicas: {'6128eb268c44': 10, '11a93acecaca': 10}
PASS: one session works on every replica, no second login (sessions are shared in Redis)
message written by 11a93acecaca; read back by ['11a93acecaca', '6128eb268c44']
PASS: a message written via one replica is read right away via another (shared PostgreSQL)
logout on 6128eb268c44; old token then rejected by ['11a93acecaca', '6128eb268c44']
PASS: logout on one replica revokes the session on all of them
first POST on 6128eb268c44 -> 201 296cb1bf-8c1c-46f2-942a-4865d1b7d6af; same key on 11a93acecaca -> 201 296cb1bf-8c1c-46f2-942a-4865d1b7d6af
PASS: Idempotency-Key is shared: a retry through another replica returns the same message
file uploaded via 6128eb268c44; downloaded byte for byte via ['11a93acecaca', '6128eb268c44']
PASS: a file uploaded through one replica is downloaded through another (shared S3, nothing local)
statuses [200, 200, 201, 400, 401, 404, 409]: every answer has X-Instance-Id of a running container ['11a93acecaca', '6128eb268c44']; api containers: ['11a93acecaca', '6128eb268c44']
PASS: X-Instance-Id is in every response and points to a real container
6 passed, 0 failed
+6
View File
@@ -0,0 +1,6 @@
# check: offline contract check (make check)
# date: 2026-10-21 21:02:57, commit: 2dbed80
# command: python.exe scripts/check_contract.py
# exit code: 0, 0.1 s
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
+47
View File
@@ -0,0 +1,47 @@
# consistency: lab4: aborted upload, crash between S3 and DB, janitor, orphans, S3 outage
# date: 2026-10-21 21:08:14, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_consistency.py
# exit code: 0, 148.7 s
declared 9 000 000 bytes, sent 211817, closed the connection
declared 9 000 000 bytes, sent 3111817, closed the connection
rows in attachments: 32 -> 32; objects in bucket: 31 -> 31
temporary upload files in api containers: {'11a93acecaca': 0, '6128eb268c44': 0} (removed when the request ends)
api containers have no volumes: the original is never stored locally
PASS: an interrupted upload leaves no row, no object and no local file
crash after S3 PUT: row 04aacbf6 state=uploading, object originals/219175ec1d5647f0aeaec84ee8243cb3 exists in S3
the half-written attachment is invisible: GET -> 404, attach to a message -> 404
janitor with default grace (3600 s) right away: {"dry_run": false, "grace_seconds": 3600, "stale_uploads": 0, "stale_uploads_deleted": 0, "objects_scanned": 33, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 1, "seconds": 0.101} -> fresh row and object are kept (the upload might still be running)
row made 2 h old; janitor --dry-run: {"dry_run": true, "grace_seconds": 3600, "stale_uploads": 1, "stale_uploads_deleted": 0, "objects_scanned": 33, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 1, "seconds": 0.092} -> nothing deleted
janitor: {"dry_run": false, "grace_seconds": 3600, "stale_uploads": 1, "stale_uploads_deleted": 1, "objects_scanned": 32, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 1, "seconds": 0.096} -> row and object deleted
janitor again: {"dry_run": false, "grace_seconds": 3600, "stale_uploads": 0, "stale_uploads_deleted": 0, "objects_scanned": 32, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 1, "seconds": 0.103} -> idempotent
the ready attachment of the same chat is untouched
PASS: S3 written but DB not committed -> invisible, reclaimed by janitor only after the grace period
object originals/867f5c5d42bf4bf9973b60ef8856d88f put into the bucket without a row in PostgreSQL
janitor --grace-seconds 3 immediately: {"dry_run": false, "grace_seconds": 3, "stale_uploads": 0, "stale_uploads_deleted": 0, "objects_scanned": 34, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 1, "seconds": 0.102} -> fresh object kept
after 4 s, --dry-run: {"dry_run": true, "grace_seconds": 3, "stale_uploads": 0, "stale_uploads_deleted": 0, "objects_scanned": 34, "orphan_objects": 1, "orphan_objects_deleted": 0, "missing_objects": 1, "seconds": 0.098} -> reported, kept
janitor: {"dry_run": false, "grace_seconds": 3, "stale_uploads": 0, "stale_uploads_deleted": 0, "objects_scanned": 34, "orphan_objects": 1, "orphan_objects_deleted": 1, "missing_objects": 1, "seconds": 0.1} -> orphan deleted
ready attachments older than the grace period are untouched (they have rows)
object of a ready attachment deleted behind the API's back: janitor reports missing_objects=2 and keeps the row; download -> 503 (not 500)
PASS: orphans are found and deleted only after the grace period; missing objects are reported
--- S3 stopped (connection refused / name not resolved): docker compose stop s3
upload -> 503 unavailable in 20141 ms, no storage details in the body
download of an existing file -> 503
metadata, messages (also with an already stored attachment) and /health/ready keep working: S3 is needed only for file bytes
uploading rows of this chat: before 0, after the failed upload 1 (kept as a pointer for janitor if the rollback could not reach S3); not visible through the API
docker compose start s3
after S3 recovery the old file downloads byte for byte
new upload -> 201
janitor after grace period: {"dry_run": false, "grace_seconds": 3600, "stale_uploads": 1, "stale_uploads_deleted": 1, "objects_scanned": 35, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 2, "seconds": 0.099}
PASS: S3 stopped (connection refused / name not resolved) -> 503 for file operations only, no visible half-uploads, everything cleaned up
--- S3 frozen (no answer, timeouts): docker compose pause s3
upload -> 503 unavailable in 14766 ms, no storage details in the body
download of an existing file -> 503
metadata, messages (also with an already stored attachment) and /health/ready keep working: S3 is needed only for file bytes
uploading rows of this chat: before 0, after the failed upload 1 (kept as a pointer for janitor if the rollback could not reach S3); not visible through the API
docker compose unpause s3
after S3 recovery the old file downloads byte for byte
new upload -> 201
janitor after grace period: {"dry_run": false, "grace_seconds": 3600, "stale_uploads": 1, "stale_uploads_deleted": 1, "objects_scanned": 37, "orphan_objects": 0, "orphan_objects_deleted": 0, "missing_objects": 2, "seconds": 0.094}
PASS: S3 frozen (no answer, timeouts) -> 503 for file operations only, no visible half-uploads, everything cleaned up
5 passed, 0 failed
+21
View File
@@ -0,0 +1,21 @@
# db: PostgreSQL: rollback, FK, Argon2id, unique keys, migrations
# date: 2026-10-21 21:09:10, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_db.py
# exit code: 0, 14.2 s
chat with unknown member -> 400; rows with this title: 0; chats without members: 0; chats insert counter: 57 -> 58
PASS: chat row was inserted and then rolled back together with members
direct INSERT of a message from a non-member -> exit code 1: ERROR: insert or update on table "messages" violates foreign key constraint "messages_chat_id_sender_id_fkey"
PASS: the database itself rejects a message from a non-member
stored password: $argon2id$v=19$m=12288,t=3,p=1$... (length 97)
PASS: password is stored as Argon2id hash
unique constraint on users: UNIQUE (username)
PASS: username is unique in the database
applied migrations: 001_init.sql,002_text_as_bytes.sql,003_idempotency.sql,004_attachments.sql; running the migrate service once more
after the second run: 001_init.sql,002_text_as_bytes.sql,003_idempotency.sql,004_attachments.sql; log: Migrations applied: none (schema is up to date)
PASS: migrations are applied once, a repeated run does nothing
api replicas that checked the schema at start: 8; api log lines 'Migrations applied': 0; migrate service: Exited (0) 6 minutes ago
PASS: only the migrate service applies migrations, replicas wait for the schema
unique constraint for Idempotency-Key: UNIQUE (chat_id, sender_id, idempotency_key)
PASS: one message per (chat, sender, Idempotency-Key) is enforced by the database
7 passed, 0 failed
+99
View File
@@ -0,0 +1,99 @@
=== Data volume
messages_total | messages_in_big_chat
----------------+----------------------
20146 | 15000
=== History index
indexdef
----------------------------------------------------------------------------------------
CREATE INDEX messages_history ON public.messages USING btree (chat_id, created_at, id)
=== 1. First page: limit=50, the app asks for 51 rows to know if there is a next page
QUERY PLAN
------------------------------------------------------------------------------------------------
Limit (actual time=0.005..0.011 rows=51 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_history on messages (actual time=0.005..0.008 rows=51 loops=1)
Index Cond: (chat_id = '7c307498-c398-4a1e-be96-13556a559cbf'::uuid)
Buffers: shared hit=5
Planning:
Buffers: shared hit=6
Planning Time: 0.060 ms
Execution Time: 0.020 ms
=== 2. Page after the 10000th message by keyset cursor (this is what the app does)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.005..0.012 rows=51 loops=1)
Buffers: shared hit=6
-> Index Scan using messages_history on messages (actual time=0.005..0.009 rows=51 loops=1)
Index Cond: ((chat_id = '7c307498-c398-4a1e-be96-13556a559cbf'::uuid) AND (ROW(created_at, id) > ROW('2026-09-01 02:46:40+00'::timestamp with time zone, '170ea586-3f7e-4314-a9bf-8e4f394941ac'::uuid)))
Buffers: shared hit=6
Planning Time: 0.044 ms
Execution Time: 0.031 ms
=== 2b. The same page exactly as the app sends it since lab4: with attachment_ids of every message
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.020..0.225 rows=51 loops=1)
Buffers: shared hit=60
-> Index Scan using messages_history on messages m (actual time=0.019..0.222 rows=51 loops=1)
Index Cond: ((chat_id = '7c307498-c398-4a1e-be96-13556a559cbf'::uuid) AND (ROW(created_at, id) > ROW('2026-09-01 02:46:40+00'::timestamp with time zone, '170ea586-3f7e-4314-a9bf-8e4f394941ac'::uuid)))
Buffers: shared hit=60
SubPlan 1
-> Sort (actual time=0.003..0.003 rows=0 loops=51)
Sort Key: a."position"
Sort Method: quicksort Memory: 25kB
Buffers: shared hit=54
-> Bitmap Heap Scan on message_attachments a (actual time=0.000..0.000 rows=0 loops=51)
Recheck Cond: (message_id = m.id)
Buffers: shared hit=51
-> Bitmap Index Scan on message_attachments_message_id_attachment_id_key (actual time=0.000..0.000 rows=0 loops=51)
Index Cond: (message_id = m.id)
Buffers: shared hit=51
Planning:
Buffers: shared hit=63
Planning Time: 0.157 ms
Execution Time: 0.242 ms
=== 3. The same page with OFFSET 10000 (the app does NOT do this)
QUERY PLAN
---------------------------------------------------------------------------------------------------
Limit (actual time=0.878..0.884 rows=51 loops=1)
Buffers: shared hit=258
-> Index Scan using messages_history on messages (actual time=0.007..0.669 rows=10051 loops=1)
Index Cond: (chat_id = '7c307498-c398-4a1e-be96-13556a559cbf'::uuid)
Buffers: shared hit=258
Planning Time: 0.037 ms
Execution Time: 0.897 ms
=== 4. Query 2 without the index (index is dropped only inside this transaction)
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=1.097..1.101 rows=51 loops=1)
Buffers: shared hit=261
-> Sort (actual time=1.097..1.098 rows=51 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=261
-> Seq Scan on messages (actual time=0.307..0.737 rows=5000 loops=1)
Filter: ((chat_id = '7c307498-c398-4a1e-be96-13556a559cbf'::uuid) AND (ROW(created_at, id) > ROW('2026-09-01 02:46:40+00'::timestamp with time zone, '170ea586-3f7e-4314-a9bf-8e4f394941ac'::uuid)))
Rows Removed by Filter: 15146
Buffers: shared hit=261
Planning:
Buffers: shared hit=4
Planning Time: 0.051 ms
Execution Time: 1.115 ms
=== ROLLBACK: test data removed, index is back
explain_users_left
--------------------
0
+43
View File
@@ -0,0 +1,43 @@
# explain: EXPLAIN of the history page (full plans: explain-history.txt)
# date: 2026-10-21 21:09:14, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/explain.py
# exit code: 0, 1.1 s
=== Data volume
=== History index
=== 1. First page: limit=50, the app asks for 51 rows to know if there is a next page
Buffers: shared hit=5
-> Index Scan using messages_history on messages (actual time=0.005..0.008 rows=51 loops=1)
Buffers: shared hit=5
Buffers: shared hit=6
Execution Time: 0.020 ms
=== 2. Page after the 10000th message by keyset cursor (this is what the app does)
Buffers: shared hit=6
-> Index Scan using messages_history on messages (actual time=0.005..0.009 rows=51 loops=1)
Buffers: shared hit=6
Execution Time: 0.031 ms
=== 2b. The same page exactly as the app sends it since lab4: with attachment_ids of every message
Buffers: shared hit=60
-> Index Scan using messages_history on messages m (actual time=0.019..0.222 rows=51 loops=1)
Buffers: shared hit=60
Buffers: shared hit=54
-> Bitmap Heap Scan on message_attachments a (actual time=0.000..0.000 rows=0 loops=51)
Buffers: shared hit=51
-> Bitmap Index Scan on message_attachments_message_id_attachment_id_key (actual time=0.000..0.000 rows=0 loops=51)
Buffers: shared hit=51
Buffers: shared hit=63
Execution Time: 0.242 ms
=== 3. The same page with OFFSET 10000 (the app does NOT do this)
Buffers: shared hit=258
-> Index Scan using messages_history on messages (actual time=0.007..0.669 rows=10051 loops=1)
Buffers: shared hit=258
Execution Time: 0.897 ms
=== 4. Query 2 without the index (index is dropped only inside this transaction)
Buffers: shared hit=261
Buffers: shared hit=261
-> Seq Scan on messages (actual time=0.307..0.737 rows=5000 loops=1)
Buffers: shared hit=261
Buffers: shared hit=4
Execution Time: 1.115 ms
=== ROLLBACK: test data removed, index is back
PASS: full plans saved to evidence\explain-history.txt
+33
View File
@@ -0,0 +1,33 @@
# failover: public failover test for every replica, file downloaded via the other one (make test-failover)
# date: 2026-10-21 21:09:54, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/run_failover.py
# exit code: 0, 39.7 s
hook: scripts\stop-one.cmd; api replicas: ['11a93acecaca', '6128eb268c44']
=== run 1: api containers before
SERVICE CONTAINER ID STATUS
api 11a93acecaca Up 36 seconds (healthy)
api 6128eb268c44 Up 36 seconds (healthy)
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 126, "failed_attempts": 0, "first_recovery_seconds": 4.39}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
api containers after
SERVICE CONTAINER ID STATUS
api 11a93acecaca Exited (0) 11 seconds ago
api 6128eb268c44 Up 53 seconds (healthy)
the hook stopped 11a93acecaca (X-Instance-Id of that replica = container ID); other api containers kept running, postgres/redis/lb were not touched
restored: docker start 11a93acecaca -> healthy and back in HAProxy
=== run 2: api containers before
SERVICE CONTAINER ID STATUS
api 11a93acecaca Up 2 seconds (healthy)
api 6128eb268c44 Up 56 seconds (healthy)
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 0, "first_recovery_seconds": 4.328}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
api containers after
SERVICE CONTAINER ID STATUS
api 11a93acecaca Up 18 seconds (healthy)
api 6128eb268c44 Exited (0) 11 seconds ago
the hook stopped 6128eb268c44 (X-Instance-Id of that replica = container ID); other api containers kept running, postgres/redis/lb were not touched
restored: docker start 6128eb268c44 -> healthy and back in HAProxy
PASS: public failover test passed 2 times; every api replica was stopped once and restored
+29
View File
@@ -0,0 +1,29 @@
# failures: Redis and PostgreSQL outages via the balancer
# date: 2026-10-21 21:11:20, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_failures.py
# exit code: 0, 55.6 s
stopping redis
/health/live -> 200, /health/ready -> 503 (8016 ms)
valid token: GET /users/me -> 503 unavailable (8000 ms), session cannot be checked
unknown token -> 503, not 200: nobody is trusted without a check
no token -> 401
login -> 503: there is nowhere to store the session
registration -> 201: it needs only PostgreSQL
starting redis
after start: the old token works, confirmed messages are in place
PASS: Redis outage gives 503 and does not let anyone in without a session check
killing redis with SIGKILL (docker compose kill redis): no graceful shutdown
right after the crash: GET /users/me -> 503
starting redis
after start: the session issued before the crash still works (AOF, appendfsync always)
PASS: sessions survive a Redis crash, not only a clean restart
stopping postgres
/health/live -> 200, /health/ready -> 503 (1016 ms)
valid token: users/me, chats, history, new message -> 503 unavailable, no details
no token -> 401, unknown token -> 401: anonymous users are not let in
login -> 503, registration -> 503
starting postgres
after start: the old token works, confirmed messages are in place
PASS: PostgreSQL outage gives limited 503 errors and keeps anonymous users out
3 passed, 0 failed
+22
View File
@@ -0,0 +1,22 @@
# idempotency: Idempotency-Key, parallel same key via replicas
# date: 2026-10-21 21:08:52, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_idempotency.py
# exit code: 0, 2.4 s
first -> 201; same JSON written differently -> 201; plain retry -> 201
PASS: a retry with the same key returns the original 201 and message, no duplicate
20 parallel POSTs with one key: statuses {201: 20}, replicas {'6128eb268c44': 10, '11a93acecaca': 10}, different bodies in answers: 1, messages in history: 1
PASS: parallel requests with one key through different replicas create exactly one message
20 parallel POSTs, one key, two different bodies: {('body A', 201): 10, ('body B', 409): 10}; saved: ['body A']
PASS: the first body wins, the same body gets 201, the other body gets 409
one key: alice in chat 1, bob in chat 1, alice in chat 2 -> 3 messages
PASS: the key is scoped to the current user and chat; another body with a used key -> 409
missing, empty, 129 chars, space, '/', non-ASCII, '"', '+' -> 400; 128 chars of A-Z a-z 0-9 . _ : - -> 201
PASS: Idempotency-Key is required and checked: [A-Za-z0-9._:-]{1,128}
key used by a 400 and by a 404 first, then valid request -> 201
PASS: rejected requests (400, 404) do not store a result for the key
same key and body by an outsider -> 404; by alice after logout -> 401
PASS: a retry checks the session and chat access again, the saved answer is not leaked
POST sent, connection closed without reading the answer; retry -> 201; messages: 1
PASS: an unconfirmed POST can be safely retried with the same key
8 passed, 0 failed
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.015,
"concurrency": 4,
"successful_requests": 7379,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 245.844,
"successful_latency_ms": {
"p50": 16.0,
"p95": 32.0,
"p99": 32.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+22
View File
@@ -0,0 +1,22 @@
# load: public load generator, 30 s, concurrency 4
# date: 2026-10-21 21:10:24, commit: 2dbed80 + uncommitted changes
# command: python.exe tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json
# exit code: 0, 30.4 s
{
"lab": 4,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.015,
"concurrency": 4,
"successful_requests": 7379,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 245.844,
"successful_latency_ms": {
"p50": 16.0,
"p95": 32.0,
"p99": 32.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+24
View File
@@ -0,0 +1,24 @@
# persistence: public persistence test incl. S3 + proof of real restarts (make test-persistence)
# date: 2026-10-21 21:12:49, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/run_persistence.py
# exit code: 0, 40.2 s
before: container, ID, started at
messenger-lab4-api-1 11a93acecaca 2026-10-21T18:11:37.067348364Z
messenger-lab4-api-2 6128eb268c44 2026-10-21T18:11:36.916459116Z
messenger-lab4-janitor-1 baefc0e97dff 2026-10-21T18:11:33.313531682Z
messenger-lab4-lb-1 03697e5fe34c 2026-10-21T18:11:40.981519931Z
messenger-lab4-postgres-1 f7a6a1ce25a7 2026-10-21T18:11:22.482229396Z
messenger-lab4-redis-1 b4523b39a0fe 2026-10-21T18:11:22.626999402Z
messenger-lab4-s3-1 e7cbe6ddfa4a 2026-10-21T18:11:32.264154477Z
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.␍
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
after (hook + waiting for readiness took 39.2 s): container, ID, started at, restarted?
messenger-lab4-api-1 11a93acecaca 2026-10-21T18:12:46.288933033Z same container: True, restarted: True
messenger-lab4-api-2 6128eb268c44 2026-10-21T18:12:46.174283308Z same container: True, restarted: True
messenger-lab4-janitor-1 baefc0e97dff 2026-10-21T18:12:42.503993973Z same container: True, restarted: True
messenger-lab4-lb-1 03697e5fe34c 2026-10-21T18:12:47.684809415Z same container: True, restarted: True
messenger-lab4-postgres-1 f7a6a1ce25a7 2026-10-21T18:12:11.527270274Z same container: True, restarted: True
messenger-lab4-redis-1 b4523b39a0fe 2026-10-21T18:12:11.368416107Z same container: True, restarted: True
messenger-lab4-s3-1 e7cbe6ddfa4a 2026-10-21T18:12:21.264135454Z same container: True, restarted: True
PASS: the hook restarted postgres, redis, s3 (SeaweedFS), all api replicas, janitor and lb (same containers, new start time); data, the attachment bytes and the old token survived
+10
View File
@@ -0,0 +1,10 @@
# race: lab2 races via the balancer
# date: 2026-10-21 21:08:56, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_race.py
# exit code: 0, 1.2 s
sent 100 messages from 10 clients in 0.22 s; read 100 in 4 pages, unique ids: 100
PASS: 100 concurrent messages from 10 clients, no losses and no duplicates
20 parallel registrations of one username: 201 x1, 409 x19
PASS: concurrent registration created exactly one user
2 passed, 0 failed
+14
View File
@@ -0,0 +1,14 @@
# redis: Redis as the session store
# date: 2026-10-21 21:09:13, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/redis_info.py
# exit code: 0, 2.8 s
session key: session:f4f1fe0235d139de...; value is the user id: True
TTL of the key, seconds: 3599
sessions in Redis: 126
config appendonly = yes
config appendfsync = always
config maxmemory-policy = noeviction
aof_enabled:1
aof_last_write_status:ok
without password: NOAUTH Authentication required.
+44
View File
@@ -0,0 +1,44 @@
# s3-security: lab4: private bucket outside API, limited API key, no console/ports, idempotent bootstrap
# date: 2026-10-21 21:03:14, commit: 2dbed80
# command: python.exe student-tests/test_s3_security.py
# exit code: 0, 9.5 s
anonymous get_object directly to S3 (from the data network) -> 403 AccessDenied
anonymous head_object directly to S3 (from the data network) -> 403
anonymous list_bucket directly to S3 (from the data network) -> 403 AccessDenied
anonymous put_object directly to S3 (from the data network) -> 403 AccessDenied
anonymous get_bucket_policy directly to S3 (from the data network) -> 403 AccessDenied
the same file through the API for a chat member -> 200
PASS: the bucket is private: no anonymous read, list, write or policy read
API key: list buckets -> ['messenger-attachments']
API key: get own object -> allowed
API key: put object -> allowed
API key: delete object -> allowed
API key: list bucket -> allowed
API key: create another bucket -> denied: AccessDenied
API key: make bucket public (put policy) -> denied: NotImplemented
API key: read bucket policy -> denied: NoSuchBucketPolicy
API key: delete bucket -> denied: AccessDenied
API key: change versioning -> denied: NotImplemented
PASS: the API key can only get/put/delete/list objects of its own bucket; bucket admin, policy and other buckets are denied
compose: s3 has no published ports, only the internal network 'data' (S3 8333, master UI 9333, filer UI 8888 are reachable only inside the stand)
127.0.0.1:8333 from the host -> connection refused
127.0.0.1:9333 from the host -> connection refused
127.0.0.1:8888 from the host -> connection refused
127.0.0.1:19333 from the host -> connection refused
secrets of api: ['cache_url', 'database_url', 's3_access_key_id', 's3_secret_access_key']
secrets of janitor: ['database_url', 's3_access_key_id', 's3_secret_access_key']
secrets of lb: -
secrets of migrate: ['database_url']
secrets of postgres: ['postgres_password']
secrets of redis: ['redis_auth']
secrets of s3: ['s3_config']
secrets of s3-init: ['s3_access_key_id', 's3_root_password', 's3_root_user', 's3_secret_access_key']
PASS: S3 is reachable only inside the stand; admin keys are only in s3 and s3-init
s3-init: s3-init: bucket messenger-attachments exists
s3-init: s3-init: api key can put/get/list/delete objects of its bucket
s3-init: s3-init: api key cannot create buckets (AccessDenied)
s3-init: s3-init: bucket is private (anonymous list/get/put -> [403])
after the repeated bootstrap: old file downloads, new upload works
PASS: bucket/user/policy bootstrap can be repeated safely
4 passed, 0 failed
+6
View File
@@ -0,0 +1,6 @@
# smoke: public smoke via the balancer (make test), with attachment
# date: 2026-10-21 21:03:01, commit: 2dbed80
# command: python.exe tests/smoke.py --base-url http://127.0.0.1:8080
# exit code: 0, 0.6 s
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+40
View File
@@ -0,0 +1,40 @@
# stack: stand layout: replicas, ports, limits, networks, secrets, S3
# date: 2026-10-21 21:03:00, commit: 2dbed80
# command: python.exe student-tests/check_stack.py
# exit code: 0, 3.0 s
host: Windows 10, AMD64 Family 26 Model 68 Stepping 0, AuthenticAMD; client Python 3.11.1
Docker 28.1.1, Docker Compose version v2.35.1-desktop.1; Docker VM: 16 CPU, 15.2 GiB RAM, Docker Desktop
SERVICE CONTAINER ID STATUS PORTS
api 11a93acecaca Up 20 seconds (healthy) 8080/tcp
api 6128eb268c44 Up 20 seconds (healthy) 8080/tcp
janitor baefc0e97dff Up 20 seconds
lb 03697e5fe34c Up 18 seconds (healthy) 127.0.0.1:8080->8080/tcp, 127.0.0.1:8404->8404/tcp
migrate aca090330db4 Exited (0) 22 seconds ago
postgres f7a6a1ce25a7 Up 2 minutes (healthy)
redis b4523b39a0fe Up 2 minutes (healthy)
s3 e7cbe6ddfa4a Up 2 minutes (healthy)
s3-init 60719e674e18 Exited (0) 21 seconds ago
container image cpus memory host ports networks
messenger-lab4-api-1 messenger-lab4-api 1.00 512 MiB - data,edge
messenger-lab4-api-2 messenger-lab4-api 1.00 512 MiB - data,edge
messenger-lab4-janitor-1 messenger-lab4-janitor 0.25 192 MiB - data
messenger-lab4-lb-1 haproxy:3.2.25-alpine 0.50 128 MiB 127.0.0.1:8080,127.0.0.1:8404 edge
messenger-lab4-postgres-1 postgres:17.11-alpine 1.00 512 MiB - data
messenger-lab4-redis-1 redis:7.4.11-alpine 0.50 128 MiB - data
messenger-lab4-s3-1 chrislusf/seaweedfs:3.80 1.00 512 MiB - data
secrets of api: ['cache_url', 'database_url', 's3_access_key_id', 's3_secret_access_key']
secrets of janitor: ['database_url', 's3_access_key_id', 's3_secret_access_key']
secrets of lb: -
secrets of migrate: ['database_url']
secrets of postgres: ['postgres_password']
secrets of redis: ['redis_auth']
secrets of s3: ['s3_config']
secrets of s3-init: ['s3_access_key_id', 's3_root_password', 's3_root_user', 's3_secret_access_key']
through http://127.0.0.1:8080 one session is served by 2 replicas: ['11a93acecaca', '6128eb268c44']
/health/ready -> 200 from 11a93acecaca
PASS: 2 api replicas behind one entry point, no direct API ports, limits on every container, postgres/redis/s3/janitor only in the internal data network, S3 admin keys only in s3 and s3-init
+26
View File
@@ -0,0 +1,26 @@
# student-tests: lab1/lab2 API tests via the balancer
# date: 2026-10-21 21:08:55, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/test_api.py
# exit code: 0, 2.7 s
PASS: duplicate username returns 409
PASS: invalid JSON returns 400
PASS: wrong and extra fields return 400
PASS: foreign chat returns 404
PASS: empty and too long messages return 400, 4000 chars is ok
PASS: pagination works across multiple pages, foreign cursor returns 400
PASS: empty cursor (?cursor= and ?cursor) returns 400, no cursor returns the first page
PASS: chat list pagination
PASS: unicode text is stored as is
PASS: strings with U+0000 are stored and returned as is
PASS: user response has no password or hash
PASS: password length 12..128, blank password is rejected
PASS: Basic login returns opaque Bearer token with expiry
PASS: wrong password and unknown user both return the same 401
PASS: malformed Basic header returns 401
PASS: password with colon and unicode works
PASS: business endpoints need Bearer; Basic and X-User-Id give 401
PASS: X-User-Id does not change the current user
PASS: 401 comes before 400 and 404
PASS: logout revokes only the current session
20 passed, 0 failed
+40
View File
@@ -0,0 +1,40 @@
# Сводка проверок
| Шаг | Что проверяет | Результат | Время, с | Файл |
| --- | --- | --- | --- | --- |
| persistence | public persistence test incl. S3 + proof of real restarts (make test-persistence) | PASS | 40 | evidence/persistence.txt |
# Замеры
Машина: Windows 10, AMD64 Family 26 Model 68 Stepping 0, AuthenticAMD; Docker VM: 16 CPU, 15.2 GiB RAM; клиент Python 3.11.1; дата прогона 2026-10-21, commit 2dbed80 + uncommitted changes. Лимиты контейнеров: api 1 CPU / 512 MiB каждая, postgres и s3 (SeaweedFS) по 1 CPU / 512 MiB, redis и lb по 0,5 CPU / 128 MiB, janitor 0,25 CPU / 192 MiB.
Публичный тест отказа (`make test-failover`, 15 с записи во время остановки реплики):
| Прогон | Остановлена реплика | Реплик до отказа | Успешных записей | Неудачных попыток (повторены с тем же ключом) | Первая запись после hook, с |
| --- | --- | --- | --- | --- | --- |
| 1 | 11a93acecaca | 2 | 126 | 0 | 4.39 |
| 2 | 6128eb268c44 | 2 | 124 | 0 | 4.328 |
Одновременные загрузки (`student-tests/upload_memory.py`, перед каждым сценарием реплики перезапускаются, лимит api 512 MiB / 1 CPU). Пик RSS — VmHWM процесса API; cgroup — память контейнера, включая page cache временных файлов:
| Сценарий | Одновременно | Объём, MiB | Время, с (p50 / max) | Реплика: загрузок | RSS до, MiB | Пик RSS, MiB | Рост, MiB | Пик cgroup, MiB |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 10 x ~9.5 MiB PNG (noise) | 10 | 94.9 | 1.38 / 1.52 | 11a93acecaca: 5 | 93.5 | 106.2 | 12.6 | 134.1 |
| | | | | 6128eb268c44: 5 | 94.8 | 105.3 | 10.5 | 135.2 |
| 10 x 40 Mpx PNG (8000x5000 RGB) | 10 | 1.1 | 0.85 / 1.09 | 11a93acecaca: 5 | 93.2 | 96.6 | 3.4 | 84.3 |
| | | | | 6128eb268c44: 5 | 93.1 | 94.7 | 1.6 | 86.8 |
| 20 mixed: large + 40 Mpx + JPEG | 20 | 133.2 | 1.37 / 1.77 | 11a93acecaca: 10 | 94.8 | 121.7 | 26.9 | 181.9 |
| | | | | 6128eb268c44: 10 | 95.0 | 116.1 | 21.0 | 155.6 |
Один PNG 8000x5000 RGB внутри контейнера api, дополнительный пик RSS: наивно (тело целиком в памяти + полное декодирование Pillow) 161 MiB, потоковая проверка 0 MiB. 10 таких наивных загрузок одновременно не поместились бы в 512 MiB.
Публичный генератор нагрузки (`tests/load.py`, closed loop, concurrency 4, 30 с, 2 реплики): 245.844 успешных POST/с, ошибок 0 (доля 0.0), задержка успешных p50 16.0 мс, p95 32.0 мс, p99 32.0 мс.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| публичный `make test-failover` для каждой реплики | запись продолжается не позже 10 с, подтверждённые сообщения на месте, дублей нет | PASS 2 раз(а), неудачных попыток: 0, 0 | первая запись после hook через 4.39, 4.328 с (hook ждёт остановки ~4 с); потерь нет |
| перезапуск всего стенда (`restart` hook: postgres, redis, s3, api, janitor, lb) | данные, файл и прежний токен живы | PASS, те же контейнеры с новым временем старта | 39.2 с до готовности; потерь нет |
| `docker compose stop s3` (SeaweedFS остановлен) | загрузка и скачивание -> 503, метаданные, сообщения и /health/ready работают | upload 503 за 20141 мс, download 503, остальное 200/201 | после start файлы на месте; uploading-строку убрал janitor; потерь нет |
| `docker compose pause s3` (SeaweedFS завис) | то же, но через таймауты S3-клиента | upload 503 за 14766 мс (2 попытки x 5 с + откат 2 с) | после unpause файлы на месте; потерь нет |
| падение между PUT в S3 и COMMIT в БД (код API в контейнере, finish_upload падает) | вложение не видно, janitor не трогает его до конца grace period, потом удаляет объект и строку | GET/прикрепление -> 404; janitor: свежая строка сохранена, dry-run только отчёт, затем удалено | мусора не осталось; повторный проход ничего не делает |
| обрыв загрузки клиентом (9 МБ заявлено, отправлено 0,2 и 3 МБ) | ничего не сохраняется | строк и объектов не прибавилось, временных файлов 0 | мгновенно |
+124
View File
@@ -0,0 +1,124 @@
{
"date": "2026-10-21 21:08",
"api_limit_mib": 512,
"api_limit_cpus": 1.0,
"runs": [
{
"scenario": "10 x ~9.5 MiB PNG (noise)",
"concurrency": 10,
"file_bytes": [
9953047
],
"total_mib": 94.9,
"all_201": true,
"wall_seconds": 1.52,
"latency_s": {
"p50": 1.38,
"max": 1.52
},
"sampler_rounds": 9,
"replicas": [
{
"replica": "11a93acecaca",
"uploads_served": 5,
"rss_before_mib": 93.5,
"rss_peak_mib": 106.2,
"rss_growth_mib": 12.6,
"rss_peak_sampled_mib": 106.2,
"cgroup_peak_mib": 134.1,
"cgroup_peak_sampled_mib": 127.7
},
{
"replica": "6128eb268c44",
"uploads_served": 5,
"rss_before_mib": 94.8,
"rss_peak_mib": 105.3,
"rss_growth_mib": 10.5,
"rss_peak_sampled_mib": 105.3,
"cgroup_peak_mib": 135.2,
"cgroup_peak_sampled_mib": 131.4
}
]
},
{
"scenario": "10 x 40 Mpx PNG (8000x5000 RGB)",
"concurrency": 10,
"file_bytes": [
116714
],
"total_mib": 1.1,
"all_201": true,
"wall_seconds": 1.09,
"latency_s": {
"p50": 0.85,
"max": 1.09
},
"sampler_rounds": 8,
"replicas": [
{
"replica": "11a93acecaca",
"uploads_served": 5,
"rss_before_mib": 93.2,
"rss_peak_mib": 96.6,
"rss_growth_mib": 3.4,
"rss_peak_sampled_mib": 96.6,
"cgroup_peak_mib": 84.3,
"cgroup_peak_sampled_mib": 77.3
},
{
"replica": "6128eb268c44",
"uploads_served": 5,
"rss_before_mib": 93.1,
"rss_peak_mib": 94.7,
"rss_growth_mib": 1.6,
"rss_peak_sampled_mib": 94.6,
"cgroup_peak_mib": 86.8,
"cgroup_peak_sampled_mib": 77.3
}
]
},
{
"scenario": "20 mixed: large + 40 Mpx + JPEG",
"concurrency": 20,
"file_bytes": [
1492,
116714,
9953047
],
"total_mib": 133.2,
"all_201": true,
"wall_seconds": 1.77,
"latency_s": {
"p50": 1.37,
"max": 1.77
},
"sampler_rounds": 10,
"replicas": [
{
"replica": "11a93acecaca",
"uploads_served": 10,
"rss_before_mib": 94.8,
"rss_peak_mib": 121.7,
"rss_growth_mib": 26.9,
"rss_peak_sampled_mib": 121.7,
"cgroup_peak_mib": 181.9,
"cgroup_peak_sampled_mib": 180.6
},
{
"replica": "6128eb268c44",
"uploads_served": 10,
"rss_before_mib": 95.0,
"rss_peak_mib": 116.1,
"rss_growth_mib": 21.0,
"rss_peak_sampled_mib": 116.1,
"cgroup_peak_mib": 155.6,
"cgroup_peak_sampled_mib": 155.6
}
]
}
],
"single_file_extra_rss_mib": {
"naive": 161,
"streaming": 0
}
}
+13
View File
@@ -0,0 +1,13 @@
# upload-memory: lab4: >=10 concurrent uploads, peak memory of api replicas
# date: 2026-10-21 21:08:48, commit: 2dbed80 + uncommitted changes
# command: python.exe student-tests/upload_memory.py --output evidence/upload-memory.json
# exit code: 0, 34.2 s
client: Python 3.11.1 on Windows 10
preparing synthetic images (random-noise PNG ~9.5 MiB each, 40 Mpx PNG)...
large: 9953047 bytes; 40 Mpx: 116714 bytes
{"scenario": "10 x ~9.5 MiB PNG (noise)", "concurrency": 10, "file_bytes": [9953047], "total_mib": 94.9, "all_201": true, "wall_seconds": 1.52, "latency_s": {"p50": 1.38, "max": 1.52}, "sampler_rounds": 9, "replicas": [{"replica": "11a93acecaca", "uploads_served": 5, "rss_before_mib": 93.5, "rss_peak_mib": 106.2, "rss_growth_mib": 12.6, "rss_peak_sampled_mib": 106.2, "cgroup_peak_mib": 134.1, "cgroup_peak_sampled_mib": 127.7}, {"replica": "6128eb268c44", "uploads_served": 5, "rss_before_mib": 94.8, "rss_peak_mib": 105.3, "rss_growth_mib": 10.5, "rss_peak_sampled_mib": 105.3, "cgroup_peak_mib": 135.2, "cgroup_peak_sampled_mib": 131.4}]}
{"scenario": "10 x 40 Mpx PNG (8000x5000 RGB)", "concurrency": 10, "file_bytes": [116714], "total_mib": 1.1, "all_201": true, "wall_seconds": 1.09, "latency_s": {"p50": 0.85, "max": 1.09}, "sampler_rounds": 8, "replicas": [{"replica": "11a93acecaca", "uploads_served": 5, "rss_before_mib": 93.2, "rss_peak_mib": 96.6, "rss_growth_mib": 3.4, "rss_peak_sampled_mib": 96.6, "cgroup_peak_mib": 84.3, "cgroup_peak_sampled_mib": 77.3}, {"replica": "6128eb268c44", "uploads_served": 5, "rss_before_mib": 93.1, "rss_peak_mib": 94.7, "rss_growth_mib": 1.6, "rss_peak_sampled_mib": 94.6, "cgroup_peak_mib": 86.8, "cgroup_peak_sampled_mib": 77.3}]}
{"scenario": "20 mixed: large + 40 Mpx + JPEG", "concurrency": 20, "file_bytes": [1492, 116714, 9953047], "total_mib": 133.2, "all_201": true, "wall_seconds": 1.77, "latency_s": {"p50": 1.37, "max": 1.77}, "sampler_rounds": 10, "replicas": [{"replica": "11a93acecaca", "uploads_served": 10, "rss_before_mib": 94.8, "rss_peak_mib": 121.7, "rss_growth_mib": 26.9, "rss_peak_sampled_mib": 121.7, "cgroup_peak_mib": 181.9, "cgroup_peak_sampled_mib": 180.6}, {"replica": "6128eb268c44", "uploads_served": 10, "rss_before_mib": 95.0, "rss_peak_mib": 116.1, "rss_growth_mib": 21.0, "rss_peak_sampled_mib": 116.1, "cgroup_peak_mib": 155.6, "cgroup_peak_sampled_mib": 155.6}]}
one 8000x5000 RGB PNG inside the api container, extra peak RSS: naive (body in RAM + full decode) 161 MiB, streaming check 0 MiB
PASS: all uploads succeeded; largest RSS growth of one replica: 26.9 MiB (limit 512 MiB); results in evidence/upload-memory.json