feat: bound upload memory with per-replica slots and a body deadline
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -96,6 +96,15 @@
|
||||
нет, готовое вложение скачивается с тем же SHA-256; триггер
|
||||
снимается в finally и в начале следующего прогона; код 1 при
|
||||
расхождении, без LB — код 2
|
||||
lb-upload-timeouts [--config F] [--image ТЕГ] без стенда: спек
|
||||
load-balancing «Загрузки через балансировщик» — временная
|
||||
сеть, HAProxy закреплённого образа с конфигурацией F (по
|
||||
умолчанию infra/haproxy/haproxy.cfg) и заглушка реплики под
|
||||
именем api; молчание заглушки 12 с до и после тела загрузки —
|
||||
201, 12 с на другом пути — 504 через ~10 с, 32 с на пути
|
||||
загрузки — 504 через ~30 с, клиент молчит посреди тела — 400
|
||||
в формате контракта; сеть и контейнеры удаляются при любом
|
||||
исходе; код 1 при расхождении
|
||||
stop остановить свой экземпляр на порту
|
||||
all start → flow → smoke → student (если есть student-tests/) → stop
|
||||
|
||||
@@ -127,6 +136,7 @@ import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
@@ -2761,6 +2771,426 @@ def report_rows(rows: list[tuple[str, str, str]]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
# lb-upload-timeouts: сроки LB пути загрузки на заглушке (design change
|
||||
# upload-memory, решение 7). Молчание заглушки: дольше timeout server
|
||||
# прочих путей (10 с), но меньше срока пути загрузки (30 с) — и дольше его
|
||||
LBTO_LABEL = "mtusi.lb-upload-timeouts"
|
||||
LBTO_SILENT_S = 12
|
||||
LBTO_LONG_S = 32
|
||||
# сколько клиент молчит посреди тела, если LB не ответил раньше: дольше
|
||||
# timeout client (30 с)
|
||||
LBTO_CLIENT_SILENT_S = 35
|
||||
LBTO_BODY_BYTES = 10 * 1024 * 1024
|
||||
LBTO_UPLOAD_PATH = f"{CHATS}/{uuid.UUID(int=1)}/attachments"
|
||||
LBTO_READY_TIMEOUT_S = 30
|
||||
# заглушка реплики на asyncio (stdlib образа API): /health/ready — 200,
|
||||
# остальное — по параметру case; тело читает только там, где сказано
|
||||
LBTO_STUB = r"""
|
||||
import asyncio, json, os
|
||||
|
||||
SILENT = float(os.environ["STUB_SILENT_S"])
|
||||
LONG = float(os.environ["STUB_LONG_S"])
|
||||
|
||||
|
||||
async def handle(reader, writer):
|
||||
try:
|
||||
head = await reader.readuntil(b"\r\n\r\n")
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
target = lines[0].split(" ")[1]
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
name, sep, value = line.partition(":")
|
||||
if sep:
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
path, _, query = target.partition("?")
|
||||
params = dict(p.split("=", 1) for p in query.split("&") if "=" in p)
|
||||
case = params.get("case", "")
|
||||
length = int(headers.get("content-length") or 0)
|
||||
status = 200
|
||||
if path != "/health/ready":
|
||||
if case == "before-body":
|
||||
await asyncio.sleep(SILENT)
|
||||
await reader.readexactly(length)
|
||||
status = 201
|
||||
elif case in ("after-body", "too-long"):
|
||||
await reader.readexactly(length)
|
||||
await asyncio.sleep(SILENT if case == "after-body" else LONG)
|
||||
status = 201
|
||||
elif case == "other-path":
|
||||
await asyncio.sleep(SILENT)
|
||||
else:
|
||||
await reader.readexactly(length)
|
||||
status = 201
|
||||
body = json.dumps({"status": "ok", "case": case}).encode()
|
||||
writer.write(
|
||||
f"HTTP/1.1 {status} Stub\r\nContent-Type: application/json\r\n"
|
||||
f"Content-Length: {len(body)}\r\nX-Request-Id: stub-{case}\r\n"
|
||||
"X-Instance-Id: stub\r\nConnection: close\r\n\r\n".encode() + body
|
||||
)
|
||||
await writer.drain()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
|
||||
async def main():
|
||||
server = await asyncio.start_server(handle, "0.0.0.0", 8080)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
|
||||
def lbto_docker(*args: str, check: bool = True) -> str:
|
||||
"""docker CLI без shell; вывод — строкой."""
|
||||
result = subprocess.run(
|
||||
["docker", *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if check and result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"docker {args[0]} {args[1] if len(args) > 1 else ''}: "
|
||||
f"{result.stderr.strip()[-300:]}",
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def lbto_haproxy_image() -> str:
|
||||
"""Образ LB рабочего стенда — тег и digest из docker-compose.yml."""
|
||||
text = (ROOT / "docker-compose.yml").read_text(encoding="utf-8")
|
||||
match = re.search(r"^\s*image:\s*(haproxy:\S+)\s*$", text, re.MULTILINE)
|
||||
if match is None:
|
||||
raise RuntimeError("no haproxy image in docker-compose.yml")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def lbto_error_ok(
|
||||
headers: dict[str, str],
|
||||
body: bytes,
|
||||
code: str,
|
||||
) -> str:
|
||||
"""Пусто — ответ LB в формате ошибки контракта; иначе — что не так."""
|
||||
media = headers.get("content-type", "").split(";")[0].strip()
|
||||
if media != "application/json":
|
||||
return f"Content-Type {media or '-'}"
|
||||
try:
|
||||
data = json.loads(body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
return "body is not JSON"
|
||||
error = data.get("error") if isinstance(data, dict) else None
|
||||
if not isinstance(error, dict) or set(data) != {"error"}:
|
||||
return "not {error: …}"
|
||||
if set(error) != {"code", "message", "request_id"}:
|
||||
return f"error fields {sorted(error)}"
|
||||
if error["code"] != code:
|
||||
return f"code {error['code']}"
|
||||
request_id = headers.get("x-request-id", "")
|
||||
if not request_id or error["request_id"] != request_id:
|
||||
return "request_id differs from X-Request-Id"
|
||||
return ""
|
||||
|
||||
|
||||
def lbto_request(
|
||||
port: int,
|
||||
method: str,
|
||||
path: str,
|
||||
body: bytes | None,
|
||||
) -> tuple[int, dict[str, str], bytes, float]:
|
||||
"""Запрос через LB: статус, заголовки, тело, секунды до ответа."""
|
||||
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
headers = {"Content-Type": "image/png"} if body is not None else {}
|
||||
conn.request(method, path, body=body, headers=headers)
|
||||
resp = conn.getresponse()
|
||||
data = resp.read()
|
||||
elapsed = time.monotonic() - started
|
||||
return (
|
||||
resp.status,
|
||||
{k.lower(): v for k, v in resp.getheaders()},
|
||||
data,
|
||||
elapsed,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def lbto_silent_client(
|
||||
port: int,
|
||||
) -> tuple[int, dict[str, str], bytes, float]:
|
||||
"""Клиент отправил половину тела и молчит: ответ LB и секунды от
|
||||
последнего отправленного байта."""
|
||||
sock = socket.create_connection(("127.0.0.1", port), timeout=10)
|
||||
try:
|
||||
head = (
|
||||
f"POST {LBTO_UPLOAD_PATH}?case=client-silent HTTP/1.1\r\n"
|
||||
f"Host: 127.0.0.1:{port}\r\nContent-Type: image/png\r\n"
|
||||
f"Content-Length: {LBTO_BODY_BYTES}\r\n\r\n"
|
||||
).encode("ascii")
|
||||
sock.sendall(head + bytes(LBTO_BODY_BYTES // 2))
|
||||
started = time.monotonic()
|
||||
sock.settimeout(LBTO_CLIENT_SILENT_S + 10)
|
||||
resp = http.client.HTTPResponse(sock, method="POST")
|
||||
resp.begin()
|
||||
data = resp.read()
|
||||
return (
|
||||
resp.status,
|
||||
{k.lower(): v for k, v in resp.getheaders()},
|
||||
data,
|
||||
time.monotonic() - started,
|
||||
)
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
|
||||
def cmd_lb_upload_timeouts(config: str, image: str) -> int:
|
||||
"""Сроки LB пути загрузки (спек `load-balancing`, «Загрузки через
|
||||
балансировщик», «Ошибки балансировщика в формате контракта»; design
|
||||
change `upload-memory`, решение 7).
|
||||
|
||||
Временная сеть, заглушка реплики под именем `api` (образ API, stdlib)
|
||||
и HAProxy закреплённого образа с `config`, порт LB — на свободном
|
||||
`127.0.0.1`. Случаи идут параллельно, каждый — своё соединение и свой
|
||||
`case` в строке запроса. Хранилищ и стендов compose не трогает; сеть и
|
||||
контейнеры по метке удаляются при любом исходе."""
|
||||
|
||||
def interrupted(signum: int, _frame: object) -> None:
|
||||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||||
|
||||
config_path = Path(config).resolve()
|
||||
if not config_path.is_file():
|
||||
print(f"config {config_path} not found")
|
||||
return 2
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
label = f"{LBTO_LABEL}={tag}"
|
||||
network = f"mtusi-lbto-{tag}"
|
||||
haproxy = lbto_haproxy_image()
|
||||
port = lbto_free_port()
|
||||
print(f"config {config_path}")
|
||||
print(f"haproxy {haproxy}, stub image {image}, LB 127.0.0.1:{port}")
|
||||
previous = {
|
||||
signum: signal.signal(signum, interrupted)
|
||||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||||
}
|
||||
mount = (
|
||||
f"type=bind,src={config_path},"
|
||||
"dst=/usr/local/etc/haproxy/haproxy.cfg,readonly"
|
||||
)
|
||||
try:
|
||||
checked = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--label",
|
||||
label,
|
||||
"-e",
|
||||
"API_PORT=8080",
|
||||
"--mount",
|
||||
mount,
|
||||
haproxy,
|
||||
"haproxy",
|
||||
"-c",
|
||||
"-f",
|
||||
"/usr/local/etc/haproxy/haproxy.cfg",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
print(f"haproxy -c: exit {checked.returncode}")
|
||||
if checked.returncode != 0:
|
||||
print((checked.stdout + checked.stderr).strip()[-600:])
|
||||
return 1
|
||||
lbto_docker("network", "create", "--label", label, network)
|
||||
lbto_docker(
|
||||
"run",
|
||||
"-d",
|
||||
"--name",
|
||||
f"{network}-api",
|
||||
"--label",
|
||||
label,
|
||||
"--network",
|
||||
network,
|
||||
"--network-alias",
|
||||
"api",
|
||||
"--no-healthcheck",
|
||||
"-e",
|
||||
f"STUB_SILENT_S={LBTO_SILENT_S}",
|
||||
"-e",
|
||||
f"STUB_LONG_S={LBTO_LONG_S}",
|
||||
"--entrypoint",
|
||||
"python",
|
||||
image,
|
||||
"-c",
|
||||
LBTO_STUB,
|
||||
)
|
||||
lbto_docker(
|
||||
"run",
|
||||
"-d",
|
||||
"--name",
|
||||
f"{network}-lb",
|
||||
"--label",
|
||||
label,
|
||||
"--network",
|
||||
network,
|
||||
"-e",
|
||||
"API_PORT=8080",
|
||||
"-p",
|
||||
f"127.0.0.1:{port}:8080",
|
||||
"--mount",
|
||||
mount,
|
||||
haproxy,
|
||||
)
|
||||
deadline = time.monotonic() + LBTO_READY_TIMEOUT_S
|
||||
while True:
|
||||
try:
|
||||
status = lbto_request(port, "GET", "/health/ready", None)[0]
|
||||
except OSError:
|
||||
status = 0
|
||||
if status == 200:
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
print(f"stub is not UP in LB after {LBTO_READY_TIMEOUT_S}s")
|
||||
return 1
|
||||
time.sleep(0.5)
|
||||
return lbto_cases(port)
|
||||
finally:
|
||||
left = lbto_docker(
|
||||
"ps",
|
||||
"-aq",
|
||||
"--filter",
|
||||
f"label={label}",
|
||||
check=False,
|
||||
).split()
|
||||
if left:
|
||||
lbto_docker("rm", "-f", *left, check=False)
|
||||
lbto_docker("network", "rm", network, check=False)
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
|
||||
|
||||
def lbto_free_port() -> int:
|
||||
"""Свободный порт 127.0.0.1; сокет закрывается до публикации LB."""
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
def lbto_cases(port: int) -> int:
|
||||
"""Случаи параллельно; таблица и код 1 при расхождении."""
|
||||
body = b"\x89PNG\r\n\x1a\n" + bytes(LBTO_BODY_BYTES - 8)
|
||||
upload = f"{LBTO_UPLOAD_PATH}?case="
|
||||
# случай, вызов, статус, code ошибки LB (пусто — ответ заглушки) и
|
||||
# границы времени ответа, с
|
||||
cases = [
|
||||
(
|
||||
"upload: replica silent 12 s before body",
|
||||
lambda: lbto_request(port, "POST", f"{upload}before-body", body),
|
||||
201,
|
||||
"",
|
||||
(LBTO_SILENT_S - 0.5, LBTO_SILENT_S + 5),
|
||||
),
|
||||
(
|
||||
"upload: replica silent 12 s after body",
|
||||
lambda: lbto_request(port, "POST", f"{upload}after-body", body),
|
||||
201,
|
||||
"",
|
||||
(LBTO_SILENT_S - 0.5, LBTO_SILENT_S + 5),
|
||||
),
|
||||
(
|
||||
"other path: replica silent 12 s",
|
||||
lambda: lbto_request(
|
||||
port,
|
||||
"GET",
|
||||
"/api/v1/users/me?case=other-path",
|
||||
None,
|
||||
),
|
||||
504,
|
||||
"unavailable",
|
||||
(9.5, 12),
|
||||
),
|
||||
(
|
||||
"upload: replica silent 32 s",
|
||||
lambda: lbto_request(port, "POST", f"{upload}too-long", body),
|
||||
504,
|
||||
"unavailable",
|
||||
(29.5, 32),
|
||||
),
|
||||
(
|
||||
"upload: client silent mid-body",
|
||||
lambda: lbto_silent_client(port),
|
||||
400,
|
||||
"invalid_request",
|
||||
(29, 33),
|
||||
),
|
||||
]
|
||||
results: dict[int, object] = {}
|
||||
|
||||
def run_case(number: int, call: object) -> None:
|
||||
try:
|
||||
results[number] = call() # type: ignore[operator]
|
||||
except Exception as e: # noqa: BLE001 — исход случая в таблицу
|
||||
results[number] = e
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=run_case, args=(number, case[1]))
|
||||
for number, case in enumerate(cases)
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
width = max(len(case[0]) for case in cases)
|
||||
print(
|
||||
f"{'case':<{width}} {'expected':<29} {'got':<24} {'time':>7}",
|
||||
)
|
||||
failed = 0
|
||||
for number, (name, _, status, code, (low, high)) in enumerate(cases):
|
||||
expected = f"{status} {code or 'replica'} {low:g}–{high:g} s"
|
||||
outcome = results.get(number)
|
||||
if isinstance(outcome, Exception):
|
||||
got, elapsed, problem = type(outcome).__name__, None, "error"
|
||||
else:
|
||||
got_status, headers, data, elapsed = outcome # type: ignore[misc]
|
||||
problem = ""
|
||||
if got_status != status:
|
||||
problem = f"status {got_status}"
|
||||
elif code:
|
||||
problem = lbto_error_ok(headers, data, code)
|
||||
elif headers.get("x-instance-id") != "stub":
|
||||
problem = "not the replica answer"
|
||||
if not problem and not low <= elapsed <= high:
|
||||
problem = f"time {elapsed:.2f} s"
|
||||
source = (
|
||||
"replica" if headers.get("x-instance-id") == "stub" else "LB"
|
||||
)
|
||||
got = f"{got_status} {source}"
|
||||
if got_status >= 400 and source == "LB":
|
||||
media = headers.get("content-type", "").split(";")[0]
|
||||
got += f" {media or '-'}"
|
||||
time_cell = "-" if elapsed is None else f"{elapsed:.2f} s"
|
||||
verdict = "" if not problem else f" FAIL: {problem}"
|
||||
failed += bool(problem)
|
||||
print(
|
||||
f"{name:<{width}} {expected:<29} {got:<24} {time_cell:>7}"
|
||||
f"{verdict}",
|
||||
)
|
||||
if failed:
|
||||
print(f"FAIL: {failed} case(s) differ")
|
||||
return 1
|
||||
print(
|
||||
"PASS: the upload path waits 30 s for the replica, other paths 10 s, "
|
||||
"LB errors are in the contract format",
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
# stop-at-start: записи журнала, по которым видны этапы старта и остановки
|
||||
STARTED_SERVER = "Started server process"
|
||||
SERVER_RUNNING = "Uvicorn running on"
|
||||
@@ -3144,6 +3574,17 @@ def main() -> int:
|
||||
failover.add_argument("--mode", choices=("stop", "kill"), default="stop")
|
||||
sub.add_parser("attachment-storage")
|
||||
sub.add_parser("upload-consistency")
|
||||
lbto = sub.add_parser("lb-upload-timeouts")
|
||||
lbto.add_argument(
|
||||
"--config",
|
||||
default=str(ROOT / "infra" / "haproxy" / "haproxy.cfg"),
|
||||
help="конфигурация HAProxy (по умолчанию — проекта)",
|
||||
)
|
||||
lbto.add_argument(
|
||||
"--image",
|
||||
default="mtusi-messenger:lab4",
|
||||
help="образ заглушки реплики (нужен только python)",
|
||||
)
|
||||
stop = sub.add_parser("stop-at-start")
|
||||
stop.add_argument("--image", default="mtusi-messenger:lab4")
|
||||
stop.add_argument(
|
||||
@@ -3226,6 +3667,8 @@ def main() -> int:
|
||||
return cmd_attachment_storage(port)
|
||||
if args.cmd == "upload-consistency":
|
||||
return cmd_upload_consistency(port)
|
||||
if args.cmd == "lb-upload-timeouts":
|
||||
return cmd_lb_upload_timeouts(args.config, args.image)
|
||||
if args.cmd == "stop-at-start":
|
||||
return cmd_stop_at_start(
|
||||
args.image,
|
||||
|
||||
Reference in New Issue
Block a user