ЛР4 - БПИ2303 - Стругов - на 4
This commit is contained in:
+5
-1
@@ -49,7 +49,11 @@ def validate(value, schema, where='response'):
|
||||
check(value == schema['const'], where + ': invalid const')
|
||||
if isinstance(value,dict):
|
||||
props = schema.get('properties',{})
|
||||
check(all(k in value for k in schema.get('required',[])), where + ': missing required fields')
|
||||
missing = set(schema.get('required', [])) - set(value)
|
||||
check(
|
||||
not missing,
|
||||
f"{where}: missing required fields {sorted(missing)}; received fields {sorted(value)}"
|
||||
)
|
||||
if schema.get('additionalProperties') is False:
|
||||
check(not set(value).difference(props), where + ': unexpected fields')
|
||||
for key, sub in props.items():
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Concurrent Idempotency-Key test for lab 3."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Concurrent idempotency test")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
message_text = "concurrent-idempotency-" + uuid.uuid4().hex
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
workers = 20
|
||||
barrier = threading.Barrier(workers)
|
||||
|
||||
def send(_):
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier.wait()
|
||||
|
||||
response = local.message(
|
||||
alice,
|
||||
chat,
|
||||
message_text,
|
||||
key=key,
|
||||
)
|
||||
|
||||
return {
|
||||
"id": response["json"]["id"],
|
||||
"instance": response["headers"].get("X-Instance-Id"),
|
||||
"message": response["json"],
|
||||
}
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as executor:
|
||||
results = list(executor.map(send, range(workers)))
|
||||
|
||||
ids = {r["id"] for r in results}
|
||||
instances = {r["instance"] for r in results if r["instance"]}
|
||||
|
||||
print(f"Concurrent requests: {workers}")
|
||||
print(f"Unique message IDs: {len(ids)}")
|
||||
print(f"Observed API instances: {len(instances)}")
|
||||
print(f"Instance IDs: {sorted(instances)}")
|
||||
|
||||
check(len(ids) == 1, "duplicate messages were created")
|
||||
check(
|
||||
all(r["message"] == results[0]["message"] for r in results),
|
||||
"idempotency responses differ",
|
||||
)
|
||||
check(len(instances) >= 2, "requests did not reach two API instances")
|
||||
|
||||
# Verify that the stored chat history contains exactly one copy.
|
||||
history = client.call(
|
||||
"GET",
|
||||
path + "?limit=100",
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
|
||||
matches = [
|
||||
item for item in history["items"]
|
||||
if item["text"] == message_text
|
||||
]
|
||||
|
||||
check(len(matches) == 1, "chat history contains duplicate messages")
|
||||
check(matches[0]["id"] in ids, "stored message ID differs")
|
||||
|
||||
print("PASS: concurrent idempotency across API replicas")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 4: ten simultaneous attachment uploads through the public API."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from client import Client, check, Failure, ROOT
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=parallel.png"
|
||||
|
||||
def upload(i):
|
||||
client = Client(args.base_url, timeout=30)
|
||||
start = time.monotonic()
|
||||
response = client.call("POST", path, 201, actor=alice, raw=data,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
att = response["json"]
|
||||
check(att["status"] == "ready", f"upload {i}: not ready")
|
||||
check(att["chat_id"] == chat["id"], f"upload {i}: wrong chat")
|
||||
check(att["size_bytes"] == len(data) and att["sha256"] == digest,
|
||||
f"upload {i}: incorrect metadata")
|
||||
return att, (time.monotonic() - start) * 1000
|
||||
|
||||
start = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures = [pool.submit(upload, i) for i in range(10)]
|
||||
results = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
elapsed = time.monotonic() - start
|
||||
ids = [att["id"] for att, _ in results]
|
||||
check(len(set(ids)) == 10, "duplicate attachment IDs")
|
||||
for att, _ in results:
|
||||
response = c.call("GET", f"/api/v1/attachments/{att['id']}/content",
|
||||
actor=bob)
|
||||
check(response["bytes"] == data, f"download differs: {att['id']}")
|
||||
check(response["headers"].get_content_type() == "image/png",
|
||||
f"incorrect content type: {att['id']}")
|
||||
|
||||
times = sorted(ms for _, ms in results)
|
||||
print(json.dumps({
|
||||
"result": "PASS",
|
||||
"simultaneous_uploads": 10,
|
||||
"successful_uploads": len(results),
|
||||
"unique_objects": len(set(ids)),
|
||||
"download_verified": len(results),
|
||||
"bytes_per_object": len(data),
|
||||
"upload_batch_seconds": round(elapsed, 3),
|
||||
"upload_latency_ms": {
|
||||
"min": round(times[0], 2),
|
||||
"median": round((times[4] + times[5]) / 2, 2),
|
||||
"max": round(times[-1], 2)
|
||||
}
|
||||
}, indent=2))
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (Failure, OSError, ValueError) as exc:
|
||||
print("FAIL:", exc)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user