Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy
This commit is contained in:
@@ -137,14 +137,23 @@ def replica_at(address: str) -> str:
|
||||
|
||||
|
||||
def raw(
|
||||
path: str, headers: dict[str, str], body: bytes, *, hang_up: bool
|
||||
path: str,
|
||||
headers: dict[str, str],
|
||||
body: bytes,
|
||||
*,
|
||||
hang_up: bool,
|
||||
piece: int = 0,
|
||||
delay: float = 0.0,
|
||||
) -> tuple[int, dict[str, Any], float]:
|
||||
parts = urlsplit(BASE_URL)
|
||||
head = f"POST {path} HTTP/1.1\r\nHost: {parts.netloc}\r\nConnection: close\r\n"
|
||||
head += "".join(f"{name}: {value}\r\n" for name, value in headers.items()) + "\r\n"
|
||||
started = time.perf_counter()
|
||||
with socket.create_connection((parts.hostname, parts.port or 80), timeout=30) as sock:
|
||||
sock.sendall(head.encode("latin-1") + body)
|
||||
sock.sendall(head.encode("latin-1"))
|
||||
for start in range(0, len(body), piece or max(len(body), 1)):
|
||||
sock.sendall(body[start : start + (piece or len(body))])
|
||||
time.sleep(delay)
|
||||
if hang_up:
|
||||
return 0, {}, 0.0
|
||||
response = HTTPResponse(sock)
|
||||
@@ -152,6 +161,56 @@ def raw(
|
||||
return response.status, json.loads(response.read()), time.perf_counter() - started
|
||||
|
||||
|
||||
READER = """
|
||||
import hashlib, http.client, sys, time
|
||||
path, token, request_id, piece, delay = sys.argv[1:6]
|
||||
connection = http.client.HTTPConnection("lb", 8080, timeout=30)
|
||||
headers = {"Authorization": "Bearer " + token, "X-Request-Id": request_id}
|
||||
connection.request("GET", path, headers=headers)
|
||||
response, digest, started = connection.getresponse(), hashlib.sha256(), time.monotonic()
|
||||
while chunk := response.read(int(piece)):
|
||||
digest.update(chunk)
|
||||
time.sleep(float(delay))
|
||||
print(response.status, digest.hexdigest(), round(time.monotonic() - started, 2))
|
||||
"""
|
||||
|
||||
|
||||
def slow_read(path: str, token: str, request_id: str, piece: int, delay: float) -> list[str]:
|
||||
template = "{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}"
|
||||
networks = subprocess.run(
|
||||
["docker", "inspect", "-f", template, compose("ps", "-q", "lb")],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.split()
|
||||
image = subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.Config.Image}}", compose("ps", "-q", "api").split()[0]],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
command = [
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--network",
|
||||
next(name for name in networks if name.endswith("_edge")),
|
||||
"--sysctl",
|
||||
"net.ipv4.tcp_rmem=4096 16384 65536",
|
||||
"--entrypoint",
|
||||
"python",
|
||||
image,
|
||||
"-c",
|
||||
READER,
|
||||
path,
|
||||
token,
|
||||
request_id,
|
||||
str(piece),
|
||||
str(delay),
|
||||
]
|
||||
return subprocess.run(command, check=True, capture_output=True, text=True).stdout.split()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def http() -> AsyncIterator[AsyncClient]:
|
||||
async with AsyncClient(base_url=BASE_URL, timeout=30, trust_env=False) as client:
|
||||
@@ -470,3 +529,49 @@ async def test_stalled_upload_is_cut_and_leaves_nothing(http: AsyncClient, fault
|
||||
assert elapsed <= REQUEST_TIMEOUT + 2
|
||||
assert seen(name) is None
|
||||
assert (await upload(http, s["alice"], s["chats"][0])).status_code == 202
|
||||
|
||||
|
||||
async def test_token_is_checked_before_the_declared_size(http: AsyncClient) -> None:
|
||||
s = await scene(http)
|
||||
headers = {"Content-Type": "image/png", "Content-Length": str(LIMIT + 1)}
|
||||
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=a.png"
|
||||
status, body, _ = await asyncio.to_thread(raw, path, headers, SAMPLE[:1024], hang_up=False)
|
||||
print(f"без токена, Content-Length {LIMIT + 1}: {status} {body['error']['code']}")
|
||||
assert (status, body["error"]["code"]) == (401, "unauthorized")
|
||||
|
||||
|
||||
async def test_slow_but_steady_transfers_outlive_the_request_timeout(http: AsyncClient) -> None:
|
||||
since = moment()
|
||||
s = await scene(http)
|
||||
picture = png(16, 16, size=3 << 20)
|
||||
sent, read = f"slow-upload-{uuid4().hex}", f"slow-download-{uuid4().hex}"
|
||||
headers = {
|
||||
**bearer(s["alice"]),
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": str(len(picture)),
|
||||
"X-Request-Id": sent,
|
||||
}
|
||||
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=slow.png"
|
||||
status, body, up = await asyncio.to_thread(
|
||||
raw, path, headers, picture, hang_up=False, piece=64 << 10, delay=0.25
|
||||
)
|
||||
assert status == 202, body
|
||||
assert body["sha256"] == sha256(picture).hexdigest()
|
||||
await waited(lambda: status_of(body["id"]) == "ready", 60)
|
||||
content = f"/api/v1/attachments/{body['id']}/content"
|
||||
code, digest, down = await asyncio.to_thread(slow_read, content, s["bob"], read, 64 << 10, 0.33)
|
||||
assert (code, digest) == ("200", body["sha256"])
|
||||
|
||||
def handled() -> dict[str, tuple[int, float]]:
|
||||
return {
|
||||
e["request_id"]: (e["status"], e["duration_ms"] / 1000)
|
||||
for e in logs(since)
|
||||
if e.get("event") == "request.handled" and e.get("request_id") in (sent, read)
|
||||
}
|
||||
|
||||
await waited(lambda: len(handled()) == 2, 15)
|
||||
replica = handled()
|
||||
print(f"upload 3 MiB ≈ 256 KiB/s: клиент {up:.1f} с, реплика {replica[sent]}")
|
||||
print(f"скачивание 3 MiB ≈ 192 KiB/s из сети edge: клиент {down} с, реплика {replica[read]}")
|
||||
assert replica[sent][0] == 202 and replica[sent][1] > REQUEST_TIMEOUT
|
||||
assert replica[read][0] == 200 and replica[read][1] > REQUEST_TIMEOUT
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -18,6 +19,7 @@ from stand import (
|
||||
new_user,
|
||||
psql,
|
||||
report,
|
||||
restart_stack,
|
||||
started_at,
|
||||
timed,
|
||||
valkey,
|
||||
@@ -55,7 +57,8 @@ async def test_chat_creation_rolls_back_on_unknown_member(http: AsyncClient) ->
|
||||
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
|
||||
headers=bearer(token),
|
||||
)
|
||||
print(f"чат с несуществующим участником: {response.status_code}")
|
||||
code = response.json()["error"]["code"]
|
||||
print(f"чат с несуществующим участником: {response.status_code} {code}")
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == "invalid_request"
|
||||
assert psql("SELECT count(*) FROM chats WHERE title = :'title'", title=title) == "0"
|
||||
@@ -208,6 +211,13 @@ async def test_postgres_stopped_gives_bounded_503_and_recovers(http: AsyncClient
|
||||
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
print(f"postgres запущен: готовность через {recovered:.1f} с, прежний токен {me.status_code}")
|
||||
assert me.json() == user
|
||||
instances = set()
|
||||
for _ in range(40):
|
||||
response = await http.post("/api/v1/users", json=new_user("recovered"))
|
||||
assert response.status_code == 201
|
||||
instances.add(response.headers["X-Instance-Id"])
|
||||
print(f"postgres запущен: 40 регистраций 201 через {len(instances)} реплики без рестарта API")
|
||||
assert len(instances) >= 2
|
||||
assert started_at("api") == api_started
|
||||
|
||||
|
||||
@@ -227,3 +237,43 @@ async def test_api_restart_keeps_session_without_extending_it(http: AsyncClient)
|
||||
print(f"expires_at при входе {session['expires_at']}, в БД после рестарта {stored}")
|
||||
assert me.status_code == 200
|
||||
assert stored.rstrip("Z").rstrip("0") == session["expires_at"].rstrip("Z").rstrip("0")
|
||||
|
||||
|
||||
async def test_full_restart_keeps_session_until_logout(http: AsyncClient) -> None:
|
||||
user, token = await enroll(http, "fullrestart")
|
||||
restart_stack()
|
||||
recovered = await wait_ready(http)
|
||||
me = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
logout = await http.delete("/api/v1/auth/sessions/current", headers=bearer(token))
|
||||
after = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
print(
|
||||
f"restart.sh: готовность через {recovered:.1f} с, прежний токен {me.status_code}, "
|
||||
f"выход {logout.status_code}, затем {after.status_code}"
|
||||
)
|
||||
assert me.json() == user
|
||||
assert logout.status_code == 204
|
||||
assert after.status_code == 401
|
||||
|
||||
|
||||
async def test_session_expires_after_restart_at_original_time(http: AsyncClient) -> None:
|
||||
user, token = await enroll(http, "shortrestart")
|
||||
expires_at = float(
|
||||
psql(
|
||||
"UPDATE sessions s SET expires_at = now() + interval '20 seconds' FROM users u "
|
||||
"WHERE u.id = s.user_id AND u.username = :'name' "
|
||||
"RETURNING extract(epoch FROM s.expires_at)",
|
||||
name=user["username"],
|
||||
).splitlines()[0]
|
||||
)
|
||||
compose("restart", "api")
|
||||
recovered = await wait_ready(http)
|
||||
fresh = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
await asyncio.sleep(max(0.0, expires_at - time.time()) + 0.5)
|
||||
stale = await http.get("/api/v1/users/me", headers=bearer(token))
|
||||
print(
|
||||
f"срок сессии сокращён до 20 с, рестарт api: готовность через {recovered:.1f} с, "
|
||||
f"до срока {fresh.status_code}, после срока {stale.status_code}"
|
||||
)
|
||||
assert fresh.status_code == 200
|
||||
assert stale.status_code == 401
|
||||
assert stale.headers["WWW-Authenticate"] == BEARER
|
||||
|
||||
Reference in New Issue
Block a user