ЛР 5 — асинхронная обработка и версии pipeline

This commit is contained in:
2026-11-16 02:38:13 +03:00
parent 276dbdad8a
commit 1f535f1b5b
163 changed files with 17194 additions and 24 deletions
+538
View File
@@ -0,0 +1,538 @@
#!/usr/bin/env python3
"""Lab2 auth acceptance tests. Uses the unchanged teacher HTTP client.
No server startup, automatic Docker actions, retries of writes or secret output.
Infrastructure hooks run only in explicitly selected suites.
"""
import argparse
import base64
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import unittest
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, LAB, check, timestamp # noqa: E402
LOGIN = "/api/v1/auth/sessions"
LOGOUT = LOGIN + "/current"
ME = "/api/v1/users/me"
ARGS = None
def basic(username, password):
value = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
return {"Authorization": "Basic " + value}
def registration(password=None):
return {
"username": "auth_" + uuid.uuid4().hex[:20],
"display_name": "Проверка auth",
"password": password if password is not None else "Aa:" + uuid.uuid4().hex,
}
def new_client(timeout=None):
return Client(ARGS.base_url, ARGS.ca_file, timeout=timeout or ARGS.timeout)
def error(c, method, path, status, code, **kwargs):
if LAB >= 3 and method == "POST" and path.endswith("/messages"):
kwargs["headers"] = {**kwargs.get("headers", {}), "Idempotency-Key": uuid.uuid4().hex}
response = c.call(method, path, status, **kwargs)
check(response["json"]["error"]["code"] == code, "incorrect contract error code")
if status == 401:
challenge = ('Basic realm="messenger", charset="UTF-8"'
if path == LOGIN else 'Bearer realm="messenger"')
check(response["headers"].get("WWW-Authenticate") == challenge,
"incorrect authentication challenge")
return response
def create_actor(c, password=None):
body = registration(password)
user = c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
session = c.call("POST", LOGIN, 201,
headers=basic(body["username"], body["password"]), schema="Session")["json"]
check(session["user"] == user, "login returned a different user")
check(timestamp(session["expires_at"]) > dt.datetime.now(dt.timezone.utc),
"new session is already expired")
return {"id": user["id"], "user": user, "registration": body,
"token": session["token"], "expires_at": session["expires_at"]}
def login(c, actor):
return c.call("POST", LOGIN, 201, schema="Session",
headers=basic(actor["registration"]["username"],
actor["registration"]["password"]))["json"]
def chat(c, owner, members=None):
members = members if members is not None else [owner["id"]]
return c.call("POST", "/api/v1/chats", 201, actor=owner,
body={"title": "Auth regression", "member_ids": members}, schema="Chat")["json"]
class AuthContract(unittest.TestCase):
"""Independent cases: a logout or rejection never poisons another test."""
def setUp(self):
self.c = new_client()
def test_public_health_and_registration(self):
for path in ("/health/live", "/health/ready"):
with self.subTest(path=path):
self.c.call("GET", path, schema="Health")
body = registration()
# Registration is public even when a stale credential is supplied.
user = self.c.call("POST", "/api/v1/users", 201, body=body,
headers={"Authorization": "Bearer invalid"}, schema="User")["json"]
check(user["username"] == body["username"], "username changed")
check(user["display_name"] == body["display_name"], "display_name changed")
def test_password_unicode_boundaries_and_colon(self):
for label, password in (
("ascii_min", "a" * 12), ("ascii_max", "b" * 128),
("unicode_min", "😀" * 12), ("unicode_max", "😀" * 128),
("colon", "начало:пароль:конец"),
("spaces_are_significant", " significant-password "),
):
with self.subTest(case=label):
actor = create_actor(self.c, password)
me = self.c.call("GET", ME, actor=actor, schema="User")["json"]
check(me == actor["user"], "current user differs from registration")
altered = password.strip() if password != password.strip() else password + "x"
error(self.c, "POST", LOGIN, 401, "unauthorized",
headers=basic(actor["registration"]["username"], altered))
def test_invalid_password_length_and_blank(self):
for label, value in (
("empty", ""), ("ascii_short", "a" * 11), ("ascii_long", "a" * 129),
("unicode_short", "😀" * 11), ("unicode_long", "😀" * 129),
("blank_ascii", " " * 12), ("blank_unicode", "\u2003" * 12),
):
with self.subTest(case=label):
body = registration(value)
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
def test_registration_required_fields_types_and_names(self):
for field in ("username", "display_name", "password"):
for label, value in (("missing", None), ("null", None), ("integer", 1),
("boolean", True), ("array", []), ("object", {})):
with self.subTest(field=field, case=label):
body = registration()
if label == "missing":
body.pop(field)
else:
body[field] = value
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
for alias in (field.upper(), field[0].upper() + field[1:]):
for extra in (False, True):
with self.subTest(field=field, alias=alias, extra=extra):
body = registration()
body[alias] = body[field] if extra else body.pop(field)
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
for root in (None, True, 1, "string", []):
with self.subTest(root_type=type(root).__name__):
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
raw=json.dumps(root).encode(), headers={"Content-Type": "application/json"})
body = registration()
body["sender_id"] = str(uuid.uuid4())
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
def test_registration_bytes_json_and_content_type(self):
for label, raw in (
("empty", b""), ("malformed", b'{"username":'),
("second_json", json.dumps(registration()).encode() + b"{}"),
("trailing_garbage", json.dumps(registration()).encode() + b" garbage"),
):
with self.subTest(case=label):
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
raw=raw, headers={"Content-Type": "application/json"})
for field in ("username", "display_name", "password"):
for label, bad in (("ff", b"\xff"), ("overlong", b"\xc0\xaf"),
("truncated", b"\xe2\x82"), ("surrogate", b"\xed\xa0\x80")):
with self.subTest(field=field, encoding=label):
body = registration()
body[field] = "BYTE_MARKER"
raw = json.dumps(body).encode().replace(b"BYTE_MARKER", b"prefix" + bad + b"suffix")
error(self.c, "POST", "/api/v1/users", 400, "invalid_request",
raw=raw, headers={"Content-Type": "application/json"})
for media in ("text/plain", "application/octet-stream"):
with self.subTest(media=media):
error(self.c, "POST", "/api/v1/users", 415, "unsupported_media_type",
raw=json.dumps(registration()).encode(), headers={"Content-Type": media})
def test_username_and_display_name_constraints(self):
for username in ("ab", "a" * 33, "ABC", "имя", "bad-name", "bad name", " bad"):
with self.subTest(case="username", length=len(username)):
body = registration()
body["username"] = username
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
for name in ("", " \t\n", "\u00a0\u2003", "😀" * 101):
with self.subTest(case="display_name", length=len(name)):
body = registration()
body["display_name"] = name
error(self.c, "POST", "/api/v1/users", 400, "invalid_request", body=body)
for length in (1, 100):
with self.subTest(case="valid_display_name", length=length):
body = registration()
body["display_name"] = "😀" * length
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
check(user["display_name"] == body["display_name"], "Unicode display name changed")
body = registration()
body["username"] = uuid.uuid4().hex
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
check(user["username"] == body["username"], "maximum-length username changed")
def test_wrong_credentials_have_same_public_error(self):
actor = create_actor(self.c)
responses = []
for label, username, password in (
("wrong_password", actor["registration"]["username"], "wrong-password"),
("unknown_user", registration()["username"], actor["registration"]["password"]),
):
with self.subTest(case=label):
responses.append(error(self.c, "POST", LOGIN, 401, "unauthorized",
headers=basic(username, password)))
if len(responses) == 2:
check(responses[0]["json"]["error"]["message"] ==
responses[1]["json"]["error"]["message"],
"credentials errors reveal whether username exists")
self.c.call("GET", ME, actor=actor, schema="User")
def test_login_rejects_missing_or_malformed_basic(self):
actor = create_actor(self.c)
encoded_no_colon = base64.b64encode(b"username-only").decode()
for label, headers in (
("absent", {}), ("legacy_id", {"X-User-Id": actor["id"]}),
("bearer", {"Authorization": "Bearer " + actor["token"]}),
("empty_basic", {"Authorization": "Basic"}),
("invalid_base64", {"Authorization": "Basic !!!"}),
("missing_separator", {"Authorization": "Basic " + encoded_no_colon}),
("invalid_username_utf8", {"Authorization": "Basic " + base64.b64encode(b"\xffuser:synthetic-password").decode("ascii")}),
("username_contains_nul", {"Authorization": "Basic " + base64.b64encode(b"bad\x00user:synthetic-password").decode("ascii")}),
("wrong_scheme", {"Authorization": "Digest anything"}),
("empty_password", basic(actor["registration"]["username"], "")),
):
with self.subTest(case=label):
error(self.c, "POST", LOGIN, 401, "unauthorized", headers=headers)
def test_login_does_not_accept_json_credentials(self):
actor = create_actor(self.c)
body = {"username": actor["registration"]["username"],
"password": actor["registration"]["password"]}
# Authentication precedes payload validation.
error(self.c, "POST", LOGIN, 401, "unauthorized", body=body)
error(self.c, "POST", LOGIN, 400, "invalid_request", body=body,
headers=basic(body["username"], body["password"]))
def test_protected_routes_require_bearer_before_validation(self):
actor = create_actor(self.c)
basic_headers = basic(actor["registration"]["username"], actor["registration"]["password"])
unknown = str(uuid.uuid4())
routes = (
("GET", ME, None), ("GET", "/api/v1/chats", None),
("POST", "/api/v1/chats", {"title": "", "member_ids": []}),
("GET", "/api/v1/chats/" + unknown, None),
("GET", "/api/v1/chats/not-a-uuid/messages?limit=0", None),
("POST", "/api/v1/chats/" + unknown + "/messages", {"text": ""}),
("DELETE", LOGOUT, None),
)
for method, path, body in routes:
for label, headers in (
("absent", {}), ("basic", basic_headers), ("legacy_id", {"X-User-Id": actor["id"]}),
("empty_bearer", {"Authorization": "Bearer"}),
("unknown_token", {"Authorization": "Bearer " + uuid.uuid4().hex * 2}),
("space_in_token", {"Authorization": "Bearer invalid token"}),
):
with self.subTest(method=method, path=path, auth=label):
error(self.c, method, path, 401, "unauthorized", body=body, headers=headers)
def test_identity_acl_and_sender_ignore_legacy_header(self):
alice, bob, eve = (create_actor(self.c) for _ in range(3))
room = chat(self.c, alice, [alice["id"], bob["id"]])
path = "/api/v1/chats/" + room["id"]
me = self.c.call("GET", ME, actor=alice, headers={"X-User-Id": eve["id"]},
schema="User")["json"]
check(me == alice["user"], "legacy ID overrode session identity")
result = self.c.call("POST", path + "/messages", 201, actor=alice,
headers={"X-User-Id": bob["id"],
**({"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {})},
body={"text": "Auth sender"}, schema="Message")["json"]
check(result["sender_id"] == alice["id"], "sender not derived from session")
for suffix in ("", "/messages"):
error(self.c, "GET", path + suffix, 404, "not_found", actor=eve,
headers={"X-User-Id": alice["id"]})
error(self.c, "POST", path + "/messages", 404, "not_found", actor=eve,
body={"text": "Forbidden"}, headers={"X-User-Id": alice["id"]})
hidden = self.c.call("GET", "/api/v1/chats?limit=100", actor=eve,
schema="ChatPage")["json"]
check(all(item["id"] != room["id"] for item in hidden["items"]), "foreign chat leaked")
page = self.c.call("GET", path + "/messages", actor=bob, schema="MessagePage")["json"]
check(page["items"] == [result], "confirmed message is not immediately visible")
error(self.c, "POST", path + "/messages", 400, "invalid_request", actor=alice,
body={"text": "Forged sender", "sender_id": bob["id"]})
def test_invalid_chat_does_not_leave_visible_partial_chat(self):
actor = create_actor(self.c)
before = self.c.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
for members in ([actor["id"], str(uuid.uuid4())],
[actor["id"], actor["id"]],
[actor["id"], actor["id"].upper()], [str(uuid.uuid4())]):
with self.subTest(member_count=len(members)):
error(self.c, "POST", "/api/v1/chats", 400, "invalid_request", actor=actor,
body={"title": "Must not exist", "member_ids": members})
after = self.c.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
check(after == before, "rejected chat request left visible partial data")
def test_logout_revokes_only_current_session(self):
actor = create_actor(self.c)
other = login(self.c, actor)
check(other["token"] != actor["token"], "separate logins reused a token")
self.c.call("DELETE", LOGOUT, 204, actor=actor)
error(self.c, "GET", ME, 401, "unauthorized", actor=actor)
error(self.c, "DELETE", LOGOUT, 401, "unauthorized", actor=actor)
second = dict(actor, token=other["token"])
me = self.c.call("GET", ME, actor=second, schema="User")["json"]
check(me == actor["user"], "logout revoked another session")
fresh = login(self.c, actor)
check(fresh["token"] not in (actor["token"], other["token"]), "login reused an earlier token")
self.c.call("GET", ME, actor=dict(actor, token=fresh["token"]), schema="User")
def test_session_ttl_matches_configuration(self):
actor = create_actor(self.c)
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(ARGS.ttl - 5 <= remaining <= ARGS.ttl + 5, "SESSION_TTL_SECONDS not respected")
for _ in range(3):
self.c.call("GET", ME, actor=actor, schema="User")
# Exact non-sliding deadline is checked by the storage and short-TTL suites.
def test_tokens_distinct_opaque_and_tamper_rejected(self):
actor = create_actor(self.c)
issued = [actor["token"]] + [login(self.c, actor)["token"] for _ in range(3)]
check(len(set(issued)) == len(issued), "independent logins reused tokens")
for token in issued:
check(token != actor["id"] and token != actor["registration"]["username"],
"token contains identity instead of an opaque credential")
check(token != actor["registration"]["password"], "password used as session token")
token = actor["token"]
changed = token[:-1] + ("A" if token[-1] != "A" else "B")
error(self.c, "GET", ME, 401, "unauthorized", actor=dict(actor, token=changed))
self.c.call("GET", ME, actor=actor, schema="User")
# Length/uniqueness is not proof of entropy. RNG is reviewed separately.
def test_duplicate_username_concurrent_registration(self):
body = registration()
barrier = threading.Barrier(4)
def send(index):
c = new_client()
candidate = dict(body, display_name="Race " + str(index), password=body["password"] + str(index))
barrier.wait(timeout=ARGS.timeout)
result = c.call("POST", "/api/v1/users", (201, 409), body=candidate, schema="User")
if result["status"] == 409:
check(result["json"]["error"]["code"] == "conflict", "race loser did not receive conflict")
return candidate, result
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(send, range(4)))
winners = [(body, result) for body, result in results if result["status"] == 201]
check(len(winners) == 1, "username race must have exactly one winner")
winner_body, result = winners[0]
session = self.c.call("POST", LOGIN, 201, headers=basic(winner_body["username"],
winner_body["password"]), schema="Session")["json"]
check(session["user"] == result["json"], "race winner was overwritten")
for candidate, response in results:
if response["status"] == 409:
error(self.c, "POST", LOGIN, 401, "unauthorized",
headers=basic(candidate["username"], candidate["password"]))
def hook(path):
script = Path(path).expanduser().resolve()
check(script.is_file() and os.access(script, os.X_OK), "hook must exist and be executable")
check(".example." not in script.name, "implement a real hook first")
try:
result = subprocess.run([str(script)], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=ARGS.hook_timeout)
except (OSError, subprocess.TimeoutExpired):
raise Failure("infrastructure hook failed or timed out; inspect it locally") from None
check(result.returncode == 0, "infrastructure hook returned an error")
def wait_ready(c):
deadline = time.monotonic() + ARGS.hook_timeout
while True:
try:
c.call("GET", "/health/ready", schema="Health")
return
except Failure:
check(time.monotonic() < deadline, "API readiness did not recover")
time.sleep(0.25)
def expiry():
c = new_client()
actor = create_actor(c)
start = time.monotonic()
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(0 < remaining <= ARGS.ttl + 5, "short TTL not applied")
c.call("GET", ME, actor=actor, schema="User")
# Reading halfway must not renew the original deadline.
time.sleep(max(0, remaining / 2))
c.call("GET", ME, actor=actor, schema="User")
time.sleep(max(0, remaining + 0.25 - (time.monotonic() - start)))
error(c, "GET", ME, 401, "unauthorized", actor=actor)
error(c, "DELETE", LOGOUT, 401, "unauthorized", actor=actor)
fresh = login(c, actor)
check(fresh["token"] != actor["token"], "expired token reused")
c.call("GET", ME, actor=dict(actor, token=fresh["token"]), schema="User")
def persistence():
c = new_client(timeout=2)
actor = create_actor(c)
revoked = dict(actor, token=login(c, actor)["token"])
c.call("DELETE", LOGOUT, 204, actor=revoked)
room = chat(c, actor)
original = c.message(actor, room, "Auth persistence")["json"]
remaining = (timestamp(actor["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(remaining > 2 * ARGS.hook_timeout + 10, "TTL too short for restart bounds")
hook(ARGS.restart_hook)
wait_ready(c)
# No re-login before checking the original token.
check(c.call("GET", ME, actor=actor, schema="User")["json"] == actor["user"],
"original session/user did not survive restart")
check(c.call("GET", "/api/v1/chats/" + room["id"], actor=actor, schema="Chat")["json"] == room,
"chat/membership changed after restart")
page = c.call("GET", "/api/v1/chats/" + room["id"] + "/messages",
actor=actor, schema="MessagePage")["json"]
check(page["items"] == [original], "confirmed message changed after restart")
error(c, "GET", ME, 401, "unauthorized", actor=revoked)
error(c, "DELETE", LOGOUT, 401, "unauthorized", actor=revoked)
c.call("DELETE", LOGOUT, 204, actor=actor)
error(c, "GET", ME, 401, "unauthorized", actor=actor)
check(login(c, actor)["user"] == actor["user"], "password/user not persistent")
# HTTP exposes expiry only at login. Storage test verifies deadline stability.
def dependency():
c = new_client()
actor = create_actor(c)
failures = []
fallback_session = None
revoked_during_outage = False
sql_with_redis = ARGS.dependency == "postgres" and getattr(ARGS, "session_store", "redis") == "redis"
if sql_with_redis:
fallback_session = dict(actor, token=login(c, actor)["token"])
def observe(name, operation):
try:
operation()
print("PASS:", name)
return True
except Failure as exc:
failures.append(name + ": " + str(exc))
print("FAIL:", name + ": " + str(exc))
return False
try:
hook(ARGS.failure_hook)
observe("liveness during outage", lambda: c.call("GET", "/health/live", schema="Health"))
critical = not (ARGS.dependency == "redis" and ARGS.cache_policy == "fallback")
if critical:
observe("readiness during outage", lambda: error(c, "GET", "/health/ready", 503, "unavailable"))
observe("valid session during outage", lambda: error(c, "GET", ME, 503, "unavailable", actor=actor))
else:
observe("fallback readiness", lambda: c.call("GET", "/health/ready", schema="Health"))
observe("fallback identity", lambda: c.call("GET", ME, actor=actor, schema="User"))
for name, headers in (("missing auth", {}), ("legacy identity", {"X-User-Id": actor["id"]})):
observe(name, lambda headers=headers: error(c, "GET", ME, 401, "unauthorized", headers=headers))
# A syntactically valid Bearer cannot be declared unknown while the
# sole session store is unavailable. The lookup failed, not identity.
unknown_status = 503 if ARGS.dependency == "redis" and critical else 401
observe("unknown bearer during outage", lambda: error(c, "GET", ME, unknown_status,
"unavailable" if unknown_status == 503 else "unauthorized",
headers={"Authorization": "Bearer " + uuid.uuid4().hex * 2}))
if critical:
observe("login during outage", lambda: error(c, "POST", LOGIN, 503, "unavailable",
headers=basic(actor["registration"]["username"], actor["registration"]["password"])))
if not critical:
fallback_session = dict(actor, token=login(c, actor)["token"])
if sql_with_redis or not critical:
revoked_during_outage = observe("Redis logout independent of SQL", lambda: c.call("DELETE", LOGOUT, 204, actor=actor))
else:
observe("logout during outage", lambda: error(c, "DELETE", LOGOUT, 503, "unavailable", actor=actor))
if ARGS.dependency == "postgres":
body = registration()
observe("registration during SQL outage", lambda: error(c, "POST", "/api/v1/users", 503, "unavailable", body=body))
finally:
hook(ARGS.recovery_hook)
observe("readiness recovers", lambda: wait_ready(c))
observe("liveness recovers", lambda: c.call("GET", "/health/live", schema="Health"))
survivor = fallback_session or actor
observe("independent session after recovery", lambda: c.call("GET", ME, actor=survivor, schema="User"))
if revoked_during_outage:
observe("logout remains revoked after recovery", lambda: error(c, "GET", ME, 401, "unauthorized", actor=actor))
if ARGS.dependency == "postgres":
observe("failed registration left no user", lambda: c.call("POST", "/api/v1/users", 201, body=body, schema="User"))
check(not failures, "; ".join(failures))
def main():
global ARGS
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--base-url", default=None)
p.add_argument("--ca-file", default=None)
p.add_argument("--timeout", type=float, default=15)
p.add_argument("--ttl", type=int, default=3600, help="actual server SESSION_TTL_SECONDS")
p.add_argument("--suite", choices=("normal", "expiry", "persistence", "dependency"), default="normal")
p.add_argument("--restart-hook")
p.add_argument("--failure-hook")
p.add_argument("--recovery-hook")
p.add_argument("--dependency", choices=("postgres", "redis"))
p.add_argument("--cache-policy", choices=("critical", "fallback"))
p.add_argument("--session-store", choices=("postgres", "redis"), default="redis",
help="declared session backend; controls logout expectation during a SQL outage")
p.add_argument("--hook-timeout", type=float, default=90)
ARGS = p.parse_args()
if LAB < 2:
p.error("this suite requires the Bearer session contract introduced in lab2")
if ARGS.timeout <= 0 or ARGS.hook_timeout <= 0:
p.error("timeouts must be positive")
if ARGS.suite == "expiry":
if not 2 <= ARGS.ttl <= 10:
p.error("expiry needs a separately configured server with TTL 2..10")
elif ARGS.ttl < 300:
p.error("normal, restart and dependency suites require TTL >= 300")
if ARGS.suite == "persistence" and not ARGS.restart_hook:
p.error("persistence requires an explicit --restart-hook")
if ARGS.suite == "dependency":
if not (ARGS.failure_hook and ARGS.recovery_hook and ARGS.dependency):
p.error("dependency suite needs failure/recovery hooks and the dependency name")
if ARGS.dependency == "redis" and not ARGS.cache_policy:
p.error("declare whether Redis is critical or has a safe fallback")
if ARGS.suite == "normal":
result = unittest.TextTestRunner(verbosity=2).run(
unittest.defaultTestLoader.loadTestsFromTestCase(AuthContract))
raise SystemExit(0 if result.wasSuccessful() else 1)
try:
{"expiry": expiry, "persistence": persistence, "dependency": dependency}[ARGS.suite]()
except (Failure, ValueError, OSError) as exc:
print("FAIL:", str(exc))
raise SystemExit(1)
print("PASS:", ARGS.suite, "(hook scope and runtime settings need separate evidence)")
if __name__ == "__main__":
main()
@@ -0,0 +1,221 @@
package auth_tests
import (
"context"
"errors"
"io"
"net/http"
"slices"
"strings"
"testing"
"testing/synctest"
"time"
"highload/internal/model"
"highload/internal/repository"
"highload/internal/service"
"highload/internal/storage"
"highload/internal/storage/s3"
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
)
type cleanupRepo struct {
repository.AttachmentRepository
referenced map[string]bool
busy string
existsErr error
checked []string
locked string
}
type cleanupTx struct{ repo *cleanupRepo }
func (tx cleanupTx) CreateQueued(context.Context, string, string, string, string, string, string, string, int64) (*model.Attachment, error) {
return nil, errors.New("cleanup fixture must not create queued attachments")
}
func (tx cleanupTx) CreateAttachment(context.Context, repository.CreateAttachmentParams) (*model.Attachment, error) {
return nil, errors.New("unexpected INSERT")
}
func (tx cleanupTx) GetAttachmentByID(context.Context, string) (*model.Attachment, error) {
return nil, errors.New("unexpected attachment lookup")
}
func (tx cleanupTx) ExistsByObjectKey(ctx context.Context, key string) (bool, error) {
r := tx.repo
if r.locked != key {
return false, errors.New("EXISTS outside locked transaction")
}
r.checked = append(r.checked, key)
return r.referenced[key], r.existsErr
}
func (r *cleanupRepo) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) {
if key == r.busy {
return false, nil
}
r.locked = key
defer func() { r.locked = "" }()
return true, fn(ctx, cleanupTx{repo: r})
}
type cleanupStore struct {
pages map[string][]storage.ObjectInfo
next map[string]string
listed, deleted []string
repo *cleanupRepo
listErr, deleteErr error
waitList bool
}
func (s *cleanupStore) ListPage(ctx context.Context, token *string, prefix string) ([]storage.ObjectInfo, *string, error) {
if prefix != "attachments/" {
return nil, nil, errors.New("unexpected prefix")
}
if _, ok := ctx.Deadline(); !ok {
return nil, nil, errors.New("LIST did not receive deadline")
}
if s.waitList {
<-ctx.Done()
return nil, nil, ctx.Err()
}
key := aws.ToString(token)
s.listed = append(s.listed, key)
if s.listErr != nil {
return nil, nil, s.listErr
}
if next, ok := s.next[key]; ok {
return s.pages[key], &next, nil
}
return s.pages[key], nil, nil
}
func (s *cleanupStore) Delete(_ context.Context, key string) error {
if s.repo.locked != key {
return errors.New("DELETE outside locked transaction")
}
s.deleted = append(s.deleted, key)
return s.deleteErr
}
func TestAttachmentCleanupPagesAndCutoff(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
now := time.Now()
old := now.Add(-time.Minute - time.Nanosecond)
orphan := "attachments/orphan"
opts := &service.AttachmentCleanupOptions{GracePeriod: time.Minute, ListTimeout: time.Second}
repo := &cleanupRepo{referenced: map[string]bool{"attachments/referenced": true}, busy: "attachments/busy"}
objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{
"": {{Key: "attachments/equal", LastModified: now.Add(-time.Minute)},
{Key: "attachments/fresh", LastModified: now.Add(-time.Second)},
{Key: "attachments/future", LastModified: now.Add(time.Hour)},
{Key: "attachments/zero"},
{Key: "other/orphan", LastModified: old},
{Key: "attachments/busy", LastModified: old}},
"last": {{Key: "attachments/referenced", LastModified: old}, {Key: orphan, LastModified: old}},
}, next: map[string]string{"": "empty", "empty": "last"}}
svc := service.NewAttachmentCleanupService(repo, objects, opts)
opts.DryRun = true
if err := svc.RunOnce(context.Background()); err != nil || len(objects.deleted) != 0 ||
!slices.Equal(repo.checked, []string{"attachments/referenced", orphan}) {
t.Fatalf("dry-run must check old unlocked keys without deleting: err=%v checked=%v deletes=%v", err, repo.checked, objects.deleted)
}
opts.DryRun = false
objects.listed = nil
if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.listed, []string{"", "empty", "last"}) ||
!slices.Equal(objects.deleted, []string{orphan}) {
t.Fatalf("wrong cutoff or page walk: err=%v pages=%v deletes=%v", err, objects.listed, objects.deleted)
}
})
}
func TestAttachmentCleanupFaults(t *testing.T) {
for _, name := range []string{"list", "exists", "delete", "list_timeout", "pass_timeout", "canceled"} {
t.Run(name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
repo := &cleanupRepo{}
objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{"": {{Key: "attachments/old", LastModified: time.Now().Add(-time.Hour)}}}}
svc := service.NewAttachmentCleanupService(repo, objects, &service.AttachmentCleanupOptions{GracePeriod: time.Second, ListTimeout: time.Second})
sentinel := errors.New("synthetic " + name + " error")
var want error = sentinel
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
switch name {
case "list":
objects.listErr = sentinel
case "exists":
repo.existsErr = sentinel
case "delete":
objects.deleteErr = sentinel
case "list_timeout":
objects.waitList = true
want = context.DeadlineExceeded
case "pass_timeout":
var stop context.CancelFunc
ctx, stop = context.WithTimeout(ctx, 100*time.Millisecond)
defer stop()
objects.waitList = true
want = context.DeadlineExceeded
case "canceled":
cancel()
want = context.Canceled
}
start := time.Now()
got := svc.RunOnce(ctx)
if !errors.Is(got, want) {
t.Fatalf("want %v, got %v", want, got)
}
if (name == "list_timeout" && time.Since(start) != time.Second) ||
(name == "pass_timeout" && time.Since(start) != 100*time.Millisecond) {
t.Fatal("wrong cancellation budget")
}
if name != "delete" && len(objects.deleted) > 0 {
t.Fatal("DELETE ran after unsafe precondition")
}
if name == "delete" && len(objects.deleted) != 1 {
t.Fatal("DELETE fault not reached")
}
repo.existsErr, objects.listErr, objects.deleteErr = nil, nil, nil
objects.waitList = false
objects.deleted = nil
if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.deleted, []string{"attachments/old"}) {
t.Fatalf("cleanup did not recover: %v %v", err, objects.deleted)
}
})
})
}
}
type cleanupListTransport func(*http.Request) (*http.Response, error)
func (fn cleanupListTransport) Do(req *http.Request) (*http.Response, error) { return fn(req) }
func TestAttachmentCleanupS3InvalidNextToken(t *testing.T) {
for _, tc := range []struct {
name string
token *string
xml string
}{
{"missing", nil, ""},
{"empty", nil, "<NextContinuationToken></NextContinuationToken>"},
{"repeat", aws.String("same"), "<NextContinuationToken>same</NextContinuationToken>"},
} {
t.Run(tc.name, func(t *testing.T) {
n := 0
obj := &s3.Storage{Bucket: "test", Client: awss3.New(awss3.Options{
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://cleanup.invalid"),
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{},
HTTPClient: cleanupListTransport(func(req *http.Request) (*http.Response, error) {
n++
if req.URL.Query().Get("continuation-token") != aws.ToString(tc.token) {
return nil, errors.New("wrong request token")
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(
"<ListBucketResult><IsTruncated>true</IsTruncated>" + tc.xml + "</ListBucketResult>"))}, nil
}),
})}
_, _, err := obj.ListPage(context.Background(), tc.token, "attachments/")
if !errors.Is(err, storage.ErrStorage) || n != 1 {
t.Fatalf("invalid token was not rejected: %v, calls=%d", err, n)
}
})
}
}
@@ -0,0 +1,340 @@
package auth_tests
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
repo "highload/internal/repository"
"highload/internal/repository/postgres"
"highload/internal/service"
"highload/internal/storage"
"highload/internal/storage/s3"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func newAttachmentTxFixture(t *testing.T) (*fixture, repo.CreateAttachmentParams) {
t.Helper()
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 4)
owner := uuid.NewString()
if _, err := f.pool.Exec(f.ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,'tx_fixture','TX fixture','unused')", owner); err != nil {
t.Fatal(err)
}
chat, err := postgres.NewChatRepository(f.queries, f.pool).CreateChat(f.ctx, "Attachment transaction", []string{owner})
if err != nil {
t.Fatal(err)
}
return f, repo.CreateAttachmentParams{
ChatID: chat.ID, OwnerID: owner, ObjectKey: "attachments/" + uuid.NewString(),
Filename: "fixture.png", ContentType: "image/png", SizeBytes: 1, Sha256: strings.Repeat("a", 64),
}
}
func assertAttachmentCount(t *testing.T, f *fixture, want int) {
t.Helper()
var attachments, jobs, outbox int
err := f.pool.QueryRow(f.ctx, `SELECT (SELECT count(*) FROM attachments),
(SELECT count(*) FROM attachment_jobs), (SELECT count(*) FROM outbox)`).Scan(&attachments, &jobs, &outbox)
if err != nil || attachments != want || jobs != want || outbox != want {
t.Fatalf("expected %d rows each, got attachments=%d jobs=%d outbox=%d (%v)", want, attachments, jobs, outbox, err)
}
}
func TestAttachmentTxLockAndRollback(t *testing.T) {
f, params := newAttachmentTxFixture(t)
// Run the isolation check on the very connection doing the callback INSERT.
// A query through the pool would only establish the observer's isolation.
if _, err := f.pool.Exec(f.ctx, `
CREATE FUNCTION assert_attachment_isolation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF current_setting('transaction_isolation') <> 'read committed' THEN
RAISE EXCEPTION 'expected read committed during attachment INSERT';
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER assert_attachment_isolation BEFORE INSERT ON attachments
FOR EACH ROW EXECUTE FUNCTION assert_attachment_isolation();
`, pgx.QueryExecModeSimpleProtocol); err != nil {
t.Fatal(err)
}
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
id := uuid.NewString()
key := "staging/" + id + "/original"
entered := make(chan struct{})
release := make(chan struct{})
type outcome struct {
locked bool
err error
}
done := make(chan outcome, 1)
holdCtx, cancelHold := context.WithCancel(f.ctx)
defer cancelHold()
go func() {
locked, err := attachments.WithObjectKeyLock(holdCtx, key, func(ctx context.Context, _ repo.AttachmentTx) error {
close(entered)
select {
case <-release:
return nil
case <-ctx.Done():
return ctx.Err()
}
})
done <- outcome{locked, err}
}()
select {
case <-entered:
case result := <-done:
t.Fatalf("holder never entered callback: %+v", result)
case <-time.After(3 * time.Second):
t.Fatal("holder did not acquire the lock")
}
unexpected := func(context.Context, repo.AttachmentTx) error {
return errors.New("contending callback ran")
}
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, unexpected); locked || err != nil {
t.Fatalf("same key must return false, nil without callback: %t, %v", locked, err)
}
noop := func(context.Context, repo.AttachmentTx) error { return nil }
if locked, err := attachments.WithObjectKeyLock(f.ctx, key+"-other", noop); !locked || err != nil {
t.Fatalf("another key was blocked: %t, %v", locked, err)
}
close(release)
select {
case result := <-done:
if !result.locked || result.err != nil {
t.Fatalf("holder did not complete: %+v", result)
}
case <-time.After(3 * time.Second):
t.Fatal("holder did not close its transaction")
}
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
t.Fatalf("committed lock was not released: %t, %v", locked, err)
}
for _, name := range []string{"callback_error", "context_canceled"} {
t.Run(name, func(t *testing.T) {
sentinel := errors.New("synthetic callback failure")
ctx, cancel := context.WithCancel(f.ctx)
defer cancel()
want := error(sentinel)
if name == "context_canceled" {
want = context.Canceled
}
locked, err := attachments.WithObjectKeyLock(ctx, key, func(txCtx context.Context, tx repo.AttachmentTx) error {
if _, err := tx.CreateQueued(txCtx, id, params.ChatID, params.OwnerID, params.ContentType,
params.Sha256, key, params.Filename, params.SizeBytes); err != nil {
return err
}
exists, err := tx.ExistsByObjectKey(txCtx, key)
if err != nil || !exists {
return fmt.Errorf("transaction did not see its INSERT: %w", err)
}
assertAttachmentCount(t, f, 0)
if name == "context_canceled" {
cancel()
return txCtx.Err()
}
return sentinel
})
if !locked || err != want {
t.Fatalf("callback error must pass through unchanged with true: %t, %v", locked, err)
}
assertAttachmentCount(t, f, 0)
if locked, err = attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
t.Fatalf("rollback failed to free lock/pool: %t, %v", locked, err)
}
t.Log("INSERT ran at read committed, rollback left zero rows and released the lock")
})
}
}
// txS3Transport observes the real SDK requests and retains synthetic bytes for GET.
// Before accepting a PUT it challenges the lock from a separate PostgreSQL session.
type txS3Transport struct {
fixture *fixture
key string
data []byte
put, get, delete int
failPut bool
}
func (s *txS3Transport) Do(request *http.Request) (*http.Response, error) {
resp := &http.Response{StatusCode: 200, Header: make(http.Header), Body: http.NoBody}
key := strings.TrimPrefix(request.URL.Path, "/tx-test/")
parts := strings.Split(key, "/")
if len(parts) != 3 || parts[0] != "staging" || parts[2] != "original" {
return nil, errors.New("unexpected synthetic S3 staging key")
}
if _, err := uuid.Parse(parts[1]); err != nil {
return nil, errors.New("staging key lacks an attachment UUID")
}
switch request.Method {
case http.MethodPut:
s.put++
s.key = key
var acquired bool
err := s.fixture.pool.QueryRow(request.Context(),
"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))", key).Scan(&acquired)
if err != nil || acquired {
return nil, fmt.Errorf("PUT ran without held object lock: acquired=%t, error=%v", acquired, err)
}
if s.failPut {
resp.StatusCode = 503
resp.Header.Set("Content-Type", "application/xml")
resp.Body = io.NopCloser(strings.NewReader("<Error><Code>SlowDown</Code><Message>Synthetic outage</Message></Error>"))
return resp, nil
}
defer request.Body.Close()
s.data, err = io.ReadAll(request.Body)
if err != nil {
return nil, err
}
case http.MethodGet:
s.get++
if key != s.key || s.data == nil {
return nil, errors.New("object unavailable in fixture")
}
resp.Body = io.NopCloser(bytes.NewReader(s.data))
resp.ContentLength = int64(len(s.data))
case http.MethodDelete:
s.delete++
s.data = nil
default:
return nil, fmt.Errorf("unexpected S3 method %s", request.Method)
}
return resp, nil
}
func TestAttachmentTxHTTP(t *testing.T) {
_, source, _, _ := runtime.Caller(0)
png, err := os.ReadFile(filepath.Join(filepath.Dir(source), "../../tests/fixtures/sample.png"))
if err != nil {
t.Fatal(err)
}
hash := fmt.Sprintf("%x", sha256.Sum256(png))
for _, scenario := range []struct {
name string
faultSQL string
http int
errorCode string
}{
{name: "s3_unavailable", http: 503, errorCode: "unavailable"},
{name: "insert_after_put", faultSQL: "ALTER TABLE attachments ADD CHECK (filename <> 'fixture.png')", http: 500, errorCode: "internal_error"},
{name: "commit_after_insert", faultSQL: `
CREATE FUNCTION reject_attachment_commit() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'synthetic deferred failure'; END $$;
CREATE CONSTRAINT TRIGGER reject_attachment_commit AFTER INSERT ON attachments
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_attachment_commit();
`, http: 500, errorCode: "internal_error"},
{name: "committed_upload_is_queued", http: http.StatusAccepted},
} {
t.Run(scenario.name, func(t *testing.T) {
f, params := newAttachmentTxFixture(t)
if scenario.faultSQL != "" {
if _, err := f.pool.Exec(f.ctx, scenario.faultSQL, pgx.QueryExecModeSimpleProtocol); err != nil {
t.Fatal(err)
}
}
transport := &txS3Transport{fixture: f, failPut: scenario.http == 503}
objects := &s3.Storage{Bucket: "tx-test", Client: awss3.New(awss3.Options{
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://tx-s3.invalid"),
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{}, HTTPClient: transport,
})}
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), nil, nil)
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
svc := service.NewAttachmentService(attachments, chats, objects)
h := handler.NewAttachmentHandler(svc)
call := func(method, path, param, value string, data []byte, next http.HandlerFunc) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, bytes.NewReader(data))
r = r.WithContext(middleware.WithUserID(f.ctx, params.OwnerID))
r.SetPathValue(param, value)
r.Header.Set("Content-Type", "image/png")
w := httptest.NewRecorder()
mid := middleware.NewMiddleware(nil, "attachment-tx")
mid.InstanceID(mid.RequestID(next)).ServeHTTP(w, r)
return w
}
w := call(http.MethodPost, "/attachments?filename=fixture.png", "chat_id", params.ChatID, png, h.CreateAttachment)
if transport.put != 1 || transport.delete != 0 {
t.Fatalf("expected one PUT and zero DELETE, got %d/%d", transport.put, transport.delete)
}
if scenario.http != http.StatusAccepted {
assertContractError(t, w, scenario.http, scenario.errorCode)
assertAttachmentCount(t, f, 0)
if scenario.http == 503 {
if transport.data != nil {
t.Fatal("failed S3 PUT stored an object")
}
_, err := svc.CreateAttachment(f.ctx, params.ChatID, params.OwnerID, "fixture.png", "image/png", bytes.NewReader(png), int64(len(png)))
if !errors.Is(err, service.ErrServiceUnavailable) || errors.Is(err, storage.ErrStorage) {
t.Fatalf("storage category did not reach service as unavailable: %v", err)
}
} else if !bytes.Equal(transport.data, png) {
t.Fatal("failed database write did not leave the already stored original")
}
if locked, err := attachments.WithObjectKeyLock(f.ctx, transport.key, func(context.Context, repo.AttachmentTx) error { return nil }); !locked || err != nil {
t.Fatalf("failed upload left key locked: %t, %v", locked, err)
}
t.Logf("direct handler HTTP %d; committed rows=0; DELETE=0", w.Code)
return
}
if w.Code != http.StatusAccepted {
t.Fatalf("expected 202 after commit, got %d", w.Code)
}
assertAttachmentCount(t, f, 1)
var response struct {
ID string `json:"id"`
SHA string `json:"sha256"`
Status string `json:"status"`
Variants []json.RawMessage `json:"variants"`
ErrorCode *string `json:"error_code"`
}
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.SHA != hash ||
response.Status != "queued" || response.Variants == nil || len(response.Variants) != 0 || response.ErrorCode != nil {
t.Fatal("invalid queued upload response or SHA-256")
}
row, err := attachments.GetAttachmentForUser(f.ctx, params.OwnerID, response.ID)
if err != nil || row.SHA256 != hash || row.ObjectKey != "" || row.StagingKey != transport.key ||
transport.key != "staging/"+response.ID+"/original" || row.SizeBytes != int64(len(png)) ||
!bytes.Equal(transport.data, png) {
t.Fatal("committed metadata/staging does not match uploaded file")
}
var linked bool
err = f.pool.QueryRow(f.ctx, `SELECT EXISTS(SELECT 1 FROM attachment_jobs j
JOIN outbox o ON o.job_id=j.id WHERE j.attachment_id=$1
AND o.payload->>'attachment_id' = $1::uuid::text AND o.payload->>'job_id'=j.id::text
AND o.sent_at IS NULL)`, response.ID).Scan(&linked)
if err != nil || !linked {
t.Fatal("202 lacks a pending outbox record for the same durable job")
}
get := call(http.MethodGet, "/attachments/"+response.ID, "attachment_id", response.ID, nil, h.GetAttachment)
if get.Code != 200 || !bytes.Equal(bytes.TrimSpace(get.Body.Bytes()), bytes.TrimSpace(w.Body.Bytes())) {
t.Fatal("metadata GET changed")
}
body := call(http.MethodGet, "/attachments/"+response.ID+"/content", "attachment_id", response.ID, nil, h.GetAttachmentContent)
assertContractError(t, body, http.StatusConflict, "conflict")
if transport.get != 0 {
t.Fatal("content GET attempted to read S3 for a queued attachment")
}
t.Logf("HTTP 202, attachment/job/outbox committed, metadata=200, queued content=409, SHA-256=%s", hash)
})
}
}
@@ -0,0 +1,32 @@
package auth_tests
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
)
func TestStorageAuthHandlerRejectsJSONBody(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
writes := f.redis.audit.writeCount()
auth := handler.NewAuthHandler(f.auth)
mid := middleware.NewMiddleware(f.auth, "auth-test")
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
request.SetBasicAuth(user.Username, password)
request.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
// Exercise the real handler independently of Router wiring.
// This component test does not replace the end-to-end login acceptance test.
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
if recorder.Code != http.StatusBadRequest {
t.Errorf("login with JSON body must return 400; received %d", recorder.Code)
}
if f.redis.audit.writeCount() != writes {
t.Error("login with forbidden JSON body attempted to create a session")
}
}
+209
View File
@@ -0,0 +1,209 @@
package auth_tests
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"highload/internal/database"
"highload/internal/database/sqlc"
"highload/internal/repository"
"highload/internal/repository/postgres"
)
func operationBudget(t *testing.T) time.Duration {
t.Helper()
value := os.Getenv("AUTH_TEST_OPERATION_BUDGET_MS")
if value == "" {
t.Log("budget_policy=provisional_3000ms; teacher has no numeric threshold; approval remains pending")
return 3 * time.Second
}
n, err := strconv.Atoi(value)
if err != nil || n < 500 || n > 10000 {
t.Fatal("AUTH_TEST_OPERATION_BUDGET_MS must be 500..10000")
}
return time.Duration(n) * time.Millisecond
}
func applicationPool(t *testing.T, f *fixture) *pgxpool.Pool {
t.Helper()
u, err := url.Parse(os.Getenv("AUTH_TEST_DATABASE_URL"))
if err != nil {
t.Fatal("invalid test URL")
}
q := u.Query()
q.Set("search_path", f.config.ConnConfig.RuntimeParams["search_path"])
u.RawQuery = q.Encode()
// Actual production constructor: never inherit fixture statement_timeout.
pool, err := database.NewPostgres(f.ctx, u.String())
if err != nil {
t.Fatal("application pool unavailable")
}
f.pool.Close()
f.pool = pool
f.queries = sqlc.New(pool)
return pool
}
func blockOperation(t *testing.T, f *fixture, mode string) func() {
t.Helper()
if mode == "blocked_query" {
tx, err := f.admin.Begin(f.ctx)
if err != nil {
t.Fatal("lock transaction failed")
}
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "users"}.Sanitize()
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
t.Fatal("isolated table lock failed")
}
return func() {
ctx, c := context.WithTimeout(context.Background(), 2*time.Second)
defer c()
_ = tx.Rollback(ctx)
}
}
max := f.pool.Config().MaxConns
if max <= 0 || max > 128 {
t.Fatal("test refuses unbounded/oversized pool")
}
held := make([]*pgxpool.Conn, 0, max)
for range max {
conn, err := f.pool.Acquire(f.ctx)
if err != nil {
for _, h := range held {
h.Release()
}
t.Fatal("pool saturation failed")
}
held = append(held, conn)
}
return func() {
for _, h := range held {
h.Release()
}
}
}
func TestPostgresOperationsHaveBoundedWaits(t *testing.T) {
budget := operationBudget(t)
for _, mode := range []string{"blocked_query", "exhausted_pool"} {
for _, scenario := range []string{"application_budget", "shorter_caller_deadline", "released_before_budget"} {
t.Run(mode+"/"+scenario, func(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
applicationPool(t, f)
release := blockOperation(t, f, mode)
released := false
defer func() {
if !released {
release()
}
}()
safety := budget + 2*time.Second
if scenario == "shorter_caller_deadline" {
safety = 150 * time.Millisecond
}
ctx, cancel := context.WithTimeout(context.Background(), safety)
defer cancel()
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil).WithContext(ctx)
request.Header.Set("Authorization", "Bearer "+session.Token)
recorder := httptest.NewRecorder()
done := make(chan struct{})
started := time.Now()
go func() { defer close(done); redisRouter(f, f.redis.client).ServeHTTP(recorder, request) }()
if scenario == "released_before_budget" {
time.Sleep(100 * time.Millisecond)
release()
released = true
}
<-done
elapsed := time.Since(started)
t.Logf("mode=%s scenario=%s elapsed_ms=%.3f caller_deadline_ms=%d budget_ms=%d caller_canceled=%t", mode, scenario, float64(elapsed)/float64(time.Millisecond), safety.Milliseconds(), budget.Milliseconds(), ctx.Err() != nil)
switch scenario {
case "application_budget":
if ctx.Err() != nil || elapsed > budget+250*time.Millisecond {
t.Error("application did not independently enforce its operation budget before test safety cancellation")
}
assertContractError(t, recorder, 503, "unavailable")
case "shorter_caller_deadline":
if elapsed > 750*time.Millisecond {
t.Error("short caller deadline was not honored")
}
assertContractError(t, recorder, 503, "unavailable")
case "released_before_budget":
if recorder.Code != 200 || elapsed >= budget {
t.Error("unblocked operation failed or missed the declared budget")
}
}
if !released {
release()
released = true
}
recovery := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/users/me", nil)
req.Header.Set("Authorization", "Bearer "+session.Token)
recoveryCtx, c := context.WithTimeout(context.Background(), 2*time.Second)
defer c()
redisRouter(f, f.redis.client).ServeHTTP(recovery, req.WithContext(recoveryCtx))
if recovery.Code != 200 {
t.Error("service did not recover after releasing lock/pool")
}
if f.pool.Stat().AcquiredConns() != 0 {
t.Error("application pool leaked an acquired connection")
}
})
}
}
}
func TestPostgresChatCancellationBeforeCommitIsAtomic(t *testing.T) {
f := newFixture(t)
user, _ := f.user(t)
applicationPool(t, f)
tx, err := f.admin.Begin(f.ctx)
if err != nil {
t.Fatal("cannot start membership blocker")
}
released := false
defer func() {
if !released {
_ = tx.Rollback(context.Background())
}
}()
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "chat_members"}.Sanitize()
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
t.Fatal("cannot block membership insertion")
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
repo := postgres.NewChatRepository(f.queries, f.pool)
_, err = repo.CreateChat(ctx, "Canceled before membership", []string{user.ID})
if !errors.Is(err, repository.ErrServiceUnavailable) {
t.Errorf("want unavailable after controlled pre-commit cancellation, got category %v", err)
}
// The membership INSERT cannot finish while this lock is held, so COMMIT
// has not been reached. No ambiguous-commit inference is made here.
_ = tx.Rollback(context.Background())
released = true
for _, name := range []string{"chats", "chat_members"} {
var count int
if f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+name).Scan(&count) != nil || count != 0 {
t.Error("pre-commit cancellation left partial chat data")
}
}
if _, err = repo.CreateChat(f.ctx, "Works after cancellation", []string{user.ID}); err != nil {
t.Error("chat repository failed to recover")
}
if f.pool.Stat().AcquiredConns() != 0 {
t.Error("chat cancellation leaked a connection")
}
}
+273
View File
@@ -0,0 +1,273 @@
package auth_tests
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"highload/internal/database/sqlc"
repository "highload/internal/repository/postgres"
"highload/internal/service"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
func TestErrorDiagnosticsRecordedOnceAndPublicResponseIsSafe(t *testing.T) {
var output bytes.Buffer
original := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil)))
defer slog.SetDefault(original)
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: errors.New("synthetic-storage-diagnostic")})))
_, cause := users.GetUser(context.Background(), uuid.NewString())
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", "Bearer synthetic-secret-not-for-logs")
recorder := httptest.NewRecorder()
mid := middleware.NewMiddleware(nil, "auth-test")
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = httputils.WriteServiceError(w, cause, middleware.RequestIDFromContext(r.Context()))
})).ServeHTTP(recorder, request)
assertContractError(t, recorder, 500, "internal_error")
if strings.Contains(recorder.Body.String(), "synthetic-storage-diagnostic") {
t.Error("public response exposed internal cause")
}
if strings.Contains(output.String(), "synthetic-secret-not-for-logs") {
t.Error("server log exposed a Bearer credential")
}
var records []map[string]any
for _, line := range strings.Split(strings.TrimSpace(output.String()), "\n") {
if line == "" {
continue
}
var record map[string]any
if json.Unmarshal([]byte(line), &record) != nil {
t.Error("diagnostic log is not structured JSON")
continue
}
// Access records are not detailed duplicate error records.
if record["msg"] != "http request" {
records = append(records, record)
}
}
if len(records) != 1 {
t.Errorf("want exactly one detailed error at response boundary, got %d", len(records))
return
}
record := records[0]
if _, malformed := record["!BADKEY"]; malformed {
t.Error("structured error log contains !BADKEY: slog arguments are not valid key/value pairs")
}
if record["request_id"] != recorder.Header().Get("X-Request-Id") || record["status"] != float64(500) ||
(record["code"] != "internal_error" && record["error_code"] != "internal_error") {
t.Error("diagnostic is missing matching request_id/status/error code")
}
encoded, _ := json.Marshal(record)
if !bytes.Contains(encoded, []byte("synthetic-storage-diagnostic")) {
t.Error("diagnostic lost storage cause")
}
}
// Faults enter through sqlc's database interface, then pass through the real
// repository, service and HTTP error mapper. Driver causes are deliberately
// not required to survive: the public category and response are the contract.
type errorCase struct {
name string
cause error
want error
status int
code string
}
func databaseErrorCases() []errorCase {
cases := []errorCase{
{"no_rows", pgx.ErrNoRows, service.ErrNotFound, 404, "not_found"},
{"duplicate", &pgconn.PgError{Code: "23505"}, service.ErrAlreadyExists, 409, "conflict"},
{"eof", io.EOF, service.ErrServiceUnavailable, 503, "unavailable"},
{"deadline", context.DeadlineExceeded, service.ErrServiceUnavailable, 503, "unavailable"},
{"unexpected_eof", io.ErrUnexpectedEOF, service.ErrServiceUnavailable, 503, "unavailable"},
{"closed_connection", pgconn.ErrConnClosed, service.ErrServiceUnavailable, 503, "unavailable"},
{"connection_refused", unavailableRow{}.Scan(), service.ErrServiceUnavailable, 503, "unavailable"},
// Docker removes the stopped service from DNS. The real outage probe
// returned a ConnectError containing this error, without a net.OpError.
{"database_dns_missing", &net.DNSError{Err: "no such host", Name: "postgres", IsNotFound: true}, service.ErrServiceUnavailable, 503, "unavailable"},
{"sql_syntax", &pgconn.PgError{Code: "42601", Message: "private SQL diagnostic"}, service.ErrServerError, 500, "internal_error"},
{"unexpected", errors.New("private database diagnostic"), service.ErrServerError, 500, "internal_error"},
}
for _, code := range []string{"53300", "57P03", "08006", "08001", "57P01", "57P02"} {
cases = append(cases, errorCase{"sqlstate_" + code, &pgconn.PgError{Code: code}, service.ErrServiceUnavailable, 503, "unavailable"})
}
// Wrapping must not change how an existing error category is recognized.
originals := append([]errorCase(nil), cases...)
for _, tc := range originals {
tc.name = "wrapped_" + tc.name
tc.cause = fmt.Errorf("database operation: %w", tc.cause)
cases = append(cases, tc)
}
return cases
}
type faultRow struct{ cause error }
func (r faultRow) Scan(...any) error { return r.cause }
type faultDB struct {
unavailableDB
cause error
}
func (d faultDB) QueryRow(context.Context, string, ...any) pgx.Row {
return faultRow{d.cause}
}
func assertContractError(t *testing.T, recorder *httptest.ResponseRecorder, status int, code string) {
t.Helper()
if recorder.Code != status {
t.Fatalf("want HTTP %d, got %d", status, recorder.Code)
}
if recorder.Header().Get("Content-Type") != "application/json" {
t.Fatal("error response must have application/json content type")
}
var payload struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
decoder := json.NewDecoder(recorder.Body)
if err := decoder.Decode(&payload); err != nil {
t.Fatal("error response is not valid JSON")
}
if decoder.Decode(new(any)) != io.EOF {
t.Fatal("error response contains more than one JSON value")
}
if payload.Error.Code != code || payload.Error.RequestID == "" ||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
t.Fatal("error category or request ID violates the API contract")
}
if payload.Error.Message == "" || strings.Contains(payload.Error.Message, "private") {
t.Fatal("error message is empty or discloses internal diagnostics")
}
}
func TestErrorDatabaseCategoryReachesHTTP(t *testing.T) {
for _, tc := range databaseErrorCases() {
t.Run(tc.name, func(t *testing.T) {
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: tc.cause})))
_, err := users.GetUser(context.Background(), uuid.NewString())
if !errors.Is(err, tc.want) {
t.Fatalf("want category %v, got %v", tc.want, err)
}
if errors.Is(tc.cause, context.DeadlineExceeded) && !strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
t.Error("deadline diagnostic context lost between repository and service")
}
recorder := httptest.NewRecorder()
mid := middleware.NewMiddleware(nil, "auth-test")
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = httputils.WriteServiceError(w, err, middleware.RequestIDFromContext(r.Context()))
})).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
assertContractError(t, recorder, tc.status, tc.code)
})
}
}
func TestErrorUnavailableSQLLoginKeepsCategory(t *testing.T) {
for _, tc := range databaseErrorCases() {
if tc.status != 503 {
continue
}
t.Run(tc.name, func(t *testing.T) {
queries := sqlc.New(faultDB{cause: tc.cause})
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
mid := middleware.NewMiddleware(auth, "auth-test")
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("synthetic_user", "Synthetic:password")
recorder := httptest.NewRecorder()
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
assertContractError(t, recorder, 503, "unavailable")
})
}
}
// The caller exists; the other member lookup fails. This isolates the service
// branch that used to replace the received err with ErrServerError.
type memberFaultDB struct {
unavailableDB
caller uuid.UUID
cause error
}
func (d memberFaultDB) QueryRow(_ context.Context, _ string, args ...any) pgx.Row {
id := uuid.UUID(args[0].(pgtype.UUID).Bytes)
if id == d.caller {
return memberUserRow{id}
}
return faultRow{d.cause}
}
type memberUserRow struct{ id uuid.UUID }
func (r memberUserRow) Scan(dst ...any) error {
*dst[0].(*pgtype.UUID) = pgtype.UUID{Bytes: [16]byte(r.id), Valid: true}
*dst[1].(*string) = "error_test_caller"
*dst[2].(*string) = "Error test caller"
*dst[3].(*string) = "unused password hash"
*dst[4].(*pgtype.Timestamptz) = pgtype.Timestamptz{Time: time.Unix(1, 0), Valid: true}
return nil
}
func TestErrorChatMemberLookupKeepsOperationMeaning(t *testing.T) {
for _, tc := range databaseErrorCases() {
if tc.status != 503 && tc.status != 404 && tc.status != 500 {
continue
}
t.Run(tc.name, func(t *testing.T) {
caller := uuid.New()
queries := sqlc.New(memberFaultDB{caller: caller, cause: tc.cause})
users := repository.NewUserRepository(queries)
// No writable repository: an invalid member list must never reach
// chat insertion. Accidentally continuing is a test failure.
chats := service.NewChatService(nil, users, service.NewUserService(users))
_, err := chats.Create(context.Background(), "Error regression", []string{caller.String(), uuid.NewString()}, caller.String())
want, status, code := tc.want, tc.status, tc.code
if tc.status == 404 {
// contracts/README.md:17: unknown members make POST /chats invalid.
want, status, code = service.ErrInvalidInput, 400, "invalid_request"
}
if !errors.Is(err, want) {
t.Fatalf("want category %v, got %v", want, err)
}
gotStatus, gotCode := httputils.ErrorFromService(err)
if gotStatus != status || gotCode != code {
t.Fatalf("want %d/%s, got %d/%s", status, code, gotStatus, gotCode)
}
})
}
}
func TestErrorMissingBasicPrecedesForbiddenBody(t *testing.T) {
mid := middleware.NewMiddleware(nil, "auth-test")
auth := handler.NewAuthHandler(nil)
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
recorder := httptest.NewRecorder()
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
assertContractError(t, recorder, 401, "unauthorized")
if recorder.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatal("missing Basic challenge")
}
}
@@ -0,0 +1,202 @@
package auth_tests
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/google/uuid"
redisclient "github.com/redis/go-redis/v9"
"highload/internal/repository"
)
type logoutObservationKey struct{}
type logoutObservation struct {
Group int `json:"clients"`
Round int `json:"round"`
PauseMS int `json:"pause_ms"`
ElapsedMS float64 `json:"elapsed_ms"`
WaitMS float64 `json:"waitaof_ms"`
DelID int64 `json:"del_connection_id"`
WaitID int64 `json:"wait_connection_id"`
Local *int64 `json:"local_fsynced"`
Replicas *int64 `json:"replicas_fsynced"`
Kind string `json:"kind"`
CommandError string `json:"command_error,omitempty"`
RepositoryError string `json:"repository_error,omitempty"`
}
type logoutAOFObservation struct{}
func (h logoutAOFObservation) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
func (h logoutAOFObservation) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
return next
}
func (h logoutAOFObservation) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
return func(ctx context.Context, cmd redisclient.Cmder) error {
started := time.Now()
err := next(ctx, cmd)
row, _ := ctx.Value(logoutObservationKey{}).(*logoutObservation)
if row == nil {
return err
}
name := cmd.Name()
if name != "del" && name != "waitaof" {
return err
}
if name == "waitaof" {
row.WaitMS = float64(time.Since(started)) / float64(time.Millisecond)
if err != nil {
row.CommandError = err.Error()
row.Kind = "command_error"
} else {
if value, ok := cmd.(*redisclient.Cmd); ok {
if reply, ok := value.Val().([]any); ok && len(reply) == 2 {
local, lok := reply[0].(int64)
replicas, rok := reply[1].(int64)
if lok && rok {
row.Local = &local
row.Replicas = &replicas
row.Kind = "acknowledged"
if local != 1 {
row.Kind = "unacknowledged"
}
}
}
}
if row.Local == nil {
row.Kind = "unexpected_reply"
}
}
}
if err == nil {
// next is bound to this Conn's processing path. The observation adds a
// read-only CLIENT ID on that same path; it never gets a second pool slot.
id := redisclient.NewIntCmd(ctx, "CLIENT", "ID")
if e := next(ctx, id); e == nil {
if name == "del" {
row.DelID = id.Val()
} else {
row.WaitID = id.Val()
}
}
}
return err
}
}
func TestRedisLogoutPersistenceDiagnostic(t *testing.T) {
f := newRedisFixture(t)
f.client.AddHook(logoutAOFObservation{})
before := f.client.PoolStats()
rows := []logoutObservation{}
var mu sync.Mutex
stop := make(chan struct{})
sampled := make(chan struct{})
poolSamples := []map[string]any{}
go func() {
defer close(sampled)
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
poolSamples = append(poolSamples, map[string]any{"at": time.Now().UTC().Format(time.RFC3339Nano), "stats": f.client.PoolStats()})
}
}
}()
defer func() {
close(stop)
<-sampled
deadline := time.Now().Add(time.Second)
for f.client.PoolStats().TotalConns != f.client.PoolStats().IdleConns && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
after := f.client.PoolStats()
if after.TotalConns != after.IdleConns || after.PendingRequests != 0 {
t.Error("logout left acquired/pending pool connections")
}
report := map[string]any{"pool_before": before, "pool_after": after, "pool_samples": poolSamples, "samples": rows, "production_options": map[string]any{"read_timeout_ms": f.client.Options().ReadTimeout.Milliseconds(), "pool_size": f.client.Options().PoolSize, "pool_timeout_ms": f.client.Options().PoolTimeout.Milliseconds()}, "instrumentation": "read-only CLIENT ID after DEL and WAITAOF, on the pinned processing path"}
if directory := os.Getenv("AUTH_TEST_DIAGNOSTICS_DIR"); directory != "" {
_ = os.MkdirAll(directory, 0700)
data, _ := json.MarshalIndent(report, "", " ")
if os.WriteFile(filepath.Join(directory, "redis-logout.json"), data, 0600) != nil {
t.Error("cannot save Redis diagnostics")
}
}
t.Logf("logout samples=%d pool_wait_count=%d wait_ns=%d pool_timeouts=%d final_busy=%d", len(rows), after.WaitCount-before.WaitCount, after.WaitDurationNs-before.WaitDurationNs, after.Timeouts-before.Timeouts, after.TotalConns-after.IdleConns)
}()
run := func(clients, round, pause int) {
var workers sync.WaitGroup
start := make(chan struct{})
for range clients {
workers.Add(1)
go func() {
defer workers.Done()
// Two sessions for one synthetic identity: revoking one must leave the
// other valid, even while other workers revoke their own sessions.
first, other := f.trackSafe(uuid.NewString()), f.trackSafe(uuid.NewString())
user := uuid.NewString()
if _, err := f.repo.Create(f.ctx, first[:], user, time.Minute); err != nil {
t.Error("create logout fixture failed")
return
}
if _, err := f.repo.Create(f.ctx, other[:], user, time.Minute); err != nil {
t.Error("create independent fixture failed")
return
}
<-start
time.Sleep(time.Duration(pause) * time.Millisecond)
row := logoutObservation{Group: clients, Round: round, PauseMS: pause}
ctx := context.WithValue(f.ctx, logoutObservationKey{}, &row)
began := time.Now()
_, err := f.repo.RevokeSession(ctx, first[:])
row.ElapsedMS = float64(time.Since(began)) / float64(time.Millisecond)
if err != nil {
row.RepositoryError = err.Error()
t.Errorf("logout clients=%d kind=%s category=%v", clients, row.Kind, err)
}
if row.Kind == "unacknowledged" && !errors.Is(err, repository.ErrServiceUnavailable) {
t.Error("unacknowledged local fsync must preserve unavailable category")
}
if row.DelID == 0 || row.DelID != row.WaitID {
t.Error("DEL/WAITAOF connection identity not preserved")
}
if _, err = f.repo.GetSessionByTokenHash(f.ctx, other[:]); err != nil {
t.Error("concurrent logout affected independent session")
}
if _, err = f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repository.ErrNotFound) {
t.Error("revoked session still available")
}
mu.Lock()
rows = append(rows, row)
mu.Unlock()
}()
}
close(start)
workers.Wait()
}
for i, pause := range []int{0, 137, 359, 613, 887, 1109} {
run(1, i+1, pause)
}
for _, clients := range []int{5, 10} {
for round := 1; round <= 3; round++ {
run(clients, round, 137*round)
}
}
}
// track modifies fixture cleanup bookkeeping; concurrent probes synchronize it.
var diagnosticTrackMu sync.Mutex
func (f *redisFixture) trackSafe(token string) [32]byte {
diagnosticTrackMu.Lock()
defer diagnosticTrackMu.Unlock()
return f.track(token)
}
@@ -0,0 +1,570 @@
package auth_tests
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"reflect"
"slices"
"strings"
"sync"
"testing"
"time"
"highload/internal/model"
domainrepo "highload/internal/repository"
postgresrepo "highload/internal/repository/postgres"
"highload/internal/service"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
"github.com/google/uuid"
)
// Uses the real handler/service/PostgreSQL repository and metadata-only fixtures.
// Authentication is already covered by the existing auth tests: only the current
// user context is injected here. No S3 server, upload endpoint or Redis is needed.
type messageAttachmentFixture struct {
*fixture
http http.Handler
alice, bob string
chat, other *model.Chat
ids, foreign []string
}
type attachmentMessage struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
// Small dependencies for the real service's one-attachment regression. They
// compare UUID identity without prescribing where normalization takes place.
// They do not implement persistence/idempotency: PostgreSQL cases prove that.
type singleAttachmentChatRepo struct {
domainrepo.ChatRepository
chat *model.Chat
}
func (r *singleAttachmentChatRepo) GetChatByID(_ context.Context, id string) (*model.Chat, error) {
if id != r.chat.ID {
return nil, domainrepo.ErrNotFound
}
return r.chat, nil
}
type singleAttachmentMessageRepo struct {
domainrepo.MessageRepository
message *model.Message
key string
calls [][]string
}
func (r *singleAttachmentMessageRepo) CreateMessage(_ context.Context, chatID, userID, text, key string, ids []string) (*model.Message, error) {
r.calls = append(r.calls, append([]string{}, ids...))
if chatID != r.message.ChatID || userID != r.message.SenderID || text != r.message.Text || key != r.key {
return nil, domainrepo.ErrServerError
}
if len(ids) != len(r.message.AttachmentIDs) {
return nil, domainrepo.ErrInvalidInput
}
for index, raw := range ids {
id, err := uuid.Parse(raw)
if err != nil || id.String() != r.message.AttachmentIDs[index] {
return nil, domainrepo.ErrInvalidInput
}
}
return r.message, nil
}
func TestMessageAttachmentsSingleIDServiceRegression(t *testing.T) {
const attachmentID = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
for _, scenario := range []struct {
name, inputID string
requests int
}{
{name: "single_attachment_without_panic", inputID: attachmentID, requests: 1},
{name: "identical_uppercase_body_replay", inputID: strings.ToUpper(attachmentID), requests: 2},
} {
t.Run(scenario.name, func(t *testing.T) {
defer func() {
if recovered := recover(); recovered != nil {
t.Errorf("CreateMessage with one valid attachment panicked: %v", recovered)
}
}()
userID, chatID, key := uuid.NewString(), uuid.NewString(), uuid.NewString()
original := &model.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: userID,
Text: "", AttachmentIDs: []string{attachmentID}, CreatedAt: time.Unix(1700000000, 0).UTC()}
repo := &singleAttachmentMessageRepo{message: original, key: key}
chatRepo := &singleAttachmentChatRepo{chat: &model.Chat{ID: chatID, MemberIDs: []string{userID}}}
chats := service.NewChatService(chatRepo, nil, nil)
messages := service.NewMessageService(repo, chats, nil)
for range scenario.requests {
// The uppercase case starts uppercase and repeats EXACTLY the same
// values. It never assumes different string bodies must be equivalent.
input := []string{scenario.inputID}
message, err := messages.CreateMessage(context.Background(), "", chatID, userID, key, input)
if err != nil || !reflect.DeepEqual(message, original) {
t.Fatalf("one attachment / identical uppercase replay: expected original Message without conflict, got %v", err)
}
}
if len(repo.calls) == 0 {
t.Fatal("service did not create the message through its repository")
}
for _, ids := range repo.calls {
if len(ids) != 1 {
t.Fatal("service lost the single attachment")
}
id, err := uuid.Parse(ids[0])
if err != nil || id.String() != attachmentID {
t.Fatal("service changed the attachment UUID identity")
}
}
})
}
}
func newMessageAttachmentFixture(t *testing.T) *messageAttachmentFixture {
t.Helper()
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 12)
result := &messageAttachmentFixture{fixture: f, alice: uuid.NewString(), bob: uuid.NewString()}
for _, id := range []string{result.alice, result.bob} {
_, err := f.pool.Exec(f.ctx, `INSERT INTO users(id,username,display_name,password_hash)
VALUES($1,$2,'Synthetic attachment test','fixture-only-not-used-for-login')`,
id, "attach_"+strings.ReplaceAll(id, "-", "")[:18])
if err != nil {
t.Fatal("cannot prepare synthetic users")
}
}
chatRepo := postgresrepo.NewChatRepository(f.queries, f.pool)
var err error
result.chat, err = chatRepo.CreateChat(f.ctx, "Message attachments", []string{result.alice, result.bob})
if err != nil {
t.Fatal("cannot prepare primary chat")
}
result.other, err = chatRepo.CreateChat(f.ctx, "Other attachment scope", []string{result.alice})
if err != nil {
t.Fatal("cannot prepare other chat")
}
attachments := postgresrepo.NewAttachmentRepository(f.queries, f.pool)
for _, chat := range []*model.Chat{result.chat, result.other} {
for i := 0; i < 11; i++ {
att, err := attachments.CreateAttachment(f.ctx, domainrepo.CreateAttachmentParams{
ChatID: chat.ID, OwnerID: result.alice, Filename: fmt.Sprintf("synthetic-%d.png", i),
ObjectKey: "metadata-only/" + uuid.NewString(), ContentType: "image/png",
Sha256: strings.Repeat("a", 64), SizeBytes: 1,
})
if err != nil {
t.Fatal("cannot seed attachment metadata through its PostgreSQL repository")
}
if chat.ID == result.chat.ID {
result.ids = append(result.ids, att.ID)
} else {
result.foreign = append(result.foreign, att.ID)
}
}
}
// Deliberately disagree with UUID ordering to catch accidental ORDER BY id.
slices.Sort(result.ids)
slices.Reverse(result.ids)
users := service.NewUserService(postgresrepo.NewUserRepository(f.queries))
chats := service.NewChatService(chatRepo, postgresrepo.NewUserRepository(f.queries), users)
messages := service.NewMessageService(postgresrepo.NewMessageRepository(f.queries, f.pool), chats, users)
h := handler.NewMessageHandler(messages)
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage)
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.GetMessagesByChatID)
mid := middleware.NewMiddleware(nil, "message-pg-test")
result.http = mid.InstanceID(mid.RequestID(mux))
return result
}
func (f *messageAttachmentFixture) call(actor, method, chatID, key string, body any) *httptest.ResponseRecorder {
var raw []byte
if body != nil {
raw, _ = json.Marshal(body)
}
request := httptest.NewRequest(method, "/api/v1/chats/"+chatID+"/messages?limit=100", bytes.NewReader(raw))
request = request.WithContext(middleware.WithUserID(f.ctx, actor))
request.Header.Set("Content-Type", "application/json")
if key != "" {
request.Header.Set("Idempotency-Key", key)
}
recorder := httptest.NewRecorder()
f.http.ServeHTTP(recorder, request)
return recorder
}
func attachmentBody(text string, ids []string) map[string]any {
return map[string]any{"text": text, "attachment_ids": ids}
}
func decodeAttachmentMessage(t *testing.T, response *httptest.ResponseRecorder) attachmentMessage {
t.Helper()
if response.Code != http.StatusCreated {
t.Fatalf("POST message: expected HTTP 201, got %d", response.Code)
}
var value map[string]json.RawMessage
if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil || len(value) != 6 {
t.Fatal("Message must contain exactly the six lab4 contract fields, including attachment_ids")
}
var message attachmentMessage
if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil || message.AttachmentIDs == nil {
t.Fatal("attachment_ids must be an array, including [] for a text-only message")
}
for _, id := range []string{message.ID, message.ChatID, message.SenderID} {
if _, err := uuid.Parse(id); err != nil {
t.Fatal("Message contains an invalid UUID")
}
}
if _, err := time.Parse(time.RFC3339Nano, message.CreatedAt); err != nil || !strings.HasSuffix(message.CreatedAt, "Z") {
t.Fatal("Message must preserve a server UTC timestamp")
}
if response.Header().Get("X-Request-Id") == "" || response.Header().Get("X-Instance-Id") != "message-pg-test" {
t.Fatal("message response is missing request/instance identity")
}
return message
}
func (f *messageAttachmentFixture) history(t *testing.T) []attachmentMessage {
t.Helper()
r := f.call(f.bob, "GET", f.chat.ID, "", nil)
var page struct {
Items []attachmentMessage `json:"items"`
NextCursor *string `json:"next_cursor"`
}
if r.Code != 200 || json.Unmarshal(r.Body.Bytes(), &page) != nil || page.NextCursor != nil {
t.Fatal("cannot read the complete synthetic history")
}
for _, message := range page.Items {
if message.AttachmentIDs == nil {
t.Fatal("history must include attachment_ids arrays")
}
}
return page.Items
}
func (f *messageAttachmentFixture) assertLinks(t *testing.T, message attachmentMessage, expected []string) {
t.Helper()
if !sameOrderedAttachmentUUIDs(message.AttachmentIDs, expected) {
t.Fatal("Message attachment order or contents differ from request")
}
rows, err := f.pool.Query(f.ctx, `SELECT attachment_id::text, position, chat_id::text
FROM messages_attachments WHERE message_id=$1 ORDER BY position`, message.ID)
if err != nil {
t.Fatal("cannot inspect attachment links")
}
defer rows.Close()
var actual []string
for rows.Next() {
var id, chatID string
var position int
if rows.Scan(&id, &position, &chatID) != nil || position != len(actual) || chatID != f.chat.ID {
t.Fatal("attachment link has incorrect position or chat scope")
}
actual = append(actual, id)
}
if rows.Err() != nil || !slices.Equal(actual, expected) {
t.Fatal("database links do not match exactly the submitted attachment order")
}
}
func sameOrderedAttachmentUUIDs(actual, expected []string) bool {
if actual == nil || len(actual) != len(expected) {
return false
}
for index, raw := range actual {
id, err := uuid.Parse(raw)
want, wantErr := uuid.Parse(expected[index])
if err != nil || wantErr != nil || id != want {
return false
}
}
return true
}
func sameHistoryMessage(actual, expected attachmentMessage) bool {
if !sameOrderedAttachmentUUIDs(actual.AttachmentIDs, expected.AttachmentIDs) {
return false
}
actual.AttachmentIDs = expected.AttachmentIDs
return reflect.DeepEqual(actual, expected)
}
func (f *messageAttachmentFixture) snapshot(t *testing.T) map[string][]string {
t.Helper()
state := make(map[string][]string)
for _, table := range []string{"messages", "messages_attachments", "message_idempotency", "attachments"} {
// Table names are fixed test constants, never request input.
rows, err := f.pool.Query(f.ctx, "SELECT to_jsonb(item)::text FROM "+table+" AS item ORDER BY to_jsonb(item)::text")
if err != nil {
t.Fatal("cannot inspect transaction state")
}
for rows.Next() {
var row string
if rows.Scan(&row) != nil {
t.Fatal("cannot decode transaction state")
}
state[table] = append(state[table], row)
}
err = rows.Err()
rows.Close()
if err != nil {
t.Fatal("cannot finish inspecting transaction state")
}
}
return state
}
func (f *messageAttachmentFixture) assertUnchanged(t *testing.T, before map[string][]string) {
t.Helper()
if !reflect.DeepEqual(before, f.snapshot(t)) {
t.Fatal("failed/conflicting request changed messages, links, idempotency or metadata")
}
}
func TestMessageAttachmentsTextCompatibility(t *testing.T) {
f := newMessageAttachmentFixture(t)
key := uuid.NewString()
first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, map[string]any{"text": "Legacy text 👋"}))
second := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody(first.Text, []string{})))
if first.ChatID != f.chat.ID || first.SenderID != f.alice || first.Text != "Legacy text 👋" || !reflect.DeepEqual(first, second) {
t.Fatal("absent attachment_ids and [] must preserve the same text-only Message")
}
f.assertLinks(t, first, []string{})
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
t.Fatal("text-only replay changed or duplicated history")
}
}
func TestMessageAttachmentsOnlyAndOrderZeroToTen(t *testing.T) {
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
}
for count := 0; count <= 10; count++ {
t.Run(fmt.Sprintf("count_%d", count), func(t *testing.T) {
f := newMessageAttachmentFixture(t)
ids := append([]string{}, f.ids[:count]...)
text := ""
if count == 0 {
text = "Text without attachments"
}
key := uuid.NewString()
body := attachmentBody(text, ids)
if count == 1 {
body = attachmentBody(text, []string{strings.ToUpper(ids[0])})
}
first := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body))
if count == 1 {
before := f.snapshot(t)
if replay := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) {
t.Fatal("identical JSON with uppercase attachment UUID must replay the same 201/Message")
}
f.assertUnchanged(t, before)
}
if first.Text != text || first.SenderID != f.bob || first.ChatID != f.chat.ID {
t.Fatal("message-only/attachment-only content or sender changed")
}
f.assertLinks(t, first, ids)
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
t.Fatal("history lost the message or attachment order")
}
})
}
}
func TestMessageAttachmentsInvalidReferencesAreAtomic(t *testing.T) {
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
}
for _, kind := range []string{"unknown_id", "attachment_from_other_chat", "foreign_chat"} {
t.Run(kind, func(t *testing.T) {
f := newMessageAttachmentFixture(t)
ids, actor, chatID := []string{f.ids[0], uuid.NewString()}, f.alice, f.chat.ID
if kind == "attachment_from_other_chat" {
ids[1] = f.foreign[0]
} else if kind == "foreign_chat" {
actor, chatID, ids = f.bob, f.other.ID, []string{f.foreign[0]}
}
before, key := f.snapshot(t), uuid.NewString()
response := f.call(actor, "POST", chatID, key, attachmentBody("Must not be written", ids))
assertContractError(t, response, 404, "not_found")
f.assertUnchanged(t, before)
// A rejected attempt must not reserve this user's key as a final result.
valid := decodeAttachmentMessage(t, f.call(actor, "POST", f.chat.ID, key, attachmentBody("Valid after 404", f.ids[:1])))
f.assertLinks(t, valid, f.ids[:1])
})
}
}
func TestMessageAttachmentsInvalidListLeavesNoRows(t *testing.T) {
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
}
for _, kind := range []string{"duplicate", "eleven"} {
t.Run(kind, func(t *testing.T) {
f := newMessageAttachmentFixture(t)
ids := f.ids
if kind == "duplicate" {
ids = []string{f.ids[0], f.ids[0]}
}
before := f.snapshot(t)
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, uuid.NewString(), attachmentBody("invalid list", ids)), 400, "invalid_request")
f.assertUnchanged(t, before)
})
}
}
func TestMessageAttachmentsIdempotencyIncludesListAndOrder(t *testing.T) {
f := newMessageAttachmentFixture(t)
key, ids := uuid.NewString(), f.ids[:2]
upperIDs := []string{strings.ToUpper(ids[0]), strings.ToUpper(ids[1])}
if slices.Equal(upperIDs, ids) {
t.Fatal("normalization fixture must contain a UUID with hexadecimal letters")
}
body := attachmentBody("Same text", upperIDs)
first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body))
before := f.snapshot(t)
for range 3 {
if replay := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) {
t.Fatal("same key/body did not return the same Message")
}
f.assertUnchanged(t, before)
}
for _, changed := range [][]string{{ids[1], ids[0]}, {ids[0], f.ids[2]}, {ids[0]}, {}} {
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Same text", changed)), 409, "conflict")
f.assertUnchanged(t, before)
}
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Changed text", ids)), 409, "conflict")
f.assertUnchanged(t, before)
f.assertLinks(t, first, ids)
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
t.Fatal("idempotency conflict changed history")
}
}
func TestMessageAttachmentsConcurrentReplayDoesNotMultiplyLinks(t *testing.T) {
f := newMessageAttachmentFixture(t)
const workers = 8
key, ids := uuid.NewString(), f.ids[:3]
gate := make(chan struct{})
results := make(chan *httptest.ResponseRecorder, workers)
var group sync.WaitGroup
for range workers {
group.Add(1)
go func() {
defer group.Done()
<-gate
results <- f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Concurrent attachment replay", ids))
}()
}
close(gate)
group.Wait()
close(results)
var first attachmentMessage
for response := range results {
message := decodeAttachmentMessage(t, response)
if first.ID == "" {
first = message
} else if !reflect.DeepEqual(message, first) {
t.Fatal("concurrent replay returned a different Message")
}
}
f.assertLinks(t, first, ids)
state := f.snapshot(t)
if len(state["messages"]) != 1 || len(state["messages_attachments"]) != len(ids) || len(state["message_idempotency"]) != 1 {
t.Fatal("concurrent replay multiplied message, link or idempotency rows")
}
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
t.Fatal("concurrent replay changed history")
}
}
func TestMessageAttachmentsLinkFailureRollsBackEverything(t *testing.T) {
f := newMessageAttachmentFixture(t)
ids, key := f.ids[:2], uuid.NewString()
// The sequence survives rollback. It proves that the fault was reached only
// after the first link was visible inside the actual application transaction.
_, err := f.pool.Exec(f.ctx, `CREATE SEQUENCE test_link_fault_reached;
CREATE FUNCTION fail_second_test_link() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (SELECT count(*) FROM messages_attachments WHERE message_id=NEW.message_id) >= 1 THEN
PERFORM nextval('test_link_fault_reached');
RAISE EXCEPTION 'synthetic link failure';
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER test_link_fault BEFORE INSERT ON messages_attachments
FOR EACH ROW EXECUTE FUNCTION fail_second_test_link();`)
if err != nil {
t.Fatal("cannot prepare isolated link fault")
}
before := f.snapshot(t)
response := f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids))
assertContractError(t, response, 500, "internal_error")
var faultReached bool
if f.pool.QueryRow(f.ctx, "SELECT is_called FROM test_link_fault_reached").Scan(&faultReached) != nil || !faultReached {
t.Fatal("test did not reach an injected link failure after one real link insert")
}
f.assertUnchanged(t, before)
if strings.Contains(response.Body.String(), "synthetic link failure") {
t.Fatal("response exposed internal SQL fault details")
}
if _, err := f.pool.Exec(f.ctx, "DROP TRIGGER test_link_fault ON messages_attachments"); err != nil {
t.Fatal("cannot clear isolated link fault")
}
message := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids)))
f.assertLinks(t, message, ids)
state := f.snapshot(t)
if len(state["messages"]) != 1 || len(state["messages_attachments"]) != 2 || len(state["message_idempotency"]) != 1 {
t.Fatal("retry after transient link failure did not commit exactly one complete message")
}
}
// The public API has immutable membership. Change it only in the isolated
// PostgreSQL fixture to exercise the same sender/key after losing access.
func TestMessageReplayRechecksCurrentChatMembership(t *testing.T) {
f := newMessageAttachmentFixture(t)
const key = "membership-recheck"
body := attachmentBody("prior authorized write", []string{})
original := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body))
before := f.snapshot(t)
// Membership is immutable in the real contract, including at the FK.
// Remove that FK only in this disposable schema to simulate a stale grant
// with historical messages left behind.
if _, err := f.pool.Exec(f.ctx, "ALTER TABLE messages DROP CONSTRAINT messages_chat_id_sender_id_fkey"); err != nil {
t.Fatal("cannot enable membership fault in the isolated fixture")
}
tag, err := f.pool.Exec(f.ctx, "DELETE FROM chat_members WHERE chat_id=$1 AND user_id=$2",
f.chat.ID, f.bob)
if err != nil || tag.RowsAffected() != 1 {
t.Fatal("cannot remove sender's membership in the isolated fixture")
}
denied := f.call(f.bob, "POST", f.chat.ID, key, body)
var payload struct {
Error struct {
Code string `json:"code"`
RequestID string `json:"request_id"`
} `json:"error"`
}
if denied.Code != http.StatusNotFound || json.Unmarshal(denied.Body.Bytes(), &payload) != nil ||
payload.Error.Code != "not_found" || payload.Error.RequestID == "" ||
payload.Error.RequestID != denied.Header().Get("X-Request-Id") {
t.Fatalf("replay after losing access must return contract 404, got %d", denied.Code)
}
f.assertUnchanged(t, before)
if _, err := f.pool.Exec(f.ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", f.chat.ID, f.bob); err != nil {
t.Fatal("cannot restore sender's membership in the isolated fixture")
}
if got := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(got, original) {
t.Fatal("restored access must replay the original Message")
}
f.assertUnchanged(t, before)
}
+126
View File
@@ -0,0 +1,126 @@
package auth_tests
import (
"errors"
"strings"
"testing"
"highload/internal/security"
)
// These are tests of the selected Argon2id implementation, not a requirement
// that lab2 use particular parameters or a particular encoded hash format.
func TestPasswordRoundTripAndRandomSalt(t *testing.T) {
password := "Синтетический:пароль:😀"
first, err := security.HashPassword(password)
if err != nil {
t.Fatal("password hashing failed")
}
second, err := security.HashPassword(password)
if err != nil {
t.Fatal("password hashing failed")
}
if first == password || second == password || first == second {
t.Fatal("hash must differ from plaintext and have a fresh random salt")
}
if !strings.HasPrefix(first, "$argon2id$") {
t.Fatal("selected password implementation did not encode Argon2id")
}
for _, encoded := range []string{first, second} {
ok, err := security.VerifyPassword(password, encoded)
if err != nil || !ok {
t.Fatal("stored hash does not verify the original password")
}
ok, err = security.VerifyPassword(password+"x", encoded)
if err != nil || ok {
t.Fatal("wrong password was accepted or verifier failed")
}
}
}
func TestPasswordDoesNotTruncateLongUTF8(t *testing.T) {
// Both passwords share much more than bcrypt's 72-byte limit; each is
// within the lab's 128-code-point maximum.
password := strings.Repeat("😀", 127) + "A"
different := strings.Repeat("😀", 127) + "B"
encoded, err := security.HashPassword(password)
if err != nil {
t.Fatal("maximum-length UTF-8 password cannot be hashed")
}
ok, err := security.VerifyPassword(password, encoded)
if err != nil || !ok {
t.Fatal("maximum-length UTF-8 password cannot be verified")
}
ok, err = security.VerifyPassword(different, encoded)
if err != nil || ok {
t.Fatal("password suffix was truncated")
}
}
func TestPasswordWhitespaceIsSignificant(t *testing.T) {
password := " synthetic-password "
encoded, err := security.HashPassword(password)
if err != nil {
t.Fatal("password hashing failed")
}
ok, err := security.VerifyPassword(strings.TrimSpace(password), encoded)
if err != nil || ok {
t.Fatal("password whitespace was discarded")
}
}
func TestMalformedPasswordHashRejectedWithoutPanic(t *testing.T) {
valid, err := security.HashPassword("synthetic-password")
if err != nil {
t.Fatal("password hashing failed")
}
parts := strings.Split(valid, "$")
if len(parts) != 6 {
t.Fatal("unexpected encoded hash format")
}
cases := map[string]string{
"empty": "",
"plaintext": "synthetic-password",
"wrong_algorithm": strings.Replace(valid, "argon2id", "argon2i", 1),
"wrong_version": strings.Replace(valid, "$v=19$", "$v=999$", 1),
"missing_version": strings.Replace(valid, "$v=19$", "$19$", 1),
"extra_field": valid + "$extra",
}
for name, params := range map[string]string{
"zero_iterations": "m=65536,t=0,p=2",
"zero_threads": "m=65536,t=3,p=0",
"tiny_memory": "m=1,t=3,p=2",
"huge_memory": "m=4294967295,t=3,p=2",
"huge_iterations": "m=65536,t=4294967295,p=2",
"huge_threads": "m=65536,t=3,p=255",
"negative": "m=-1,t=3,p=2",
"non_numeric": "m=no,t=3,p=2",
"missing_param": "m=65536,t=3",
} {
copyParts := append([]string(nil), parts...)
copyParts[3] = params
cases[name] = strings.Join(copyParts, "$")
}
for name, field := range map[string]int{"salt": 4, "hash": 5} {
for label, value := range map[string]string{
"empty": "", "bad_base64": "!!!", "wrong_size": "YQ",
} {
copyParts := append([]string(nil), parts...)
copyParts[field] = value
cases[name+"_"+label] = strings.Join(copyParts, "$")
}
}
for name, encoded := range cases {
t.Run(name, func(t *testing.T) {
defer func() {
if recover() != nil {
t.Error("malformed stored hash caused a panic")
}
}()
ok, err := security.VerifyPassword("synthetic-password", encoded)
if ok || !errors.Is(err, security.ErrInvalidHash) {
t.Error("malformed stored hash was not rejected")
}
})
}
}
+455
View File
@@ -0,0 +1,455 @@
package auth_tests
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"testing"
"time"
"highload/internal/config"
"highload/internal/database"
repoerrors "highload/internal/repository"
"highload/internal/repository/postgres"
redisrepo "highload/internal/repository/redis"
"highload/internal/service"
httptransport "highload/internal/transport/http"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
"github.com/google/uuid"
redisclient "github.com/redis/go-redis/v9"
)
func TestRedisAddressIsAnAddressNotAFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "postgres_url")
if err := os.WriteFile(path, []byte("postgres://fixture:fixture@postgres/messenger"), 0600); err != nil {
t.Fatal("cannot create synthetic config fixture")
}
t.Setenv("DATABASE_URL_FILE", path)
t.Setenv("REDIS_ADDR", "redis:6379")
t.Setenv("SESSION_TTL_SECONDS", "3600")
t.Setenv("SESSION_STORE", "redis")
t.Setenv("S3_ENDPOINT", "http://s3-fixture.invalid")
t.Setenv("S3_REGION", "us-east-1")
t.Setenv("S3_BUCKET", "health-fixture")
for variable, value := range map[string]string{
"S3_ACCESS_KEY_ID_FILE": "fixture-access-key",
"S3_SECRET_ACCESS_KEY_FILE": "fixture-secret-key",
} {
keyFile := filepath.Join(dir, variable)
if err := os.WriteFile(keyFile, []byte(value), 0600); err != nil {
t.Fatal("cannot create synthetic S3 key file")
}
t.Setenv(variable, keyFile)
}
cfg, err := config.Load()
if err != nil {
t.Fatalf("cannot load synthetic config with REDIS_ADDR=redis:6379: %v", err)
}
if cfg.Database.RedisAddr != "redis:6379" {
t.Fatal("REDIS_ADDR did not reach the Redis configuration")
}
}
type redisFixture struct {
ctx context.Context
client *redisclient.Client
repo *redisrepo.SessionRepository
keys []string
audit *sessionWriteAudit
}
// Only observe writes through this test's client. No global key counting or
// FLUSH commands: other clients' sessions must not affect assertions/cleanup.
type sessionWriteAudit struct {
sync.Mutex
keys map[string]bool
writes int
}
func (a *sessionWriteAudit) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
func (a *sessionWriteAudit) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
return next
}
func (a *sessionWriteAudit) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
return func(ctx context.Context, cmd redisclient.Cmder) error {
if cmd.Name() == "set" && len(cmd.Args()) > 1 {
if key, ok := cmd.Args()[1].(string); ok {
a.Lock()
a.keys[key] = true
a.writes++
a.Unlock()
}
}
return next(ctx, cmd)
}
}
func (a *sessionWriteAudit) writeCount() int { a.Lock(); defer a.Unlock(); return a.writes }
func (a *sessionWriteAudit) ownedKeys() []string {
a.Lock()
defer a.Unlock()
keys := make([]string, 0, len(a.keys))
for key := range a.keys {
keys = append(keys, key)
}
return keys
}
type aofReplyHook struct {
reply any
err error
}
func (h aofReplyHook) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
func (h aofReplyHook) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
return next
}
func (h aofReplyHook) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
return func(ctx context.Context, cmd redisclient.Cmder) error {
if cmd.Name() == "waitaof" {
// DEL still runs on the real test Redis. Only its persistence
// acknowledgement is fault-injected deterministically.
value := cmd.(*redisclient.Cmd)
value.SetVal(h.reply)
value.SetErr(h.err)
return h.err
}
return next(ctx, cmd)
}
}
func TestRedisUnconfirmedAOFNeverReturnsSuccessfulLogout(t *testing.T) {
for _, tc := range []struct {
name string
reply any
err error
}{
{"local_not_fsynced", []any{int64(0), int64(0)}, nil},
{"only_replica_fsynced", []any{int64(0), int64(1)}, nil},
{"malformed_reply", []any{int64(1)}, nil},
{"command_failure", nil, errors.New("synthetic acknowledgement failure")},
} {
t.Run(tc.name, func(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
f.redis.client.AddHook(aofReplyHook{tc.reply, tc.err})
request := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
request.Header.Set("Authorization", "Bearer "+session.Token)
recorder := httptest.NewRecorder()
redisRouter(f, f.redis.client).ServeHTTP(recorder, request)
if recorder.Code != 500 && recorder.Code != 503 {
t.Fatalf("unconfirmed persistence must fail logout, got HTTP %d", recorder.Code)
}
if (tc.name == "local_not_fsynced" || tc.name == "only_replica_fsynced") && recorder.Code != 503 {
t.Errorf("valid reply without local acknowledgement must be HTTP 503, got %d", recorder.Code)
}
code := "internal_error"
if recorder.Code == 503 {
code = "unavailable"
}
assertContractError(t, recorder, recorder.Code, code)
hash := sha256.Sum256([]byte(session.Token))
if f.redis.client.Exists(f.ctx, "session:"+hex.EncodeToString(hash[:])).Val() != 0 {
t.Fatal("fault fixture did not actually execute DEL before WAITAOF")
}
})
}
}
func newRedisFixture(t *testing.T) *redisFixture {
t.Helper()
addr := os.Getenv("AUTH_TEST_REDIS_ADDR")
if addr == "" {
t.Skip("Redis not verified: set AUTH_TEST_REDIS_ADDR to a dedicated test Redis with AOF")
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
t.Cleanup(cancel)
client, err := database.NewRedis(ctx, addr)
if err != nil {
t.Fatal("dedicated test Redis is unavailable")
}
audit := &sessionWriteAudit{keys: make(map[string]bool)}
client.AddHook(audit)
f := &redisFixture{ctx: ctx, client: client, repo: redisrepo.NewSessionRepository(client), audit: audit}
t.Cleanup(func() {
cleanup, done := context.WithTimeout(context.Background(), 3*time.Second)
defer done()
// No FLUSHDB/FLUSHALL: delete only this test's own random token keys.
keys := append(f.audit.ownedKeys(), f.keys...)
if len(keys) > 0 {
if err := client.Del(cleanup, keys...).Err(); err != nil {
t.Error("test-owned Redis key cleanup failed")
}
}
_ = client.Close()
})
return f
}
func (f *redisFixture) track(token string) [32]byte {
hash := sha256.Sum256([]byte(token))
f.keys = append(f.keys, "session:"+hex.EncodeToString(hash[:]))
return hash
}
func TestRedisSessionHasTTLAndReadsDoNotExtendIt(t *testing.T) {
f := newRedisFixture(t)
hash := f.track("synthetic-" + uuid.NewString())
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 5*time.Second)
if err != nil {
t.Fatal("cannot create Redis session")
}
key := f.keys[0]
before := f.client.PTTL(f.ctx, key).Val()
if before <= 0 || before > 5*time.Second {
t.Fatal("session key has no bounded positive TTL")
}
time.Sleep(120 * time.Millisecond)
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
if err != nil || loaded == nil {
t.Fatal("cannot read Redis session")
}
if loaded.UserID != created.UserID || !loaded.ExpiresAt.Equal(created.ExpiresAt) ||
!loaded.CreatedAt.Equal(created.CreatedAt) {
t.Fatal("session identity or original timestamps changed on read")
}
after := f.client.PTTL(f.ctx, key).Val()
if after <= 0 || after >= before {
t.Fatal("reading refreshed or removed the session TTL")
}
}
func TestRedisExpiredAndUnknownSessionsAreNotFound(t *testing.T) {
f := newRedisFixture(t)
hash := f.track(uuid.NewString())
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
t.Fatal("unknown session must be not found")
}
if _, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 200*time.Millisecond); err != nil {
t.Fatal("cannot create short-lived test session")
}
time.Sleep(350 * time.Millisecond)
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
t.Fatal("expired Redis session is still available")
}
}
func TestRedisLogoutOnlyRemovesSelectedSession(t *testing.T) {
f := newRedisFixture(t)
first, second := f.track(uuid.NewString()), f.track(uuid.NewString())
userID := uuid.NewString()
for _, hash := range [][32]byte{first, second} {
if _, err := f.repo.Create(f.ctx, hash[:], userID, time.Minute); err != nil {
t.Fatal("cannot create independent sessions")
}
}
count, err := f.repo.RevokeSession(f.ctx, first[:])
if err != nil || count != 1 {
t.Fatal("logout failed to remove exactly one session or acknowledge persistence")
}
if _, err := f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repoerrors.ErrNotFound) {
t.Fatal("revoked session is still readable")
}
if _, err := f.repo.GetSessionByTokenHash(f.ctx, second[:]); err != nil {
t.Fatal("logout removed another session")
}
}
func TestRedisSessionsSurviveActualRestartWithoutExtendingTTL(t *testing.T) {
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
if hook == "" {
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
}
f := newRedisFixture(t)
active, revoked := f.track(uuid.NewString()), f.track(uuid.NewString())
created, err := f.repo.Create(f.ctx, active[:], uuid.NewString(), 30*time.Second)
if err != nil {
t.Fatal("cannot create active session")
}
if _, err := f.repo.Create(f.ctx, revoked[:], created.UserID, time.Minute); err != nil {
t.Fatal("cannot create revocation fixture")
}
if _, err := f.repo.RevokeSession(f.ctx, revoked[:]); err != nil {
t.Fatal("cannot persist logout before restart")
}
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
}
deadline := time.Now().Add(5 * time.Second)
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
time.Sleep(50 * time.Millisecond)
}
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, active[:])
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) {
t.Fatal("restart lost active session or changed its original deadline")
}
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
t.Fatal("restart extended or lost remaining TTL")
}
if _, err := f.repo.GetSessionByTokenHash(f.ctx, revoked[:]); !errors.Is(err, repoerrors.ErrNotFound) {
t.Fatal("restart revived a revoked session")
}
}
func TestRedisActiveSessionSurvivesRestartIndependentlyOfLogout(t *testing.T) {
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
if hook == "" {
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
}
f := newRedisFixture(t)
hash := f.track(uuid.NewString())
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 30*time.Second)
if err != nil {
t.Fatal("cannot create active session")
}
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
}
deadline := time.Now().Add(5 * time.Second)
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
time.Sleep(50 * time.Millisecond)
}
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) || loaded.UserID != created.UserID {
t.Fatal("restart lost active session identity or changed its deadline")
}
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
t.Fatal("restart extended or removed the session TTL")
}
}
func refusedRedis(t *testing.T) *redisclient.Client {
t.Helper()
client := redisclient.NewClient(&redisclient.Options{
Addr: "synthetic-unavailable:6379", MaxRetries: -1,
Dialer: func(context.Context, string, string) (net.Conn, error) {
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
},
})
t.Cleanup(func() { _ = client.Close() })
return client
}
func TestRedisUnavailableKeepsUnavailableCategory(t *testing.T) {
repo := redisrepo.NewSessionRepository(refusedRedis(t))
hash := sha256.Sum256([]byte("synthetic-failed-token"))
t.Run("create", func(t *testing.T) {
_, err := repo.Create(context.Background(), hash[:], uuid.NewString(), time.Minute)
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
t.Fatalf("want service unavailable, got %v", err)
}
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
t.Error("Redis network diagnostic context was lost")
}
})
t.Run("read", func(t *testing.T) {
_, err := repo.GetSessionByTokenHash(context.Background(), hash[:])
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
t.Fatalf("want service unavailable, got %v", err)
}
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
t.Error("Redis network diagnostic context was lost")
}
})
t.Run("logout", func(t *testing.T) {
_, err := repo.RevokeSession(context.Background(), hash[:])
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
t.Fatalf("want service unavailable, got %v", err)
}
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
t.Error("Redis network diagnostic context was lost")
}
})
auth := service.NewAuthService(nil, repo, time.Hour)
_, err := auth.ValidateSession(context.Background(), "synthetic-error-context")
if !errors.Is(err, service.ErrServiceUnavailable) || !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
t.Error("service lost Redis unavailable category or diagnostic context")
}
}
func redisRouter(f *fixture, client *redisclient.Client) http.Handler {
users := postgres.NewUserRepository(f.queries)
auth := service.NewAuthService(users, redisrepo.NewSessionRepository(client), time.Hour)
userService := service.NewUserService(users)
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), users, userService)
messages := service.NewMessageService(postgres.NewMessageRepository(f.queries, f.pool), chats, userService)
objects := readyS3Storage()
attachments := service.NewAttachmentService(postgres.NewAttachmentRepository(f.queries, f.pool), chats, objects)
return httptransport.NewRouter(middleware.NewMiddleware(auth, "auth-test"), handler.NewAuthHandler(auth),
handler.NewHealthHandler(f.pool, client, objects), handler.NewChatHandler(chats), handler.NewUserHandler(userService),
handler.NewMessageHandler(messages), handler.NewAttachmentHandler(attachments)).Handler()
}
func TestRedisCriticalOutageHTTPAndReadiness(t *testing.T) {
f := newFixture(t)
router := redisRouter(f, refusedRedis(t))
for _, tc := range []struct {
name, path string
status int
}{
{"liveness", "/health/live", 200},
{"readiness", "/health/ready", 503},
{"protected_request", "/api/v1/users/me", 503},
} {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
request.Header.Set("Authorization", "Bearer synthetic-outage-token")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
if recorder.Code != tc.status {
t.Fatalf("want HTTP %d, got %d", tc.status, recorder.Code)
}
if tc.status == 503 {
assertContractError(t, recorder, 503, "unavailable")
}
})
}
}
func TestRedisHTTPAuthContract(t *testing.T) {
f := newFixture(t)
r := newRedisFixture(t)
server := httptest.NewServer(redisRouter(f, r.client))
t.Cleanup(server.Close)
_, source, _, _ := runtime.Caller(0)
root := filepath.Clean(filepath.Join(filepath.Dir(source), "..", ".."))
// Test the auth contract in this fixture. The public smoke now needs a
// durable broker and worker and runs against the full stand in lab5/acceptance.py.
acceptanceCtx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
defer cancel()
cmd := exec.CommandContext(acceptanceCtx, "python3", "-B", filepath.Join(root, "student-tests/auth_contract.py"),
"--base-url", server.URL, "--ttl", "3600")
cmd.Dir = root
output, err := cmd.CombinedOutput()
if err == nil {
return
}
if acceptanceCtx.Err() != nil {
t.Fatal("HTTP auth acceptance subprocess timed out")
}
for _, line := range strings.Split(string(output), "\n") {
if strings.HasPrefix(line, "FAIL: test_") || strings.HasPrefix(line, "ERROR: test_") {
// Print only the method name, never credentials or subtest values.
name := strings.Fields(line)[1]
t.Log("failed auth case: " + name)
}
}
t.Fatal("HTTP auth acceptance failed with Redis-backed sessions")
}
@@ -0,0 +1,121 @@
package auth_tests
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"net/http"
"os"
"os/exec"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestRedisHTTPFullRestartKeepsDeadlineAndRevocation(t *testing.T) {
base, hook := os.Getenv("AUTH_TEST_BASE_URL"), os.Getenv("AUTH_TEST_STACK_RESTART_HOOK")
if base == "" || hook == "" {
t.Skip("set AUTH_TEST_BASE_URL and AUTH_TEST_STACK_RESTART_HOOK for a disposable API+stores stack")
}
for _, withLogout := range []bool{false, true} {
name := "active_only"
if withLogout {
name = "active_and_revoked"
}
t.Run(name, func(t *testing.T) {
f := newRedisFixture(t)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
client := &http.Client{Timeout: 5 * time.Second}
username := "restart_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
password := "Synthetic:" + uuid.NewString()
call := func(method, path, token string, body any, basic bool, want int, dst any) {
t.Helper()
var data bytes.Buffer
if body != nil {
if json.NewEncoder(&data).Encode(body) != nil {
t.Fatal("cannot encode test request")
}
}
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(base, "/")+path, &data)
if err != nil {
t.Fatal("cannot construct test request")
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if basic {
req.SetBasicAuth(username, password)
} else if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(req)
if err != nil {
t.Fatal("restart HTTP request failed")
}
defer response.Body.Close()
if response.StatusCode != want {
t.Fatalf("%s %s: want %d, got %d", method, path, want, response.StatusCode)
}
if dst != nil && json.NewDecoder(response.Body).Decode(dst) != nil {
t.Fatal("invalid restart response JSON")
}
}
call("POST", "/api/v1/users", "", map[string]string{"username": username, "password": password, "display_name": "Restart fixture"}, false, 201, nil)
var active struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &active)
hash := f.track(active.Token)
before, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
if err != nil {
t.Fatal("cannot inspect issued session")
}
if !before.ExpiresAt.Equal(active.ExpiresAt) {
t.Fatal("HTTP and Redis expiry differ")
}
remaining := f.client.PTTL(ctx, f.keys[0]).Val()
if remaining < 2*time.Minute {
t.Fatal("normal restart suite requires long session TTL")
}
revoked := ""
if withLogout {
var other struct {
Token string `json:"token"`
}
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &other)
revoked = other.Token
f.track(revoked)
call("DELETE", "/api/v1/auth/sessions/current", revoked, nil, false, 204, nil)
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
}
if exec.CommandContext(ctx, hook).Run() != nil {
t.Fatal("real API+stores restart hook failed")
}
call("GET", "/health/live", "", nil, false, 200, nil)
call("GET", "/health/ready", "", nil, false, 200, nil)
call("GET", "/api/v1/users/me", active.Token, nil, false, 200, nil)
after, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
if err != nil {
t.Fatal("restart lost session")
}
if !after.ExpiresAt.Equal(before.ExpiresAt) || after.UserID != before.UserID || !after.CreatedAt.Equal(before.CreatedAt) {
t.Fatal("actual API+Redis restart changed session identity/deadline")
}
if ttl := f.client.PTTL(ctx, f.keys[0]).Val(); ttl <= 0 || ttl >= remaining {
t.Fatal("restart reset/removed original TTL")
}
if revoked != "" {
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
revokedHash := sha256.Sum256([]byte(revoked))
if _, err = f.repo.GetSessionByTokenHash(ctx, revokedHash[:]); err == nil {
t.Fatal("revoked credential reappeared after restart")
}
}
})
}
}
+345
View File
@@ -0,0 +1,345 @@
package auth_tests
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"testing"
"time"
"highload/internal/database/sqlc"
"highload/internal/model"
repository "highload/internal/repository/postgres"
redisrepo "highload/internal/repository/redis"
"highload/internal/security"
"highload/internal/service"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type fixture struct {
admin *pgxpool.Pool
pool *pgxpool.Pool
config *pgxpool.Config
queries *sqlc.Queries
users *service.UserService
auth *service.AuthService
redis *redisFixture
ctx context.Context
}
func newFixture(t *testing.T) *fixture {
t.Helper()
f := newDatabaseFixture(t, "AUTH_TEST_DATABASE_URL", 4)
f.redis = newRedisFixture(t)
userRepo := repository.NewUserRepository(f.queries)
f.users = service.NewUserService(userRepo)
f.auth = service.NewAuthService(userRepo, redisrepo.NewSessionRepository(f.redis.client), time.Hour)
return f
}
// Shared PostgreSQL fixture: attachment transaction checks do not require Redis/S3.
func newDatabaseFixture(t *testing.T, environment string, maxConnections int32) *fixture {
t.Helper()
url := os.Getenv(environment)
if url == "" {
t.Skip("PENDING_INFRA: set " + environment + " for a dedicated test PostgreSQL")
}
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
t.Cleanup(cancel)
config, err := pgxpool.ParseConfig(url)
if err != nil {
t.Fatal("cannot parse test PostgreSQL configuration (credentials suppressed)")
}
config.MaxConns = maxConnections
config.MinConns = 0
config.ConnConfig.ConnectTimeout = 3 * time.Second
config.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
admin, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
t.Fatal("cannot open test PostgreSQL pool")
}
t.Cleanup(admin.Close)
if err := admin.Ping(ctx); err != nil {
t.Fatal("test PostgreSQL is unavailable")
}
// Only this uniquely named schema is created and dropped. Existing tables
// and volumes are never removed. The role needs CREATE SCHEMA permission.
schema := "auth_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
quoted := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quoted); err != nil {
t.Fatal("cannot create isolated test schema")
}
t.Cleanup(func() {
cleanupCtx, done := context.WithTimeout(context.Background(), 5*time.Second)
defer done()
if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
t.Error("isolated test schema cleanup failed")
}
})
config = config.Copy()
config.ConnConfig.RuntimeParams["search_path"] = schema
pool, err := pgxpool.NewWithConfig(ctx, config.Copy())
if err != nil {
t.Fatal("cannot connect to isolated test schema")
}
f := &fixture{admin: admin, config: config, ctx: ctx, pool: pool, queries: sqlc.New(pool)}
t.Cleanup(func() { f.pool.Close() })
_, source, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot locate migration files")
}
migrations, err := filepath.Glob(filepath.Join(filepath.Dir(source), "..", "..", "db", "migrations", "*.sql"))
if err != nil || len(migrations) == 0 {
t.Fatal("migration SQL is missing")
}
sort.Strings(migrations)
for _, path := range migrations {
data, err := os.ReadFile(path)
if err != nil {
t.Fatal("cannot read migration SQL")
}
// Current migrations are ordinary SQL with Goose Up/Down markers.
// This applies schema fixtures; it is NOT a test of Goose version tracking.
up, _, _ := strings.Cut(string(data), "-- +goose Down")
if !strings.Contains(up, "-- +goose Up") {
t.Fatal("test fixture expects SQL migrations with Goose Up/Down markers")
}
if _, err := f.pool.Exec(ctx, up, pgx.QueryExecModeSimpleProtocol); err != nil {
t.Fatal("migration cannot initialize isolated schema")
}
}
return f
}
func (f *fixture) connect(t *testing.T, ttl time.Duration) {
t.Helper()
pool, err := pgxpool.NewWithConfig(f.ctx, f.config.Copy())
if err != nil {
t.Fatal("cannot connect to isolated schema")
}
f.pool = pool
f.queries = sqlc.New(pool)
userRepo := repository.NewUserRepository(f.queries)
sessionRepo := redisrepo.NewSessionRepository(f.redis.client)
f.users = service.NewUserService(userRepo)
f.auth = service.NewAuthService(userRepo, sessionRepo, ttl)
}
func (f *fixture) user(t *testing.T) (*model.User, string) {
t.Helper()
password := "Synthetic:" + uuid.NewString()
username := "auth_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
user, err := f.users.CreateUser(f.ctx, username, "Auth storage", password)
if err != nil {
t.Fatal("cannot create synthetic user")
}
return user, password
}
func (f *fixture) session(t *testing.T, user *model.User, password string) *service.CreatedSession {
t.Helper()
session, err := f.auth.CreateSession(f.ctx, user.Username, password)
if err != nil {
t.Fatal("cannot create synthetic session")
}
return session
}
func TestStoragePasswordIsKDFAndDuplicateCannotOverwrite(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
stored, err := f.queries.GetUserByUsername(f.ctx, user.Username)
if err != nil || stored.PasswordHash == password || !strings.HasPrefix(stored.PasswordHash, "$argon2id$") {
t.Fatal("database did not preserve the selected password KDF")
}
ok, err := security.VerifyPassword(password, stored.PasswordHash)
if err != nil || !ok {
t.Fatal("stored password does not verify")
}
_, err = f.users.CreateUser(f.ctx, user.Username, "Overwrite", password+"x")
if !errors.Is(err, service.ErrAlreadyExists) {
t.Fatal("duplicate username was not rejected")
}
after, err := f.queries.GetUserByUsername(f.ctx, user.Username)
if err != nil || after.ID != stored.ID || after.PasswordHash != stored.PasswordHash ||
after.DisplayName != stored.DisplayName {
t.Fatal("failed duplicate registration changed the original user")
}
}
func TestStorageSessionHashAndReconnectPreserveDeadline(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
hash := sha256.Sum256([]byte(session.Token))
key := "session:" + hex.EncodeToString(hash[:])
row, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
value, getErr := f.redis.client.Get(f.ctx, key).Result()
if err != nil || getErr != nil || strings.Contains(key, session.Token) || strings.Contains(value, session.Token) {
t.Fatal("selected session storage did not use SHA-256 of the opaque token")
}
for _, ownedKey := range f.redis.audit.ownedKeys() {
storedValue, err := f.redis.client.Get(f.ctx, ownedKey).Result()
if err != nil || strings.Contains(ownedKey, session.Token) || strings.Contains(storedValue, session.Token) {
t.Fatal("raw session token was persisted in Redis")
}
}
if f.redis.client.Exists(f.ctx, "session:"+session.Token, session.Token).Val() != 0 {
t.Fatal("raw token was stored as a Redis key")
}
if ttl := f.redis.client.PTTL(f.ctx, key).Val(); ttl <= 0 || ttl > time.Hour {
t.Fatal("session must have a positive bounded Redis TTL")
}
if session.TokenType != "Bearer" || len(session.Token) < 32 || row.RevokedAt != nil ||
!row.ExpiresAt.Equal(session.ExpiresAt) || !row.ExpiresAt.After(row.CreatedAt) {
t.Fatal("invalid stored session metadata")
}
beforeDeadline := row.ExpiresAt
for range 3 {
id, err := f.auth.ValidateSession(f.ctx, session.Token)
if err != nil || id != user.ID {
t.Fatal("valid session rejected or mapped to another user")
}
}
f.pool.Close()
// A different process configuration must not reset already stored expiry.
f.connect(t, 24*time.Hour)
id, err := f.auth.ValidateSession(f.ctx, session.Token)
if err != nil || id != user.ID {
t.Fatal("new pool/services lost the existing session")
}
after, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
if err != nil || !after.ExpiresAt.Equal(beforeDeadline) {
t.Fatal("reads or reconnection extended session TTL")
}
}
func TestStorageWrongCredentialsNeverCreateSession(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
writes := f.redis.audit.writeCount()
for _, credentials := range [][2]string{
{user.Username, password + "x"}, {"unknown_auth_user", password},
} {
_, err := f.auth.CreateSession(f.ctx, credentials[0], credentials[1])
if !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("wrong credentials did not yield the same unauthorized error")
}
}
if f.redis.audit.writeCount() != writes {
t.Fatal("failed login created a session")
}
for _, token := range []string{"", uuid.NewString()} {
if _, err := f.auth.ValidateSession(f.ctx, token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("empty or unknown token accepted")
}
}
}
func TestStorageRevocationIsPersistentAndSessionSpecific(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
first, second := f.session(t, user, password), f.session(t, user, password)
if first.Token == second.Token {
t.Fatal("two logins reused the same token")
}
if err := f.auth.RevokeSession(f.ctx, first.Token); err != nil {
t.Fatal("logout failed")
}
f.pool.Close()
f.connect(t, time.Hour)
if _, err := f.auth.ValidateSession(f.ctx, first.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("revoked session revived after reconnect")
}
id, err := f.auth.ValidateSession(f.ctx, second.Token)
if err != nil || id != user.ID {
t.Fatal("logout affected another session")
}
}
func TestStorageExpiredSessionCannotRevive(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
hash := sha256.Sum256([]byte(session.Token))
key := "session:" + hex.EncodeToString(hash[:])
if err := f.redis.client.PExpire(f.ctx, key, time.Millisecond).Err(); err != nil {
t.Fatal("cannot set an expired fixture")
}
time.Sleep(20 * time.Millisecond)
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("expired session accepted")
}
f.pool.Close()
f.connect(t, 24*time.Hour)
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("new TTL configuration revived an expired session")
}
}
func TestStorageShortTTLExpiresAndReLoginWorks(t *testing.T) {
f := newFixture(t)
f.auth = service.NewAuthService(repository.NewUserRepository(f.queries),
redisrepo.NewSessionRepository(f.redis.client), 2*time.Second)
user, password := f.user(t)
session := f.session(t, user, password)
if remaining := time.Until(session.ExpiresAt); remaining <= 0 || remaining > 3*time.Second {
t.Fatal("two-second TTL was not used for the stored session")
}
if id, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil || id != user.ID {
t.Fatal("fresh short-lived session was rejected")
}
time.Sleep(max(0, time.Until(session.ExpiresAt)/2))
if _, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil {
t.Fatal("session expired before its original deadline")
}
timer := time.NewTimer(max(0, time.Until(session.ExpiresAt)) + 100*time.Millisecond)
defer timer.Stop()
select {
case <-timer.C:
case <-f.ctx.Done():
t.Fatal("expiry fixture exceeded its deadline")
}
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("short-lived session was accepted after its stored deadline")
}
fresh := f.session(t, user, password)
if fresh.Token == session.Token {
t.Fatal("re-login reused the expired token")
}
if id, err := f.auth.ValidateSession(f.ctx, fresh.Token); err != nil || id != user.ID {
t.Fatal("re-login did not produce a usable session")
}
}
func TestStorageChatRollbackAfterMemberInsertFailure(t *testing.T) {
f := newFixture(t)
user, _ := f.user(t)
repo := repository.NewChatRepository(f.queries, f.pool)
// A valid first member is inserted before the nonexistent member fails.
// Calling the repository bypasses prevalidation and tests real rollback.
_, err := repo.CreateChat(f.ctx, "Must roll back", []string{user.ID, uuid.NewString()})
if err == nil {
t.Fatal("chat with nonexistent member unexpectedly committed")
}
for _, table := range []string{"chats", "chat_members"} {
var count int
err := f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+table).Scan(&count)
if err != nil || count != 0 {
t.Fatal("failed transaction left partial chat or membership rows")
}
}
created, err := repo.CreateChat(f.ctx, "Valid after rollback", []string{user.ID})
if err != nil || created == nil {
t.Fatal("rollback poisoned subsequent valid transaction")
}
}
+226
View File
@@ -0,0 +1,226 @@
package auth_tests
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"syscall"
"testing"
"time"
"highload/internal/database/sqlc"
repository "highload/internal/repository/postgres"
"highload/internal/service"
"highload/internal/storage/s3"
httptransport "highload/internal/transport/http"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
"github.com/aws/aws-sdk-go-v2/aws"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
const healthFixtureBucket = "health-fixture"
type readyS3Client struct {
mu sync.Mutex
objects map[string][]byte
}
func (s *readyS3Client) Do(req *http.Request) (*http.Response, error) {
bucketPath := "/" + healthFixtureBucket
response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody}
if req.Method == http.MethodHead && req.URL.Path == bucketPath {
return response, nil
}
if !strings.HasPrefix(req.URL.Path, bucketPath+"/attachments/") {
return nil, fmt.Errorf("unexpected path in S3 fixture")
}
s.mu.Lock()
defer s.mu.Unlock()
switch req.Method {
case http.MethodPut:
defer req.Body.Close()
data, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
s.objects[req.URL.Path] = data
case http.MethodGet:
data, ok := s.objects[req.URL.Path]
if !ok {
response.StatusCode = http.StatusNotFound
return response, nil
}
response.Body = io.NopCloser(bytes.NewReader(data))
response.ContentLength = int64(len(data))
default:
return nil, fmt.Errorf("unexpected method in S3 fixture")
}
return response, nil
}
// Supply local S3 responses for readiness and the attachment upload in the HTTP smoke test.
func readyS3Storage() *s3.Storage {
return &s3.Storage{
Bucket: healthFixtureBucket,
Client: awss3.New(awss3.Options{
Region: "us-east-1",
BaseEndpoint: aws.String("http://s3-fixture.invalid"),
UsePathStyle: true,
Credentials: aws.AnonymousCredentials{},
HTTPClient: &readyS3Client{objects: make(map[string][]byte)},
}),
}
}
type unavailableDB struct{}
type unavailableRow struct{}
func (unavailableRow) Scan(...any) error {
return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
}
func (unavailableDB) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
return pgconn.CommandTag{}, unavailableRow{}.Scan()
}
func (unavailableDB) Query(context.Context, string, ...any) (pgx.Rows, error) {
return nil, unavailableRow{}.Scan()
}
func (unavailableDB) QueryRow(context.Context, string, ...any) pgx.Row {
return unavailableRow{}
}
func TestSQLUnavailableLoginStopsBeforeSessionCreation(t *testing.T) {
queries := sqlc.New(unavailableDB{})
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
mid := middleware.NewMiddleware(auth, "auth-test")
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("synthetic_user", "Synthetic:password")
recorder := httptest.NewRecorder()
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
assertContractError(t, recorder, 503, "unavailable")
}
func TestMiddlewareMalformedAuthWritesExactlyOneError(t *testing.T) {
// Invalid syntax must be rejected before asking an auth service or DB.
// A nil service deliberately makes an accidental dependency call visible.
mid := middleware.NewMiddleware(nil, "auth-test")
for _, header := range []string{"", "Basic invalid", "Bearer", "Bearer ",
"Bearer invalid token", "Digest invalid"} {
t.Run("malformed", func(t *testing.T) {
nextCalled := false
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalled = true })
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", header)
recorder := httptest.NewRecorder()
mid.RequestID(mid.Auth(next)).ServeHTTP(recorder, request)
if nextCalled || recorder.Code != http.StatusUnauthorized {
t.Fatal("malformed auth reached business handler or did not yield 401")
}
if recorder.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
t.Fatal("missing contract Bearer challenge")
}
var payload struct {
Error struct {
Code string `json:"code"`
RequestID string `json:"request_id"`
} `json:"error"`
}
decoder := json.NewDecoder(recorder.Body)
if err := decoder.Decode(&payload); err != nil {
t.Fatal("401 is not one valid JSON object")
}
if err := decoder.Decode(new(any)); err != io.EOF {
t.Fatal("middleware wrote more than one response after 401")
}
if payload.Error.Code != "unauthorized" || payload.Error.RequestID == "" ||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
t.Fatal("error request ID or code violates contract")
}
})
}
}
func TestStorageHTTPAuthRoutingAndLogout(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
userRepo := repository.NewUserRepository(f.queries)
chatRepo := repository.NewChatRepository(f.queries, f.pool)
chatService := service.NewChatService(chatRepo, userRepo, f.users)
messageService := service.NewMessageService(repository.NewMessageRepository(f.queries, f.pool), chatService, f.users)
objects := readyS3Storage()
attachmentService := service.NewAttachmentService(repository.NewAttachmentRepository(f.queries, f.pool), chatService, objects)
router := httptransport.NewRouter(
middleware.NewMiddleware(f.auth, "auth-test"), handler.NewAuthHandler(f.auth),
handler.NewHealthHandler(f.pool, f.redis.client, objects),
handler.NewChatHandler(chatService), handler.NewUserHandler(f.users),
handler.NewMessageHandler(messageService),
handler.NewAttachmentHandler(attachmentService),
).Handler()
call := func(method, path, token string, login bool) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, path, nil)
if login {
request.SetBasicAuth(user.Username, password)
} else if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
if recorder.Header().Get("X-Request-Id") == "" {
t.Fatal("auth response missing X-Request-Id")
}
return recorder
}
defer func() {
if recover() != nil {
t.Error("auth router panicked; check constructor/handler wiring")
}
}()
response := call("POST", "/api/v1/auth/sessions", "", true)
if response.Code != 201 {
t.Fatal("Basic login route did not return 201")
}
var session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
}
if err := json.Unmarshal(response.Body.Bytes(), &session); err != nil ||
session.Token == "" || session.TokenType != "Bearer" {
t.Fatal("login route returned invalid session")
}
other := f.session(t, user, password)
response = call("GET", "/api/v1/users/me", session.Token, false)
if response.Code != 200 || strings.Contains(response.Body.String(), "password") {
t.Fatal("Bearer user route failed or exposed password fields")
}
response = call("DELETE", "/api/v1/auth/sessions/current", session.Token, false)
if response.Code != 204 || response.Body.Len() != 0 {
t.Fatal("contract logout path must return empty 204")
}
for _, route := range [][2]string{
{"GET", "/api/v1/users/me"}, {"DELETE", "/api/v1/auth/sessions/current"},
} {
response = call(route[0], route[1], session.Token, false)
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
t.Fatal("revoked token was accepted or challenged with wrong scheme")
}
}
if response := call("GET", "/api/v1/users/me", other.Token, false); response.Code != 200 {
t.Fatal("logout invalidated an independent session of the same user")
}
}
+44
View File
@@ -0,0 +1,44 @@
# Как воспроизводятся отказы ЛР 5
`compose.fault.test.yaml` подключается только к изолированному Compose-проекту.
В нём API, relay и worker получают общий тестовый каталог. Реализация атомарно
переименовывает `POINT.arm` в `POINT.used`, записывает идентификатор в `POINT.hit`
и ждёт `POINT.release` или своего дедлайна. Адаптер сверяет job ID с PostgreSQL
перед остановкой процесса. Job, версия и исходный upload остаются прежними.
| Имя сценария | Marker | Что проверяем |
| --- | --- | --- |
| `commit-before-publish` | `before_publish.hit` | Принятая job и единственная unsent запись outbox переживают SIGKILL relay. После запуска исходная job доходит до ready. |
| `publish-before-mark` | `after_publish.hit` | RabbitMQ подтвердил publish, а outbox ещё не помечен. Первый и повторный publish не создают два эффекта. Worker остановлен до обоих действий. |
| `object-before-ack` | `after_objects.hit` | Файлы уже в S3, а job ещё processing. SIGKILL worker оставляет lease. После его истечения новая попытка завершает ту же job. |
| `ready-before-ack` | `before_ack.hit` | Ready и варианты уже закоммичены. SIGKILL worker до ack проверяет повторную доставку без новой попытки. |
| `bounded-processing-timeout-and-prefetch` | `after_objects.hit` | Точку оставляем удержанной до дедлайна. Проверка требует `processing_timeout`, новую попытку, тот же job ID и фактический prefetch из RabbitMQ. |
| `retry-transient` | Изоляция только worker от S3 | RabbitMQ и PostgreSQL остаются доступны. Ожидаются retry в заданных пределах jitter, терминальный failed, явный replay после восстановления S3. |
| `fail-permanent` | Тестовая порча SHA синтетического staging | Worker видит mismatch, пишет failed за одну попытку. Тест восстанавливает SHA и проверяет replay через настоящую операторскую команду. Ранее принятый Message по тому же ключу остаётся доступен, новый POST с failed-вложением возвращает 409. |
| `mismatched-broker-envelope-DLQ` | Доставки с неверным job ID, attachment ID или pipeline version | RabbitMQ принимает и доставляет сообщения. Все три уходят в DLQ. Опубликованный результат остаётся прежним. |
Сценарий сохранности брокера останавливает worker, проверяет наличие доставки в
durable очереди, останавливает relay перед рестартом RabbitMQ и сверяет число
сообщений после запуска. Так relay не может скрыть утрату повторной публикацией.
Повтор идёт через настоящую очередь. S3 проверяется фактическим listing, а
PostgreSQL показывает опубликованное поколение, попытки, outbox и аудит replay.
## Интерфейс адаптера
`pipeline_action.py` использует текущую схему Compose и `/app/jobs` в
`attachment-cleanup`. Базовые переменные передаёт `acceptance.py`. Оператор
задаёт `LAB5_TEST_FAULT_HOST_DIR`, содержащий `.lab5-test-project` с именем
изолированного проекта. Аргументы запускаются как argv:
- `reset`, `worker-stop`, `worker-start`, `relay-start`, `broker-restart`, `restart-apis`.
- `arm POINT`, `await POINT ATTACHMENT_ID`, `crash POINT ATTACHMENT_ID`. `await` возвращает
JSON с точкой, attachment ID и job ID из маркера. `crash` считывает
статус задания и посылает SIGKILL в пределах окна точки одним вызовом.
- `activate POINT ATTACHMENT_ID` и `clear POINT ATTACHMENT_ID` для retry/failed.
- `inspect ATTACHMENT_ID`, `worker-limits`, `drain`, `failed ATTACHMENT_ID`,
`replay ATTACHMENT_ID`, `redeliver ATTACHMENT_ID`, `invalid-job ATTACHMENT_ID`.
Код 78 сообщает, что необходимый компонент ещё не подключён. Другой ненулевой
код показывает ошибку адаптера или невыполненное условие. Если сценарий остановлен
вручную, можно вызвать `reset` в том же контексте проекта. HTTP-клиенты и вывод
runner не сохраняют учётные данные.
+91
View File
@@ -0,0 +1,91 @@
# Приёмка лабораторной 5 на «4»
Это студенческие проверки. Обязательные документы: [рубрика ЛР 5](../../README.md),
[накопительность и совместимость](../../COURSE.md), [семантика HTTP](../../contracts/README.md),
[OpenAPI и примеры](../../contracts/), [инфраструктурный контракт](../../contracts/infrastructure.json),
[публичные проверки](../../tests/README.md). Порядок защиты и доказательства сверяются с
[REPORT.md](../../REPORT.md), [CONTRIBUTING.md](../../CONTRIBUTING.md), [MAINTAINERS.md](../../MAINTAINERS.md),
[infra](../../infra/README.md), [examples](../../examples/requests.http) и [.env.example](../../.env.example).
| Сценарий | Что требует контракт или задание | Где доказательство |
| --- | --- | --- |
| Сохранённый HTTP и тексты | Ключ 1–128 ASCII, отсутствующий/неверный → 400, конфликт → 409 без эффекта. область пользователя/чата. семантическое равенство JSON. конкурентные повторы. отозванный токен. timeout после подтверждённого commit | `http` / `idempotency-lb`, история чата. timeout на реальном клиентском сокете, прокси пересылает POST в LB и не отдаёт ответ клиенту |
| Проверка отзыва доступа на replay | Публичный API не меняет membership. В отдельной PostgreSQL-схеме тест имитирует отзыв уже выданного доступа, повторяет тот же POST и проверяет 404, состояние БД и неизменный replay после восстановления доступа | `TestMessageReplayRechecksCurrentChatMembership`. временное снятие FK ограничено тестовой схемой |
| LB и отказ процесса | ≥2 живых API за опубликованным адресом LB, одинаковый токен. каждый API по очереди получает SIGTERM и остаётся остановленным до проверки. чтение подтверждённых данных и запись ≤10 с. старый Message воспроизводится другой репликой | `idempotency-lb`, `failover`. Docker state, X-Instance-Id, запросы и время восстановления |
| Сохранность | Сессия, запись и ключ переживают реальный перезапуск API и хранилищ | `persistence`. StartedAt каждого процесса и прежний токен |
| Readiness, hard limits, rolling | Live/ready с контрактными телами. неготовый API доступен из сети LB и отвечает 503, публичные запросы идут мимо него. CPU/RAM API заданы и нет обхода LB. мигратор один. обновление ровно одной реплики за шаг | `http`, `unready`, `resources`, `migrations`, `rolling`. Для rolling требуется операторский hook с образом кандидата |
| ЛР 5, уровень 3 | Upload 202 после коммита метаданных, job и outbox. queued можно прикрепить, download → 409, worker остановлен. API и broker действительно перезапускаются, дубли не размножают запись. thumbnail и original | `TestAttachmentTxHTTP`, `pipeline-http`, `durable-broker-worker-stop-and-redelivery`, публичные make-цели |
| ЛР 5, уровень 4 | Crop и WebP: измерения из данных, checksum, MIME, bytes. лимиты bytes/pixels и невалидный PNG. fault после COMMIT / до publish, после записи объекта / до ack, после ready / до ack. lease, retries/jitter/terminal failed и операторский replay. staging cleanup | `pipeline-http`, `pipeline-faults`. маркеры процесса, PostgreSQL, S3 list, аудит replay, RabbitMQ DLQ, HTTP |
| Доказательства и рекомендации | Прогрев, интенсивность, длительность, RPS, ошибки, p50/95/99 и CPU/RAM, временная шкала и число записей. полный decode через установленный ImageMagick можно добавить флагом `--magick` | JSONL + логи make. Closed-loop даёт результаты конкретного стенда. проходного RPS нет |
Readiness и отсутствие опубликованных портов API обязательны по инфраструктурному контракту.
CPU/RAM API, проверка SIGTERM с clean exit, Go проверка устаревшего доступа и rolling относятся к
дополнительным условиям этого прогона. Для rolling установлен дополнительный критерий: запросы
под нагрузкой не теряют подтверждённые сообщения и не возвращают ошибок во время обоих шагов.
Сценарий нельзя объявить пройденным по одному заголовку. Исследовательский трек «5» не входит в прогон.
## Запуск
Для итогового прогона использовали Python 3.14.6, Go из `go.mod` и Docker Compose.
У публичного клиента на Python 3.9 возможен отказ разбора дробных секунд
RFC 3339, которые выдаёт Go. Для локального HTTP используйте
изолированный учебный стенд. Команды из отдельной копии репозитория:
```sh
./scripts/init-local.sh
export LAB5_HTTP_PORT=18085 LAB5_POSTGRES_PORT=25485
export LAB5_TEST_FAULT_HOST_DIR="$(mktemp -d)"
printf '%s\n' highload-lab5-student > "$LAB5_TEST_FAULT_HOST_DIR/.lab5-test-project"
chmod 777 "$LAB5_TEST_FAULT_HOST_DIR" # только новый тестовый каталог, чтобы UID контейнера мог писать маркеры
export COMPOSE_PROJECT_NAME=highload-lab5-student
cpfiles() {
docker compose -p "$COMPOSE_PROJECT_NAME" -f compose.yaml \
-f student-tests/lab5/compose.readiness.test.yaml \
-f student-tests/lab5/compose.fault.test.yaml "$@"
}
cpfiles config --quiet
cpfiles up -d --build
make check
go test ./... # интеграционные Go-тесты показывают SKIP без их переменных окружения
python3 student-tests/lab5/acceptance.py --scenario all \
--base-url "http://127.0.0.1:$LAB5_HTTP_PORT" --project "$COMPOSE_PROJECT_NAME" --exercise \
--compose-file compose.yaml --compose-file student-tests/lab5/compose.readiness.test.yaml \
--compose-file student-tests/lab5/compose.fault.test.yaml \
--store redis --store s3 --store rabbitmq --output /tmp/lab5-acceptance.jsonl
# После прогона при необходимости: cpfiles stop
```
Для быстрого профиля сохраняйте в **отдельной копии** `.env`:
`JOB_TIMEOUT_SECONDS=14`, `JOB_LEASE_SECONDS=18`, `JOB_MAX_ATTEMPTS=3`,
`JOB_RETRY_BASE_SECONDS=2`, `CLEANUP_GRACE_SECONDS=1`, `CLEANUP_INTERVAL_SECONDS=1`,
`STAGING_RETENTION_SECONDS=600`, `WORKER_CONCURRENCY=1`, `WORKER_PREFETCH=1`.
Учитывайте задержку Docker Desktop при физических рестартах. Миграциям нужно пустое окружение
для проверки полного чистого bootstrap. Итоговый runner включает
`make test`, `make test-persistence`, `make test-failover`. Вывод каждой цели сохраняется отдельно.
Тестовый хук получает то же имя проекта и те же Compose-файлы.
При одной реплике можно отдельно запустить `--scenario http --base-url http://127.0.0.1:8080 --output ...`:
Этот режим проверяет контрактный HTTP. Для LB и failover нужна топология из двух реплик.
Флаги `--scenario` и `--compose-file` можно повторять. Для точечного повтора
укажите `--case` с именем проверки из вывода runner. Смена сервисных имён,
портов и диагностического образа curl задаётся в `--help`. Приёмка заменила
временный `baseline.py` из начала ЛР 5, ожидавший upload `201 ready`.
Ожидаемая отсутствующая инфраструктура/хук → **PENDING**, системная ошибка/невыполненное условие →
**FAIL**, только наблюдавшееся условие → **PASS**. Коды запуска: 0 — все выбранные проверки
прошли, 1 — есть FAIL, 2 — есть PENDING и нет FAIL. Строки без результатов не засчитываются.
`--roll-hook /abs/path/to/hook` вызывается один раз на каждый исходный контейнер, с
`TARGET_CONTAINER_ID`, `TARGET_INSTANCE_ID`, `COMPOSE_PROJECT_NAME`, `BASE_URL`. Хук сам заменяет
контейнер образом кандидата, сохраняет остальное и возвращает 0 после подключения кандидата;
runner проверяет новый digest, связь с тем же LB, выдерживает окно нагрузки и проверяет,
что мигратор не запускался снова. Пока такого хука нет, сценарий **PENDING**.
Подробнее о fault hooks: [FAULT-HOOKS.md](FAULT-HOOKS.md).
Переменные Go-проверок: `LAB4_TEST_DATABASE_URL` (историческое имя fixture),
`AUTH_TEST_DATABASE_URL`, `AUTH_TEST_REDIS_ADDR`, `MIGRATE_TEST_DATABASE_URL`. используйте
изолированные БД/Redis. Для опциональных прежних сценариев auth/restart см. их SKIP-строки.
Повторный прогон должен писать в новый файл. Не сохраняйте токены, env, секреты, содержимое БД
или полные логи контейнеров.
Эксперимент на «5» описан в [VERSIONED.md](VERSIONED.md). Для него есть отдельный сценарий `pipeline-versioned`.
+53
View File
@@ -0,0 +1,53 @@
# ЛР 5. Трек 2: версия pipeline и повторная доставка
Гипотеза. Если worker публикует результат только для текущей версии и
действующего поколения lease, валидные старые сообщения и опоздавшая попытка
не изменят готовый результат v2. В S3 версии и поколения имеют разные ключи.
Подтверждённое задание текущей версии переживает сбой worker и доходит до ready.
| Сценарий | Воздействие и критерий |
| --- | --- |
| Дубль v2 и устаревшая v1 | Довести v1 и v2 до ready. По очереди повторно опубликовать байты сохранённых валидных envelopе v2 и v1 в RabbitMQ. Очередь опустела, DLQ не выросла, длина истории попыток, ключи и опубликованные SHA не изменились. |
| Reorder v2 → v1 | Остановить relay перед upload. Отложить исходную запись outbox v1 через `available_at`, поставить v2 штатным `jobs upgrade`. Дождаться ready v2 и только тогда отпустить исходную v1. Сверить идентичность envelope и порядок `sent_at`. У v1 ноль попыток. |
| Crash до и после S3 | На v2 удержать worker перед первым PUT или сразу после записи всех объектов. Снять фактический listing (0 или 4 ключа поколения), послать SIGKILL до дедлайна и вернуть контейнер. Первая попытка истекает, новое поколение той же job завершает обработку. Исторический набор v1 остаётся целым, сироты и staging исчезают. |
| Запоздавший worker v1 | Удержать живой процесс после записи объектов v1. Запустить второго worker и довести v2 до ready, затем отпустить прежний процесс до исходных deadline и lease. Получить его лог `job finalization rejected`, проверить ACK, ноль новых попыток v2, прежние ключи v2 и удаление четырёх неопубликованных объектов v1. |
При каждом переходе повторный `jobs upgrade` обязан вернуть тот же job ID и
`queued=false`. Проверяется один outbox для новой job до инъекции дополнительных
доставок. Используется один и тот же исходный PNG. Варианты проверяются через HTTP
и повторным чтением S3 по сохранённым ключам. Сравниваются SHA-256, размеры,
метаданные, номера версий и поколения, исходные байты. Опубликованные результаты
v1 и v2 различимы по SHA, а v2 воспроизводится на одинаковом исходнике во всей серии.
Автоматизация подтверждает идемпотентность эффекта в наблюдавшихся окнах отказа.
Брокер может доставить payload несколько раз, рабочий процесс может повторно
вычислить и записать объекты. Успешным считается один опубликованный набор
текущей версии. Измерения относятся к одному Docker-хосту и одному размеру файла.
## Запуск
Поднимите отдельный учебный проект с чистыми томами по [основной инструкции](README.md),
с `compose.readiness.test.yaml` и `compose.fault.test.yaml`. Установите миграцию
с `attachment_jobs.published_original_key` и текущий образ, поддерживающий `jobs upgrade`.
В начале нужен один worker с `WORKER_CONCURRENCY=1` и `WORKER_PREFETCH=1`.
Тест временно масштабирует его до двух процессов в последнем сценарии каждой серии.
Фиксируйте фактические лимиты в локальной копии `.env`; профиль прогона использует
`JOB_TIMEOUT_SECONDS=30`, `JOB_LEASE_SECONDS=36`, `CLEANUP_GRACE_SECONDS=1` и
`CLEANUP_INTERVAL_SECONDS=1`. На медленном хосте окно старого worker можно увеличить,
с теми же контрольными условиями по времени относительно исходного lease.
```sh
python3 student-tests/lab5/acceptance.py --scenario pipeline-versioned --repetitions 3 \
--base-url "http://127.0.0.1:$LAB5_HTTP_PORT" --project "$COMPOSE_PROJECT_NAME" --exercise \
--compose-file compose.yaml --compose-file student-tests/lab5/compose.readiness.test.yaml \
--compose-file student-tests/lab5/compose.fault.test.yaml --output /tmp/lab5-versioned.jsonl
```
Выбор `--scenario all` по-прежнему запускает приёмку уровня 4. Трек добавляется
явно через `--scenario pipeline-versioned`. При отсутствии миграции или
каталога fault ожидается PENDING. Провал отдельного повтора сохраняется в
строке `versioned_trial` и даёт ненулевой код запуска. Итоговая строка
`versioned_summary` хранит число попыток эксперимента, min/median/max
наблюдаемого времени до ready и стабильные SHA-256 результата v2.
Для crash секундомер начинается перед SIGKILL. В остальных случаях он
охватывает ожидание ready после ответа штатной команды upgrade или запуска relay.
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env python3
"""Run Lab 5 checks against an isolated Compose stand and write JSONL evidence."""
import argparse
import os
from pathlib import Path
import platform
import subprocess
import sys
import time
from urllib.parse import urlsplit
sys.dont_write_bytecode = True
from checks import ROOT, Evidence, Failure, Pending, Probe, check, health, idempotency
from pipeline import Pipeline, make_decoder, upload_rejects, variants
from stand import Stand
HERE = Path(__file__).resolve().parent
TEST_HOOK = HERE / "compose_action.py"
def arguments():
cases = ("http", "idempotency-lb", "resources", "persistence", "failover",
"unready", "rolling", "migrations", "pipeline-http", "pipeline-faults", "pipeline-versioned", "public", "all")
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--scenario", choices=cases, action="append", required=True)
p.add_argument("--case", action="append", help="run only the named case within the selected scenario(s)")
p.add_argument("--base-url", default=os.environ.get("BASE_URL"))
p.add_argument("--ca-file", default=os.environ.get("CA_FILE"))
p.add_argument("--output", required=True, help="new JSONL file; no overwrite")
p.add_argument("--project", help="explicit disposable Compose project required for fault scenarios")
p.add_argument("--exercise", action="store_true", help="allow fault actions on this isolated project")
p.add_argument("--compose-file", action="append", default=[])
for k, default in (("api", "api"), ("lb", "lb"), ("db", "postgres"), ("migrate", "migrate"),
("db-user", "messenger"), ("db-name", "messenger")):
p.add_argument("--" + k, default=default)
p.add_argument("--store", action="append", help="additional persistence stores; repeat per service")
p.add_argument("--api-port", type=int, default=8080)
p.add_argument("--network", help="shared API/LB Docker network for diagnostics")
p.add_argument("--probe-image", default="rustfs/rustfs:1.0.4",
help="local image with curl, for direct health diagnostics from the LB namespace")
p.add_argument("--workers", type=int, default=6)
p.add_argument("--timeout", type=float, default=2)
p.add_argument("--window", type=float, default=3)
p.add_argument("--warmup", type=float, default=2)
p.add_argument("--pipeline-timeout", type=int, default=120)
p.add_argument("--repetitions", type=int, default=3, help="number of complete versioned experiment series")
p.add_argument("--magick", help="optional path to ImageMagick 7 for full image decode")
for k in ("restart", "stop", "unready", "ready", "roll", "pipeline"):
p.add_argument("--" + k + "-hook", type=str)
a = p.parse_args()
if not a.base_url:
p.error("--base-url (or BASE_URL) is required")
url = urlsplit(a.base_url)
if (url.scheme not in ("http", "https") or not url.hostname or url.username or url.password
or url.query or url.fragment or url.path not in ("", "/")):
p.error("use an HTTP(S) origin without credentials, query, path, or fragment")
if not 2 <= a.workers <= 64 or not 0 < a.timeout <= 5 or not 2 <= a.window <= 30 or not 0 < a.warmup <= 30:
p.error("workers=2..64, timeout=(0,5], window=2..30, warmup=(0,30]")
if not 1 <= a.pipeline_timeout <= 600:
p.error("pipeline timeout must be 1..600 s")
if not 1 <= a.repetitions <= 10:
p.error("repetitions must be 1..10")
if a.store is None:
a.store = ["redis", "s3", "rabbitmq"]
if a.exercise and (not a.project or a.project == "highload-lab5"):
p.error("--exercise requires --project for a disposable stand (not highload-lab5)")
return a
def control_env(a):
import json
return dict(os.environ, COMPOSE_PROJECT_NAME=a.project or "",
LAB5_TEST_COMPOSE_FILES=json.dumps([str(Path(f).resolve()) for f in a.compose_file]),
LAB5_TEST_API=a.api, LAB5_TEST_DB=a.db, LAB5_TEST_LB=a.lb,
LAB5_TEST_DB_USER=a.db_user, LAB5_TEST_DB_NAME=a.db_name,
LAB5_TEST_STORES=" ".join(a.store), PYTHONDONTWRITEBYTECODE="1")
def safe_to_exercise(args):
if not args.exercise:
raise Pending("requires --exercise and a dedicated --project")
def public_case(stand, mode, out):
a, e = stand.a, stand.e
if mode != "test":
safe_to_exercise(a)
apis = stand.public_topology()
env = control_env(a)
cmd = ["make", mode, "BASE_URL=" + stand.c.base, "PYTHON=" + sys.executable]
if a.ca_file:
cmd.append("CA_FILE=" + a.ca_file)
if mode != "test":
hook = a.restart_hook if mode == "test-persistence" else a.stop_hook
# The default test-only hook is scoped to the explicit project and uses
# the same scope passed to the student scenarios.
hook = hook or str(TEST_HOOK)
check(Path(hook).is_file() and os.access(hook, os.X_OK), "public action hook is not executable")
cmd.append("ACTION_SCRIPT=" + str(Path(hook).resolve()))
env["LAB5_HOOK_MODE"] = "restart" if mode == "test-persistence" else "stop-one"
path = Path(out).with_suffix(f".{mode}.log")
start = time.monotonic()
try:
with path.open("xb") as log:
result = subprocess.run(cmd, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT, timeout=300)
e.event("public_run", command=mode, exit_code=result.returncode, log=path.name,
elapsed_s=time.monotonic() - start)
check(result.returncode == 0, f"make {mode} returned {result.returncode}; see {path.name}")
except subprocess.TimeoutExpired:
raise Failure(f"make {mode} exceeded its timeout; see {path.name}") from None
finally:
if mode == "test-failover":
before = {r["id"] for r in apis}
rows = [r for r in stand.containers(a.api) if r["id"] in before and r["state"] == "exited"]
if rows:
stand.command("restore after teacher failover", ["docker", "start", *[r["id"] for r in rows]])
def main():
a = arguments()
e = Evidence(a.output)
e.event("environment", base=a.base_url, project=a.project, workers=a.workers, timeout=a.timeout,
fault_window=a.window, warmup=a.warmup, python=platform.python_version(),
host=platform.machine(), os=platform.system(), logical_cpus=os.cpu_count())
c = Probe(a.base_url, a.ca_file, a.timeout, e)
s = Stand(a, c)
decoder = make_decoder(s, a.magick)
if not a.pipeline_hook and "compose.fault.test.yaml" in [Path(f).name for f in a.compose_file]:
a.pipeline_hook = str(HERE / "pipeline_action.py")
pipeline = Pipeline(s, decoder)
def exercise(f):
def wrapper():
safe_to_exercise(a)
f()
return wrapper
def idem_lb():
s.public_topology()
idempotency(c, a.workers, known_instances=s.a_ids)
def readiness():
# Use the bundled hook only with its explicit edge network override.
explicit = [Path(f).name for f in a.compose_file]
if "compose.readiness.test.yaml" in explicit:
a.unready_hook = a.unready_hook or str(TEST_HOOK)
a.ready_hook = a.ready_hook or str(TEST_HOOK)
s.unready()
def persist():
previous = a.restart_hook
a.restart_hook = previous or str(TEST_HOOK)
try:
s.persistence()
finally:
a.restart_hook = previous
def versioned():
from versioned import series
series(pipeline, a.repetitions)
# The test-only restart hook uses the same Compose file/service selection.
os.environ.update(control_env(a))
os.environ["LAB5_HOOK_MODE"] = "restart"
groups = {
"http": [("health", lambda: health(c)), ("idempotency", lambda: idempotency(c, a.workers))],
"idempotency-lb": [("idempotency-across-LB", idem_lb)],
"resources": [("CPU-RAM-ports", s.resources)],
"migrations": [("single-migration-start", lambda: (s.public_topology(), s.migration_snapshot()))],
"persistence": [("persistent-idempotency", exercise(persist))],
"failover": [("each-SIGTERM-read-write-with-load", exercise(s.failover))],
"unready": [("LB-excludes-unready-API", exercise(readiness))],
"rolling": [("one-API-at-a-time-under-load", exercise(s.rolling))],
"pipeline-http": [("upload-byte-pixel-media-limits", lambda: upload_rejects(c)),
("async-output-variants", lambda: variants(c, min(60, a.pipeline_timeout), decoder))],
"pipeline-faults": [
("durable-broker-worker-stop-and-redelivery", exercise(pipeline.durable)),
("crash-COMMIT-before-publish", exercise(lambda: pipeline.crash("commit-before-publish"))),
("crash-relay-after-confirm-before-mark", exercise(lambda: pipeline.crash("publish-before-mark"))),
("crash-object-before-ack-lease", exercise(lambda: pipeline.crash("object-before-ack"))),
("crash-ready-before-ack", exercise(lambda: pipeline.crash("ready-before-ack"))),
("bounded-processing-timeout-and-prefetch", exercise(pipeline.bounded_processing)),
("mismatched-broker-envelope-DLQ", exercise(pipeline.malformed_job)),
("backoff-jitter-permanent-failed-replay", exercise(pipeline.retry_replay)),
],
"pipeline-versioned": [("pipeline-versioned-series", exercise(versioned))],
"public": [(f"make-{m}", lambda m=m: public_case(s, m, a.output))
for m in ("test", "test-persistence", "test-failover")],
}
if "all" in a.scenario:
selectors = [name for name in groups if name != "pipeline-versioned" or name in a.scenario]
# The LB case covers HTTP idempotency as well; avoid a duplicate run.
groups["http"] = groups["http"][:1]
else:
selectors = list(dict.fromkeys(a.scenario))
if "idempotency-lb" in selectors and "http" in selectors:
groups["http"] = groups["http"][:1]
selected = [(label, fn) for group in selectors for label, fn in groups[group]]
if a.case:
check(set(a.case) <= {label for label, _ in selected}, "--case is outside the selected scenarios")
selected = [(label, fn) for label, fn in selected if label in a.case]
results = []
try:
for label, fn in selected:
results.append(e.case(label, fn))
e.event("summary", **{k: results.count(k) for k in ("PASS", "FAIL", "PENDING")})
return 1 if "FAIL" in results else (2 if "PENDING" in results else 0)
finally:
e.file.close()
if __name__ == "__main__":
try:
raise SystemExit(main())
except (Failure, OSError) as exc:
print("FAIL:", exc if isinstance(exc, Failure) else type(exc).__name__, file=sys.stderr)
raise SystemExit(1) from None
+279
View File
@@ -0,0 +1,279 @@
"""Shared assertions and safe evidence for Lab 5 acceptance."""
import base64
from collections import Counter
import concurrent.futures
import http.client
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import math
from pathlib import Path
import ssl
import sys
import threading
import time
from urllib.parse import urlsplit
import uuid
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
from resilience import history
IO_ERRORS = (OSError, http.client.HTTPException)
class Pending(Exception):
"""A scenario has no configured infrastructure; exit status is not zero."""
class Evidence:
def __init__(self, path):
self.started = time.monotonic()
self.lock = threading.Lock()
self.phase = "setup"
self.file = Path(path).open("x", encoding="utf-8", buffering=1)
def event(self, event, **fields):
with self.lock:
line = {"event": event, "t_s": round(time.monotonic() - self.started, 6),
"phase": self.phase, **fields}
self.file.write(json.dumps(line, ensure_ascii=False) + "\n")
return line
def case(self, name, fn):
self.phase = name
print(f"RUN: {name}", flush=True)
try:
fn()
except Pending as exc:
status, note = "PENDING", str(exc)
except (Failure, ValueError, OSError, http.client.HTTPException) as exc:
status, note = "FAIL", str(exc) if isinstance(exc, Failure) else type(exc).__name__
else:
status, note = "PASS", ""
self.event("result", status=status, note=note)
print(f"{status}: {name}" + (f" — {note}" if note else ""), flush=True)
return status
class ObservedOpener:
def __init__(self, opener, capture):
self.opener = opener
self.capture = capture
def open(self, request, **kwargs):
from urllib.error import HTTPError
try:
response = self.opener.open(request, **kwargs)
except HTTPError as response:
self.capture(response)
raise
self.capture(response)
return response
class Probe(Client):
def __init__(self, base, ca, timeout, evidence):
super().__init__(base, ca, timeout=timeout)
self.ca = ca
self.evidence = evidence
self.local = threading.local()
self.opener = ObservedOpener(self.opener, self.capture)
def capture(self, response):
self.local.status = response.code
self.local.instance = response.headers.get("X-Instance-Id")
self.local.request_id = response.headers.get("X-Request-Id")
def call(self, method, path, *args, **kwargs):
self.local.status = self.local.instance = self.local.request_id = None
started = time.monotonic()
result = None
try:
result = super().call(method, path, *args, **kwargs)
return result
except IO_ERRORS as exc:
raise Failure(f"{method}: {type(exc).__name__} while reading response") from None
finally:
self.evidence.event("http", method=method, path=path.split("?")[0],
status=self.local.status, instance=self.local.instance,
request_id=self.local.request_id, ok=result is not None,
elapsed_s=time.monotonic() - started)
def key():
return uuid.uuid4().hex
def message_path(chat):
return f"/api/v1/chats/{chat['id']}/messages"
def post(c, actor, chat, k, text, *, status=201, body=None, code=None):
r = c.call("POST", message_path(chat), status, actor=actor,
headers={} if k is None else {"Idempotency-Key": k},
body={"text": text} if body is None else body, schema="Message")
if status == 201:
m = r["json"]
check((m["chat_id"], m["sender_id"], m["text"], m["attachment_ids"]) ==
(chat["id"], actor["id"], text, (body or {}).get("attachment_ids", [])),
"Message fields differ from POST")
elif code:
check(r["json"]["error"]["code"] == code, f"expected error code {code}")
if status == 401:
check(r["headers"].get("WWW-Authenticate") == 'Bearer realm="messenger"',
"incorrect Bearer challenge")
return r
def health(c):
for endpoint in ("live", "ready"):
r = c.call("GET", f"/health/{endpoint}", schema="Health")
check(r["json"] == {"status": "ok"}, f"/health/{endpoint}: unexpected payload")
def assert_history(c, actor, chat, expected):
actual = history(c, actor, chat)
check(len(actual) == len(expected) and {m["id"]: m for m in actual} ==
{m["id"]: m for m in expected}, "history has a missing, changed or extra Message")
def idempotency(c, workers, known_instances=None):
alice, bob, eve, chat = c.bootstrap()
other = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "Independent key scope", "member_ids": [alice["id"]]})["json"]
for bad in (None, "", "a" * 129, "a b", "a/b", "a@b", "nonASCII-é"):
post(c, alice, chat, bad, "must not persist", status=400, code="invalid_request")
assert_history(c, bob, chat, [])
k, upper = "A", ("AZaz09._:-" * 13)[:128]
check(len(upper) == 128, "length-128 fixture")
first = post(c, alice, chat, k, "Сообщение")["json"]
for body in (None, {"attachment_ids": [], "text": "Сообщение"},
{"text": "Сообщение", "attachment_ids": []}):
check(post(c, alice, chat, k, "Сообщение", body=body)["json"] == first,
"same semantic JSON must return the same 201 Message")
post(c, alice, chat, k, "different text", status=409, code="conflict")
assert_history(c, bob, chat, [first])
boundary = post(c, alice, chat, upper, "128-byte key")["json"]
check(post(c, alice, chat, upper, "128-byte key")["json"] == boundary, "max-key replay changed")
user_scope = post(c, bob, chat, k, "another user")["json"]
chat_scope = post(c, alice, other, k, "another chat")["json"]
check(len({first["id"], user_scope["id"], chat_scope["id"]}) == 3, "key leaked across scopes")
assert_history(c, alice, other, [chat_scope])
post(c, eve, chat, k, "Сообщение", status=404, code="not_found")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
post(c, alice, chat, k, "Сообщение", status=401, code="unauthorized")
reg = alice["registration"]
basic = base64.b64encode(f'{reg["username"]}:{reg["password"]}'.encode()).decode()
session = c.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
headers={"Authorization": "Basic " + basic})["json"]
alice = {**alice, "token": session["token"]}
check(post(c, alice, chat, k, "Сообщение")["json"] == first, "key unexpectedly scoped to session")
concurrent_key = key()
barrier = threading.Barrier(workers, timeout=10)
def race(_):
barrier.wait()
return post(c, alice, chat, concurrent_key, "same concurrent request")
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(race, range(workers)))
m = responses[0]["json"]
check(all(r["json"] == m for r in responses), "concurrent requests returned different Messages")
instances = {r["headers"]["X-Instance-Id"] for r in responses}
c.evidence.event("concurrent_posts", attempts=workers, instances=sorted(instances), message=m["id"])
assert_history(c, bob, chat, [first, boundary, user_scope, m])
lost_key, lost_text = key(), "commit with response unobserved by sender"
recorded = timeout_after_commit(c, alice, bob, chat, lost_key, lost_text)
check(post(c, alice, chat, lost_key, lost_text)["json"] == recorded,
"retry after loss of response changed Message")
assert_history(c, bob, chat, [first, boundary, user_scope, m, recorded])
if known_instances is not None:
check(len(instances) >= 2 and instances <= known_instances,
"concurrent POSTs did not reach two API replicas of this project")
def timeout_after_commit(c, actor, reader, chat, k, text):
# One shot loopback relay. The caller times out waiting for a response
# which the relay intentionally withholds after forwarding through the LB.
target = urlsplit(c.base)
cls = http.client.HTTPConnection if target.scheme == "http" else http.client.HTTPSConnection
opts = {} if target.scheme == "http" else {"context": ssl.create_default_context(cafile=c.ca)}
received = {}
finished, release = threading.Event(), threading.Event()
class DropResponse(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_POST(self):
upstream = cls(target.hostname, target.port, timeout=c.timeout, **opts)
try:
payload = self.rfile.read(int(self.headers["Content-Length"]))
headers = {h: self.headers[h] for h in ("Content-Type", "Idempotency-Key", "Authorization")}
upstream.request("POST", self.path, body=payload, headers=headers)
with upstream.getresponse() as response:
received["status"] = response.status
received["instance"] = response.getheader("X-Instance-Id")
if response.status == 201:
received["message"] = json.loads(response.read(1024 * 1024))
except (ValueError, OSError, http.client.HTTPException):
received["error"] = "upstream connection or invalid response"
finally:
upstream.close()
finished.set()
release.wait(8)
with HTTPServer(("127.0.0.1", 0), DropResponse) as relay:
relay.timeout = 3
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as jobs:
served = jobs.submit(relay.handle_request)
downstream = http.client.HTTPConnection(*relay.server_address, timeout=0.5)
timed_out = False
try:
downstream.request("POST", message_path(chat), body=json.dumps({"text": text}),
headers={"Content-Type": "application/json",
"Idempotency-Key": k, "Authorization": "Bearer " + actor["token"]})
try:
downstream.getresponse().close()
except TimeoutError:
timed_out = True
check(timed_out, "client did not actually time out on the dropped response")
check(finished.wait(6) and received.get("status") == 201 and received.get("instance"),
"relay did not observe committed upstream 201")
outcome = received["message"]
check(outcome in history(c, reader, chat), "original timed-out invocation did not durably commit")
c.evidence.event("lost_response", downstream="TimeoutError", upstream_status=201,
instance=received["instance"], message=outcome["id"])
return outcome
finally:
release.set()
downstream.close()
served.result(timeout=10)
def wait(fn, seconds, label):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
value = fn()
except Failure:
value = None
if value and time.monotonic() <= deadline:
return value
time.sleep(0.1)
raise Failure(label)
def summarize(evidence, records, elapsed, window="full"):
times = sorted(r["elapsed_s"] for r in records if r["ok"])
percentiles = {f"p{p}_ms": round(times[math.ceil(len(times)*p/100)-1]*1000, 3) if times else None
for p in (50, 95, 99)}
evidence.event("load_summary", window=window, elapsed_s=elapsed, attempts=len(records), successes=len(times),
successful_rps=len(times) / elapsed, failures=len(records)-len(times),
error_ratio=(len(records)-len(times))/len(records) if records else None,
statuses=dict(Counter(str(r["status"]) for r in records)), **percentiles)
@@ -0,0 +1,40 @@
# Optional only on the isolated Lab 5 acceptance project.
# The worker can lose S3 while retaining its database and broker connections.
x-fault-env: &fault-env
LAB5_FAULT_DIR: /lab5-test-faults
x-fault-mount: &fault-mount
type: bind
source: ${LAB5_TEST_FAULT_HOST_DIR:?create a fresh writable fault directory}
target: /lab5-test-faults
services:
api:
environment: *fault-env
volumes: [*fault-mount]
networks:
default: {}
lab5_edge: {}
lab5_object: {}
relay:
environment: *fault-env
volumes: [*fault-mount]
worker:
environment: *fault-env
volumes: [*fault-mount]
networks:
default: {}
lab5_object: {}
attachment-cleanup:
networks:
default: {}
lab5_object: {}
s3:
networks:
lab5_object: {}
s3-init:
networks:
default: {}
lab5_object: {}
networks:
lab5_object: {}
@@ -0,0 +1,13 @@
# Optional on a dedicated test project. The LB can still reach API when a
# single API is disconnected from the private dependency network.
services:
api:
networks:
default: {}
lab5_edge: {}
lb:
networks:
lab5_edge: {}
networks:
lab5_edge: {}
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Student hook for teacher tests: explicit disposable Compose project only."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[2]
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME")
API = os.environ.get("LAB5_TEST_API", "api")
LB = os.environ.get("LAB5_TEST_LB", "lb")
DB = os.environ.get("LAB5_TEST_DB", "postgres")
STORES = os.environ.get("LAB5_TEST_STORES", "redis s3").split()
def run(argv, timeout=30):
result = subprocess.run(argv, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
if result.returncode:
raise RuntimeError("Docker command failed")
return result.stdout.decode().strip()
def main():
if not PROJECT or PROJECT == "highload-lab5":
raise RuntimeError("disposable COMPOSE_PROJECT_NAME is required")
compose = ["docker", "compose", "--project-name", PROJECT]
for file in json.loads(os.environ.get("LAB5_TEST_COMPOSE_FILES", "[]")):
compose.extend(["--file", file])
def ids(service):
return run(compose + ["ps", "-q", service]).split()
mode = os.environ.get("LAB5_HOOK_MODE")
if mode in ("unready", "ready"):
cid = os.environ.get("TARGET_CONTAINER_ID")
if cid not in ids(API):
# Compose ps abbreviates IDs whereas inspect returns the full ID.
if not cid or not any(cid.startswith(i) for i in ids(API)):
raise RuntimeError("selected API is not in the disposable project")
net = PROJECT + "_default"
if mode == "unready":
run(["docker", "network", "disconnect", net, cid])
else:
current = json.loads(run(["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", cid]))
if net not in current:
run(["docker", "network", "connect", "--alias", API, net, cid])
return
if mode == "stop-one":
alias = os.environ.get("TARGET_INSTANCE_ID")
matches = [i for i in ids(API) if run(["docker", "inspect", "-f", "{{.Config.Hostname}}", i]) == alias]
if len(matches) != 1:
raise RuntimeError("could not resolve exactly one running API alias")
run(["docker", "stop", "--signal", "SIGTERM", "--time", "5", matches[0]], 10)
return
if os.environ.get("LAB5_HOOK_MODE") != "restart":
raise RuntimeError("LAB5_HOOK_MODE must be restart or stop-one")
def restart(selected, budget):
if not selected:
raise RuntimeError("selected service is not running")
run(["docker", "restart", "--time", "8", *selected], budget)
def healthy(selected):
deadline = time.monotonic() + 25
for cid in selected:
while time.monotonic() < deadline:
state = run(["docker", "inspect", "-f",
"{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}", cid])
if state in ("healthy", "running"):
break
time.sleep(0.25)
else:
raise RuntimeError("container did not become healthy")
stores = [ids(s) for s in (DB, *STORES)]
if any(not g for g in stores):
raise RuntimeError("missing configured persistence store")
store_ids = [cid for group in stores for cid in group]
apis = ids(API)
restart(store_ids, 30)
healthy(store_ids)
restart(apis, 24)
healthy(apis)
restart(ids(LB), 12)
if __name__ == "__main__":
try:
main()
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
print("Compose hook failed:", exc if isinstance(exc, RuntimeError) else type(exc).__name__, file=sys.stderr)
sys.exit(1)
+115
View File
@@ -0,0 +1,115 @@
// imageprobe exercises the ImageMagick runtime in its Docker image.
package main
import (
"bytes"
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
)
func magick(args ...string) string {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "magick", args...).CombinedOutput()
if err != nil {
log.Fatalf("magick %v: %v\n%s", args, err, out)
}
return strings.TrimSpace(string(out))
}
func checkImage(path, expected string, signature []byte, offset int) {
raw, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
if len(raw) < offset+len(signature) || !bytes.Equal(raw[offset:offset+len(signature)], signature) {
log.Fatalf("%s has an unexpected header", path)
}
if got := magick("identify", "+ping", "-regard-warnings", "-format", "%m %wx%h", path); got != expected {
log.Fatalf("unexpected output format or dimensions: %s", got)
}
fmt.Printf("PASS: decoded %s\n", expected)
}
func checkDeadline(dir string) error {
fifo := filepath.Join(dir, "incomplete.png")
if err := syscall.Mkfifo(fifo, 0o600); err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "magick", "identify", "png:"+fifo)
var stderr bytes.Buffer
cmd.Stderr = &stderr
start := time.Now()
if err := cmd.Start(); err != nil {
return err
}
var writer *os.File
for ctx.Err() == nil {
file, err := os.OpenFile(fifo, os.O_WRONLY|syscall.O_NONBLOCK, 0)
if err == nil {
writer = file
break
}
if !errors.Is(err, syscall.ENXIO) {
cancel()
_ = cmd.Wait()
return err
}
time.Sleep(10 * time.Millisecond)
}
if writer == nil {
return fmt.Errorf("magick never opened the input FIFO: %v: %s", cmd.Wait(), stderr.String())
}
defer writer.Close()
if _, err := writer.Write([]byte("\x89PNG\r\n\x1a\n")); err != nil {
cancel()
_ = cmd.Wait()
return err
}
err := cmd.Wait()
elapsed := time.Since(start)
var exit *exec.ExitError
if !errors.Is(ctx.Err(), context.DeadlineExceeded) || !errors.As(err, &exit) ||
exit.ProcessState.Sys().(syscall.WaitStatus).Signal() != syscall.SIGKILL || elapsed > 3*time.Second {
return fmt.Errorf("expected deadline and SIGKILL, got %v, %v after %s: %s", ctx.Err(), err, elapsed, stderr.String())
}
fmt.Printf("PASS: CommandContext killed and reaped blocked magick after %s (deadline 1s)\n", elapsed.Round(time.Millisecond))
return nil
}
func main() {
log.SetFlags(0)
if len(os.Args) != 2 {
log.Fatal("usage: imageprobe /path/to/sample.png")
}
dir, err := os.MkdirTemp("", "imageprobe-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
fmt.Println(strings.SplitN(magick("-version"), "\n", 2)[0])
input := os.Args[1]
if got := magick("identify", "-format", "%m %wx%h", input); got != "PNG 320x200" {
log.Fatalf("unexpected fixture: %s", got)
}
jpeg := filepath.Join(dir, "sample.jpg")
webp := filepath.Join(dir, "sample.webp")
magick(input, "-auto-orient", "-resize", "256x256>", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "-quality", "85", jpeg)
magick(input, "-auto-orient", "-resize", "1280x1280>", "-strip", "-quality", "80", webp)
checkImage(jpeg, "JPEG 256x160", []byte{0xff, 0xd8, 0xff}, 0)
checkImage(webp, "WEBP 320x200", []byte("WEBP"), 8)
if err := checkDeadline(dir); err != nil {
log.Fatal(err)
}
}
+386
View File
@@ -0,0 +1,386 @@
"""Lab 5 grade 3+4: HTTP outputs and deterministic operator-injected faults."""
import hashlib
import json
from pathlib import Path
import os
import struct
import tempfile
import time
import uuid
import zlib
from checks import ROOT, Failure, Pending, check, post, key, assert_history, wait
from image_probe import jpeg_size
STAGING = ("queued", "processing")
VARIANTS = {
"thumbnail": ("image/jpeg", 256, 160),
"crop": ("image/jpeg", 128, 128),
"optimized": ("image/webp", 320, 200),
}
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def attachment_path(att):
return f"/api/v1/attachments/{att['id']}"
def metadata(c, actor, att):
return c.call("GET", attachment_path(att), actor=actor, schema="Attachment")["json"]
def until_status(c, actor, att, desired, timeout):
started = time.monotonic()
while time.monotonic()-started < timeout:
current = metadata(c, actor, att)
state = current["status"]
if state == desired:
check(time.monotonic()-started <= timeout, f"{desired} observed after deadline")
c.evidence.event("attachment_state", attachment=att["id"], status=state,
seconds=time.monotonic()-started)
return current
check(state in STAGING, f"wanted {desired}, reached terminal state {state}")
time.sleep(0.25)
raise Failure(f"attachment never reached {desired} within {timeout} seconds")
def png_chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
def oversized_pixels():
# 40,010,000 pixels, but a small valid PNG; never allocate the decoded image.
width, height = 10000, 4001
enc = zlib.compressobj()
row = bytes(width+1)
compressed = b"".join(enc.compress(row) for _ in range(height)) + enc.flush()
return (SAMPLE[:8] + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0))
+ png_chunk(b"IDAT", compressed) + png_chunk(b"IEND", b""))
def upload_rejects(c):
alice, _, _, chat = c.bootstrap()
path = f"/api/v1/chats/{chat['id']}/attachments?filename=limits.png"
n = 10 * 1024 * 1024
padded = SAMPLE[:-12] + png_chunk(b"npAD", bytes(n + 1 - len(SAMPLE) - 12)) + SAMPLE[-12:]
check(len(padded) == n + 1, "invalid bytes-boundary fixture")
for data, status, code in (
(padded, 413, "payload_too_large"),
(oversized_pixels(), 413, "payload_too_large"),
(b"not a PNG", 415, "unsupported_media_type"),
(SAMPLE[:30], 415, "unsupported_media_type"),
):
r = c.call("POST", path, status, actor=alice, raw=data, headers={"Content-Type": "image/png"})
check(r["json"]["error"]["code"] == code, f"upload must return {code}")
def decoded_webp_size(data):
# Read actual bitstream dimensions. Check the complete RIFF framing, not
# metadata or filename alone; full pixel decode can also run via ImageMagick.
check(len(data) >= 20 and data[:4] == b"RIFF" and data[8:12] == b"WEBP"
and int.from_bytes(data[4:8], "little") + 8 == len(data), "invalid WebP RIFF")
i, canvas, image = 12, None, None
while i < len(data):
check(i + 8 <= len(data), "truncated WebP chunk")
size = int.from_bytes(data[i+4:i+8], "little")
name, start = data[i:i+4], i+8
i = start+size+(size % 2)
check(i <= len(data), "truncated WebP chunk body")
if name == b"VP8X":
check(size == 10, "invalid WebP canvas")
canvas = tuple(1 + int.from_bytes(data[start+x:start+x+3], "little") for x in (4, 7))
elif name == b"VP8 ":
check(size >= 10 and data[start+3:start+6] == b"\x9d\x01\x2a", "invalid VP8 bitstream")
image = tuple(int.from_bytes(data[start+x:start+x+2], "little") & 0x3fff for x in (6, 8))
elif name == b"VP8L":
check(size >= 5 and data[start] == 0x2f, "invalid VP8L bitstream")
bits = int.from_bytes(data[start+1:start+5], "little")
image = (1+(bits & 0x3fff), 1+((bits >> 14) & 0x3fff))
check(image and (canvas is None or canvas == image), "WebP missing image or inconsistent canvas")
return image
def verify_ready(c, reader, queued, ready, *, decoder=None):
stable = ("id", "chat_id", "owner_id", "filename", "content_type", "sha256", "size_bytes", "created_at")
check(all(ready[k] == queued[k] for k in stable), "original metadata changed from queued to ready")
check(ready["status"] == "ready" and ready["error_code"] is None, "invalid ready state")
entries = {v["name"]: v for v in ready["variants"]}
check(len(ready["variants"]) == len(entries) and set(entries) >= set(VARIANTS),
"ready requires exactly one thumbnail, crop and optimized variant each")
path = attachment_path(ready) + "/content"
original = c.call("GET", path, actor=reader)
check(original["bytes"] == SAMPLE and original["headers"].get_content_type() == "image/png",
"published original changed")
for name, (mime, w, h) in VARIANTS.items():
v = entries[name]
r = c.call("GET", f"{path}?variant={name}", actor=reader)
data = r["bytes"]
check((v["content_type"], v["width"], v["height"]) == (mime, w, h), f"{name}: metadata differs")
check(r["headers"].get_content_type() == mime and len(data) == v["size_bytes"]
and hashlib.sha256(data).hexdigest() == v["sha256"], f"{name}: MIME/size/hash mismatch")
size = jpeg_size(data) if mime == "image/jpeg" else decoded_webp_size(data)
check(size == (w, h), f"{name}: wrong dimensions in image bytes")
if decoder:
decoder(data, mime, w, h)
c.evidence.event("variant", name=name, width=w, height=h, bytes=len(data), sha256=v["sha256"])
return ready
def variants(c, timeout, decoder):
alice, bob, eve, chat = c.bootstrap()
que, _ = c.attachment(alice, chat)
check(que["variants"] == [] and que["error_code"] is None, "queued upload disclosed a result or error")
ready = until_status(c, bob, que, "ready", timeout)
verify_ready(c, bob, que, ready, decoder=decoder)
c.call("GET", attachment_path(que), 404, actor=eve)
c.call("GET", attachment_path(que) + "/content?variant=crop", 404, actor=eve)
class Pipeline:
def __init__(self, stand, decoder):
self.stand, self.c, self.a = stand, stand.c, stand.a
self.decoder = decoder
def action(self, command, *args):
if not self.a.pipeline_hook:
raise Pending("awaiting worker, broker, relay and app-specific fault adapter")
path = Path(self.a.pipeline_hook).resolve()
check(path.is_file() and os.access(path, os.X_OK), "pipeline hook is not executable")
env = dict(os.environ, BASE_URL=self.c.base)
if self.a.project:
env["COMPOSE_PROJECT_NAME"] = self.a.project
result = self.stand.command("pipeline " + command + (" " + args[0] if command in
("arm", "await", "clear", "crash") else ""),
[str(path), command, *args], env=env, timeout=self.a.pipeline_timeout,
allow_failure=True)
if result.returncode == 78:
raise Pending(f"pipeline adapter prerequisite unavailable for {command}")
if result.returncode and path == Path(__file__).with_name("pipeline_action.py"):
# The bundled adapter emits bounded, whitelisted action labels.
self.c.evidence.event("adapter_diagnostic", action=command, note=result.stderr.decode()[:300].strip())
check(result.returncode == 0, f"pipeline adapter rejected {command} (exit {result.returncode})")
if command in ("inspect", "await", "crash", "broker-restart", "restart-apis",
"replay", "invalid-job", "worker-limits", "drain"):
data = json.loads(result.stdout)
check(isinstance(data, dict), "pipeline hook did not return an object")
if command in ("broker-restart", "restart-apis", "invalid-job", "replay", "worker-limits", "drain"):
self.c.evidence.event(command, evidence=data)
return data
return None
def snapshot(self, att):
o = self.action("inspect", att["id"])
fields = ("job_id", "jobs", "outbox", "staging_exists", "variant_objects", "failed_registered",
"attempts", "max_attempts", "lease_seconds", "prefetch", "concurrency",
"job_timeout_seconds", "worker_memory_bytes", "retry_base_seconds",
"published", "generation", "result_count", "original_exists", "audit_replays", "envelope_valid",
"scheduled_delays_ms")
check(set(fields) <= o.keys(), "incomplete durable pipeline observation")
check(isinstance(o["job_id"], str), "observation has no job ID")
uuid.UUID(o["job_id"])
attempts = [{k: row[k] for k in ("attempt", "kind", "delay_seconds", "error_code")} for row in o["attempts"]
if isinstance(row, dict) and {"attempt", "kind", "delay_seconds", "error_code"} <= row.keys()]
check(len(attempts) == len(o["attempts"]), "malformed attempt history")
rows = {k: o[k] for k in fields}
rows["attempts"] = attempts
self.c.evidence.event("pipeline_state", attachment=att["id"], **rows)
check(o["jobs"] == 1 and o["outbox"] >= 1 and o["envelope_valid"] is True,
"lost, duplicated or invalid durable processing intent")
check(all(isinstance(o[k], (int, float)) and o[k] > 0 for k in
("max_attempts", "lease_seconds", "prefetch", "concurrency",
"job_timeout_seconds", "worker_memory_bytes", "retry_base_seconds")),
"unbounded worker/process configuration")
check(o["job_timeout_seconds"] < o["lease_seconds"] and o["prefetch"] >= o["concurrency"],
"worker lease/prefetch do not cover work admitted by worker")
return o
def accepted(self, uploader, reader, chat):
att, _ = self.c.attachment(uploader, chat)
check(metadata(self.c, reader, att)["status"] in STAGING, "processed while worker must be held")
fail = self.c.call("GET", attachment_path(att) + "/content", 409, actor=reader)
check(fail["json"]["error"]["code"] == "conflict", "non-ready content must be a conflict")
before = self.snapshot(att)
check(before["staging_exists"] is True, "202 returned without durable staging")
return att, before
def finished(self, reader, att, previous):
ready = until_status(self.c, reader, att, "ready", self.a.pipeline_timeout)
verify_ready(self.c, reader, att, ready, decoder=self.decoder)
def cleaned():
row = self.snapshot(att)
check(row["job_id"] == previous["job_id"], "job identity changed during recovery")
if row["staging_exists"] or row["result_count"] != len(VARIANTS) + 1:
return None
check(row["original_exists"] is True and sorted(row["variant_objects"]) == sorted(VARIANTS),
"S3 must contain the original and one published object per required variant")
return row
current = wait(cleaned, self.a.pipeline_timeout, "staging or orphan results were not cleaned")
return ready, current
def durable(self):
self.action("reset")
alice, bob, _, chat = self.c.bootstrap()
try:
self.action("worker-stop")
att, previous = self.accepted(alice, bob, chat)
msg = post(self.c, alice, chat, key(), "", body={"text": "", "attachment_ids": [att["id"]]})["json"]
wait(lambda: self.snapshot(att)["published"] > 0, 30, "original job was not published")
self.action("restart-apis")
self.action("broker-restart")
wait(lambda: self.c.call("GET", "/health/ready", schema="Health"), 60, "API not ready after restart")
check(metadata(self.c, bob, att)["status"] == "queued", "job did not stay queued without worker")
assert_history(self.c, bob, chat, [msg])
self.action("worker-start")
ready, prior = self.finished(bob, att, previous)
self.action("relay-start")
self.action("redeliver", att["id"])
after, row = self.finished(bob, att, previous)
check(after == ready and row["attempts"] == prior["attempts"],
"duplicate broker event changed published effect or executed again")
finally:
self.action("reset")
def crash(self, point):
self.action("reset")
alice, bob, _, chat = self.c.bootstrap()
try:
if point == "publish-before-mark":
self.action("worker-stop")
self.action("arm", point)
att, _ = self.c.attachment(alice, chat)
mark = self.action("crash", point, att["id"])
check(mark.get("point") == point and mark.get("attachment_id") == att["id"]
and mark.get("signal") == "SIGKILL", "fault did not identify and kill the expected process")
self.c.evidence.event("fault_reached", evidence=mark)
if point == "publish-before-mark":
self.action("worker-start")
_, current = self.finished(bob, att, mark)
self.action("drain")
if point == "object-before-ack":
check([row["kind"] for row in current["attempts"]] == ["lease_expired", "success"]
and current["generation"] > mark["generation"], "lost processing lease was not recovered")
if point == "ready-before-ack":
check(current["generation"] == mark["generation"] and current["attempts"] == mark["attempts"],
"redelivery started a new attempt after durable completion")
finally:
self.action("reset")
def bounded_processing(self):
self.action("reset")
alice, bob, _, chat = self.c.bootstrap()
settings = wait(lambda: settings_with_consumer(self), 20, "no active worker consumer observed")
limits = settings["image_limits"]
check(all(value and value not in ("0", "unlimited", "0 seconds") for value in limits.values())
and settings["worker_memory_bytes"] > 0, "worker or ImageMagick has unbounded resources")
consumers = settings["consumers"]
check(len(consumers) == settings["concurrency"] and all(
row["active"] and row["ack_required"] and row["prefetch"] == settings["prefetch"] > 0
for row in consumers), "broker consumer count, ack or prefetch differs from worker configuration")
try:
self.action("arm", "object-before-ack")
att, _ = self.c.attachment(alice, chat)
marker = self.action("await", "object-before-ack", att["id"])
# Leave the worker paused. Its own work deadline must end the
# attempt, record a temporary failure and permit automatic retry.
_, recovered = self.finished(bob, att, {"job_id": marker["job_id"]})
observed = [(x["kind"], x["error_code"]) for x in recovered["attempts"]]
check(observed == [("temporary", "processing_timeout"), ("success", None)],
"worker did not time out and finish the same job on retry")
finally:
self.action("reset")
def malformed_job(self):
self.action("reset")
alice, bob, _, chat = self.c.bootstrap()
try:
att, _ = self.c.attachment(alice, chat)
ready = until_status(self.c, bob, att, "ready", self.a.pipeline_timeout)
original, prior = self.finished(bob, att, self.snapshot(att))
self.action("invalid-job", att["id"])
later, after = self.finished(bob, att, prior)
check(ready == original == later and prior["attempts"] == after["attempts"],
"invalid broker message changed a ready result or created a new delivery effect")
finally:
self.action("reset")
def retry_replay(self):
self.action("reset")
alice, bob, _, chat = self.c.bootstrap()
schedules = []
try:
for point in ("retry-transient", "retry-transient", "fail-permanent"):
self.action("arm", point)
att, _ = self.c.attachment(alice, chat)
linked_key = key()
linked_body = {"text": "", "attachment_ids": [att["id"]]}
linked = None
if point == "fail-permanent":
linked = post(self.c, alice, chat, linked_key, "", body=linked_body)["json"]
self.action("activate", point, att["id"])
failed = until_status(self.c, bob, att, "failed", self.a.pipeline_timeout)
code = "invalid_image" if point == "fail-permanent" else "retry_exhausted"
check(failed["error_code"] == code and not failed["variants"], "wrong terminal error code/metadata")
row = self.snapshot(att)
self.action("failed", att["id"])
check(row["failed_registered"] and row["staging_exists"], "failed job not registered or replay input lost")
unavailable = self.c.call("GET", attachment_path(att) + "/content", 409, actor=bob)
check(unavailable["json"]["error"]["code"] == "conflict", "failed attachment content is not a conflict")
post(self.c, alice, chat, key(), "", body=linked_body, status=409, code="conflict")
if linked:
check(post(self.c, alice, chat, linked_key, "", body=linked_body)["json"] == linked,
"prior accepted Message must remain replayable after its attachment fails")
assert_history(self.c, bob, chat, [linked])
attempts = row["attempts"]
if point == "fail-permanent":
check(len(attempts) == 1 and attempts[0]["kind"] == "permanent"
and attempts[0]["delay_seconds"] is None, "permanent fault was retried")
else:
check(len(attempts) == row["max_attempts"] and len(attempts) >= 2
and all(x["kind"] == "temporary" for x in attempts),
"transient failure did not stop at configured attempt bound")
delays = row["scheduled_delays_ms"]
check(len(delays) == len(attempts)-1, "retry offsets were not recorded for each retry")
for i, (ms, attempt) in enumerate(zip(delays, attempts[:-1])):
upper = min(30, row["retry_base_seconds"] * (2 ** min(i, 4)))
observed = attempt["delay_seconds"]
check(1000 <= ms <= 1000 * upper and isinstance(observed, (int, float))
and 0 < observed <= upper, "retry outside documented backoff and jitter bounds")
schedules.append(delays)
self.action("clear", point, att["id"])
self.action("replay", att["id"])
# A checksum fault changed metadata only within this test; replay
# must serve the original fixture's data and checksum.
ready, current = self.finished(bob, att, row)
check(current["audit_replays"] == row["audit_replays"] + 1,
"operator replay did not leave exactly one audit record")
self.action("replay", att["id"])
snapshot = self.snapshot(att)
check(metadata(self.c, bob, att) == ready and snapshot["attempts"] == current["attempts"]
and snapshot["outbox"] == current["outbox"], "replay of ready job was not a no-op")
check(len(schedules) == 2 and schedules[0] != schedules[1], "identical retry schedules: jitter not observed")
finally:
self.action("reset")
def settings_with_consumer(pipeline):
settings = pipeline.action("worker-limits")
return settings if settings["consumers"] else None
def make_decoder(stand, executable):
if not executable:
return None
def decode(data, mime, w, h):
# Bytes are synthetic and the command sees only a temporary file.
suffix = ".jpg" if mime == "image/jpeg" else ".webp"
with tempfile.NamedTemporaryFile(suffix=suffix) as file:
file.write(data)
file.flush()
result = stand.command("decode downloaded " + mime, [
executable, "identify", "+ping", "-regard-warnings", "-format", "%wx%h", file.name,
], timeout=10)
check(result.stdout.decode().strip() == f"{w}x{h}", "full image decode has wrong dimensions")
return decode
+477
View File
@@ -0,0 +1,477 @@
#!/usr/bin/env python3
"""Fault adapter for the Lab 5 Compose implementation, only on an isolated project."""
import json
import os
import re
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.dont_write_bytecode = True
from compose_action import API, DB, PROJECT, ROOT
HERE = Path(__file__).resolve().parent
BROKER = os.environ.get("LAB5_TEST_BROKER", "rabbitmq")
WORKER = os.environ.get("LAB5_TEST_WORKER", "worker")
RELAY = os.environ.get("LAB5_TEST_RELAY", "relay")
CLEANER = os.environ.get("LAB5_TEST_CLEANUP", "attachment-cleanup")
POINTS = {"commit-before-publish": ("before_publish", RELAY),
"publish-before-mark": ("after_publish", RELAY),
"object-before-ack": ("after_objects", WORKER),
"ready-before-ack": ("before_ack", WORKER)}
ORIGINAL = (ROOT / "tests/fixtures/sample.png").read_bytes()
S3_SETUP = """set -eu
rc=/usr/bin/rc
"$rc" alias set app http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" \
"$(cat /run/secrets/s3_secret_access_key)" --bucket-lookup path \
--region "$S3_REGION" >/dev/null
"""
S3_RC = S3_SETUP + """for prefix do
"$rc" bucket list --recursive --json "app/$S3_BUCKET/$prefix"
done
"""
class Unsupported(Exception):
pass
def require(ok, message):
if not ok:
raise RuntimeError(message)
def run(argv, label, timeout=30, allow_fail=False):
try:
r = subprocess.run(argv, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
except subprocess.TimeoutExpired:
raise RuntimeError(f"{label}: exceeded {timeout}s") from None
require(allow_fail or r.returncode == 0, f"{label}: exit {r.returncode}")
return r
def until(fn, label, seconds=24):
end = time.monotonic() + seconds
while time.monotonic() < end:
try:
value = fn()
except (RuntimeError, ValueError):
value = None
if value:
return value
time.sleep(0.2)
raise RuntimeError(label)
def compose(*args, label=None, timeout=30, allow_fail=False):
files = json.loads(os.environ.get("LAB5_TEST_COMPOSE_FILES", "[]"))
cmd = ["docker", "compose", "--project-name", PROJECT]
for file in files:
cmd += ["-f", file]
return run(cmd + list(args), label or "compose " + args[0], timeout, allow_fail)
def sql(query):
return compose("exec", "-T", DB, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-At",
"-U", os.environ["LAB5_TEST_DB_USER"], "-d", os.environ["LAB5_TEST_DB_NAME"],
"-c", query, label="fixture SQL").stdout.decode().strip()
def one_container(service):
rows = compose("ps", "-aq", service).stdout.decode().split()
require(len(rows) == 1, f"expected one {service} in isolated project")
return rows[0]
def start(*services):
# Start the existing containers only. Compose start can also rerun a finished
# one-shot dependency, which would invalidate the migration experiment.
ids = [one_container(service) for service in services]
run(["docker", "start", *ids], "start selected containers")
def set_storage_net(attached):
cid = one_container(WORKER)
net = PROJECT + "_lab5_object"
current = json.loads(run(["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", cid],
"worker networks").stdout)
if attached and net not in current:
run(["docker", "network", "connect", "--alias", WORKER, net, cid], "restore worker S3 network")
if not attached and net in current:
run(["docker", "network", "disconnect", net, cid], "isolate worker S3 network")
def marker_dir():
path = Path(os.environ.get("LAB5_TEST_FAULT_HOST_DIR", "/nonexistent")).resolve()
if not path.is_dir() or not (path / ".lab5-test-project").is_file():
raise Unsupported("set a dedicated fault directory with .lab5-test-project marker")
require((path / ".lab5-test-project").read_text().strip() == PROJECT, "fault directory belongs to another project")
return path
def clean_point(point):
for suffix in ("arm", "used", "hit", "release"):
p = marker_dir() / f"{point}.{suffix}"
if p.exists():
p.unlink()
def broker_ctl(command, *columns):
return compose("exec", "-T", "-e", "RABBITMQ_CTL_ERL_ARGS=+S 1:1 +A 1", BROKER,
"rabbitmqctl", command, "-p", "messenger", "--quiet", "--formatter", "json",
*columns, label="RabbitMQ " + command, timeout=20)
def queue(name="image.jobs"):
r = broker_ctl("list_queues", "name", "durable", "messages_ready", "messages_unacknowledged", "consumers").stdout
rows = json.loads(r)
image = [row for row in rows if row["name"] == name]
require(len(image) == 1 and image[0]["durable"] is True, "expected durable queue not found")
return image[0]
def snapshot(att):
row = sql(f"""
SELECT json_build_object(
'job_id', j.id, 'jobs', (SELECT count(*) FROM attachment_jobs WHERE attachment_id=a.id),
'outbox', (SELECT count(*) FROM outbox WHERE job_id=j.id),
'published', (SELECT count(*) FROM outbox WHERE job_id=j.id AND sent_at IS NOT NULL),
'status', a.status, 'max_attempts', j.max_attempts,
'failed_registered', a.status='failed' AND a.error_code IS NOT NULL,
'generation', j.lease_generation, 'original_key', a.object_key,
'has_staging_ref', a.staging_key IS NOT NULL,
'processing_age_seconds', (SELECT extract(epoch FROM clock_timestamp()-r.started_at)
FROM attachment_attempts r WHERE r.job_id=j.id AND r.lease_generation=j.lease_generation),
'variant_keys', COALESCE((SELECT json_object_agg(name, object_key) FROM attachment_variants
WHERE attachment_id = a.id AND pipeline_version = j.pipeline_version), '{{}}'),
'audit_replays', (SELECT count(*) FROM attachment_replays WHERE job_id=j.id),
'envelope_valid', EXISTS (SELECT 1 FROM outbox o WHERE o.job_id=j.id AND
o.payload->>'schema_version'='1' AND o.payload->>'type'='attachment.process.v1'
AND o.payload->>'job_id'=j.id::text AND o.payload->>'attachment_id'=a.id::text
AND o.payload->>'attempt'='1' AND o.payload->>'pipeline_version'=j.pipeline_version::text
AND (o.payload - ARRAY['schema_version','type','job_id','attachment_id','attempt','pipeline_version',
'created_at','traceparent','tracestate']) = '{{}}'::jsonb),
'attempts', COALESCE((SELECT json_agg(json_build_object(
'attempt', r.attempt,
'kind', CASE r.outcome WHEN 'ready' THEN 'success' WHEN 'retry' THEN 'temporary'
WHEN 'failed' THEN CASE WHEN r.error_code='retry_exhausted' THEN 'temporary' ELSE 'permanent' END
WHEN 'lease_expired' THEN 'lease_expired' ELSE 'processing' END,
'delay_seconds', extract(epoch FROM o.available_at-r.finished_at), 'error_code', r.error_code
) ORDER BY r.attempt) FROM attachment_attempts r LEFT JOIN outbox o
ON o.dedup_key = 'retry/' || j.id || '/' || (r.attempt + 1) WHERE r.job_id=j.id), '[]')
)
FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id AND j.pipeline_version=a.pipeline_version
WHERE a.id='{att}';
""")
require(row and "\n" not in row, "expected exactly one pipeline observation")
return json.loads(row)
def list_key_sets(*prefixes):
r = compose("run", "--no-deps", "--rm", "-T", "--entrypoint", "/bin/sh", "s3-init",
"-c", S3_RC, "lab5-test", *prefixes, label="list synthetic S3 prefixes", timeout=20)
source = r.stdout.decode().lstrip()
decoder = json.JSONDecoder()
sets = []
for prefix in prefixes:
page, offset = decoder.raw_decode(source)
source = source[offset:].lstrip()
require(page.get("truncated") is False and isinstance(page.get("items"), list),
"S3 prefix listing is incomplete")
keys = {entry["key"] for entry in page["items"] if not entry["is_dir"]}
require(all(key.startswith(prefix) for key in keys), "S3 response escaped the fixture prefix")
sets.append(keys)
require(not source, "unexpected S3 output after the requested listings")
return sets
def runtime():
cid = one_container(WORKER)
fields = run(["docker", "inspect", "-f", "{{json .Config.Env}}\t{{.HostConfig.Memory}}", cid],
"worker limits").stdout.decode().strip().split("\t")
env, mem = json.loads(fields[0]), int(fields[1])
settings = dict(x.split("=", 1) for x in env if "=" in x)
def value(names, default):
return next((int(settings[n]) for n in names if n in settings), default)
return {"worker_memory_bytes": mem,
"concurrency": value(("WORKER_CONCURRENCY",), 1),
"prefetch": value(("WORKER_PREFETCH", "JOB_PREFETCH"), 1),
"lease_seconds": value(("JOB_LEASE_SECONDS", "WORKER_LEASE_SECONDS"), 90),
"job_timeout_seconds": value(("JOB_TIMEOUT_SECONDS", "WORKER_TIMEOUT_SECONDS"), 60),
"retry_base_seconds": value(("JOB_RETRY_BASE_SECONDS", "WORKER_RETRY_BASE_SECONDS"), 2)}
def worker_limits():
settings = runtime()
r = compose("exec", "-T", WORKER, "magick", "-list", "resource", label="ImageMagick policy")
limits = dict((name.strip(), val.strip()) for line in r.stdout.decode().splitlines()
if ":" in line for name, val in [line.split(":", 1)])
settings["image_limits"] = {key: limits.get(key, "") for key in ("Memory", "Map", "Disk", "Thread", "Time")}
r = broker_ctl("list_consumers")
rows = json.loads(r.stdout)
settings["consumers"] = [
{"prefetch": row["prefetch_count"], "ack_required": row["ack_required"], "active": row["active"]}
for row in rows if row["queue_name"] == "image.jobs"
]
return settings
def retry_delays_ms(job_id):
cid = one_container(WORKER)
# Preserve only the observed scheduling values, never container logs.
output = run(["docker", "logs", cid], "worker retry delay evidence")
delays = []
for line in (output.stderr + output.stdout).decode().splitlines():
if "job retry scheduled" not in line:
continue
if line.startswith("{"):
item = json.loads(line)
if item.get("job_id") == job_id and item.get("msg") == "job retry scheduled":
delays.append(int(item["delay_ms"]))
elif f"job_id={job_id}" in line:
match = re.search(r"\bdelay_ms=(\d+)", line)
require(match is not None, "worker retry log did not record jitter")
delays.append(int(match.group(1)))
return delays
def inspect(att):
row = snapshot(att)
staging, results = list_key_sets(f"staging/{att}/", f"results/{att}/")
keys = row.pop("variant_keys")
original = row.pop("original_key")
row["staging_exists"] = f"staging/{att}/original" in staging
row["variant_objects"] = sorted(name for name in keys if keys[name] in results)
row["original_exists"] = original in results
row["result_count"] = len(results)
row["scheduled_delays_ms"] = retry_delays_ms(row["job_id"]) if any(
attempt["delay_seconds"] is not None for attempt in row["attempts"]) else []
row.update(runtime())
return row
def restart_broker_with_pending():
# Stop the relay so it cannot republish a lost message during recovery.
compose("stop", "-t", "4", RELAY)
before = until(lambda: (q if (q := queue())["messages_ready"] > 0 and q["consumers"] == 0 else None),
"expected a durable broker delivery before restart")
cid = one_container(BROKER)
run(["docker", "restart", "--time", "8", cid], "physical RabbitMQ restart", timeout=70)
after = until(queue, "durable queue did not reappear", seconds=45)
require(after["messages_ready"] == before["messages_ready"] and after["consumers"] == 0,
"accepted broker deliveries did not survive restart")
return {"broker_before": before, "broker_after": after}
def drained():
def empty():
value = queue()
return value if value["consumers"] > 0 and value["messages_ready"] == 0 and value["messages_unacknowledged"] == 0 else None
return until(empty, "broker delivery was not acknowledged/drained", seconds=45)
def await_publication(outbox_id):
until(lambda: sql(f"SELECT sent_at IS NOT NULL FROM outbox WHERE id='{outbox_id}'") == "t",
"fixture delivery not confirmed")
return drained()
def publish_fixture(att, field=None, *, version=None):
dedup = "test_delivery/" + str(uuid.uuid4())
payload = "o.payload"
if field in ("attachment_id", "job_id"):
payload = f"jsonb_set(o.payload, '{{{field}}}', to_jsonb('{uuid.uuid4()}'::text))"
elif field == "pipeline_version":
payload = "jsonb_set(o.payload, '{pipeline_version}', to_jsonb(j.pipeline_version+1))"
version_filter = "" if version is None else f" AND j.pipeline_version={int(version)}"
row = sql(f"""INSERT INTO outbox(job_id,payload,available_at,dedup_key)
SELECT o.job_id,{payload}, clock_timestamp(), '{dedup}' FROM outbox o
JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='{att}'{version_filter}
ORDER BY o.created_at, o.id LIMIT 1 RETURNING id""").splitlines()
require(len(row) == 2 and row[1] == "INSERT 0 1", "unable to insert fixture delivery")
outbox_id = str(uuid.UUID(row[0]))
await_publication(outbox_id)
return outbox_id
def invalid_job(att):
before = queue("image.invalid")["messages_ready"]
for field in ("attachment_id", "job_id", "pipeline_version"):
publish_fixture(att, field)
after = until(lambda: (n if (n := queue("image.invalid")["messages_ready"]) == before+3 else None),
"invalid delivery was not rejected to DLQ")
return {"dead_letters_before": before, "dead_letters_after": after}
def failed(att):
row = snapshot(att)
result = compose("exec", "-T", CLEANER, "/app/jobs", "failed", label="list failed via operator CLI")
values = json.loads(result.stdout)
require(isinstance(values, list) and any(r["job_id"] == row["job_id"] and r["attachment_id"] == att
for r in values),
"failed job absent from operator registry")
def replay(att):
default = [CLEANER, "/app/jobs", "replay", "-job-id", "{job_id}", "-request-id", "{request_id}",
"-operator", "test", "-reason", "acceptance", "-extra-attempts", "1"]
# JSON argv with explicitly recognized substitutions; shell is never used.
cmd = json.loads(os.environ["LAB5_TEST_REPLAY_CMD"]) if os.environ.get("LAB5_TEST_REPLAY_CMD") else default
row = snapshot(att)
mapping = {"{job_id}": row["job_id"], "{attachment_id}": att, "{request_id}": str(uuid.uuid4())}
argv = [mapping.get(x, x) for x in cmd]
result = compose("exec", "-T", *argv, label="operator replay")
data = json.loads(result.stdout)
require(data["job_id"] == row["job_id"] and data["replayed"] is (row["status"] == "failed"),
"operator replay did not report the expected status")
return {"accepted": data["replayed"], "request_id": mapping["{request_id}"], "job_id": row["job_id"]}
def wait_marker(label, att):
point, _ = POINTS[label]
job = snapshot(att)["job_id"]
hit = marker_dir() / (point + ".hit")
matched = until(lambda: hit.read_text().strip() if hit.is_file() else None,
"instrumented process did not reach intended fault")
require(matched == job, "fault marker matched a different job")
return hit, {"point": label, "attachment_id": att, "job_id": matched}
def crash_observed(label, att):
point, service = POINTS[label]
cid = one_container(service)
hit, evidence = wait_marker(label, att)
row = snapshot(att)
expected = {"commit-before-publish": "queued", "publish-before-mark": "queued",
"object-before-ack": "processing", "ready-before-ack": "ready"}[label]
require(row["status"] == expected, "attachment state does not match held crash boundary")
if expected == "queued":
require(row["published"] == 0 and row["outbox"] == 1, "outbox is not committed and unsent")
if expected != "ready":
require(row["has_staging_ref"], "staging reference removed before safe completion")
if expected == "processing":
age_limit = runtime()["job_timeout_seconds"] - row["processing_age_seconds"]
else:
age_limit = None
marker_mtime = hit.stat().st_mtime
started = time.monotonic()
# Read state and signal consecutively, within the actual fault window.
# The relay timeout starts slightly before the marker (transaction setup).
limit = 6 if expected == "queued" else 25
if expected == "processing":
require(age_limit > 0.3, "worker deadline expired before the crash")
else:
require(time.time() - marker_mtime < limit, "fault marker expired before the crash")
require(not (marker_dir() / (point + ".release")).exists(), "fault point was released")
run(["docker", "kill", "--signal", "KILL", cid], "kill at held fault marker", timeout=5)
elapsed = time.monotonic() - started
if expected == "processing":
require(elapsed < age_limit, "worker deadline elapsed before SIGKILL")
else:
require(time.time() - marker_mtime < limit, "fault window elapsed before SIGKILL")
stored = None
try:
if expected == "processing":
stored = len(list_key_sets(f"results/{att}/")[0])
require(stored >= 4, "S3 did not contain the written output set at worker crash")
finally:
clean_point(point)
start(service)
evidence.update(container=cid, signal="SIGKILL", status=expected, generation=row["generation"],
attempts=row["attempts"], outbox=row["outbox"], published=row["published"],
result_count=stored, kill_elapsed_s=elapsed)
return evidence
def main():
require(bool(PROJECT) and PROJECT != "highload-lab5", "explicit disposable project required")
marker_dir()
command, *args = sys.argv[1:]
if command == "reset":
services = set(compose("config", "--services").stdout.decode().split())
if not {WORKER, RELAY, BROKER} <= services:
raise Unsupported("worker, relay and broker are not configured")
for point, _ in POINTS.values():
hit = marker_dir() / (point + ".hit")
if hit.exists():
(marker_dir() / (point + ".release")).touch()
(marker_dir() / (point + ".arm")).unlink(missing_ok=True)
start(BROKER, RELAY, WORKER)
set_storage_net(True)
return None
if command == "worker-limits":
return worker_limits()
if command == "drain":
return drained()
if command == "worker-stop":
compose("stop", "-t", "5", WORKER)
elif command == "worker-start":
start(WORKER)
elif command == "relay-start":
start(RELAY)
elif command == "restart-apis":
old = compose("ps", "-q", API).stdout.decode().split()
require(len(old) >= 2, "need two real API containers to restart")
def starts():
return {i: run(["docker", "inspect", "-f", "{{.State.StartedAt}}", i],
"API StartedAt").stdout.decode().strip() for i in old}
before = starts()
run(["docker", "restart", "--time", "8", *old], "restart APIs")
after = starts()
require(all(after[i] != before[i] for i in old), "not all APIs restarted")
return {"started_before": before, "started_after": after}
elif command == "broker-restart":
return restart_broker_with_pending()
elif command == "arm" and args[0] in POINTS:
point, _ = POINTS[args[0]]
clean_point(point)
(marker_dir() / (point + ".arm")).touch(exist_ok=False)
elif command == "await":
return wait_marker(args[0], str(uuid.UUID(args[1])))[1]
elif command == "crash":
return crash_observed(args[0], str(uuid.UUID(args[1])))
elif command == "arm" and args[0] == "retry-transient":
set_storage_net(False)
elif command == "clear" and args[0] == "retry-transient":
set_storage_net(True)
elif command == "arm" and args[0] == "fail-permanent":
compose("stop", "-t", "5", WORKER)
elif command in ("activate", "clear") and args[0] == "fail-permanent":
att = str(uuid.UUID(args[1]))
if command == "activate":
value = "0" * 64
else:
import hashlib
value = hashlib.sha256(ORIGINAL).hexdigest()
require(sql(f"UPDATE attachments SET sha256='{value}' WHERE id='{att}' RETURNING id").splitlines() ==
[att, "UPDATE 1"],
"could not inject/restore staging checksum fault")
if command == "activate":
start(WORKER)
elif command == "activate" and args[0] == "retry-transient":
pass
elif command in ("inspect", "redeliver", "replay", "failed", "invalid-job"):
att = str(uuid.UUID(args[0]))
return {"inspect": inspect, "redeliver": publish_fixture, "replay": replay,
"failed": failed, "invalid-job": invalid_job}[command](att)
else:
raise Unsupported("pipeline action unavailable")
return None
if __name__ == "__main__":
try:
result = main()
if result is not None:
print(json.dumps(result))
except Unsupported as exc:
print(str(exc), file=sys.stderr)
sys.exit(78)
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
print("pipeline adapter:", exc if isinstance(exc, RuntimeError) else type(exc).__name__, file=sys.stderr)
sys.exit(1)
+457
View File
@@ -0,0 +1,457 @@
"""Observe and exercise a Compose stand. Business traffic always goes via the LB."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import http.client
import io
import json
from pathlib import Path
import os
import subprocess
import threading
import time
from urllib.parse import urlsplit
from checks import ROOT, Failure, Pending, assert_history, check, history, message_path, key, post, summarize, wait
from client import shape
class Stand:
# Whitelist inspect fields: no environment, mounts, or container log dumps.
FORMAT = "\t".join(("{{.Id}}", "{{.Config.Hostname}}", "{{.Image}}", "{{.State.Status}}",
"{{.State.StartedAt}}", "{{.State.FinishedAt}}", "{{.State.ExitCode}}",
"{{.State.OOMKilled}}", "{{.HostConfig.NanoCpus}}", "{{.HostConfig.CpuQuota}}",
"{{.HostConfig.CpuPeriod}}", "{{.HostConfig.Memory}}",
"{{json .NetworkSettings.Ports}}", "{{json .HostConfig.PortBindings}}",
"{{.HostConfig.NetworkMode}}", "{{.HostConfig.PublishAllPorts}}"))
def __init__(self, args, c):
self.a = args
self.c = c
self.e = c.evidence
self.compose = ["docker", "compose"]
if args.project:
self.compose += ["--project-name", args.project]
for file in args.compose_file:
self.compose += ["--file", str(Path(file).resolve())]
def command(self, name, argv, *, timeout=30, env=None, allow_failure=False):
start = time.monotonic()
try:
result = subprocess.run(argv, cwd=ROOT, env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=timeout)
except (OSError, subprocess.TimeoutExpired) as exc:
self.e.event("command", action=name, elapsed_s=time.monotonic()-start, error=type(exc).__name__)
raise Failure(f"{name}: {type(exc).__name__}") from None
self.e.event("command", action=name, elapsed_s=time.monotonic()-start, exit_code=result.returncode)
check(allow_failure or result.returncode == 0, f"{name}: exit {result.returncode}")
return result
def ids(self, service, all_states=True):
return self.command("compose ps " + service, self.compose + ["ps"] +
(["-a"] if all_states else []) + ["-q", service]).stdout.decode().split()
def containers(self, service):
results = []
for cid in self.ids(service):
result = self.command("inspect " + service, ["docker", "inspect", "--format", self.FORMAT, cid])
parts = result.stdout.decode().rstrip("\n").split("\t")
fields = ("id", "alias", "image", "state", "started_at", "finished_at", "exit_code", "oom",
"nano_cpus", "cpu_quota", "cpu_period", "memory", "ports", "bindings", "network", "publish_all")
check(len(parts) == len(fields), "unexpected docker inspect format")
for index in range(6, len(fields)):
parts[index] = json.loads(parts[index]) if fields[index] != "network" else parts[index]
results.append(dict(zip(fields, parts)))
return results
def public_topology(self):
try:
if not hasattr(self, "engine"):
fmt = "{{.ServerVersion}}\t{{.OSType}}\t{{.Architecture}}\t{{.NCPU}}\t{{.MemTotal}}"
result = self.command("Docker availability", ["docker", "info", "--format", fmt])
self.engine = result.stdout.decode().strip().split("\t")
check(len(self.engine) == 5, "unexpected Docker engine metadata")
self.e.event("docker_environment", version=self.engine[0], os=self.engine[1],
architecture=self.engine[2], logical_cpus=int(self.engine[3]),
memory_bytes=int(self.engine[4]))
except Failure:
raise Pending("Docker daemon not available") from None
services = self.command("Compose service names", self.compose + ["config", "--services"]).stdout.decode().split()
if self.a.api not in services or self.a.lb not in services:
raise Pending("Compose does not define API and LB services")
api = [r for r in self.containers(self.a.api) if r["state"] == "running"]
lb = [r for r in self.containers(self.a.lb) if r["state"] == "running"]
self.e.event("topology", api=api, lb=lb)
if len(api) < 2 or not lb:
raise Pending("stand needs two running API replicas and a public LB")
self.a_ids = {r["alias"] for r in api}
check(len(self.a_ids) == len(api), "API aliases are not unique")
self.lb = lb[0]
port = urlsplit(self.c.base).port or (443 if self.c.base.startswith("https:") else 80)
check(any(int(binding["HostPort"]) == port for r in lb
for group in (r["ports"] or {}).values() for binding in group or []),
"BASE_URL port is not published by the selected LB")
return api
def resources(self):
api = self.public_topology()
for r in api:
check(r["nano_cpus"] > 0 or (r["cpu_quota"] > 0 and r["cpu_period"] > 0),
"API CPU has no hard limit")
check(r["memory"] > 0, "API RAM has no hard limit")
check(not any((r["ports"] or {}).values()) and not any((r["bindings"] or {}).values())
and not r["publish_all"] and r["network"] != "host", "API bypasses LB via host ports/network")
self.stats()
def stats(self):
ids = self.ids(self.a.api, False) + [self.lb["id"]]
result = self.command("docker stats", ["docker", "stats", "--no-stream", "--format",
"{{.ID}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids], timeout=10)
self.e.event("resource_sample", samples=result.stdout.decode().splitlines())
def observe(self, actor, wanted=None, *, duration=3, forbidden=None):
wanted = self.a_ids if wanted is None else wanted
deadline, seen, attempts = time.monotonic() + duration, set(), 0
while time.monotonic() < deadline:
result = self.c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
check(result["json"] == actor["user"], "same Bearer token resolved to another user")
alias = result["headers"]["X-Instance-Id"]
check(alias != forbidden, "LB routed authenticated request to the excluded replica")
check(alias in self.a_ids, "LB routed to an API outside this Compose project")
seen.add(alias)
attempts += 1
if forbidden is not None:
time.sleep(0.05)
if forbidden is None and wanted <= seen:
break
self.e.event("routing", wanted=sorted(wanted), observed=sorted(seen), excluded=forbidden, attempts=attempts)
check(wanted <= seen and attempts >= (10 if forbidden else 2), "LB did not exercise the required replicas")
return seen
def network_target(self, target):
fmt = "{{json .NetworkSettings.Networks}}"
def networks(cid):
r = self.command("container networks", ["docker", "inspect", "--format", fmt, cid])
return json.loads(r.stdout)
net = networks(target["id"])
shared = net.keys() & networks(self.lb["id"]).keys()
chosen = self.a.network or (sorted(shared)[0] if shared else None)
check(chosen in shared and net[chosen]["IPAddress"], "no shared API/LB network with IPv4")
return net[chosen]["IPAddress"]
def direct_health(self, target, endpoint, status):
# From the LB network namespace, bypass routing only for health diagnostics.
ip = self.network_target(target)
result = self.command("direct health/" + endpoint, [
"docker", "run", "--rm", "--pull", "never", "--network", "container:" + self.lb["id"],
"--entrypoint", "curl", self.a.probe_image, "--http1.1", "--noproxy", "*",
"--include", "--silent", "--show-error", "--max-time", "4",
f"http://{ip}:{self.a.api_port}/health/{endpoint}",
], timeout=12)
response = http.client.HTTPResponse(type("Socket", (), {"makefile": lambda *_: io.BytesIO(result.stdout)})())
with response:
response.begin()
self.e.event("direct_health", endpoint=endpoint, status=response.status,
instance=response.getheader("X-Instance-Id"))
check(response.status == status and response.getheader("X-Instance-Id") == target["alias"],
f"target /health/{endpoint}: expected {status}, got {response.status}")
value = json.loads(response.read())
rid = response.getheader("X-Request-Id")
check(bool(rid) and response.headers.get_content_type() == "application/json",
"direct health response is missing required headers")
if status == 200:
check(shape(value, "Health") == {"status": "ok"}, "direct health payload differs")
else:
check(shape(value, "Error")["error"]["code"] == "unavailable"
and value["error"]["request_id"] == rid, "readiness 503 error envelope differs")
return True
def hook(self, executable, target=None, timeout=90, **extra):
if not executable:
raise Pending("operator hook is not configured")
path = Path(executable).resolve()
check(path.is_file() and os.access(path, os.X_OK), "operator hook must be an executable file")
env = dict(os.environ, BASE_URL=self.c.base, **extra)
if self.a.project:
env["COMPOSE_PROJECT_NAME"] = self.a.project
if target:
env.update(TARGET_INSTANCE_ID=target["alias"], TARGET_CONTAINER_ID=target["id"])
self.command("hook " + path.name, [str(path)], env=env, timeout=timeout)
def unready(self):
api = self.public_topology()
if not (self.a.unready_hook and self.a.ready_hook):
raise Pending("configure hooks to fault and restore one API dependency without disconnecting LB")
alice = self.c.user("readiness")
self.observe(alice)
target = api[0]
self.direct_health(target, "live", 200)
self.direct_health(target, "ready", 200)
try:
self.hook(self.a.unready_hook, target, LAB5_HOOK_MODE="unready")
wait(lambda: self.direct_health(target, "ready", 503), 20, "target never returned readiness 503")
self.direct_health(target, "live", 200)
# Allow LB convergence, then require sustained exclusion while the
# target remains reachable from the LB network and answers 503.
others = self.a_ids - {target["alias"]}
def routed_elsewhere():
response = self.c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
return response["headers"]["X-Instance-Id"] in others
wait(routed_elsewhere, 10, "no authenticated request routed to a ready replica")
wait(lambda: self.observe(alice, others, duration=3, forbidden=target["alias"]), 15,
"LB did not consistently exclude a running 503 replica")
self.direct_health(target, "live", 200)
self.direct_health(target, "ready", 503)
finally:
self.hook(self.a.ready_hook, target, LAB5_HOOK_MODE="ready")
wait(lambda: self.direct_health(target, "ready", 200), 20, "target stayed unready after restore")
wait(lambda: self.observe(alice), 20, "restored API did not rejoin LB")
def ready_aliases(self, actor):
api = self.public_topology()
self.observe(actor)
return api
def migration_snapshot(self):
service = self.a.migrate
rows = self.containers(service)
check(len(rows) == 1, "expected one migrator container")
row = rows[0]
check(row["state"] == "exited" and row["exit_code"] == 0, "migrator did not exit cleanly")
log = self.command("migrator logs", ["docker", "logs", row["id"]])
completions = []
for line in (log.stdout + log.stderr).splitlines():
try:
item = json.loads(line)
except (ValueError, UnicodeError):
continue
if isinstance(item, dict) and item.get("msg") == "migrations completed":
completions.append(item.get("applied"))
check(len(completions) == 1, "migrator must log exactly one successful invocation")
sql = ("SELECT version_id, is_applied, count(*) FROM goose_db_version "
"GROUP BY 1,2 ORDER BY 1,2;")
output = self.command("migration version counts", self.compose + [
"exec", "-T", self.a.db, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-At",
"-U", self.a.db_user, "-d", self.a.db_name, "-c", sql,
]).stdout.decode().splitlines()
versions = sorted(int(p.name.split("_", 1)[0]) for p in (ROOT / "db/migrations").glob("*.sql"))
check(output == [f"{v}|t|1" for v in [0, *versions]], "migration history differs from one apply per version")
check(all(r["started_at"] >= row["finished_at"] for r in self.containers(self.a.api)
if r["state"] == "running"), "API started before migrations completed")
self.e.event("migrations", container=row, applied=completions, versions=output)
return row, output
def persistence(self):
api = self.public_topology()
if not self.a.restart_hook:
raise Pending("configure a hook that restarts API and stores without removing volumes")
stores = [self.a.db, *self.a.store]
before = {s: self.containers(s) for s in stores}
check(all(rows and all(r["state"] == "running" for r in rows) for rows in before.values()),
"configured persistence stores must be running")
alice, bob, _, chat = self.c.bootstrap()
self.observe(alice)
k, text = key(), "committed before restarting API and stores"
original = post(self.c, alice, chat, k, text)["json"]
self.hook(self.a.restart_hook)
wait(lambda: self.c.call("GET", "/health/ready", schema="Health"), 90, "LB did not recover after restart")
after = self.public_topology()
for s, previous, current in [(self.a.api, api, after)] + [
(s, before[s], self.containers(s)) for s in stores]:
check(len(previous) == len(current) and all(r["state"] == "running" for r in current)
and not {r["started_at"] for r in previous} & {r["started_at"] for r in current},
f"restart did not change StartedAt for every {s}")
self.e.event("restart_observed", service=s, before=previous, after=current)
self.observe(alice)
check(post(self.c, alice, chat, k, text)["json"] == original, "idempotency lost after restart")
assert_history(self.c, bob, chat, [original])
def verify_stopped(self, target):
now = {r["id"]: r for r in self.containers(self.a.api)}
row = now.get(target["id"])
check(row is not None and row["state"] == "exited", "SIGTERM did not stop the selected process")
check(row["exit_code"] == 0 and not row["oom"], "API did not exit gracefully on SIGTERM")
self.e.event("stopped", container=row)
def failover(self):
api = self.public_topology()
alice, bob, _, chat = self.c.bootstrap()
self.observe(alice)
with traffic(self.c, alice, bob, self.a.workers) as load:
self.sample_under_load(load)
for target in api:
self.e.event("target", action="SIGTERM", alias=target["alias"], container=target["id"])
k, text, sent = wait(lambda: write_from(self.c, alice, chat, target["alias"]), 10,
"could not confirm original POST on selected replica")
others = self.a_ids - {target["alias"]}
endpoint = self.network_target(target)
started = time.monotonic()
first_record = len(load.records)
# Race real client traffic and recovery probes with Docker stop.
with ThreadPoolExecutor(max_workers=1) as pool:
stop = pool.submit(self.command, "SIGTERM " + target["alias"], [
"docker", "stop", "--signal", "SIGTERM", "--time", "20", target["id"],
])
try:
recovered = self.recover(alice, bob, chat, target, stop, started)
self.e.event("recovery", target=target["alias"], seconds=recovered)
if recovered is not None:
print(f" {target['alias']}: read/write restored in {recovered:.3f} s", flush=True)
check(recovered is not None and recovered <= 10, "read and write recovery exceeded 10 seconds")
stop.result()
self.verify_stopped(target)
probe = self.command("fresh TCP to stopped API", ["docker", "exec", self.lb["id"],
"nc", "-w", "2", "-z", endpoint, str(self.a.api_port)],
allow_failure=True, timeout=5)
check(probe.returncode == 1, "fresh connection to stopped replica was accepted or probe failed")
replay = post(self.c, alice, chat, k, text)
check(replay["json"] == sent["json"] and replay["headers"]["X-Instance-Id"] in others,
"different replica did not replay the original Message")
self.observe(alice, others, duration=self.a.window, forbidden=target["alias"])
read_back = history(self.c, bob, chat)
check([m for m in read_back if m["text"] == text] == [sent["json"]],
"confirmed pre-stop POST missing, changed or duplicated")
check(len({m["text"] for m in read_back}) == len(read_back),
"an uncertain retry created duplicate effects")
finally:
summarize(self.e, load.records[first_record:], time.monotonic() - started,
window="target " + target["alias"])
# Settle the stop before starting the same container.
try:
stop.result()
finally:
self.command("restore " + target["alias"], ["docker", "start", target["id"]])
wait(lambda: self.observe(alice), 25, "restored replica did not rejoin LB")
def recover(self, alice, bob, chat, target, stop, started):
k, text = key(), "recovery probe " + key()
deadline = started + 10
while time.monotonic() < deadline:
if stop.done():
stop.result()
try:
result = post(self.c, alice, chat, k, text)
if result["headers"]["X-Instance-Id"] != target["alias"]:
page = self.c.call("GET", message_path(chat) + "?limit=100", actor=bob, schema="MessagePage")
if (page["headers"]["X-Instance-Id"] != target["alias"]
and result["json"] in page["json"]["items"]):
return time.monotonic() - started
except Failure:
pass # Keep the exact key/body after an uncertain write.
time.sleep(0.1)
return None
def sample_under_load(self, load):
time.sleep(self.a.warmup)
check(load.successes() >= 1, "no successful business request during load warm-up")
self.stats()
def rolling(self):
api = self.public_topology()
if not self.a.roll_hook:
raise Pending("awaiting rolling update hook/candidate image")
before = self.migration_snapshot()
alice, bob, _, _ = self.c.bootstrap()
self.observe(alice)
original_ids = {r["id"] for r in api}
previous = {r["id"]: r for r in api}
with traffic(self.c, alice, bob, self.a.workers) as load:
self.sample_under_load(load)
start_index = len(load.records)
for target in api:
step_at = time.monotonic()
self.e.event("target", action="rolling_update", alias=target["alias"], container=target["id"])
self.hook(self.a.roll_hook, target)
current = {r["id"]: r for r in self.public_topology()}
stable = set(previous) - {target["id"]}
new = set(current) - set(previous)
check(set(current) == stable | new and len(new) == 1, "rolling step did not replace exactly one API")
check(all(current[r] == previous[r] for r in stable), "rolling step also disturbed another API")
replacement = current[new.pop()]
check(replacement["image"] != target["image"], "rolling step did not apply a new immutable image")
self.observe(alice)
time.sleep(self.a.window)
self.e.event("rolling_step", previous=target, replacement=replacement,
seconds=time.monotonic() - step_at)
previous = current
check(not original_ids & set(previous), "some original replicas were not updated")
stats = load.records[start_index:]
check(stats and all(r["ok"] for r in stats), "business request failed during rolling update")
check(self.migration_snapshot() == before, "rolling update restarted migrations or changed version history")
def write_from(c, actor, chat, alias):
k, text = key(), "before SIGTERM " + key()
r = post(c, actor, chat, k, text)
return (k, text, r) if r["headers"]["X-Instance-Id"] == alias else None
class Traffic:
def __init__(self, c, actor, reader, chat):
self.c, self.actor, self.reader, self.chat = c, actor, reader, chat
self.stop = threading.Event()
self.records = []
self.confirmed = {}
self.offered = set()
self.lock = threading.Lock()
def lane(self):
while not self.stop.is_set():
k = key()
with self.lock:
self.offered.add(k)
for op in ("write", "read"):
started = time.monotonic()
ok = False
status = None
try:
if op == "write":
result = post(self.c, self.actor, self.chat, k, k)
with self.lock:
self.confirmed[k] = result["json"]
else:
result = self.c.call("GET", "/api/v1/users/me", actor=self.actor, schema="User")
check(result["json"] == self.actor["user"], "load token resolved to another user")
ok = True
except Failure:
pass
finally:
status = self.c.local.status
row = self.c.evidence.event("load_request", op=op, status=status, ok=ok,
instance=self.c.local.instance, elapsed_s=time.monotonic()-started)
with self.lock:
self.records.append(row)
if self.stop.is_set():
break
def successes(self):
with self.lock:
return sum(r["ok"] for r in self.records)
def reconcile(self):
found = history(self.c, self.reader, self.chat)
by_text = {m["text"]: m for m in found}
check(len(by_text) == len(found) and set(by_text) <= self.offered,
"load history contains duplicate writes or unknown data")
check(all(by_text.get(k) == v for k, v in self.confirmed.items()),
"confirmed load write missing or changed in history")
self.c.evidence.event("load_history", observed=len(found), confirmed=len(self.confirmed),
offered=len(self.offered))
@contextmanager
def traffic(c, actor, reader, workers):
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
body={"title": "Lab 5 load", "member_ids": [actor["id"], reader["id"]]})["json"]
load = Traffic(c, actor, reader, chat)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(load.lane) for _ in range(workers)]
try:
yield load
finally:
load.stop.set()
for future in futures:
future.result()
elapsed = time.monotonic() - started
summarize(c.evidence, load.records, elapsed)
load.reconcile()
+430
View File
@@ -0,0 +1,430 @@
"""Track 2 experiment. Each trial uses a separate attachment and real deliveries."""
from collections import defaultdict
from datetime import datetime, timedelta
import hashlib
import json
from statistics import median
import time
import uuid
from checks import Failure, Pending, check, wait
from pipeline import SAMPLE, VARIANTS, metadata, verify_ready
ORIGINAL = hashlib.sha256(SAMPLE).hexdigest()
def utc(value):
return datetime.fromisoformat(value.replace("Z", "+00:00"))
def jobs(row):
return {j["version"]: j for j in row["jobs"]}
def deliveries(row, version):
return [e for e in row["outbox"] if e["version"] == version]
def fingerprint(row):
# Dynamic clock and transport bookkeeping are intentionally outside the
# effect. Attempts, pointers, generations and timestamps remain comparable.
return {k: row[k] for k in ("version", "status", "original", "updated_at", "jobs")}
class Versioned:
def __init__(self, pipeline, ops):
self.pipeline = pipeline
self.c = pipeline.c
self.e = self.c.evidence
self.ops = ops
self.timeout = pipeline.a.pipeline_timeout
def state(self, att):
attachment = str(uuid.UUID(att["id"]))
value = self.ops.sql(f"""
SELECT json_build_object(
'version', a.pipeline_version, 'status', a.status, 'original', a.object_key,
'sha256', a.sha256, 'size', a.size_bytes, 'updated_at', a.updated_at, 'db_now', clock_timestamp(),
'jobs', COALESCE((SELECT json_agg(json_build_object(
'id', j.id, 'version', j.pipeline_version, 'generation', j.lease_generation,
'attempt_count', j.attempts_started, 'lease_until', j.lease_until,
'published_original', j.published_original_key,
'variants', COALESCE((SELECT json_object_agg(v.name, json_build_object(
'key',v.object_key,'sha256',v.sha256,'size',v.size_bytes,'width',v.width,'height',v.height))
FROM attachment_variants v WHERE v.attachment_id=a.id AND v.pipeline_version=j.pipeline_version), '{{}}'),
'attempts', COALESCE((SELECT json_agg(json_build_object(
'attempt', x.attempt, 'generation', x.lease_generation,'started_at', x.started_at,
'finished_at', x.finished_at, 'outcome', x.outcome, 'error_code', x.error_code) ORDER BY x.attempt)
FROM attachment_attempts x WHERE x.job_id=j.id), '[]')
) ORDER BY j.pipeline_version) FROM attachment_jobs j WHERE j.attachment_id=a.id), '[]'),
'outbox', COALESCE((SELECT json_agg(json_build_object(
'id', o.id, 'job_id', j.id, 'version', j.pipeline_version, 'available_at', o.available_at,
'sent_at', o.sent_at, 'envelope', o.payload) ORDER BY o.created_at,o.id)
FROM outbox o JOIN attachment_jobs j ON o.job_id=j.id WHERE j.attachment_id=a.id), '[]')
) FROM attachments a WHERE a.id='{attachment}';
""")
check(bool(value), "accepted attachment disappeared")
state = json.loads(value)
check(state["sha256"] == ORIGINAL and state["size"] == len(SAMPLE), "original metadata changed")
return state
def observe(self, name, att, row=None):
row = self.state(att) if row is None else row
self.e.event("versioned_state", stage=name, attachment=att["id"], state=row)
return row
def ready(self, att, version, job_id, started=None):
started = time.monotonic() if started is None else started
deadline = started + self.timeout
while time.monotonic() < deadline:
row = self.state(att)
check(row["version"] == version and jobs(row).get(version, {}).get("id") == job_id,
"active version or job changed while waiting for ready")
check(row["status"] in ("queued", "processing", "ready"), f"version {version} reached {row['status']}")
if row["status"] == "ready" and time.monotonic() <= deadline:
elapsed = time.monotonic() - started
self.e.event("versioned_ready", version=version, job=job_id, seconds=elapsed)
return elapsed
time.sleep(0.25)
raise Failure(f"version {version} did not reach ready within {self.timeout}s")
def verify_s3(self, expected):
# Read every named object, including historical published objects that
# are no longer exposed by GET. Store digests and sizes, not the bodies.
shell = self.ops.S3_SETUP + """for key do
"$rc" object show "app/$S3_BUCKET/$key" >/tmp/lab5-object
digest=$(sha256sum /tmp/lab5-object)
size=$(wc -c </tmp/lab5-object)
printf '%s %s %s\\n' "$key" "${digest%% *}" "$size"
done
"""
result = self.ops.compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "/bin/sh", "s3-init",
"-c", shell, "lab5-versioned", *expected,
label="read exact published S3 keys", timeout=30)
rows = {}
for line in result.stdout.decode().splitlines():
key, sha256, size = line.split()
check(key not in rows, "S3 returned duplicate keys")
rows[key] = (sha256, int(size))
self.e.event("versioned_s3", objects=rows)
check(rows == expected, "actual published S3 objects differ from recorded hashes or sizes")
def verify(self, reader, att, version, expected_versions, stage):
row = self.observe(stage, att)
current = jobs(row)
versions = {1, 2} if version == 2 else {1}
check(set(current) == versions, "unexpected job versions")
active = current[version]
check(row["status"] == "ready" and row["version"] == version
and row["original"] and row["original"] == active["published_original"], "wrong current published pointer")
ready = verify_ready(self.c, reader, att, metadata(self.c, reader, att), decoder=self.pipeline.decoder)
for item in ready["variants"]:
db = active["variants"][item["name"]]
check((db["sha256"], db["size"], db["width"], db["height"]) ==
(item["sha256"], item["size_bytes"], item["width"], item["height"]),
"HTTP variant differs from the current published DB row")
expected = {}
for v, job in current.items():
if v not in expected_versions:
check(not job["published_original"] and not job["variants"],
"superseded attempt published an unexpected result")
continue
check(set(job["variants"]) == set(VARIANTS), "published version has missing or duplicate variants")
check(job["attempt_count"] == len(job["attempts"]) and job["attempts"]
and job["attempts"][-1]["outcome"] == "ready", "published job has no successful attempt")
prefix = f"results/{att['id']}/v{v}/{job['generation']}/"
keys = [job["published_original"], *[d["key"] for d in job["variants"].values()]]
check(all(isinstance(k, str) and k.startswith(prefix) and not any(c.isspace() for c in k)
for k in keys) and len(set(keys)) == 4, "published keys do not isolate version and generation")
expected[keys[0]] = (ORIGINAL, len(SAMPLE))
expected.update({d["key"]: (d["sha256"], d["size"]) for d in job["variants"].values()})
def cleaned():
staging, actual = self.ops.list_key_sets(f"staging/{att['id']}/", f"results/{att['id']}/")
self.e.event("versioned_listing", attachment=att["id"], staging=sorted(staging), results=sorted(actual))
check(set(expected) <= actual, "cleanup lost a published object")
return not staging and actual == set(expected)
wait(cleaned, self.timeout, "unpublished objects or staging remained after cleanup")
self.verify_s3(expected)
if expected_versions == {1, 2}:
check(all(current[1]["variants"][n]["sha256"] != current[2]["variants"][n]["sha256"] for n in VARIANTS),
"fixture does not distinguish the two pipeline outputs")
return row
def upgrade(self, att):
attachment = att["id"]
def cli():
result = self.ops.compose("exec", "-T", self.ops.CLEANER, "/app/jobs", "upgrade",
"-attachment-id", attachment, "-to-version", "2", label="operator upgrade")
data = json.loads(result.stdout)
check(data["attachment_id"] == attachment and data["pipeline_version"] == 2,
"upgrade returned the wrong attachment/version")
data["job_id"] = str(uuid.UUID(data["job_id"]))
return data
first, repeated = cli(), cli()
self.e.event("versioned_upgrade", first=first, repeated=repeated)
check(first["queued"] is True and repeated["queued"] is False
and first["job_id"] == repeated["job_id"], "upgrade retry created or selected a different job")
row = self.state(att)
check(set(jobs(row)) == {1, 2} and jobs(row)[2]["id"] == first["job_id"]
and len(deliveries(row, 2)) == 1, "upgrade did not atomically create one v2 job and outbox")
return first["job_id"]
def started_v1(self):
alice, bob, _, chat = self.c.bootstrap()
return bob, self.c.attachment(alice, chat)[0]
def ready_v1(self):
reader, att = self.started_v1()
self.ready(att, 1, jobs(self.state(att))[1]["id"])
original = self.verify(reader, att, 1, {1}, "v1 baseline")
self.ops.drained()
return reader, att, original
def no_dlq(self, previous):
now = self.ops.queue("image.invalid")["messages_ready"]
self.e.event("versioned_dlq", before=previous, after=now)
check(now == previous, "valid stale or duplicate delivery went to DLQ")
def duplicate_and_stale(self):
reader, att, original = self.ready_v1()
jid = self.upgrade(att)
elapsed = self.ready(att, 2, jid)
before = self.verify(reader, att, 2, {1, 2}, "before duplicate delivery")
check(jobs(before)[1] == jobs(original)[1], "upgrade changed the previously published v1 job")
self.ops.drained()
dead = self.ops.queue("image.invalid")["messages_ready"]
for version in (2, 1):
outbox_id = self.ops.publish_fixture(att["id"], version=version)
after = self.verify(reader, att, 2, {1, 2}, f"after valid v{version} delivery")
injected = next(o for o in after["outbox"] if o["id"] == outbox_id)
source = deliveries(before, version)[0]
check(injected["sent_at"] and injected["envelope"] == source["envelope"],
"injected job was not the original valid envelope")
check(fingerprint(after) == fingerprint(before), "valid repeated/stale delivery changed the effect")
self.no_dlq(dead)
check(all(j["attempt_count"] == 1 for j in jobs(after).values()), "duplicate started another attempt")
return after, elapsed
def reorder(self):
self.ops.compose("stop", "-t", "4", self.ops.RELAY)
oid = None
try:
reader, att = self.started_v1()
queued = self.observe("v1 committed, relay stopped", att)
(old,) = deliveries(queued, 1)
check(old["sent_at"] is None and jobs(queued)[1]["attempt_count"] == 0, "v1 leaked before reorder")
oid = str(uuid.UUID(old["id"]))
changed = self.ops.sql(f"""UPDATE outbox SET available_at=clock_timestamp()+interval '12 hours'
WHERE id='{oid}' AND sent_at IS NULL RETURNING id""").splitlines()
check(changed == [oid, "UPDATE 1"], "could not delay the original v1 outbox row")
jid = self.upgrade(att)
held = self.observe("v1 delayed while v2 queued", att)
self.ops.start(self.ops.RELAY)
elapsed = self.ready(att, 2, jid)
before = self.verify(reader, att, 2, {2}, "v2 ready before release of v1")
check(deliveries(before, 1)[0]["id"] == oid and deliveries(before, 1)[0]["sent_at"] is None
and jobs(before)[1]["attempt_count"] == 0, "old intent disappeared or was delivered ahead of v2")
dead = self.ops.queue("image.invalid")["messages_ready"]
self.release_outbox(oid)
self.ops.await_publication(oid)
after = self.verify(reader, att, 2, {2}, "after original v1 delivery")
v1, v2 = deliveries(after, 1)[0], deliveries(after, 2)[0]
check(v1["envelope"] == old["envelope"] == deliveries(held, 1)[0]["envelope"]
and v1["sent_at"] and v2["sent_at"] and utc(v1["sent_at"]) > utc(v2["sent_at"]),
"broker publication order or original envelope does not prove reorder")
check(fingerprint(after) == fingerprint(before) and jobs(after)[2]["attempt_count"] == 1,
"v1 sent after v2 changed jobs or published data")
self.no_dlq(dead)
return after, elapsed
finally:
if oid:
self.release_outbox(oid)
self.ops.start(self.ops.RELAY)
def release_outbox(self, oid):
self.ops.sql(f"UPDATE outbox SET available_at=clock_timestamp() WHERE id='{oid}' AND sent_at IS NULL")
def arm(self, point):
self.ops.clean_point(point)
(self.ops.marker_dir() / (point + ".arm")).touch(exist_ok=False)
def marker(self, point, jid):
path = self.ops.marker_dir() / (point + ".hit")
value = self.ops.until(lambda: path.read_text().strip() if path.is_file() else None,
f"no marker for {point}", seconds=30)
check(value == jid, f"{point} marker was from a different job")
self.e.event("versioned_marker", point=point, job=jid)
def release(self, point):
(self.ops.marker_dir() / (point + ".release")).touch()
def crash(self, point):
reader, att, baseline = self.ready_v1()
cid = self.ops.one_container(self.ops.WORKER)
self.arm(point)
try:
jid = self.upgrade(att)
self.marker(point, jid)
row = self.observe("before crash", att)
job = jobs(row)[2]
check(row["status"] == "processing" and job["attempt_count"] == 1 and job["lease_until"],
"marker did not hold an active v2 attempt")
expected = 0 if point == "before_objects" else 4
prefix = f"results/{att['id']}/v2/{job['generation']}/"
objects = self.ops.list_key_sets(prefix)[0]
check(len(objects) == expected, "S3 side effect does not match the intended crash window")
work_end = utc(job["attempts"][0]["started_at"]) + timedelta(
seconds=self.ops.runtime()["job_timeout_seconds"])
deadline = min(utc(job["lease_until"]), work_end)
read_started = time.monotonic()
remaining = (deadline - utc(self.state(att)["db_now"])).total_seconds()
check(remaining > 0, "work deadline or lease elapsed before crash")
started = time.monotonic()
self.ops.run(["docker", "kill", "--signal", "KILL", cid], "kill held worker", timeout=8)
check(time.monotonic() - read_started < remaining, "SIGKILL did not land while attempt was held")
self.e.event("versioned_crash", point=point, container=cid, job=jid,
work_budget_remaining_s=remaining, object_keys=sorted(objects))
finally:
self.release(point)
self.ops.start(self.ops.WORKER)
elapsed = self.ready(att, 2, jid, started)
self.ops.drained()
after = self.verify(reader, att, 2, {1, 2}, "after recovery")
check(jobs(after)[1] == jobs(baseline)[1], "v2 crash changed historical v1")
job = jobs(after)[2]
check(job["attempt_count"] == 2 and
[x["outcome"] for x in job["attempts"]] == ["lease_expired", "ready"] and
job["generation"] > jobs(row)[2]["generation"], "crash did not recover in a new fenced attempt")
return after, elapsed
def workers(self, count):
self.ops.compose("up", "-d", "--no-deps", "--no-build", "--scale", f"{self.ops.WORKER}={count}",
self.ops.WORKER, label=f"set {count} worker processes")
def started_at(self, cid):
return self.ops.run(["docker", "inspect", "-f", "{{.State.StartedAt}}", cid],
"old worker StartedAt").stdout.decode().strip()
def rejection(self, cid, jid, since):
result = self.ops.run(["docker", "logs", "--timestamps", "--since", since, cid],
"old worker finalization log")
for line in (result.stdout + result.stderr).decode().splitlines():
if "job finalization rejected" in line and jid in line:
return line.split()[0]
return None
def late_worker(self):
old_cid = self.ops.one_container(self.ops.WORKER)
original_process = self.started_at(old_cid)
budget = self.ops.runtime()["job_timeout_seconds"]
point = "after_objects"
self.arm(point)
scaled = False
try:
reader, att = self.started_v1()
jid = jobs(self.state(att))[1]["id"]
self.marker(point, jid)
hold = self.observe("v1 stopped after its S3 writes", att)
old = jobs(hold)[1]
check(hold["status"] == "processing" and old["attempt_count"] == 1 and old["lease_until"],
"v1 was not held with an active lease")
prefix = f"results/{att['id']}/v1/{old['generation']}/"
keys = self.ops.list_key_sets(prefix)[0]
self.e.event("versioned_old_effect", job=jid, keys=sorted(keys))
check(len(keys) == 4, "old worker did not write its output set")
scaled = True
self.workers(2)
self.ops.until(lambda: self.ops.queue()["consumers"] == 2, "two workers did not join")
check(self.started_at(old_cid) == original_process, "old worker was replaced")
next_id = self.upgrade(att)
elapsed = self.ready(att, 2, next_id)
before = self.observe("v2 ready while v1 remains held", att)
deadline = min(utc(old["lease_until"]), utc(old["attempts"][0]["started_at"]) + timedelta(seconds=budget))
dead = self.ops.queue("image.invalid")["messages_ready"]
released = utc(self.ops.sql("SELECT clock_timestamp()"))
check(released < deadline, "old work deadline/lease elapsed before release")
self.release(point)
reject = self.ops.until(lambda: self.rejection(old_cid, jid, old["attempts"][0]["started_at"]),
"resumed old worker did not reject finalization")
self.e.event("versioned_rejected_commit", job=jid, container=old_cid, released_at=released.isoformat(),
rejected_at=reject, deadline=deadline.isoformat())
check(released <= utc(reject) < deadline and self.started_at(old_cid) == original_process,
"old worker did not reach the version check within its original lease")
self.ops.drained()
after = self.verify(reader, att, 2, {2}, "after old worker rejection")
check(jobs(after)[1]["attempt_count"] == 1 and jobs(after)[2]["attempt_count"] == 1
and jobs(after)[2] == jobs(before)[2] and after["original"] == before["original"]
and after["updated_at"] == before["updated_at"], "old worker overrode the v2 effect")
self.no_dlq(dead)
return after, elapsed
finally:
self.release(point)
if scaled:
self.workers(1)
def series(pipeline, repetitions):
# Imported after acceptance has set the explicit Compose scope.
import pipeline_action as ops
if not ops.PROJECT or ops.PROJECT == "highload-lab5":
raise Failure("explicit isolated versioned project required")
try:
ops.marker_dir()
except ops.Unsupported as exc:
raise Pending(str(exc)) from None
pipeline.stand.public_topology()
supported = ops.sql("""SELECT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema=current_schema() AND table_name='attachment_jobs'
AND column_name='published_original_key')""") == "t"
if not supported:
raise Pending("versioned pipeline migration is not installed on this stand")
experiment = Versioned(pipeline, ops)
cases = (
("duplicate-v2-and-stale-v1", experiment.duplicate_and_stale),
("reorder-v2-before-v1", experiment.reorder),
("crash-before-S3", lambda: experiment.crash("before_objects")),
("crash-after-S3", lambda: experiment.crash("after_objects")),
("late-v1-worker-after-v2", experiment.late_worker),
)
samples = defaultdict(list)
digests = set()
for repetition in range(1, repetitions + 1):
for name, case in cases:
start = time.monotonic()
pipeline.c.evidence.event("versioned_trial_start", scenario=name, repetition=repetition)
try:
pipeline.action("reset")
ops.one_container(ops.WORKER)
ops.drained()
row, ready_s = case()
digest = {n: v["sha256"] for n, v in jobs(row)[2]["variants"].items()}
digests.add(tuple(sorted(digest.items())))
sample = {"status": "PASS", "ready_s": ready_s, "v2_sha256": digest,
"attempts": {v: j["attempt_count"] for v, j in jobs(row).items()}}
except (Failure, RuntimeError, OSError, ValueError) as exc:
note = str(exc) if isinstance(exc, (Failure, RuntimeError)) else type(exc).__name__
sample = {"status": "FAIL", "reason": note}
sample["elapsed_s"] = time.monotonic() - start
samples[name].append(sample)
pipeline.c.evidence.event("versioned_trial", scenario=name, repetition=repetition, **sample)
print(f"{sample['status']}: {name}, repeat {repetition}/{repetitions}"
+ (f" — {sample['reason']}" if "reason" in sample else ""), flush=True)
aggregates = {}
for name, trials in samples.items():
ready = [r["ready_s"] for r in trials if r["status"] == "PASS"]
aggregates[name] = {
"attempted": len(trials), "passed": len(ready), "failed": len(trials) - len(ready),
"ready_seconds": [min(ready), median(ready), max(ready)] if ready else None,
}
stable = len(digests) == 1
pipeline.c.evidence.event("versioned_summary", repeats=repetitions, results=aggregates,
identical_v2=stable, v2_sha256=dict(next(iter(digests))) if stable else None)
check(all(result["passed"] == repetitions for result in aggregates.values()) and stable,
"versioned experiment failed a trial or produced different v2 checksums")