feat: route terminal jobs to a durable DLQ
Declare the classic dead-letter topology, reject terminal worker outcomes without requeue, and add coverage for malformed messages and retry jitter.
This commit is contained in:
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "${SCRIPT_DIR}/.."
|
||||
|
||||
if [[ ! -f .env ]]; then
|
||||
cp .env.example .env
|
||||
echo "Создан .env из .env.example"
|
||||
fi
|
||||
|
||||
python3 scripts/setup-local-secrets.py
|
||||
docker compose --env-file .env config --quiet
|
||||
|
||||
echo "== Сборка и запуск учебного стенда =="
|
||||
echo "При первом запуске Docker может скачать образы."
|
||||
docker compose --env-file .env up -d --build --scale api=2
|
||||
docker compose --env-file .env up -d --wait --scale api=2 api lb worker publisher
|
||||
|
||||
echo
|
||||
docker compose --env-file .env ps
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/demo-common.sh"
|
||||
demo_preflight
|
||||
|
||||
echo
|
||||
echo "== 1. Сквозной API сценарий: upload → 202 → ready → оригинал и thumbnail =="
|
||||
make test BASE_URL="$BASE_URL"
|
||||
|
||||
echo
|
||||
echo "== 2. Проверка вариантов, checksum и доступа через API =="
|
||||
python3 student-tests/test_variants_api.py --base-url "$BASE_URL"
|
||||
|
||||
echo
|
||||
echo "Готово. Проверки создают синтетические записи в учебных PostgreSQL и S3 volumes."
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/demo-common.sh"
|
||||
demo_preflight
|
||||
|
||||
echo
|
||||
echo "== Durable handoff: загрузка сохраняется, пока broker и worker остановлены =="
|
||||
echo "Тест временно останавливает broker, publisher и worker, перезапускает API/broker, затем ждёт ready."
|
||||
python3 student-tests/test_upload_handoff.py --base-url "$BASE_URL"
|
||||
|
||||
echo
|
||||
echo "Готово. Тест сам запускает broker, publisher и worker обратно, включая cleanup при ошибке."
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/demo-common.sh"
|
||||
demo_preflight
|
||||
|
||||
echo
|
||||
echo "== 1. Потеря подтверждения outbox после broker confirm и повторная доставка =="
|
||||
python3 student-tests/test_publish_confirm_gap.py --base-url "$BASE_URL"
|
||||
|
||||
echo
|
||||
echo "== 2. Crash/retry/lease/replay и защита новой версии от старой доставки =="
|
||||
echo "Обычные publisher и worker будут остановлены на время fault-injection и запущены обратно при любом исходе."
|
||||
restore_consumers=0
|
||||
restore() {
|
||||
if [[ "$restore_consumers" == 1 ]]; then
|
||||
docker compose --env-file .env up -d publisher worker >/dev/null || \
|
||||
echo "Не удалось автоматически поднять publisher/worker; запустите: docker compose --env-file .env up -d publisher worker" >&2
|
||||
fi
|
||||
}
|
||||
restore_consumers=1
|
||||
trap restore EXIT
|
||||
docker compose --env-file .env stop publisher worker
|
||||
docker compose --env-file .env run --rm --no-deps -T worker python - < student-tests/test_pipeline_faults.py
|
||||
docker compose --env-file .env up -d publisher worker
|
||||
restore_consumers=0
|
||||
|
||||
echo
|
||||
echo "Готово. Тест оставляет синтетические записи и объекты в учебных volumes; down -v не выполняется."
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/demo-common.sh"
|
||||
demo_preflight
|
||||
|
||||
echo
|
||||
echo "== DLQ: terminal outcomes are rejected without requeue and routed via DLX =="
|
||||
echo "The test checks a malformed message and a permanently invalid image, then removes both test messages from the DLQ."
|
||||
docker compose --env-file .env run --rm --no-deps -T worker python - < student-tests/test_dlq.py
|
||||
+64
-13
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Idempotently declare the durable processing queue via RabbitMQ management API."""
|
||||
"""Declare durable classic processing and dead-letter queues."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
@@ -10,6 +10,11 @@ from urllib.parse import quote, unquote, urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
QUEUE = "attachments.process"
|
||||
DLQ = "attachments.dlq"
|
||||
DLX = "attachments.dlx"
|
||||
DLQ_ROUTING_KEY = "attachments.dead"
|
||||
|
||||
broker_url = open(os.environ.get("BROKER_URL_FILE", "/run/secrets/broker_url"), encoding="utf-8").read().strip()
|
||||
parsed = urlsplit(broker_url)
|
||||
if parsed.scheme != "amqp" or not parsed.username or not parsed.password:
|
||||
@@ -19,24 +24,70 @@ headers = {
|
||||
"Authorization": "Basic " + base64.b64encode(credentials).decode("ascii"),
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
url = "http://broker:15672/api/queues/%2F/" + quote("attachments.process", safe="")
|
||||
body = json.dumps(
|
||||
{"durable": True, "auto_delete": False, "arguments": {"x-queue-type": "quorum"}}
|
||||
).encode()
|
||||
api = "http://broker:15672/api"
|
||||
|
||||
|
||||
def request(method, resource, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = Request(f"{api}/{resource}", data=data, headers=headers, method=method)
|
||||
with urlopen(req, timeout=3) as response:
|
||||
payload = response.read()
|
||||
return json.loads(payload) if payload else None
|
||||
|
||||
|
||||
def ensure_queue(name, arguments):
|
||||
resource = f"queues/%2F/{quote(name, safe='')}"
|
||||
expected = {"x-queue-type": "classic", **arguments}
|
||||
try:
|
||||
current = request("GET", resource)
|
||||
except HTTPError as exc:
|
||||
if exc.code != 404:
|
||||
raise
|
||||
request("PUT", resource, {
|
||||
"durable": True,
|
||||
"auto_delete": False,
|
||||
"arguments": expected,
|
||||
})
|
||||
current = request("GET", resource)
|
||||
if (current.get("type") != "classic" or not current.get("durable") or
|
||||
current.get("arguments", {}) != expected):
|
||||
raise SystemExit(
|
||||
f"Queue {name} has incompatible settings; stop consumers, inspect and drain it, "
|
||||
"then delete and redeclare it"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
exchange_resource = f"exchanges/%2F/{quote(DLX, safe='')}"
|
||||
request("PUT", exchange_resource, {
|
||||
"type": "direct",
|
||||
"durable": True,
|
||||
"auto_delete": False,
|
||||
"internal": False,
|
||||
"arguments": {},
|
||||
})
|
||||
|
||||
ensure_queue(DLQ, {})
|
||||
binding_resource = f"bindings/%2F/e/{quote(DLX, safe='')}/q/{quote(DLQ, safe='')}"
|
||||
bindings = request("GET", binding_resource) or []
|
||||
if not any(binding.get("routing_key") == DLQ_ROUTING_KEY and
|
||||
binding.get("arguments", {}) == {} for binding in bindings):
|
||||
request("POST", binding_resource, {"routing_key": DLQ_ROUTING_KEY, "arguments": {}})
|
||||
|
||||
ensure_queue(QUEUE, {
|
||||
"x-dead-letter-exchange": DLX,
|
||||
"x-dead-letter-routing-key": DLQ_ROUTING_KEY,
|
||||
})
|
||||
print(f"Durable classic queue {QUEUE} and DLQ {DLQ} via {DLX} are ready")
|
||||
|
||||
|
||||
for attempt in range(30):
|
||||
try:
|
||||
with urlopen(Request(url, data=body, headers=headers, method="PUT"), timeout=3):
|
||||
pass
|
||||
with urlopen(Request(url, headers=headers), timeout=3) as response:
|
||||
queue = json.load(response)
|
||||
if queue.get("type") != "quorum" or not queue.get("durable"):
|
||||
raise SystemExit("Processing queue is not durable quorum")
|
||||
print("Durable quorum queue attachments.process is ready")
|
||||
main()
|
||||
break
|
||||
except HTTPError as exc:
|
||||
if exc.code in (400, 401, 403, 406):
|
||||
raise SystemExit(f"RabbitMQ queue declaration failed (HTTP {exc.code})") from None
|
||||
raise SystemExit(f"RabbitMQ topology declaration failed (HTTP {exc.code})") from None
|
||||
except URLError:
|
||||
pass
|
||||
if attempt == 29:
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
DEMO_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
LAB_ROOT="$(cd -- "${DEMO_DIR}/.." && pwd)"
|
||||
cd "${LAB_ROOT}"
|
||||
|
||||
demo_preflight() {
|
||||
if [[ ! -f .env ]]; then
|
||||
echo "Не найден .env. Подготовьте стенд по REPORT.md: cp .env.example .env и python3 scripts/setup-local-secrets.py" >&2
|
||||
return 2
|
||||
fi
|
||||
|
||||
local port
|
||||
port="${APP_PORT:-$(awk -F= '$1 == "APP_PORT" { gsub(/"/, "", $2); gsub(/[[:space:]]/, "", $2); print $2; exit }' .env)}"
|
||||
export BASE_URL="${BASE_URL:-http://localhost:${port:-8080}}"
|
||||
|
||||
for service in postgres s3 broker publisher worker lb; do
|
||||
if [[ -z "$(docker compose --env-file .env ps -q "$service")" ]]; then
|
||||
echo "Сервис '$service' не запущен. Поднимите стенд командами из REPORT.md; скрипт не скачивает образы и не запускает зависимости автоматически." >&2
|
||||
return 2
|
||||
fi
|
||||
done
|
||||
|
||||
python3 - "$BASE_URL" <<'PYTHON'
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
url = sys.argv[1].rstrip("/") + "/health/ready"
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=5) as response:
|
||||
print(f"API готов: HTTP {response.status} ({url})")
|
||||
except (urllib.error.URLError, TimeoutError) as exc:
|
||||
raise SystemExit(f"API недоступен по {url}: {exc}")
|
||||
PYTHON
|
||||
}
|
||||
Reference in New Issue
Block a user