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>
This commit is contained in:
2026-10-10 18:05:05 +03:00
co-authored by Claude Opus 5.5
parent 8e15e02898
commit ab71c3b51e
31 changed files with 1295 additions and 240 deletions
+59 -4
View File
@@ -19,7 +19,12 @@ from api_client import (
registration,
unique_username,
)
from contract import assert_error, assert_ok
from contract import (
assert_error,
assert_instance_id,
assert_ok,
assert_replicas,
)
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
@@ -152,9 +157,48 @@ def test_same_key_at_once(
"""Спек `student-tests`, сценарий «Гонка одного ключа»: одно тело с
одним ключом от `CLIENTS` клиентов сразу — ровно одно сообщение.
Против одного процесса API гонку решает PostgreSQL так же, как между
репликами; ответы разных реплик требует change `replicas-lb`.
На любом стенде: против одного процесса API гонку решает PostgreSQL
так же, как между репликами. Ответы разных реплик требует
`test_same_key_through_replicas`.
"""
results = race_one_key(api, alice, chat, base_url)
peak = max_in_flight([(start, end) for _, start, end in results])
assert peak >= 2, "requests did not overlap: race is not proven"
@pytest.mark.spec("idempotency", "Гонка одного ключа через реплики")
def test_same_key_through_replicas(
api: Api,
alice: Actor,
chat: dict[str, Any],
base_url: str,
replicas: int,
) -> None:
"""Та же гонка через балансировщик: среди ответов есть пара
пересекающихся по времени запросов, которые обслужили разные реплики.
Это и есть «одновременно через разные реплики», а не просто «разные
реплики за весь прогон». Против одного процесса — пропуск."""
results = race_one_key(api, alice, chat, base_url)
spans = [
(assert_instance_id(resp), start, end) for resp, start, end in results
]
served = Counter(instance for instance, _, _ in spans)
print(f"key race through replicas: {dict(served)}")
assert_replicas(served, replicas)
assert overlap_on_different_replicas(spans), (
f"no overlapping requests on different replicas: {dict(served)}"
)
def race_one_key(
api: Api,
alice: Actor,
chat: dict[str, Any],
base_url: str,
) -> list[tuple[httpx.Response, float, float]]:
"""`CLIENTS` клиентов сразу шлют одно тело с одним ключом: все 201 с
одним `Message`, в истории ровно одно сообщение. Возвращает ответы со
временем начала и конца."""
key = new_key()
body = {"text": "один раз"}
@@ -172,8 +216,19 @@ def test_same_key_at_once(
f"max in flight {peak}; history: {len(history)} messages",
)
assert peak >= 2, "requests did not overlap: race is not proven"
assert statuses == {201: CLIENTS}, statuses
messages = [assert_ok(resp, 201, "Message") for resp, _, _ in results]
assert all(message == messages[0] for message in messages)
assert history == [messages[0]]
return results
def overlap_on_different_replicas(
spans: list[tuple[str, float, float]],
) -> bool:
"""Есть два запроса разных реплик, которые были в полёте одновременно."""
return any(
first[0] != second[0] and first[1] < second[2] and second[1] < first[2]
for number, first in enumerate(spans)
for second in spans[number + 1 :]
)