forked from mtusi2026/mtusi2026lab4
Реализована лабораторная 4: MinIO и вложения
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise upload limits, image validation, attachment ACL, and message links."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def oversized_png_header(width, height):
|
||||
def chunk(kind, data):
|
||||
checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
|
||||
|
||||
image_header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", image_header)
|
||||
+ chunk(b"IDAT", zlib.compress(b"\x00"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Validate Lab4 attachment upload rules")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
endpoint = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
|
||||
content = (Path(__file__).resolve().parent / "fixtures" / "sample.png").read_bytes()
|
||||
uploaded = client.call(
|
||||
"POST",
|
||||
endpoint + quote("sample.png", safe=""),
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(uploaded["status"] == "ready", "uploaded attachment is not ready")
|
||||
check(uploaded["variants"] == [] and uploaded["error_code"] is None,
|
||||
"Lab4 attachment must have no processing variants or error")
|
||||
check(uploaded["sha256"] == hashlib.sha256(content).hexdigest(),
|
||||
"attachment checksum differs from original")
|
||||
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"] + "/content",
|
||||
actor=bob,
|
||||
)
|
||||
check(downloaded["bytes"] == content, "download differs from uploaded bytes")
|
||||
for suffix in ("", "/content"):
|
||||
client.call("GET", "/api/v1/attachments/" + uploaded["id"] + suffix,
|
||||
404, actor=eve)
|
||||
|
||||
def rejected(filename, data, content_type, status):
|
||||
client.call(
|
||||
"POST",
|
||||
endpoint + quote(filename, safe=""),
|
||||
status,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": content_type},
|
||||
)
|
||||
|
||||
rejected("../sample.png", content, "image/png", 400)
|
||||
rejected("mismatch.jpg", content, "image/jpeg", 415)
|
||||
rejected("corrupt.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415)
|
||||
rejected("too-large.png", b"x" * (MAX_UPLOAD_BYTES + 1), "image/png", 413)
|
||||
rejected("too-many-pixels.png", oversized_png_header(20001, 2000),
|
||||
"image/png", 413)
|
||||
|
||||
message = client.message(alice, chat, "", attachments=[uploaded["id"]])["json"]
|
||||
check(message["attachment_ids"] == [uploaded["id"]],
|
||||
"message did not retain attachment_ids")
|
||||
history = client.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)["json"]["items"]
|
||||
check(any(item["id"] == message["id"] and
|
||||
item["attachment_ids"] == [uploaded["id"]] for item in history),
|
||||
"message history did not return attachment_ids")
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
message_path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
first = client.call(
|
||||
"POST", message_path, 201, actor=alice, body={"text": "semantic replay"},
|
||||
headers={"Idempotency-Key": key}, schema="Message",
|
||||
)["json"]
|
||||
replay = client.call(
|
||||
"POST", message_path, 201, actor=alice, body={"text": "semantic replay", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": key}, schema="Message",
|
||||
)["json"]
|
||||
check(replay == first, "missing attachment_ids and [] should be idempotently equivalent")
|
||||
|
||||
other_chat = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Different attachment scope", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other_chat["id"] + "/messages",
|
||||
404,
|
||||
actor=alice,
|
||||
body={"text": "", "attachment_ids": [uploaded["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
print("PASS: PNG upload/download, authorization, file limits, and message attachment links")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify concurrent same-key requests are shared across API replicas."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from threading import Barrier
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--requests', type=int, default=16)
|
||||
|
||||
args = arguments('Concurrent cross-replica idempotency check', configure)
|
||||
check(2 <= args.requests <= 64, '--requests must be between 2 and 64')
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'concurrent idempotency ' + key
|
||||
barrier = Barrier(args.requests)
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
def submit():
|
||||
worker = Client(args.base_url, args.ca_file)
|
||||
barrier.wait(timeout=10)
|
||||
return worker.call(
|
||||
'POST',
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body={'text': text},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.requests) as executor:
|
||||
responses = list(executor.map(lambda _: submit(), range(args.requests)))
|
||||
|
||||
messages = [response['json'] for response in responses]
|
||||
check(all(message == messages[0] for message in messages), 'replay response changed')
|
||||
instances = {response['headers']['X-Instance-Id'] for response in responses}
|
||||
check(len(instances) >= 2, 'concurrent requests did not reach two API replicas')
|
||||
|
||||
history = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats/' + chat['id'] + '/messages?limit=100',
|
||||
actor=bob,
|
||||
schema='MessagePage',
|
||||
)['json']['items']
|
||||
created = [message for message in history if message['text'] == text]
|
||||
check(created == [messages[0]], 'concurrent replay created duplicate messages')
|
||||
print(
|
||||
'PASS: %d concurrent requests across %d API replicas created one message'
|
||||
% (args.requests, len(instances))
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify bounded API errors during an S3 outage, then restore the service."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
command = [
|
||||
"docker", "compose", "--project-directory", str(ROOT),
|
||||
"--env-file", str(ROOT / ".env"), *args,
|
||||
]
|
||||
subprocess.run(
|
||||
command,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify API responses when MinIO is unavailable")
|
||||
client = Client(args.base_url, args.ca_file, timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
health = client.call("GET", "/health/ready", 503)
|
||||
if health["elapsed"] > 10:
|
||||
raise AssertionError("S3 readiness failure exceeded 10 seconds")
|
||||
upload = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote("sample.png"),
|
||||
503,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
if upload["elapsed"] > 10:
|
||||
raise AssertionError("S3 upload failure exceeded 10 seconds")
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
compose("up", "-d", "--wait", "s3")
|
||||
client.call("GET", "/health/ready", 200)
|
||||
|
||||
print("PASS: MinIO outage returns bounded 503 errors and recovers")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user