lab5 - оценка 4
This commit is contained in:
@@ -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])
|
||||
@@ -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)
|
||||
Executable
+49
@@ -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"
|
||||
Executable
+25
@@ -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
|
||||
Executable
+40
@@ -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
|
||||
Executable
+45
@@ -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
|
||||
Executable
+35
@@ -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
|
||||
Executable
+147
@@ -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()
|
||||
Executable
+10
@@ -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
|
||||
|
||||
Executable
+29
@@ -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
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user