forked from mtusi2026/mtusi2026lab4
57 lines
2.5 KiB
Python
57 lines
2.5 KiB
Python
import base64, hashlib, json, struct, subprocess, time, urllib.error, urllib.request, uuid, zlib
|
|
|
|
BASE = "http://localhost:8080"; PWD = "correct-horse-battery-staple"
|
|
|
|
|
|
def call(method, path, body=None, headers=None, token=None, basic=None, timeout=10):
|
|
h = dict(headers or {})
|
|
if token: h["Authorization"] = "Bearer " + token
|
|
if basic: h["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
|
|
req = urllib.request.Request(BASE + path, data=body, method=method, headers=h)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return r.status, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
|
|
|
|
def jcall(method, path, obj, token=None):
|
|
st, raw = call(method, path, json.dumps(obj).encode(), {"Content-Type": "application/json"}, token)
|
|
return st, json.loads(raw or b"null")
|
|
|
|
|
|
def tiny_png():
|
|
def chunk(t, d):
|
|
c = struct.pack(">I", len(d)) + t + d
|
|
return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
|
|
raw = b"".join(b"\x00" + b"\xff\x00\x00" * 8 for _ in range(8))
|
|
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0))
|
|
+ chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
|
|
|
|
|
|
name = "pr_" + uuid.uuid4().hex[:8]
|
|
_, user = jcall("POST", "/api/v1/users", {"username": name, "display_name": "probe", "password": PWD})
|
|
st, raw = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}")
|
|
tok = json.loads(raw)["token"]
|
|
_, chat = jcall("POST", "/api/v1/chats", {"title": "probe", "member_ids": [user["id"]]}, tok)
|
|
png = tiny_png()
|
|
st, raw = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=probe.png", png,
|
|
{"Content-Type": "image/png"}, tok)
|
|
att = json.loads(raw)
|
|
print("upload:", st, att.get("id"))
|
|
want = hashlib.sha256(png).hexdigest()
|
|
|
|
t0 = time.time()
|
|
subprocess.run(["docker", "compose", "restart", "seaweedfs"], capture_output=True)
|
|
print(f"restart seaweedfs returned after {time.time() - t0:.1f}s")
|
|
while time.time() - t0 < 90:
|
|
t1 = time.time()
|
|
try:
|
|
st, data = call("GET", f"/api/v1/attachments/{att['id']}/content", token=tok, timeout=5)
|
|
ok = st == 200 and hashlib.sha256(data).hexdigest() == want
|
|
print(f"t={time.time() - t0:5.1f}s status={st} bytes_ok={ok} took={time.time() - t1:.1f}s")
|
|
if ok:
|
|
break
|
|
except Exception as e:
|
|
print(f"t={time.time() - t0:5.1f}s {type(e).__name__} took={time.time() - t1:.1f}s")
|
|
time.sleep(1) |