Лаб6 - оценка 4

This commit is contained in:
Rakshasa2
2026-11-19 18:40:32 +03:00
parent 470d9d6f1e
commit dbce1eb574
62 changed files with 6087 additions and 15 deletions
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
set -e
mkdir -p evidence
echo " Запуск эксперимента с polling alerts "
docker compose stop postgres
sleep 3
python3 student-tests/trigger_error_rate.py &
BG_PID=$!
echo "Polling alerts каждые 3 секунды..."
FIRED=0
for i in $(seq 1 60); do
sleep 3
STATE=$(curl -s http://localhost:9090/api/v1/alerts | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
firing = []
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
if alert['state'] == 'firing':
firing.append(alert['labels']['alertname'])
if firing:
print('FIRING:' + ','.join(firing))
else:
print('NONE')
except:
print('ERROR')
")
echo "[$((i*3))s] alerts: $STATE"
if [[ "$STATE" == FIRING:* ]]; then
echo ""
echo " ALERT FIRING DETECTED!"
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json
curl -s 'http://localhost:9090/api/v1/query' \
--data-urlencode 'query=sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m]))' \
> evidence/error_rate_metric.json
FIRED=1
break
fi
done
kill $BG_PID 2>/dev/null || true
docker compose start postgres
sleep 15
if [ $FIRED -eq 1 ]; then
echo ""
echo "FIRING ALERT ЗАФИКСИРОВАН "
echo ""
python3 -c "
import json
with open('evidence/alerts_firing.json') as f:
data = json.load(f)
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
if alert['state'] == 'firing':
print(f\"✓ {alert['labels']['alertname']}: FIRING\")
print(f\" Summary: {alert.get('annotations',{}).get('summary','')}\")
print(f\" Active since: {alert.get('activeAt','?')}\")
"
else
echo ""
echo "✗ Alert не сработал за 3 минуты"
fi
make test
+57
View File
@@ -0,0 +1,57 @@
import requests
import json
import time
import base64
import hashlib
BASE = "http://localhost:8080"
USERNAME = f"test{int(time.time())}"
PASSWORD = "CorrectHorseBattery1"
print("1. Creating user...")
r = requests.post(f"{BASE}/api/v1/users", json={"username": USERNAME, "display_name": "Test", "password": PASSWORD})
print(" Status:", r.status_code)
print("2. Logging in...")
auth = base64.b64encode(f"{USERNAME}:{PASSWORD}".encode()).decode()
r = requests.post(f"{BASE}/api/v1/auth/sessions", headers={"Authorization": f"Basic {auth}"})
token = r.json()["token"]
headers = {"Authorization": f"Bearer {token}"}
print("3. Creating chat...")
r = requests.get(f"{BASE}/api/v1/users/me", headers=headers)
uid = r.json()["id"]
r = requests.post(f"{BASE}/api/v1/chats", headers=headers, json={"title": "test", "member_ids": [uid]})
chat_id = r.json()["id"]
print("4. Uploading attachment...")
with open("../tests/fixtures/sample.png", "rb") as f:
original_data = f.read()
r = requests.post(f"{BASE}/api/v1/chats/{chat_id}/attachments?filename=sample.png",
headers={**headers, "Content-Type": "image/png"},
data=original_data)
att_id = r.json()["id"]
print(" Attachment ID:", att_id)
print("5. Downloading attachment...")
# Увеличиваем таймаут, чтобы исключить преждевременное отключение
r = requests.get(f"{BASE}/api/v1/attachments/{att_id}/content", headers=headers, timeout=30)
print(" Download Status:", r.status_code)
print(" Content-Type:", r.headers.get("Content-Type"))
print(" Content-Length header:", r.headers.get("Content-Length"))
downloaded_data = r.content
print(" Original length:", len(original_data))
print(" Downloaded length:", len(downloaded_data))
orig_hash = hashlib.sha256(original_data).hexdigest()
down_hash = hashlib.sha256(downloaded_data).hexdigest()
print(" Original SHA256: ", orig_hash)
print(" Downloaded SHA256:", down_hash)
if original_data == downloaded_data:
print("\n SUCCESS: Files match perfectly!")
else:
print("\n FAIL: Files differ!")
print(" First 100 bytes of downloaded data:", downloaded_data[:100])
+31
View File
@@ -0,0 +1,31 @@
import requests
import uuid
import base64
base = 'http://localhost:8080'
# Пользователь
u = requests.post(f'{base}/api/v1/users',
json={'username':f'user{uuid.uuid4().hex[:8]}','display_name':'T','password':'correcthorsebatterystaple'}).json()
print(f'User: {u["id"]}')
# Токен
token = requests.post(f'{base}/api/v1/auth/sessions',
auth=(u['username'],'correcthorsebatterystaple')).json()['token']
auth_h = {'Authorization': f'Bearer {token}'}
# Чат
chat = requests.post(f'{base}/api/v1/chats',
json={'title':'t','member_ids':[u['id']]},
headers={**auth_h, 'Content-Type': 'application/json'}).json()
print(f'Chat: {chat["id"]}')
# Минимальный валидный PNG 1x1
png = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
# Upload
r = requests.post(f'{base}/api/v1/chats/{chat["id"]}/attachments?filename=t.png',
headers={**auth_h, 'Content-Type': 'image/png'},
data=png)
att = r.json()
print(f'Attachment: {att["id"]}, status: {att["status"]}')
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
P="python3 student-tests/lab5_probe.py"
DC="docker compose --env-file .env"
POINT="${1:-after_commit_before_ack}"
SQL() { $DC exec -T postgres sh -c "psql -U \"\$POSTGRES_USER\" -d \"\$POSTGRES_DB\" -c \"$1\""; }
{
echo "=== C. детерминированный обрыв: $POINT ==="
$P new
echo "--- пересоздаём worker с точкой обрыва (lease=5s, reclaim=3s) ---"
JOB_LEASE_SECONDS=5 JOB_POLL_SECONDS=2 JOB_RECLAIM_IDLE_SECONDS=3 FAULT_EXIT_AT="$POINT" \
$DC up -d --force-recreate worker
$P upload
echo "--- ждём FAULT ---"
for i in $(seq 1 60); do
if $DC logs worker --tail=200 | grep -q "FAULT:.*$POINT"; then break; fi
sleep 1
done
$DC logs worker --tail=20
echo "--- состояние СРАЗУ после обрыва ---"
SQL "SELECT id,status,error_code FROM attachments ORDER BY created_at DESC LIMIT 1;"
SQL "SELECT id,status,attempts,lease_until FROM attachment_jobs ORDER BY created_at DESC LIMIT 1;"
SQL "SELECT count(*) AS variants_written FROM attachment_variants;"
echo "--- неподтверждённые сообщения (PEL) ---"
$DC exec -T broker redis-cli -n 1 XPENDING attachment_jobs worker_group - + 10
echo "--- перезапуск того же контейнера: marker блокирует повторный обрыв ---"
JOB_LEASE_SECONDS=5 JOB_POLL_SECONDS=2 JOB_RECLAIM_IDLE_SECONDS=3 FAULT_EXIT_AT="$POINT" \
$DC start worker
sleep 25
$DC logs worker --tail=25
$P wait --timeout 120
echo "--- набор вариантов не удвоился ---"
SQL "SELECT attachment_id,kind,count(*) FROM attachment_variants GROUP BY 1,2 HAVING count(*)>1;"
echo "--- staging очищен ---"
SQL "SELECT count(*) AS leftover_staging FROM attachments WHERE staging_key IS NOT NULL AND status='ready';"
echo "--- PEL пуст ---"
$DC exec -T broker redis-cli -n 1 XPENDING attachment_jobs worker_group - + 10
$P fetch --variant thumbnail
echo "--- возврат worker в штатный режим ---"
$DC up -d --force-recreate worker
} 2>&1 | tee "evidence/C_${POINT}.txt"
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
P="python3 student-tests/lab5_probe.py"
DC="docker compose --env-file .env"
{
echo "=== B. crash между COMMIT и publish ==="
$DC stop worker broker
$P new
echo "--- upload: publish не пройдёт, намерение в БД (ожидаем 202) ---"
$P upload
echo "--- jobs в БД ---"
$DC exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT id,status,attempts FROM attachment_jobs ORDER BY created_at DESC LIMIT 3;"'
echo "--- убиваем API до восстановления брокера ---"
$DC kill api
$DC start broker
sleep 8
$DC start api worker
sleep 25
echo "--- задача доходит до ready без ручного создания задания ---"
$P wait --timeout 150
$P fetch --variant thumbnail
} 2>&1 | tee evidence/B_commit_publish.txt
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
P="python3 student-tests/lab5_probe.py"
DC="docker compose --env-file .env"
SQL() { $DC exec -T postgres sh -c "psql -U \"\$POSTGRES_USER\" -d \"\$POSTGRES_DB\" -c \"$1\""; }
ARM="JOB_LEASE_SECONDS=5 JOB_POLL_SECONDS=2 JOB_RECLAIM_IDLE_SECONDS=3 FAULT_EXIT_AT=after_claim"
{
echo "=== D. смерть worker, удерживающего lease ==="
$P new
echo "--- worker с обрывом сразу после ClaimJob (lease=5s) ---"
env $ARM $DC up -d --force-recreate worker
$P upload
for i in $(seq 1 60); do
if $DC logs worker --tail=200 | grep -q "FAULT:.*after_claim"; then break; fi
sleep 1
done
$DC logs worker --tail=15
echo "--- job ЗАХВАЧЕН: processing, attempts=1, lease_until в будущем ---"
SQL "SELECT id,status,attempts,leased_by,lease_until FROM attachment_jobs ORDER BY created_at DESC LIMIT 1;"
SQL "SELECT id,status FROM attachments ORDER BY created_at DESC LIMIT 1;"
echo "--- перезапуск того же контейнера: marker блокирует повторный обрыв ---"
env $ARM $DC start worker
sleep 20
$DC logs worker --tail=20
echo "--- lease истёк, работа возвращена и завершена (attempts=2) ---"
SQL "SELECT id,status,attempts,lease_until FROM attachment_jobs ORDER BY created_at DESC LIMIT 1;"
$P wait --timeout 120
SQL "SELECT attachment_id,kind,count(*) FROM attachment_variants GROUP BY 1,2 HAVING count(*)>1;"
$P fetch --variant crop
echo "--- возврат worker в штатный режим ---"
$DC up -d --force-recreate worker
} 2>&1 | tee evidence/D_lease.txt
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
P="python3 student-tests/lab5_probe.py"
DC="docker compose --env-file .env"
SQL() { $DC exec -T postgres sh -c "psql -U \"\$POSTGRES_USER\" -d \"\$POSTGRES_DB\" -c \"$1\""; }
{
echo "=== E. transient-ошибка → backoff → исчерпание → DLQ → replay ==="
$P new
echo "--- max_attempts=2 (env читает API), worker падает во временную ошибку ---"
JOB_MAX_ATTEMPTS=2 JOB_POLL_SECONDS=2 FAULT_FAIL_MODE=transient FAULT_FAIL_TIMES=99 \
$DC up -d --force-recreate api worker
sleep 15
$P upload
echo "--- ждём терминального failed ---"
for i in $(seq 1 60); do
s=$(SQL "SELECT status FROM attachments ORDER BY created_at DESC LIMIT 1;" | sed -n 3p | tr -d ' ')
[ "$s" = "failed" ] && break
sleep 2
done
$DC logs worker --tail=40
echo "--- видны две попытки с разным backoff (jitter) и error_code ---"
SQL "SELECT id,status,attempts,max_attempts,next_run_at,last_error FROM attachment_jobs ORDER BY created_at DESC LIMIT 1;"
SQL "SELECT id,status,error_code FROM attachments ORDER BY created_at DESC LIMIT 1;"
echo "--- DLQ ---"
$DC exec -T broker redis-cli -n 1 XRANGE attachment_jobs_dlq - + COUNT 10
echo "--- снимаем fault: worker пересоздан без инъекции ---"
JOB_MAX_ATTEMPTS=5 $DC up -d --force-recreate api worker
sleep 12
echo "--- операторский replay: только failed, где attachment НЕ ready ---"
SQL "WITH cand AS (SELECT j.id FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.status='failed' AND a.status<>'ready') UPDATE attachment_jobs j SET status='pending',attempts=0,last_error=NULL,lease_until=NULL,leased_by=NULL,next_run_at=NOW(),updated_at=NOW() FROM cand WHERE j.id=cand.id RETURNING j.id,j.attachment_id;"
SQL "UPDATE attachments a SET status='queued',error_code=NULL,updated_at=NOW() FROM attachment_jobs j WHERE j.attachment_id=a.id AND j.status='pending' AND a.status='failed' RETURNING a.id;"
$P wait --timeout 120
SQL "SELECT attachment_id,kind,count(*) FROM attachment_variants GROUP BY 1,2 HAVING count(*)>1;"
$P fetch --variant thumbnail
echo "--- защита от дубля: повторный replay уже ready-задачи ничего не меняет ---"
SQL "WITH cand AS (SELECT j.id FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.status='failed' AND a.status<>'ready') UPDATE attachment_jobs j SET status='pending',attempts=0 FROM cand WHERE j.id=cand.id RETURNING j.id;"
} 2>&1 | tee evidence/E_retry_replay.txt
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
P="python3 student-tests/lab5_probe.py"
DC="docker compose --env-file .env"
{
echo "=== A. worker остановлен ==="
$DC stop worker
$P new
$P upload
echo "--- content до обработки (ожидаем 409) ---"
$P fetch || true
echo "--- сообщение с queued вложением (ожидаем 201) ---"
$P send --text "queued attachment"
echo "--- рестарт API с сохранением volumes ---"
$DC restart api
sleep 20
echo "--- рестарт broker с сохранением volume ---"
$DC restart broker
sleep 8
echo "--- запуск worker ---"
$DC start worker
sleep 5
$P wait --timeout 120
echo "--- оригинал ---"
$P fetch
echo "--- thumbnail ---"
$P fetch --variant thumbnail
echo "--- crop ---"
$P fetch --variant crop
echo "--- optimized ---"
$P fetch --variant optimized
} 2>&1 | tee evidence/A_worker_down.txt
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
set -e
echo " Сценарий: получение ApiHighErrorRate firing "
docker compose stop postgres
sleep 3
python3 student-tests/trigger_error_rate.py &
BG_PID=$!
echo "Ждём 150 секунд для срабатывания alert..."
sleep 150
echo ""
echo " Состояние alerts в момент отказа (PostgreSQL STOPPED) "
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json
python3 -c "
import json
with open('evidence/alerts_firing.json') as f:
data = json.load(f)
firing_found = False
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
state = alert['state']
name = alert['labels']['alertname']
print(f\"{name}: {state}\")
if state == 'firing':
firing_found = True
print(f\" ✓ FIRING: {alert.get('annotations',{}).get('summary','')}\")
if firing_found:
print('\\n✓ ALERT FIRING CONFIRMED')
else:
print('\\n✗ No alerts firing')
"
echo ""
echo " Метрика error rate "
curl -s 'http://localhost:9090/api/v1/query' \
--data-urlencode 'query=sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[5m])) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[5m])), 0.001)' \
| python3 -c "import sys,json; d=json.load(sys.stdin); [print(f'{float(r[\"value\"][1])*100:.2f}%') for r in d['data']['result']]" \
| tee evidence/error_rate_at_firing.txt
echo ""
echo " Восстановление PostgreSQL "
docker compose start postgres
wait $BG_PID 2>/dev/null || true
echo "Ждём 20 секунд на восстановление..."
sleep 20
echo ""
echo " Состояние alerts после восстановления "
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_resolved.json
python3 -c "
import json
with open('evidence/alerts_resolved.json') as f:
data = json.load(f)
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
print(f\"{alert['labels']['alertname']}: {alert['state']}\")
"
echo ""
echo " Финальная проверка smoke "
make test
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env bash
set -e
mkdir -p evidence
echo "=== Сценарий: AttachmentQueueLagHigh через остановку S3 ==="
# 1. Остановить S3
docker compose stop s3
sleep 3
# 2. Создать 5 attachments (jobs попадут в pending)
python3 -c "
import requests, uuid, base64, time
base = 'http://localhost:8080'
# Один пользователь, один чат
u = requests.post(f'{base}/api/v1/users',
json={'username':f'user{uuid.uuid4().hex[:8]}','display_name':'T','password':'correcthorsebatterystaple'}).json()
token = requests.post(f'{base}/api/v1/auth/sessions',
auth=(u['username'],'correcthorsebatterystaple')).json()['token']
auth_h = {'Authorization': f'Bearer {token}'}
chat = requests.post(f'{base}/api/v1/chats',
json={'title':'t','member_ids':[u['id']]},
headers={**auth_h, 'Content-Type': 'application/json'}).json()
png = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
print('Creating 5 attachments...')
for i in range(5):
r = requests.post(f'{base}/api/v1/chats/{chat[\"id\"]}/attachments?filename=t{i}.png',
headers={**auth_h, 'Content-Type': 'image/png'},
data=png)
print(f'{i+1}/5: status={r.status_code}')
time.sleep(0.5)
"
# 3. Проверить, что jobs в pending
echo ""
echo "=== Jobs в БД ==="
docker compose exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT status,count(*) FROM attachment_jobs GROUP BY status;"'
# 4. Polling alerts каждые 5 секунд
echo ""
echo "Polling alerts каждые 5 секунд..."
FIRED=0
for i in $(seq 1 36); do
sleep 5
STATE=$(curl -s http://localhost:9090/api/v1/alerts | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
firing = []
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
if alert['state'] == 'firing':
firing.append(alert['labels']['alertname'])
if firing:
print('FIRING:' + ','.join(firing))
else:
print('NONE')
except:
print('ERROR')
")
echo "[$((i*5))s] alerts: $STATE"
if [[ "$STATE" == FIRING:* ]]; then
echo ""
echo "✓ ALERT FIRING DETECTED!"
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json
curl -s 'http://localhost:9090/api/v1/query' \
--data-urlencode 'query=attachment_jobs_oldest_age_seconds' \
> evidence/queue_lag_metric.json
FIRED=1
break
fi
done
# 5. Восстановить S3
docker compose start s3
sleep 15
if [ $FIRED -eq 1 ]; then
echo ""
echo "✓✓✓ FIRING ALERT ЗАФИКСИРОВАН ✓✓✓"
python3 -c "
import json
with open('evidence/alerts_firing.json') as f:
data = json.load(f)
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
if alert['state'] == 'firing':
print(f\"✓ {alert['labels']['alertname']}: FIRING\")
print(f\" Summary: {alert.get('annotations',{}).get('summary','')}\")
"
else
echo ""
echo "✗ Alert не сработал"
fi
make test
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Синтетические проверки lab5. Токен хранится во временном файле и не печатается."""
import argparse, base64, hashlib, json, os, sys, time, uuid
import requests
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
SESS = "/tmp/lab5_session.json"
FIXTURE = "tests/fixtures/sample.png"
def save(d):
with open(SESS, "w") as f:
json.dump(d, f)
def load():
with open(SESS) as f:
return json.load(f)
def hdr(s):
return {"Authorization": "Bearer " + s["token"]}
def cmd_new(_):
u = "p" + uuid.uuid4().hex[:12]
p = "CorrectHorseBattery1"
r = requests.post(BASE + "/api/v1/users",
json={"username": u, "display_name": "Probe", "password": p}, timeout=15)
r.raise_for_status()
uid = r.json()["id"]
basic = base64.b64encode(f"{u}:{p}".encode()).decode()
r = requests.post(BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + basic}, timeout=15)
r.raise_for_status()
token = r.json()["token"]
r = requests.post(BASE + "/api/v1/chats", headers=hdr({"token": token}),
json={"title": "probe", "member_ids": [uid]}, timeout=15)
r.raise_for_status()
save({"token": token, "user_id": uid, "chat_id": r.json()["id"]})
print(json.dumps({"user_id": uid, "chat_id": r.json()["id"]}, indent=2))
def cmd_upload(a):
s = load()
data = open(a.file or FIXTURE, "rb").read()
r = requests.post(f"{BASE}/api/v1/chats/{s['chat_id']}/attachments",
params={"filename": os.path.basename(a.file or FIXTURE)},
headers={**hdr(s), "Content-Type": "image/png"}, data=data, timeout=60)
out = {"http_status": r.status_code, "attachment": r.json(),
"original_sha256": hashlib.sha256(data).hexdigest()}
if r.status_code == 202:
s["attachment_id"] = r.json()["id"]
s["original_sha256"] = out["original_sha256"]
save(s)
print(json.dumps(out, indent=2))
def cmd_wait(a):
s = load()
aid = a.id or s["attachment_id"]
deadline = time.time() + a.timeout
last = None
while time.time() < deadline:
r = requests.get(f"{BASE}/api/v1/attachments/{aid}", headers=hdr(s), timeout=15)
r.raise_for_status()
last = r.json()
if last["status"] in ("ready", "failed"):
print(json.dumps({"elapsed_note": "terminal", "attachment": last}, indent=2))
return 0 if last["status"] == "ready" else 1
time.sleep(1)
print(json.dumps({"elapsed_note": "timeout", "attachment": last}, indent=2))
return 1
def cmd_fetch(a):
s = load()
aid = a.id or s["attachment_id"]
params = {"variant": a.variant} if a.variant else {}
r = requests.get(f"{BASE}/api/v1/attachments/{aid}/content",
headers=hdr(s), params=params, timeout=60)
print(json.dumps({
"http_status": r.status_code,
"content_type": r.headers.get("Content-Type"),
"content_length_header": r.headers.get("Content-Length"),
"bytes": len(r.content),
"sha256": hashlib.sha256(r.content).hexdigest(),
}, indent=2))
return 0 if r.status_code == 200 else 1
def cmd_send(a):
s = load()
aid = a.id or s["attachment_id"]
r = requests.post(f"{BASE}/api/v1/chats/{s['chat_id']}/messages",
headers={**hdr(s), "Content-Type": "application/json",
"Idempotency-Key": uuid.uuid4().hex},
json={"text": a.text, "attachment_ids": [aid]}, timeout=30)
print(json.dumps({"http_status": r.status_code, "message": r.json()}, indent=2))
return 0 if r.status_code == 201 else 1
def cmd_parallel(a):
import concurrent.futures as cf
s = load()
data = open(FIXTURE, "rb").read()
def one(i):
r = requests.post(f"{BASE}/api/v1/chats/{s['chat_id']}/attachments",
params={"filename": f"par{i}.png"},
headers={**hdr(s), "Content-Type": "image/png"}, data=data, timeout=60)
return r.status_code, r.json().get("id")
t0 = time.time()
with cf.ThreadPoolExecutor(max_workers=a.n) as ex:
res = list(ex.map(one, range(a.n)))
ids = [x[1] for x in res if x[0] == 202]
ready = 0
deadline = time.time() + a.timeout
while time.time() < deadline and ready < len(ids):
ready = 0
for aid in ids:
rr = requests.get(f"{BASE}/api/v1/attachments/{aid}", headers=hdr(s), timeout=15)
if rr.json().get("status") == "ready":
ready += 1
if ready < len(ids):
time.sleep(2)
print(json.dumps({"submitted": a.n, "accepted_202": len(ids),
"ready": ready, "wall_seconds": round(time.time() - t0, 2)}, indent=2))
return 0 if ready == len(ids) else 1
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("new").set_defaults(fn=cmd_new)
p = sub.add_parser("upload"); p.add_argument("--file"); p.set_defaults(fn=cmd_upload)
p = sub.add_parser("wait"); p.add_argument("--id"); p.add_argument("--timeout", type=int, default=90); p.set_defaults(fn=cmd_wait)
p = sub.add_parser("fetch"); p.add_argument("--id"); p.add_argument("--variant"); p.set_defaults(fn=cmd_fetch)
p = sub.add_parser("send"); p.add_argument("--id"); p.add_argument("--text", default=""); p.set_defaults(fn=cmd_send)
p = sub.add_parser("parallel"); p.add_argument("-n", type=int, default=10); p.add_argument("--timeout", type=int, default=180); p.set_defaults(fn=cmd_parallel)
a = ap.parse_args()
sys.exit(a.fn(a) or 0)
if __name__ == "__main__":
main()
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
{
python3 student-tests/lab5_probe.py new
python3 student-tests/lab5_probe.py parallel -n 12 --timeout 240
docker stats --no-stream
} 2>&1 | tee evidence/F_parallel.txt
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p evidence
DC="docker compose --env-file .env"
{
echo "=== E. реестр failed и DLQ ==="
$DC exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT id,attachment_id,status,attempts,last_error FROM attachment_jobs WHERE status='"'"'failed'"'"';"'
$DC exec -T broker redis-cli -n 1 XRANGE attachment_jobs_dlq - + COUNT 20
echo "=== replay: только failed, у которых attachment НЕ ready ==="
$DC exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "
WITH cand AS (
SELECT j.id FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE j.status = '"'"'failed'"'"' AND a.status <> '"'"'ready'"'"'
)
UPDATE attachment_jobs j
SET status='"'"'pending'"'"', attempts=0, last_error=NULL,
lease_until=NULL, leased_by=NULL, next_run_at=NOW(), updated_at=NOW()
FROM cand WHERE j.id = cand.id
RETURNING j.id, j.attachment_id;"'
$DC exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "
UPDATE attachments a SET status='"'"'queued'"'"', error_code=NULL, updated_at=NOW()
FROM attachment_jobs j
WHERE j.attachment_id=a.id AND j.status='"'"'pending'"'"' AND a.status='"'"'failed'"'"'
RETURNING a.id;"'
} 2>&1 | tee evidence/E_replay.txt
+60
View File
@@ -0,0 +1,60 @@
import requests
import json
import time
import base64
BASE = "http://localhost:8080"
USERNAME = f"test{int(time.time())}"
PASSWORD = "CorrectHorseBattery1"
def do_req(method, path, **kwargs):
url = f"{BASE}{path}"
r = requests.request(method, url, **kwargs)
print(f"=== {method} {path} (Status: {r.status_code}) ===")
try:
print(json.dumps(r.json(), indent=2))
except:
print(r.text)
print()
return r
# 1. Create User
r = do_req("POST", "/api/v1/users", json={"username": USERNAME, "display_name": "Test", "password": PASSWORD})
assert r.status_code == 201
# 2. Login
auth = base64.b64encode(f"{USERNAME}:{PASSWORD}".encode()).decode()
r = do_req("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {auth}"})
assert r.status_code == 201
token = r.json()["token"]
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
# 3. Get Me
r = do_req("GET", "/api/v1/users/me", headers=headers)
uid = r.json()["id"]
# 4. Create Chat
r = do_req("POST", "/api/v1/chats", headers=headers, json={"title": "test", "member_ids": [uid]})
assert r.status_code == 201
chat_id = r.json()["id"]
# 5. Upload Attachment
with open("../tests/fixtures/sample.png", "rb") as f:
r = requests.post(f"{BASE}/api/v1/chats/{chat_id}/attachments?filename=test.png",
headers={"Authorization": f"Bearer {token}", "Content-Type": "image/png"},
data=f.read())
print("=== POST /attachments (Status: {r.status_code}) ===")
print(json.dumps(r.json(), indent=2))
print()
att_id = r.json()["id"]
# 6. Get Attachment Metadata
r = do_req("GET", f"/api/v1/attachments/{att_id}", headers={"Authorization": f"Bearer {token}"})
# 7. Send Message with Attachment
r = do_req("POST", f"/api/v1/chats/{chat_id}/messages",
headers={**headers, "Idempotency-Key": "test-key-1"},
json={"text": "hello", "attachment_ids": [att_id]})
# 8. Get Messages
r = do_req("GET", f"/api/v1/chats/{chat_id}/messages", headers=headers)
+14
View File
@@ -0,0 +1,14 @@
import requests, time
base = 'http://localhost:8080'
headers = {'Authorization': 'Bearer invalid_token_12345'}
print('Generating errors for 240 seconds...')
for i in range(240):
try:
r = requests.get(f'{base}/api/v1/users/me', headers=headers, timeout=2)
print(f'{i+1}/240: status={r.status_code}', end='\r')
except Exception as e:
print(f'{i+1}/240: error', end='\r')
time.sleep(1)
print('\nDone')