Files
mtusi2026lab4/tests/upload_abort_check.py
T

159 lines
4.2 KiB
Python

from __future__ import annotations
import base64
import hashlib
import http.client
import json
import secrets
import struct
import time
import urllib.request
import zlib
from app.cleanup_orphans import database_connection
from app.storage import bucket_name, get_client
BASE = "http://lb:8080/api/v1"
token = None
def api(method, path, *, payload=None, data=None, headers=None):
headers = dict(headers or {})
if token and "Authorization" not in headers:
headers["Authorization"] = "Bearer " + token
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
request = urllib.request.Request(
BASE + path, method=method, headers=headers, data=data
)
with urllib.request.urlopen(request, timeout=15) as response:
assert response.code == 201
return json.loads(response.read())
def chunk(kind, content):
return (
struct.pack(">I", len(content))
+ kind + content
+ struct.pack(">I", zlib.crc32(kind + content) & 0xffffffff)
)
image = (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(b"\x00\x12\x34\x56"))
+ chunk(b"IEND", b"")
)
username = "abort_" + secrets.token_hex(6)
password = "Lab4-" + secrets.token_hex(16)
user = api(
"POST", "/users",
payload={
"username": username,
"display_name": "Upload abort check",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
session = api(
"POST", "/auth/sessions",
headers={"Authorization": "Basic " + basic},
)
token = session["token"]
chat = api(
"POST", "/chats",
payload={
"title": "Upload abort check",
"member_ids": [user["id"]],
},
)
chat_id = chat["id"]
client = get_client()
bucket = bucket_name()
def object_keys():
return {
item["Key"]
for page in client.get_paginator("list_objects_v2").paginate(
Bucket=bucket, Prefix="originals/"
)
for item in page.get("Contents", [])
}
before = object_keys()
for number in range(1, 4):
connection = http.client.HTTPConnection("api", 8080, timeout=10)
try:
connection.request("GET", "/health/live")
response = connection.getresponse()
response.read()
assert response.status == 200
instance = response.getheader("X-Instance-Id")
connection.putrequest(
"POST",
f"/api/v1/chats/{chat_id}/attachments"
f"?filename=aborted-{number}.png",
)
connection.putheader("Authorization", "Bearer " + token)
connection.putheader("Content-Type", "image/png")
connection.putheader("Content-Length", str(len(image)))
connection.endheaders()
connection.send(image[:len(image) // 2])
time.sleep(0.3)
finally:
connection.close()
print(
f"Соединение {number} оборвано после половины тела; "
f"instance={instance}",
flush=True,
)
time.sleep(2)
with database_connection() as conn:
count = conn.execute(
"SELECT count(*) AS n FROM attachments WHERE chat_id = %s",
(chat_id,),
).fetchone()["n"]
assert count == 0, f"Появились метаданные: {count}"
print("OK: метаданные незавершённых загрузок не созданы", flush=True)
new_keys = object_keys() - before
assert not new_keys, f"Появились новые S3-ключи: {new_keys}"
print("OK: новые S3-объекты не появились", flush=True)
attachment = api(
"POST",
f"/chats/{chat_id}/attachments?filename=complete.png",
data=image,
headers={"Content-Type": "image/png"},
)
assert attachment["sha256"] == hashlib.sha256(image).hexdigest()
request = urllib.request.Request(
BASE + f"/attachments/{attachment['id']}/content",
headers={"Authorization": "Bearer " + token},
)
with urllib.request.urlopen(request, timeout=15) as response:
assert response.read() == image
print("OK: последующая загрузка и скачивание успешны", flush=True)
print("PASS: interrupted uploads leave no metadata or objects", flush=True)