Files
mtusi2026lab3/.claude/skills/run-mtusi-messenger/driver.py
T
ricoromaandClaude Opus 5.5 ab71c3b51e feat: put API replicas behind HAProxy
HAProxy 3.4 is the only published entry point; api runs as
API_REPLICAS replicas without ports, found through Docker DNS and
checked on /health/ready. Retries only on connection failure, LB errors
in the contract error format, resource limits and per-service secrets.
Adds scripts/stop-one.sh, LB-aware restart.sh, make replicas /
instances / lb_stats and replica tests driven by EXPECT_REPLICAS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:05:05 +03:00

652 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Драйвер API мессенджера для агента: запуск, сценарий, запросы, остановка.
Только стандартная библиотека. Запускать из корня репозитория:
python3 .claude/skills/run-mtusi-messenger/driver.py [--port N] <cmd>
Команды:
start `make upgrade start_cache` (Postgres из compose и миграции,
Valkey), затем поднять `python -m src` в фоне (console,
reload) и дождаться /health/ready; лог и pid —
/tmp/mtusi-api-<port>.{log,pid}
status кто слушает порт и что отвечает /health/ready
flow сквозной сценарий по HTTP с проверками; код выхода 1 при провале
req один запрос: req METHOD PATH [--token T | --basic USER:PASS]
[--data JSON] [--key K | --no-key]; POST сообщения без --key
получает новый Idempotency-Key (печатается для повтора)
smoke публичный tests/smoke.py против этого порта
student собственные тесты student-tests/ (make student_test) против
этого порта; против своего процесса — с EXPECT_REPLICAS=1
instances [--count N] распределение одной сессии по репликам: вход
одним синтетическим пользователем, N × GET /users/me с одним
токеном, X-Instance-Id каждого ответа и итог по репликам
stop остановить свой экземпляр на порту
all start → flow → smoke → student (если есть student-tests/) → stop
Порт по умолчанию 18080, а не 8080: на 8080 обычно работает стенд
`make run_docker` (HAProxy перед репликами API) или `make run_dev`
пользователя, и их процессы трогать не надо. Экземпляр драйвера пишет в
ту же рабочую базу Postgres. flow, req, smoke, student и instances
работают с любым сервером на порту, в том числе со стендом через
балансировщик (`--port 8080`).
"""
import argparse
import base64
import contextlib
import json
import os
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
DEFAULT_PORT = 18080
USERS = "/api/v1/users"
CHATS = "/api/v1/chats"
SESSIONS = "/api/v1/auth/sessions"
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
# с лабы 3 обязателен у POST сообщения: одна отправка — один ключ
IDEMPOTENCY_KEY = "Idempotency-Key"
def key_header(key: str | None = None) -> dict[str, str]:
"""Заголовок ключа идемпотентности; без `key` — новый ключ."""
return {IDEMPOTENCY_KEY: key or uuid.uuid4().hex}
def paths(port: int) -> tuple[Path, Path]:
return (
Path(f"/tmp/mtusi-api-{port}.log"),
Path(f"/tmp/mtusi-api-{port}.pid"),
)
def base_url(port: int) -> str:
return f"http://127.0.0.1:{port}"
def basic(username: str, password: str) -> str:
"""Значение `Authorization: Basic` из username и пароля в UTF-8."""
raw = f"{username}:{password}".encode()
return "Basic " + base64.b64encode(raw).decode("ascii")
def call(
port: int,
method: str,
path: str,
*,
token: str | None = None,
authorization: str | None = None,
extra: dict[str, str] | None = None,
body: object = None,
raw: bytes | None = None,
) -> tuple[int, dict[str, str], object]:
data = raw
headers = {"Accept": "application/json"}
if body is not None:
data = json.dumps(body).encode()
if data is not None:
headers["Content-Type"] = "application/json"
if token is not None:
headers["Authorization"] = f"Bearer {token}"
if authorization is not None:
headers["Authorization"] = authorization
headers.update(extra or {})
request = urllib.request.Request(
base_url(port) + path,
data=data,
method=method,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=5) as response:
status = response.status
hdrs = dict(response.headers)
payload = response.read()
except urllib.error.HTTPError as error:
status, hdrs, payload = error.code, dict(error.headers), error.read()
hdrs = {key.lower(): value for key, value in hdrs.items()}
try:
parsed = json.loads(payload) if payload else None
except json.JSONDecodeError:
parsed = payload.decode(errors="replace")
return status, hdrs, parsed
def listener_pids(port: int) -> list[int]:
out = subprocess.run(
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
capture_output=True,
text=True,
check=False,
).stdout
return [int(pid) for pid in out.split()]
def is_ready(port: int) -> bool:
try:
status, _, _ = call(port, "GET", "/health/ready")
except OSError:
return False
return status == 200
def cmd_start(port: int) -> int:
log_path, pid_path = paths(port)
if listener_pids(port):
if is_ready(port):
print(f"already up on {base_url(port)}")
return 0
print(f"port {port} is busy:", listener_pids(port))
return 1
# без Postgres сервис стартует, но /health/ready отвечает 503; без
# Valkey работает, но мимо кэша
upgrade = subprocess.run(
["make", "upgrade", "start_cache"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if upgrade.returncode != 0:
print("make upgrade start_cache failed:")
print((upgrade.stdout + upgrade.stderr)[-2000:])
return 1
env = os.environ | {"APP__RUN_MODE": "console", "APP__PORT": str(port)}
with log_path.open("wb") as log:
proc = subprocess.Popen(
["uv", "run", "python", "-m", "src"],
cwd=ROOT,
env=env,
stdout=log,
stderr=subprocess.STDOUT,
# своя группа процессов: stop гасит uv, reloader и worker разом
start_new_session=True,
)
pid_path.write_text(str(proc.pid))
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if proc.poll() is not None:
print(f"server exited with {proc.returncode}; log: {log_path}")
print(log_path.read_text()[-2000:])
return 1
if is_ready(port):
print(f"up on {base_url(port)} pgid={proc.pid} log={log_path}")
return 0
time.sleep(0.25)
print(f"not ready after 30s; log: {log_path}")
return 1
def cmd_stop(port: int) -> int:
_, pid_path = paths(port)
if not pid_path.exists():
# экземпляр не наш (например, make run_dev): не трогаем
if listener_pids(port):
print(f"port {port} is not ours (no pid file); left running")
return 1
print(f"nothing on {port}")
return 0
with contextlib.suppress(ProcessLookupError):
os.killpg(int(pid_path.read_text()), signal.SIGTERM)
pid_path.unlink()
deadline = time.monotonic() + 12
while listener_pids(port) and time.monotonic() < deadline:
time.sleep(0.2)
if listener_pids(port):
print(f"still listening on {port}:", listener_pids(port))
return 1
print(f"stopped {port}")
return 0
def cmd_status(port: int) -> int:
pids = listener_pids(port)
print("listeners:", pids or "none")
if pids:
print("ready:", is_ready(port))
return 0 if pids else 1
def cmd_req(port: int, args: argparse.Namespace) -> int:
body = json.loads(args.data) if args.data is not None else None
authorization = None
if args.basic is not None:
username, _, password = args.basic.partition(":")
authorization = basic(username, password)
method = args.method.upper()
extra = {}
sends_message = method == "POST" and args.path.rstrip("/").endswith(
"/messages",
)
if args.key is not None or (sends_message and not args.no_key):
extra = key_header(args.key)
# синтетический ключ: для повтора той же отправки через --key
print("idempotency-key:", extra[IDEMPOTENCY_KEY])
status, hdrs, payload = call(
port,
method,
args.path,
token=args.token,
authorization=authorization,
extra=extra,
body=body,
)
print(
status,
"x-request-id:",
hdrs.get("x-request-id"),
"x-instance-id:",
hdrs.get("x-instance-id"),
)
if "www-authenticate" in hdrs:
print("www-authenticate:", hdrs["www-authenticate"])
print(json.dumps(payload, ensure_ascii=False, indent=2))
return 0 if status < 400 else 2
class Flow:
def __init__(self, port: int) -> None:
self.port = port
self.failures = 0
def check(self, label: str, ok: bool, detail: object = "") -> None:
mark = "ok " if ok else "FAIL"
print(f"[{mark}] {label}" + (f" {detail}" if detail else ""))
if not ok:
self.failures += 1
def expect(
self,
label: str,
method: str,
path: str,
status: int,
challenge: str | None = None,
**kwargs: object,
) -> object:
"""Запрос + проверка статуса, X-Request-Id, X-Instance-Id (с лабы
3), формата ошибки и, если задан, `WWW-Authenticate`."""
got, hdrs, payload = call(self.port, method, path, **kwargs)
request_id = hdrs.get("x-request-id")
ok = got == status and bool(request_id)
ok = ok and bool(hdrs.get("x-instance-id"))
detail = str(got)
if got >= 400:
error = {}
if isinstance(payload, dict):
error = payload.get("error", {})
ok = ok and error.get("request_id") == request_id
detail = f"{got} {error.get('code')}"
if challenge is not None:
ok = ok and hdrs.get("www-authenticate") == challenge
detail += f" {hdrs.get('www-authenticate')}"
shown = path if len(path) <= 60 else path[:57] + "..."
self.check(f"{method} {shown} -> {status} ({label})", ok, detail)
return payload
def cmd_flow(port: int) -> int:
flow = Flow(port)
tag = uuid.uuid4().hex[:8]
flow.expect("live", "GET", "/health/live", 200)
flow.expect("ready", "GET", "/health/ready", 200)
me_path = f"{USERS}/me"
ids, tokens, logins = {}, {}, {}
for name in ("alice", "bob", "eve"):
username, password = f"{name}_{tag}", f"Pw-{name}-{uuid.uuid4().hex}"
body = {
"username": username,
"display_name": f"{name} ✨",
"password": password,
}
user = flow.expect("register", "POST", USERS, 201, body=body)
flow.check("no password in User", "password" not in user)
session = flow.expect(
"login",
"POST",
SESSIONS,
201,
authorization=basic(username, password),
)
ids[name], tokens[name] = user["id"], session["token"]
logins[name] = (username, password)
alice, bob, eve = tokens["alice"], tokens["bob"], tokens["eve"]
dup = {
"username": f"alice_{tag}",
"display_name": "again",
"password": "Another-password-1",
}
flow.expect("duplicate username", "POST", USERS, 409, body=dup)
no_password = {"username": f"nopw_{tag}", "display_name": "x"}
flow.expect("no password", "POST", USERS, 400, body=no_password)
username, password = logins["alice"]
wrong = basic(username, "Wrong-password-1")
flow.expect(
"wrong password",
"POST",
SESSIONS,
401,
challenge=BASIC_CHALLENGE,
authorization=wrong,
)
me = flow.expect("me", "GET", me_path, 200, token=alice)
flow.check("me.id == alice", me.get("id") == ids["alice"])
flow.expect("no token", "GET", me_path, 401, challenge=BEARER_CHALLENGE)
flow.expect(
"Basic on business endpoint",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
authorization=basic(username, password),
)
flow.expect(
"only X-User-Id",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
extra={"X-User-Id": ids["alice"]},
)
spoofed = flow.expect(
"X-User-Id ignored",
"GET",
me_path,
200,
token=alice,
extra={"X-User-Id": ids["eve"]},
)
flow.check("still alice", spoofed.get("id") == ids["alice"])
flow.expect(
"unknown token",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
token=uuid.uuid4().hex * 2,
)
body = {"title": "Проект 🚀", "member_ids": [ids["alice"], ids["bob"]]}
chat = flow.expect("new chat", "POST", CHATS, 201, token=alice, body=body)
chat_path = f"{CHATS}/{chat['id']}"
msgs = f"{chat_path}/messages"
body = {"title": "x", "member_ids": [ids["alice"]]}
flow.expect("not a member", "POST", CHATS, 400, token=eve, body=body)
texts = ["привет", "hi 👋", "третье", "четвёртое", "пятое"]
for index, text in enumerate(texts):
sender = alice if index % 2 == 0 else bob
body = {"text": text}
flow.expect(
"send",
"POST",
msgs,
201,
token=sender,
body=body,
extra=key_header(),
)
# с ключом: 400 из-за тела, а не из-за отсутствия ключа
blank = {"text": " "}
flow.expect(
"blank text",
"POST",
msgs,
400,
token=alice,
body=blank,
extra=key_header(),
)
spoof = {"text": "x", "sender_id": ids["alice"]}
flow.expect(
"sender_id",
"POST",
msgs,
400,
token=alice,
body=spoof,
extra=key_header(),
)
seen, cursor, pages = [], None, 0
while pages < 10:
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
page = flow.expect("page", "GET", msgs + query, 200, token=bob)
seen += [item["text"] for item in page["items"]]
cursor, pages = page["next_cursor"], pages + 1
if cursor is None:
break
flow.check("history order via cursor", seen == texts, f"{pages} pages")
flow.check("created_at ends with Z", chat["created_at"].endswith("Z"))
flow.expect("outsider reads chat", "GET", chat_path, 404, token=eve)
flow.expect("outsider reads history", "GET", msgs, 404, token=eve)
hi = {"text": "hi"}
flow.expect(
"outsider posts",
"POST",
msgs,
404,
token=eve,
body=hi,
extra=key_header(),
)
# идемпотентность (лаба 3): повтор, другое тело, нет и неверный ключ
key = key_header()
once = {"text": "один раз"}
sent = flow.expect(
"keyed send",
"POST",
msgs,
201,
token=alice,
body=once,
extra=key,
)
again = flow.expect(
"replay",
"POST",
msgs,
201,
token=alice,
body=once,
extra=key,
)
flow.check("replay returns the same message", again == sent)
other = {"text": "другое"}
flow.expect(
"same key, other body",
"POST",
msgs,
409,
token=alice,
body=other,
extra=key,
)
flow.expect("no key", "POST", msgs, 400, token=alice, body=other)
flow.expect(
"bad key",
"POST",
msgs,
400,
token=alice,
body=other,
extra=key_header("bad key"),
)
history = flow.expect(
"history",
"GET",
msgs + "?limit=100",
200,
token=bob,
)
keyed = [item for item in history["items"] if item["text"] == once["text"]]
flow.check("one message per key", len(keyed) == 1, f"{len(keyed)} found")
flow.expect("no token beats 404", "GET", chat_path, 401)
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, token=alice)
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, token=alice)
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, token=alice)
flow.expect("malformed json", "POST", USERS, 400, raw=b"{not json")
flow.expect("unknown path", "GET", "/nope", 404)
chats = flow.expect("list chats", "GET", CHATS, 200, token=bob)
listed = [item["id"] for item in chats["items"]]
flow.check("bob sees the chat", chat["id"] in listed)
flow.expect("logout", "DELETE", f"{SESSIONS}/current", 204, token=eve)
flow.expect(
"token after logout",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
token=eve,
)
print(
f"\nalice={ids['alice']}\nbob={ids['bob']}\neve={ids['eve']}"
f"\nchat={chat['id']}"
# синтетический токен локального стенда: для `req --token`
f"\nalice_token={alice}",
)
print("FAILED:", flow.failures or "none")
return 1 if flow.failures else 0
def cmd_smoke(port: int) -> int:
return subprocess.call(
[
sys.executable,
"tests/smoke.py",
"--base-url",
f"http://localhost:{port}",
],
cwd=ROOT,
)
def cmd_student(port: int) -> int:
if not (ROOT / "student-tests").is_dir():
print("no student-tests/ in this checkout")
return 1
command = ["make", "student_test", f"BASE_URL=http://localhost:{port}"]
_, pid_path = paths(port)
if pid_path.exists():
# на порту свой процесс драйвера: один API без балансировщика,
# тесты реплик пропускаются с причиной
command.append("EXPECT_REPLICAS=1")
return subprocess.call(command, cwd=ROOT)
def cmd_instances(port: int, count: int) -> int:
"""Распределение одной сессии по репликам: один вход, `count`
запросов `GET /users/me` с одним токеном. Токен не печатается."""
tag = uuid.uuid4().hex[:8]
username, password = f"lb_{tag}", f"Pw-lb-{uuid.uuid4().hex}"
body = {
"username": username,
"display_name": "LB demo",
"password": password,
}
status, _, _ = call(port, "POST", USERS, body=body)
if status != 201:
print(f"register: {status}")
return 1
status, _, session = call(
port,
"POST",
SESSIONS,
authorization=basic(username, password),
)
if status != 201 or not isinstance(session, dict):
print(f"login: {status}")
return 1
token = session["token"]
counts: Counter[str] = Counter()
failures = 0
for number in range(1, count + 1):
status, hdrs, payload = call(port, "GET", f"{USERS}/me", token=token)
instance = hdrs.get("x-instance-id", "-")
ok = status == 200 and isinstance(payload, dict)
ok = ok and payload.get("username") == username
failures += not ok
print(
f"{number:>3} GET /api/v1/users/me {status} "
f"x-instance-id: {instance}" + ("" if ok else " UNEXPECTED"),
)
counts[instance] += 1
print(f"user {username}: one login, {count} requests with one token")
for instance, served in counts.most_common():
print(f" {instance}: {served}")
print(f"instances: {len(counts)}")
return 1 if failures else 0
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
sub = parser.add_subparsers(dest="cmd", required=True)
for name in ("start", "stop", "status", "flow", "smoke", "student", "all"):
sub.add_parser(name)
instances = sub.add_parser("instances")
instances.add_argument("--count", type=int, default=12)
req = sub.add_parser("req")
req.add_argument("method")
req.add_argument("path")
auth = req.add_mutually_exclusive_group()
auth.add_argument("--token", help="Bearer-токен сессии")
auth.add_argument("--basic", help="USER:PASS для POST /auth/sessions")
req.add_argument("--data")
key = req.add_mutually_exclusive_group()
key.add_argument("--key", help="Idempotency-Key (повтор отправки)")
key.add_argument(
"--no-key",
action="store_true",
help="POST сообщения без Idempotency-Key (ожидается 400)",
)
args = parser.parse_args()
port = args.port
if args.cmd == "all":
if cmd_start(port) != 0:
return 1
try:
flow_rc = cmd_flow(port)
smoke_rc = cmd_smoke(port)
student_rc = 0
if (ROOT / "student-tests").is_dir():
student_rc = cmd_student(port)
finally:
cmd_stop(port)
return flow_rc or smoke_rc or student_rc
if args.cmd == "req":
return cmd_req(port, args)
if args.cmd == "instances":
return cmd_instances(port, args.count)
handlers = {
"start": cmd_start,
"stop": cmd_stop,
"status": cmd_status,
"flow": cmd_flow,
"smoke": cmd_smoke,
"student": cmd_student,
}
return handlers[args.cmd](port)
if __name__ == "__main__":
sys.exit(main())