forked from mtusi2026/mtusi2026lab4
feat: implement S3 attachments and presigned uploads
This commit is contained in:
@@ -0,0 +1,304 @@
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, check
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
FIXTURE = ROOT / "tests" / "fixtures" / "sample_large.png"
|
||||
API_CONTAINERS = ("mtusi-lab4-api-1", "mtusi-lab4-api-2")
|
||||
CONCURRENCY = 10
|
||||
OUTPUT = ROOT / "evidence" / "concurrent-upload-results.csv"
|
||||
|
||||
|
||||
def parse_mib(value):
|
||||
units = {
|
||||
"B": 1 / (1024 * 1024),
|
||||
"KiB": 1 / 1024,
|
||||
"MiB": 1,
|
||||
"GiB": 1024,
|
||||
"Ki": 1 / 1024,
|
||||
"Mi": 1,
|
||||
"Gi": 1024,
|
||||
"kB": 1000 / (1024 * 1024),
|
||||
"MB": 1000 * 1000 / (1024 * 1024),
|
||||
"GB": 1000 * 1000 * 1000 / (1024 * 1024),
|
||||
}
|
||||
for unit in sorted(units, key=len, reverse=True):
|
||||
if value.endswith(unit):
|
||||
return float(value[:-len(unit)].strip()) * units[unit]
|
||||
raise ValueError(f"Unknown Docker memory unit: {value}")
|
||||
|
||||
|
||||
def docker_memory():
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker", "stats", "--no-stream",
|
||||
"--format", "{{.Name}}|{{.MemUsage}}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
values = {}
|
||||
for line in result.stdout.splitlines():
|
||||
if "|" not in line:
|
||||
continue
|
||||
name, usage = line.split("|", 1)
|
||||
if name in API_CONTAINERS:
|
||||
values[name] = parse_mib(usage.split("/", 1)[0].strip())
|
||||
|
||||
missing = set(API_CONTAINERS) - set(values)
|
||||
if missing:
|
||||
raise RuntimeError("Missing API containers: " + ", ".join(missing))
|
||||
return values
|
||||
|
||||
|
||||
class MemoryMonitor:
|
||||
def __init__(self):
|
||||
self.running = False
|
||||
self.samples = []
|
||||
self.thread = None
|
||||
self.errors = []
|
||||
|
||||
def sample(self):
|
||||
while self.running:
|
||||
try:
|
||||
values = docker_memory()
|
||||
self.samples.append(values)
|
||||
except Exception as exc:
|
||||
self.errors.append(type(exc).__name__)
|
||||
time.sleep(0.1)
|
||||
|
||||
def __enter__(self):
|
||||
self.baseline = docker_memory()
|
||||
self.samples = [dict(self.baseline)]
|
||||
self.running = True
|
||||
self.thread = threading.Thread(target=self.sample, daemon=True)
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.running = False
|
||||
self.thread.join(timeout=5)
|
||||
try:
|
||||
self.samples.append(docker_memory())
|
||||
except Exception as exc:
|
||||
self.errors.append(type(exc).__name__)
|
||||
|
||||
def summary(self):
|
||||
peak_by_container = {
|
||||
name: max(sample[name] for sample in self.samples)
|
||||
for name in API_CONTAINERS
|
||||
}
|
||||
total_samples = [
|
||||
sum(sample[name] for name in API_CONTAINERS)
|
||||
for sample in self.samples
|
||||
]
|
||||
baseline_total = sum(self.baseline.values())
|
||||
peak_total = max(total_samples)
|
||||
return {
|
||||
"baseline_total_mib": round(baseline_total, 2),
|
||||
"peak_total_mib": round(peak_total, 2),
|
||||
"peak_delta_total_mib": round(peak_total - baseline_total, 2),
|
||||
"api1_peak_mib": round(peak_by_container[API_CONTAINERS[0]], 2),
|
||||
"api2_peak_mib": round(peak_by_container[API_CONTAINERS[1]], 2),
|
||||
"samples": len(self.samples),
|
||||
"sampling_errors": len(self.errors),
|
||||
}
|
||||
|
||||
|
||||
def response_json(response):
|
||||
return json.loads(response["bytes"].decode("utf-8"))
|
||||
|
||||
|
||||
def upload_one(index, method, actor, chat, content, digest, barrier):
|
||||
client = Client(BASE_URL)
|
||||
barrier.wait(timeout=30)
|
||||
started = time.monotonic()
|
||||
|
||||
if method == "proxy":
|
||||
response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments"
|
||||
f"?filename=parallel-{index}.png",
|
||||
201,
|
||||
actor=actor,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
attachment = response_json(response)
|
||||
api_elapsed = response["elapsed"]
|
||||
api_body_bytes = len(content)
|
||||
s3_body_bytes = 0
|
||||
|
||||
else:
|
||||
body = {
|
||||
"filename": f"parallel-{index}.png",
|
||||
"content_type": "image/png",
|
||||
"size_bytes": len(content),
|
||||
"sha256": digest,
|
||||
}
|
||||
create_response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments/presigned",
|
||||
201,
|
||||
actor=actor,
|
||||
body=body,
|
||||
)
|
||||
created = response_json(create_response)
|
||||
|
||||
request = urllib.request.Request(
|
||||
created["upload_url"],
|
||||
data=content,
|
||||
headers=created["headers"],
|
||||
method="PUT",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=90) as response:
|
||||
check(response.status in (200, 201, 204), "S3 PUT failed")
|
||||
|
||||
complete_response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/attachments/uploads/{created['upload_id']}/complete",
|
||||
200,
|
||||
actor=actor,
|
||||
)
|
||||
attachment = response_json(complete_response)
|
||||
api_elapsed = create_response["elapsed"] + complete_response["elapsed"]
|
||||
api_body_bytes = len(json.dumps(body).encode("utf-8"))
|
||||
s3_body_bytes = len(content)
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
check(attachment["status"] == "ready", "attachment is not ready")
|
||||
check(attachment["size_bytes"] == len(content), "wrong attachment size")
|
||||
check(attachment["sha256"] == digest, "wrong attachment checksum")
|
||||
|
||||
return {
|
||||
"worker": index,
|
||||
"elapsed_total_s": round(elapsed, 4),
|
||||
"elapsed_api_s": round(api_elapsed, 4),
|
||||
"client_to_api_body_bytes": api_body_bytes,
|
||||
"client_to_s3_upload_bytes": s3_body_bytes,
|
||||
"attachment_id": attachment["id"],
|
||||
}
|
||||
|
||||
|
||||
def run_method(method, actor, chat, content, digest):
|
||||
print(f"\nStarting {CONCURRENCY} simultaneous {method} uploads...")
|
||||
barrier = threading.Barrier(CONCURRENCY)
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
with MemoryMonitor() as memory:
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=CONCURRENCY) as executor:
|
||||
futures = [
|
||||
executor.submit(
|
||||
upload_one, index, method, actor, chat,
|
||||
content, digest, barrier,
|
||||
)
|
||||
for index in range(1, CONCURRENCY + 1)
|
||||
]
|
||||
|
||||
for future in as_completed(futures):
|
||||
try:
|
||||
results.append(future.result())
|
||||
except Exception as exc:
|
||||
errors.append(f"{type(exc).__name__}: {exc}")
|
||||
|
||||
wall_time = time.monotonic() - started
|
||||
|
||||
mem = memory.summary()
|
||||
successful = len(results)
|
||||
print(
|
||||
f"{method}: success={successful}/{CONCURRENCY}, "
|
||||
f"errors={len(errors)}, wall={wall_time:.3f}s, "
|
||||
f"peak API RAM={mem['peak_total_mib']} MiB, "
|
||||
f"delta={mem['peak_delta_total_mib']} MiB, "
|
||||
f"samples={mem['samples']}"
|
||||
)
|
||||
|
||||
for error in errors:
|
||||
print("ERROR:", error)
|
||||
|
||||
return {
|
||||
"method": method,
|
||||
"concurrency": CONCURRENCY,
|
||||
"file_size_bytes": len(content),
|
||||
"successful_uploads": successful,
|
||||
"failed_uploads": len(errors),
|
||||
"wall_time_s": round(wall_time, 4),
|
||||
"throughput_uploads_per_s": round(successful / wall_time, 3),
|
||||
"peak_api_total_mib": mem["peak_total_mib"],
|
||||
"baseline_api_total_mib": mem["baseline_total_mib"],
|
||||
"peak_delta_api_total_mib": mem["peak_delta_total_mib"],
|
||||
"api1_peak_mib": mem["api1_peak_mib"],
|
||||
"api2_peak_mib": mem["api2_peak_mib"],
|
||||
"memory_samples": mem["samples"],
|
||||
"memory_sampling_errors": mem["sampling_errors"],
|
||||
"avg_upload_time_s": round(
|
||||
sum(item["elapsed_total_s"] for item in results) / successful, 4
|
||||
) if successful else None,
|
||||
"max_upload_time_s": max(
|
||||
(item["elapsed_total_s"] for item in results), default=None
|
||||
),
|
||||
"api_body_bytes_per_upload": (
|
||||
results[0]["client_to_api_body_bytes"] if results else None
|
||||
),
|
||||
"s3_body_bytes_per_upload": (
|
||||
results[0]["client_to_s3_upload_bytes"] if results else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if not FIXTURE.exists():
|
||||
raise FileNotFoundError(FIXTURE)
|
||||
|
||||
content = FIXTURE.read_bytes()
|
||||
if len(content) > 10 * 1024 * 1024:
|
||||
raise RuntimeError("Fixture exceeds 10 MiB")
|
||||
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=10) as response:
|
||||
check(response.status == 200, "API is not ready")
|
||||
|
||||
# Prepare identities and chat before measuring concurrent uploads.
|
||||
setup = Client(BASE_URL)
|
||||
alice, _, _, chat = setup.bootstrap()
|
||||
|
||||
rows = []
|
||||
for method in ("proxy", "presigned"):
|
||||
rows.append(run_method(method, alice, chat, content, digest))
|
||||
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
with OUTPUT.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.DictWriter(file, fieldnames=list(rows[0].keys()))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
print("\nResults:", OUTPUT)
|
||||
print("Fixture:", FIXTURE.name)
|
||||
print("File size:", len(content), "bytes")
|
||||
print("SHA-256:", digest)
|
||||
|
||||
if any(row["successful_uploads"] != CONCURRENCY for row in rows):
|
||||
raise SystemExit("FAIL: at least one concurrent upload failed")
|
||||
|
||||
print("PASS: 10 concurrent uploads completed for both methods")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,375 @@
|
||||
import csv
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, check
|
||||
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
FIXTURES = [
|
||||
ROOT / "tests" / "fixtures" / "sample.png",
|
||||
ROOT / "tests" / "fixtures" / "sample_large.png",
|
||||
]
|
||||
|
||||
API_CONTAINERS = [
|
||||
"mtusi-lab4-api-1",
|
||||
"mtusi-lab4-api-2",
|
||||
]
|
||||
|
||||
REPEATS = 3
|
||||
OUTPUT = ROOT / "evidence" / "track1-results.csv"
|
||||
|
||||
|
||||
def docker_memory():
|
||||
"""Return current memory usage in MiB for both API containers."""
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--format",
|
||||
"{{.Name}}|{{.MemUsage}}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
|
||||
values = {}
|
||||
|
||||
for line in result.stdout.splitlines():
|
||||
if "|" not in line:
|
||||
continue
|
||||
|
||||
name, usage = line.split("|", 1)
|
||||
|
||||
if name not in API_CONTAINERS:
|
||||
continue
|
||||
|
||||
memory_value = usage.split("/", 1)[0].strip()
|
||||
values[name] = parse_memory_mib(memory_value)
|
||||
|
||||
missing = set(API_CONTAINERS) - set(values)
|
||||
|
||||
if missing:
|
||||
raise RuntimeError(
|
||||
"Could not read memory for containers: "
|
||||
+ ", ".join(sorted(missing))
|
||||
)
|
||||
|
||||
return values
|
||||
|
||||
|
||||
|
||||
def parse_memory_mib(value):
|
||||
"""Convert Docker memory values to MiB."""
|
||||
value = value.strip()
|
||||
|
||||
units = {
|
||||
"B": 1 / (1024 * 1024),
|
||||
"KiB": 1 / 1024,
|
||||
"MiB": 1,
|
||||
"GiB": 1024,
|
||||
"kB": 1000 / (1024 * 1024),
|
||||
"MB": 1000 * 1000 / (1024 * 1024),
|
||||
"GB": 1000 * 1000 * 1000 / (1024 * 1024),
|
||||
"Ki": 1 / 1024,
|
||||
"Mi": 1,
|
||||
"Gi": 1024,
|
||||
}
|
||||
|
||||
for unit in sorted(units, key=len, reverse=True):
|
||||
if value.endswith(unit):
|
||||
number = value[:-len(unit)].strip()
|
||||
return float(number) * units[unit]
|
||||
|
||||
raise ValueError(f"Unknown Docker memory unit: {value}")
|
||||
|
||||
|
||||
|
||||
class MemoryMonitor:
|
||||
"""Sample API container memory while one upload is running."""
|
||||
|
||||
def __init__(self):
|
||||
self.baseline = {}
|
||||
self.peak = {}
|
||||
self.running = False
|
||||
self.thread = None
|
||||
|
||||
def _sample(self):
|
||||
while self.running:
|
||||
try:
|
||||
current = docker_memory()
|
||||
|
||||
for name, value in current.items():
|
||||
self.peak[name] = max(
|
||||
self.peak.get(name, value),
|
||||
value,
|
||||
)
|
||||
except Exception as exc:
|
||||
print(
|
||||
"WARNING: memory sampling failed:",
|
||||
type(exc).__name__,
|
||||
)
|
||||
|
||||
time.sleep(0.1)
|
||||
|
||||
def __enter__(self):
|
||||
self.baseline = docker_memory()
|
||||
self.peak = dict(self.baseline)
|
||||
self.running = True
|
||||
self.thread = threading.Thread(
|
||||
target=self._sample,
|
||||
daemon=True,
|
||||
)
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.running = False
|
||||
|
||||
if self.thread:
|
||||
self.thread.join(timeout=3)
|
||||
|
||||
try:
|
||||
current = docker_memory()
|
||||
|
||||
for name, value in current.items():
|
||||
self.peak[name] = max(
|
||||
self.peak.get(name, value),
|
||||
value,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@property
|
||||
def peak_rss_mib(self):
|
||||
return max(self.peak.values())
|
||||
|
||||
@property
|
||||
def peak_delta_mib(self):
|
||||
return max(
|
||||
self.peak[name] - self.baseline[name]
|
||||
for name in API_CONTAINERS
|
||||
)
|
||||
|
||||
|
||||
def response_json(response):
|
||||
return json.loads(response["bytes"].decode("utf-8"))
|
||||
|
||||
|
||||
def proxy_upload(client, actor, chat, content):
|
||||
"""Upload a file through the API proxy endpoint."""
|
||||
started = time.monotonic()
|
||||
|
||||
response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=benchmark.png",
|
||||
201,
|
||||
actor=actor,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
attachment = response_json(response)
|
||||
|
||||
check(attachment["status"] == "ready", "proxy attachment is not ready")
|
||||
check(
|
||||
attachment["size_bytes"] == len(content),
|
||||
"proxy attachment size mismatch",
|
||||
)
|
||||
check(
|
||||
attachment["sha256"] == hashlib.sha256(content).hexdigest(),
|
||||
"proxy attachment checksum mismatch",
|
||||
)
|
||||
|
||||
return {
|
||||
"elapsed_total_s": elapsed,
|
||||
"elapsed_api_s": response["elapsed"],
|
||||
"api_request_body_bytes": len(content),
|
||||
"s3_upload_bytes": 0,
|
||||
}
|
||||
|
||||
|
||||
def presigned_upload(client, actor, chat, content):
|
||||
"""Upload a file directly to S3 using a presigned URL."""
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
create_body = {
|
||||
"filename": "benchmark.png",
|
||||
"content_type": "image/png",
|
||||
"size_bytes": len(content),
|
||||
"sha256": digest,
|
||||
}
|
||||
|
||||
create_body_bytes = len(
|
||||
json.dumps(create_body, ensure_ascii=False).encode("utf-8")
|
||||
)
|
||||
|
||||
started = time.monotonic()
|
||||
|
||||
create_response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments/presigned",
|
||||
201,
|
||||
actor=actor,
|
||||
body=create_body,
|
||||
)
|
||||
|
||||
created = response_json(create_response)
|
||||
|
||||
check(created["method"] == "PUT", "unexpected upload method")
|
||||
|
||||
s3_request = urllib.request.Request(
|
||||
created["upload_url"],
|
||||
data=content,
|
||||
headers=created["headers"],
|
||||
method="PUT",
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(s3_request, timeout=60) as response:
|
||||
check(
|
||||
response.status in (200, 201, 204),
|
||||
"direct S3 upload failed",
|
||||
)
|
||||
|
||||
complete_response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/attachments/uploads/{created['upload_id']}/complete",
|
||||
200,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
attachment = response_json(complete_response)
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
check(attachment["status"] == "ready", "presigned attachment is not ready")
|
||||
check(
|
||||
attachment["size_bytes"] == len(content),
|
||||
"presigned attachment size mismatch",
|
||||
)
|
||||
check(
|
||||
attachment["sha256"] == digest,
|
||||
"presigned attachment checksum mismatch",
|
||||
)
|
||||
|
||||
return {
|
||||
"elapsed_total_s": elapsed,
|
||||
"elapsed_api_s": (
|
||||
create_response["elapsed"] + complete_response["elapsed"]
|
||||
),
|
||||
"api_request_body_bytes": create_body_bytes,
|
||||
"s3_upload_bytes": len(content),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for path in FIXTURES:
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
if path.stat().st_size > 10 * 1024 * 1024:
|
||||
raise RuntimeError(f"Fixture exceeds 10 MiB: {path.name}")
|
||||
|
||||
print("Checking API readiness...")
|
||||
with urllib.request.urlopen(
|
||||
BASE_URL + "/health/ready",
|
||||
timeout=10,
|
||||
) as response:
|
||||
check(response.status == 200, "API is not ready")
|
||||
|
||||
client = Client(BASE_URL)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
rows = []
|
||||
|
||||
for fixture in FIXTURES:
|
||||
content = fixture.read_bytes()
|
||||
size_bytes = len(content)
|
||||
|
||||
for method in ("proxy", "presigned"):
|
||||
for repeat in range(1, REPEATS + 1):
|
||||
print(
|
||||
f"Running {method}: {fixture.name}, "
|
||||
f"repeat {repeat}/{REPEATS}"
|
||||
)
|
||||
|
||||
with MemoryMonitor() as memory:
|
||||
if method == "proxy":
|
||||
metrics = proxy_upload(
|
||||
client,
|
||||
alice,
|
||||
chat,
|
||||
content,
|
||||
)
|
||||
else:
|
||||
metrics = presigned_upload(
|
||||
client,
|
||||
alice,
|
||||
chat,
|
||||
content,
|
||||
)
|
||||
|
||||
row = {
|
||||
"method": method,
|
||||
"file": fixture.name,
|
||||
"file_size_bytes": size_bytes,
|
||||
"repeat": repeat,
|
||||
"elapsed_total_s": round(
|
||||
metrics["elapsed_total_s"], 4
|
||||
),
|
||||
"elapsed_api_s": round(
|
||||
metrics["elapsed_api_s"], 4
|
||||
),
|
||||
"client_to_api_body_bytes": (
|
||||
metrics["api_request_body_bytes"]
|
||||
),
|
||||
"client_to_s3_upload_bytes": (
|
||||
metrics["s3_upload_bytes"]
|
||||
),
|
||||
"api_peak_rss_mib": round(
|
||||
memory.peak_rss_mib, 2
|
||||
),
|
||||
"api_peak_delta_mib": round(
|
||||
memory.peak_delta_mib, 2
|
||||
),
|
||||
}
|
||||
|
||||
rows.append(row)
|
||||
|
||||
print(
|
||||
f" total={row['elapsed_total_s']}s, "
|
||||
f"API={row['elapsed_api_s']}s, "
|
||||
f"API body={row['client_to_api_body_bytes']} bytes, "
|
||||
f"peak RAM={row['api_peak_rss_mib']} MiB, "
|
||||
f"RAM delta={row['api_peak_delta_mib']} MiB"
|
||||
)
|
||||
|
||||
fieldnames = list(rows[0].keys())
|
||||
|
||||
with OUTPUT.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.DictWriter(file, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
print()
|
||||
print("PASS: Track 1 benchmark completed")
|
||||
print(f"Results: {OUTPUT}")
|
||||
print(f"Measurements: {len(rows)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,45 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURES = ROOT / "tests" / "fixtures"
|
||||
|
||||
WIDTH = 1600
|
||||
HEIGHT = 1200
|
||||
|
||||
|
||||
def main():
|
||||
FIXTURES.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
source = FIXTURES / "sample.png"
|
||||
large = FIXTURES / "sample_large.png"
|
||||
|
||||
if not source.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Small fixture not found: {source}"
|
||||
)
|
||||
|
||||
pixels = os.urandom(WIDTH * HEIGHT * 3)
|
||||
|
||||
image = Image.frombytes(
|
||||
"RGB",
|
||||
(WIDTH, HEIGHT),
|
||||
pixels,
|
||||
)
|
||||
image.save(large, format="PNG", optimize=False)
|
||||
|
||||
for path in (source, large):
|
||||
size = path.stat().st_size
|
||||
print(f"{path.name}: {size} bytes ({size / 1024 / 1024:.2f} MiB)")
|
||||
|
||||
if large.stat().st_size > 10 * 1024 * 1024:
|
||||
raise RuntimeError("Large fixture exceeds the 10 MiB upload limit")
|
||||
|
||||
print("PASS: Track 1 fixtures prepared")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Regular → Executable
+2
-2
@@ -1,4 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Restart all stateful dependencies and all API replicas without touching volumes.
|
||||
docker compose restart postgres redis api
|
||||
|
||||
docker compose restart postgres redis minio api
|
||||
|
||||
Regular → Executable
+14
-8
@@ -1,17 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
project="${COMPOSE_PROJECT_NAME:-mtusi-lab3}"
|
||||
|
||||
project="${COMPOSE_PROJECT_NAME:-mtusi-lab4}"
|
||||
found=""
|
||||
|
||||
for id in $(docker ps -q --filter "label=com.docker.compose.project=${project}" --filter "label=com.docker.compose.service=api"); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
found="$id"
|
||||
break
|
||||
fi
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
found="$id"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$found" ]; then
|
||||
echo "No running API container matches TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
echo "No running API container matches TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
docker stop --time 3 "$found" >/dev/null
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import hashlib
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client
|
||||
from app.core.config import settings
|
||||
from app.db.models import AttachmentUpload
|
||||
from app.db.session import SessionLocal
|
||||
from app.services.object_storage import client as s3_client
|
||||
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
FIXTURE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
|
||||
def main():
|
||||
content = FIXTURE.read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
api = Client(BASE_URL)
|
||||
alice, _, _, chat = api.bootstrap()
|
||||
|
||||
upload_id = uuid.uuid4()
|
||||
object_key = f"cleanup-test/{chat['id']}/{upload_id}"
|
||||
|
||||
# Host-side test uses the published S3 endpoint.
|
||||
s3 = s3_client()
|
||||
|
||||
s3.put_object(
|
||||
Bucket=settings.s3_bucket,
|
||||
Key=object_key,
|
||||
Body=content,
|
||||
ContentType="image/png",
|
||||
)
|
||||
|
||||
with SessionLocal() as db:
|
||||
upload = AttachmentUpload(
|
||||
id=upload_id,
|
||||
chat_id=uuid.UUID(chat["id"]),
|
||||
owner_id=uuid.UUID(alice["id"]),
|
||||
filename="cleanup-test.png",
|
||||
content_type="image/png",
|
||||
expected_size_bytes=len(content),
|
||||
expected_sha256=digest,
|
||||
object_key=object_key,
|
||||
status="pending",
|
||||
# Older than expiry + 10-minute grace period.
|
||||
expires_at=datetime.now(timezone.utc) - timedelta(minutes=11),
|
||||
)
|
||||
db.add(upload)
|
||||
db.commit()
|
||||
|
||||
print(f"Created synthetic pending upload: {upload_id}")
|
||||
print("Waiting for background cleanup (up to 90 seconds)...")
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
final_status = None
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
with SessionLocal() as db:
|
||||
row = db.get(AttachmentUpload, upload_id)
|
||||
final_status = row.status if row else None
|
||||
|
||||
if final_status == "expired":
|
||||
break
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
if final_status != "expired":
|
||||
raise SystemExit(
|
||||
f"FAIL: expected status expired, got {final_status!r}"
|
||||
)
|
||||
|
||||
try:
|
||||
s3.head_object(Bucket=settings.s3_bucket, Key=object_key)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if code not in ("404", "NoSuchKey", "NotFound") and status != 404:
|
||||
raise
|
||||
else:
|
||||
raise SystemExit("FAIL: S3 object still exists")
|
||||
|
||||
print("PASS: abandoned upload marked expired")
|
||||
print("PASS: corresponding S3 object deleted")
|
||||
print(f"Upload ID: {upload_id}")
|
||||
print(f"Object size: {len(content)} bytes")
|
||||
print(f"SHA-256: {digest}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,285 @@
|
||||
import uuid
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, check
|
||||
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
IMAGE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
|
||||
def response_json(response):
|
||||
return json.loads(response["bytes"].decode("utf-8"))
|
||||
|
||||
|
||||
def create_upload(client, actor, chat, content, filename="sample.png"):
|
||||
"""Create a presigned upload and return its metadata."""
|
||||
response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments/presigned",
|
||||
201,
|
||||
actor=actor,
|
||||
body={
|
||||
"filename": filename,
|
||||
"content_type": "image/png",
|
||||
"size_bytes": len(content),
|
||||
"sha256": hashlib.sha256(content).hexdigest(),
|
||||
},
|
||||
)
|
||||
return response_json(response)
|
||||
|
||||
|
||||
def create_upload_with_metadata(
|
||||
client,
|
||||
actor,
|
||||
chat,
|
||||
content,
|
||||
expected_size=None,
|
||||
expected_sha256=None,
|
||||
):
|
||||
"""Create an upload with deliberately supplied expected metadata."""
|
||||
response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments/presigned",
|
||||
201,
|
||||
actor=actor,
|
||||
body={
|
||||
"filename": "sample.png",
|
||||
"content_type": "image/png",
|
||||
"size_bytes": (
|
||||
len(content) if expected_size is None else expected_size
|
||||
),
|
||||
"sha256": (
|
||||
hashlib.sha256(content).hexdigest()
|
||||
if expected_sha256 is None
|
||||
else expected_sha256
|
||||
),
|
||||
},
|
||||
)
|
||||
return response_json(response)
|
||||
|
||||
|
||||
def put_to_s3(upload, content):
|
||||
"""Upload bytes directly to S3 using the presigned URL."""
|
||||
request = urllib.request.Request(
|
||||
upload["upload_url"],
|
||||
data=content,
|
||||
headers=upload["headers"],
|
||||
method="PUT",
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
check(
|
||||
response.status in (200, 201, 204),
|
||||
"S3 upload failed",
|
||||
)
|
||||
|
||||
|
||||
def complete_upload(client, actor, upload_id, expected_status=200):
|
||||
return client.call(
|
||||
"POST",
|
||||
f"/api/v1/attachments/uploads/{upload_id}/complete",
|
||||
expected_status,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
content = IMAGE.read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
client = Client(BASE_URL)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
# 1. Incorrect SHA-256 must be rejected.
|
||||
wrong_digest = "0" * 64
|
||||
check(wrong_digest != digest, "test checksum unexpectedly matches")
|
||||
|
||||
upload = create_upload_with_metadata(
|
||||
client,
|
||||
alice,
|
||||
chat,
|
||||
content,
|
||||
expected_sha256=wrong_digest,
|
||||
)
|
||||
put_to_s3(upload, content)
|
||||
|
||||
complete_upload(
|
||||
client,
|
||||
alice,
|
||||
upload["upload_id"],
|
||||
expected_status=409,
|
||||
)
|
||||
|
||||
print("PASS: incorrect SHA-256 rejected with HTTP 409")
|
||||
|
||||
# 2. Incorrect expected size must be rejected.
|
||||
upload = create_upload_with_metadata(
|
||||
client,
|
||||
alice,
|
||||
chat,
|
||||
content,
|
||||
expected_size=len(content) + 1,
|
||||
)
|
||||
put_to_s3(upload, content)
|
||||
|
||||
complete_upload(
|
||||
client,
|
||||
alice,
|
||||
upload["upload_id"],
|
||||
expected_status=409,
|
||||
)
|
||||
|
||||
print("PASS: incorrect file size rejected with HTTP 409")
|
||||
|
||||
# 3. Corrupted image must be rejected.
|
||||
corrupt_content = b"This is not a valid PNG image"
|
||||
|
||||
upload = create_upload(
|
||||
client,
|
||||
alice,
|
||||
chat,
|
||||
corrupt_content,
|
||||
)
|
||||
put_to_s3(upload, corrupt_content)
|
||||
|
||||
complete_upload(
|
||||
client,
|
||||
alice,
|
||||
upload["upload_id"],
|
||||
expected_status=415,
|
||||
)
|
||||
|
||||
print("PASS: corrupted image rejected with HTTP 415")
|
||||
|
||||
# 4. Another user must not complete Alice's upload.
|
||||
upload = create_upload(
|
||||
client,
|
||||
alice,
|
||||
chat,
|
||||
content,
|
||||
)
|
||||
put_to_s3(upload, content)
|
||||
|
||||
complete_upload(
|
||||
client,
|
||||
eve,
|
||||
upload["upload_id"],
|
||||
expected_status=404,
|
||||
)
|
||||
|
||||
print("PASS: foreign user cannot complete another user's upload")
|
||||
|
||||
# The legitimate owner must still be able to complete it.
|
||||
owner_response = complete_upload(
|
||||
client,
|
||||
alice,
|
||||
upload["upload_id"],
|
||||
expected_status=200,
|
||||
)
|
||||
attachment = response_json(owner_response)
|
||||
|
||||
check(
|
||||
attachment["status"] == "ready",
|
||||
"owner's attachment is not ready",
|
||||
)
|
||||
check(
|
||||
attachment["owner_id"] == alice["id"],
|
||||
"attachment owner does not match",
|
||||
)
|
||||
check(
|
||||
attachment["sha256"] == digest,
|
||||
"attachment checksum mismatch",
|
||||
)
|
||||
|
||||
print("PASS: legitimate owner can complete the upload")
|
||||
# 5. Proxy upload must reject files larger than 10 MiB.
|
||||
oversized_content = b"\x00" * (10 * 1024 * 1024 + 1)
|
||||
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=oversized.png",
|
||||
expected=413,
|
||||
actor=alice,
|
||||
raw=oversized_content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
print("PASS: oversized proxy upload rejected with HTTP 413")
|
||||
|
||||
# 6. PNG content must not be accepted as JPEG.
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=mismatch.jpg",
|
||||
expected=415,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/jpeg"},
|
||||
)
|
||||
|
||||
print("PASS: MIME mismatch rejected with HTTP 415")
|
||||
|
||||
# 7. Create a ready attachment in Alice and Bob's chat.
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
attachment_id = attachment["id"]
|
||||
|
||||
# Eve is not a member of Alice and Bob's chat.
|
||||
client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment_id}",
|
||||
expected=404,
|
||||
actor=eve,
|
||||
)
|
||||
|
||||
print("PASS: non-member cannot access attachment metadata")
|
||||
|
||||
# 8. A non-member must not download the attachment.
|
||||
client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment_id}/content",
|
||||
expected=404,
|
||||
actor=eve,
|
||||
)
|
||||
|
||||
print("PASS: non-member cannot download attachment")
|
||||
|
||||
# 9. Create another chat where Alice and Eve are members.
|
||||
second_chat = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={
|
||||
"title": "Cross-chat attachment test",
|
||||
"member_ids": [alice["id"], eve["id"]],
|
||||
},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
|
||||
# Try to attach a file from the first chat to a message in the second.
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{second_chat['id']}/messages",
|
||||
expected=404,
|
||||
actor=alice,
|
||||
body={
|
||||
"text": "Cross-chat attachment test",
|
||||
"attachment_ids": [attachment_id],
|
||||
},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
|
||||
print("PASS: attachment from another chat rejected with HTTP 404")
|
||||
print()
|
||||
print("PASS: all presigned negative scenarios")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,123 @@
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, check
|
||||
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
IMAGE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
|
||||
def response_json(response):
|
||||
"""Decode JSON from the raw response bytes."""
|
||||
return json.loads(response["bytes"].decode("utf-8"))
|
||||
|
||||
|
||||
def main():
|
||||
content = IMAGE.read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
|
||||
client = Client(BASE_URL)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
# 1. Request a short-lived upload URL.
|
||||
create_response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments/presigned",
|
||||
201,
|
||||
actor=alice,
|
||||
body={
|
||||
"filename": "sample.png",
|
||||
"content_type": "image/png",
|
||||
"size_bytes": len(content),
|
||||
"sha256": digest,
|
||||
},
|
||||
)
|
||||
|
||||
created = response_json(create_response)
|
||||
|
||||
check(created["method"] == "PUT", "unexpected upload method")
|
||||
check(bool(created["upload_id"]), "missing upload_id")
|
||||
check(created["expires_in"] > 0, "invalid upload expiration")
|
||||
|
||||
# 2. Upload directly to S3, without sending the file through the API.
|
||||
request = urllib.request.Request(
|
||||
created["upload_url"],
|
||||
data=content,
|
||||
headers=created["headers"],
|
||||
method="PUT",
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
check(
|
||||
response.status in (200, 201, 204),
|
||||
"S3 upload failed",
|
||||
)
|
||||
|
||||
# 3. Complete the upload.
|
||||
complete_path = (
|
||||
f"/api/v1/attachments/uploads/{created['upload_id']}/complete"
|
||||
)
|
||||
|
||||
complete_response = client.call(
|
||||
"POST",
|
||||
complete_path,
|
||||
200,
|
||||
actor=alice,
|
||||
)
|
||||
|
||||
attachment = response_json(complete_response)
|
||||
|
||||
check(attachment["status"] == "ready", "attachment is not ready")
|
||||
check(attachment["chat_id"] == chat["id"], "wrong attachment chat")
|
||||
check(attachment["owner_id"] == alice["id"], "wrong attachment owner")
|
||||
check(attachment["sha256"] == digest, "attachment checksum mismatch")
|
||||
check(
|
||||
attachment["size_bytes"] == len(content),
|
||||
"attachment size mismatch",
|
||||
)
|
||||
|
||||
# 4. Complete again: must return the same attachment.
|
||||
repeated_response = client.call(
|
||||
"POST",
|
||||
complete_path,
|
||||
200,
|
||||
actor=alice,
|
||||
)
|
||||
|
||||
repeated = response_json(repeated_response)
|
||||
|
||||
check(
|
||||
repeated["id"] == attachment["id"],
|
||||
"repeated completion created a duplicate",
|
||||
)
|
||||
|
||||
# 5. Download through the authorized API endpoint.
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
200,
|
||||
actor=alice,
|
||||
)["bytes"]
|
||||
|
||||
check(downloaded == content, "downloaded bytes differ from original")
|
||||
check(
|
||||
hashlib.sha256(downloaded).hexdigest() == digest,
|
||||
"downloaded checksum mismatch",
|
||||
)
|
||||
|
||||
print("PASS: presigned upload, completion, idempotency and download")
|
||||
print(f"Upload ID: {created['upload_id']}")
|
||||
print(f"Attachment ID: {attachment['id']}")
|
||||
print(f"File size: {len(content)} bytes")
|
||||
print(f"SHA-256: {digest}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,127 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
ROOT = Path("/app")
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, check
|
||||
from app.core.config import settings
|
||||
from app.db.models import Attachment
|
||||
from app.db.session import SessionLocal
|
||||
from app.services.object_storage import client as s3_client
|
||||
|
||||
|
||||
TRIGGER_NAME = "lab4_force_attachment_insert_failure"
|
||||
FUNCTION_NAME = "lab4_fail_attachment_insert"
|
||||
TEST_FILENAME = "lab4-forced-db-failure.png"
|
||||
|
||||
|
||||
def install_failure_trigger():
|
||||
table = Attachment.__table__
|
||||
schema = table.schema or "public"
|
||||
qualified_table = f'"{schema}"."{table.name}"'
|
||||
|
||||
with SessionLocal() as db:
|
||||
db.execute(text(f"""
|
||||
CREATE OR REPLACE FUNCTION public.{FUNCTION_NAME}()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
IF NEW.filename = '{TEST_FILENAME}' THEN
|
||||
RAISE EXCEPTION 'Lab 4 controlled metadata failure'
|
||||
USING ERRCODE = 'P0001';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
"""))
|
||||
db.execute(text(
|
||||
f'DROP TRIGGER IF EXISTS {TRIGGER_NAME} ON {qualified_table}'
|
||||
))
|
||||
db.execute(text(
|
||||
f'CREATE TRIGGER {TRIGGER_NAME} '
|
||||
f'BEFORE INSERT ON {qualified_table} '
|
||||
f'FOR EACH ROW EXECUTE FUNCTION public.{FUNCTION_NAME}()'
|
||||
))
|
||||
db.commit()
|
||||
|
||||
|
||||
def remove_failure_trigger():
|
||||
table = Attachment.__table__
|
||||
schema = table.schema or "public"
|
||||
qualified_table = f'"{schema}"."{table.name}"'
|
||||
|
||||
with SessionLocal() as db:
|
||||
db.execute(text(
|
||||
f'DROP TRIGGER IF EXISTS {TRIGGER_NAME} ON {qualified_table}'
|
||||
))
|
||||
db.execute(text(
|
||||
f'DROP FUNCTION IF EXISTS public.{FUNCTION_NAME}()'
|
||||
))
|
||||
db.commit()
|
||||
|
||||
|
||||
def object_keys(s3, prefix):
|
||||
result = s3.list_objects_v2(
|
||||
Bucket=settings.s3_bucket,
|
||||
Prefix=prefix,
|
||||
)
|
||||
return {
|
||||
item["Key"]
|
||||
for item in result.get("Contents", [])
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("http://127.0.0.1:8080")
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
prefix = f"original/{chat['id']}/"
|
||||
|
||||
s3 = s3_client()
|
||||
before = object_keys(s3, prefix)
|
||||
|
||||
install_failure_trigger()
|
||||
print("Temporary PostgreSQL failure trigger installed.")
|
||||
|
||||
try:
|
||||
response = client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments"
|
||||
f"?filename={TEST_FILENAME}",
|
||||
expected=503,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
check(
|
||||
response["status"] == 503,
|
||||
"Expected HTTP 503 after forced metadata failure",
|
||||
)
|
||||
print("PASS: S3 upload succeeded, PostgreSQL metadata insert failed")
|
||||
|
||||
after = object_keys(s3, prefix)
|
||||
unexpected_objects = after - before
|
||||
|
||||
check(
|
||||
not unexpected_objects,
|
||||
"Compensation failed: unexpected S3 objects remain",
|
||||
)
|
||||
print("PASS: uploaded S3 object was deleted after DB failure")
|
||||
|
||||
print()
|
||||
print("PASS: S3/PostgreSQL compensation scenario")
|
||||
|
||||
finally:
|
||||
remove_failure_trigger()
|
||||
print("Temporary PostgreSQL trigger removed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user