forked from mtusi2026/mtusi2026lab7
тесты и healthcheck устойчивее к медленному хосту: время пробы внутри контейнера, healthcheck timeout 5 с, дочитывание TLS-ответа, grace уборщика 15 с
This commit is contained in:
@@ -456,12 +456,21 @@ def attachment_row(attachment_id: str) -> dict | None:
|
||||
return json.loads(out) if out else None
|
||||
|
||||
|
||||
def probe_inside(replica: dict, path: str) -> int:
|
||||
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB) - lab 7: on
|
||||
the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client certificate."""
|
||||
code = ("import urllib.request as u, urllib.error as e\n"
|
||||
"try: print(u.urlopen('http://127.0.0.1:8081%s', timeout=3).status)\n"
|
||||
"except e.HTTPError as x: print(x.code)") % path
|
||||
def probe_inside_timed(replica: dict, path: str) -> tuple[int, float]:
|
||||
"""(HTTP status, seconds) of `path` asked inside the replica container itself (bypassing the LB) -
|
||||
lab 7: on the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client
|
||||
certificate. The time is measured INSIDE the container around the request only: `docker exec`
|
||||
and the Python start-up (seconds on a loaded Windows host) are the test tool's cost, not the
|
||||
replica's responsiveness."""
|
||||
code = ("import time, urllib.request as u, urllib.error as e\n"
|
||||
"t = time.perf_counter()\n"
|
||||
"try: s = u.urlopen('http://127.0.0.1:8081%s', timeout=5).status\n"
|
||||
"except e.HTTPError as x: s = x.code\n"
|
||||
"print(s, round(time.perf_counter() - t, 3))") % path
|
||||
out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True,
|
||||
timeout=30).stdout.strip()
|
||||
return int(out or 0)
|
||||
timeout=60).stdout.split()
|
||||
return (int(out[0]), float(out[1])) if len(out) == 2 else (0, 99.0)
|
||||
|
||||
|
||||
def probe_inside(replica: dict, path: str) -> int:
|
||||
return probe_inside_timed(replica, path)[0]
|
||||
|
||||
@@ -15,7 +15,7 @@ import uuid
|
||||
import httpx2 as httpx
|
||||
import pytest
|
||||
|
||||
from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside, psql, replica_stopped, run_hook, \
|
||||
from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside_timed, psql, replica_stopped, run_hook, \
|
||||
running_replicas, wait_healthy, wait_stand
|
||||
|
||||
pytestmark = pytest.mark.stack
|
||||
@@ -109,10 +109,10 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position
|
||||
time.sleep(0.1)
|
||||
detected = time.monotonic() - started
|
||||
for _ in range(3): # the process stays responsive (event loop never blocked) ...
|
||||
started_probe = time.monotonic()
|
||||
assert probe_inside(replica, "/health/live") == 200
|
||||
assert probe_inside(replica, "/health/ready") == 503 # ... but not ready
|
||||
assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable"
|
||||
live, live_s = probe_inside_timed(replica, "/health/live")
|
||||
ready, ready_s = probe_inside_timed(replica, "/health/ready")
|
||||
assert live == 200 and ready == 503 # ... but not ready
|
||||
assert live_s + ready_s < 4.5, ("replica froze while its dependencies were unreachable", live_s, ready_s)
|
||||
seen = instances_seen(api, actor["token"], 40)
|
||||
assert replica["instance"] not in seen and len(seen) == 40
|
||||
for i in range(20): # writes keep working, only through the ready replicas
|
||||
|
||||
@@ -60,7 +60,19 @@ def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_ans
|
||||
sock.close()
|
||||
return b""
|
||||
time.sleep(wait_answer)
|
||||
answer = sock.recv(65536)
|
||||
answer = b""
|
||||
sock.settimeout(5)
|
||||
try:
|
||||
while chunk := sock.recv(65536): # lab 7: TLS delivers headers and body in separate records
|
||||
answer += chunk
|
||||
if b"\r\n\r\n" in answer:
|
||||
head, _, body = answer.partition(b"\r\n\r\n")
|
||||
length = next((int(line.split(b":", 1)[1]) for line in head.split(b"\r\n")
|
||||
if line.lower().startswith(b"content-length:")), None)
|
||||
if length is not None and len(body) >= length:
|
||||
break
|
||||
except (TimeoutError, OSError):
|
||||
pass
|
||||
sock.close()
|
||||
return answer
|
||||
|
||||
@@ -84,14 +96,16 @@ def test_crash_after_staging_before_job_is_cleaned_by_janitor(api):
|
||||
(object first) and then the intent row; no job, no message ever existed."""
|
||||
alice = api.user("alice")
|
||||
chat = api.chat(alice)
|
||||
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
|
||||
# grace 15 s: the checks below go through docker exec (seconds each on a loaded host) and must
|
||||
# see the orphan BEFORE the janitor may remove it.
|
||||
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="15", JANITOR_INTERVAL_SECONDS="1"):
|
||||
assert api.upload(alice, chat, SAMPLE, 503).json()["error"]["code"] == "unavailable"
|
||||
[(attachment_id, status, key)] = rows_of_chat(chat["id"])
|
||||
assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) # the orphan-to-be exists
|
||||
assert jobs_of(attachment_id) == (0, 0) # no job, no outbox row
|
||||
api.call("GET", f"/api/v1/attachments/{attachment_id}", 404, token=alice["token"]) # invisible
|
||||
api.post_message(alice, chat, {"text": "", "attachment_ids": [attachment_id]}, 404) # not attachable
|
||||
wait_for(lambda: rows_of_chat(chat["id"]) == [], 30, "janitor did not remove the stale intent")
|
||||
wait_for(lambda: rows_of_chat(chat["id"]) == [], 60, "janitor did not remove the stale intent")
|
||||
assert s3_size(key, "staging") is None # object removed first
|
||||
# Normal configuration again: an upload in the same chat works and is not touched.
|
||||
att = api.upload(alice, chat, SAMPLE).json()
|
||||
|
||||
Reference in New Issue
Block a user