Files
mtusi2026lab5/tests/pipeline_upload_crash.py
2026-11-06 21:15:31 +03:00

87 lines
3.3 KiB
Python

from concurrent.futures import ThreadPoolExecutor
import json
import uuid
from pathlib import Path
from client import Client, check, run
from pipeline_support import compose, ready_api, sql, wait_for, wait_ready
def staging_keys():
code = """import json
from pipeline.config import Settings
from pipeline.storage import Storage
s=Storage(Settings())
print(json.dumps([o['Key'] for p in s.client.get_paginator('list_objects_v2').paginate(Bucket=s.settings.bucket,Prefix='staging/') for o in p.get('Contents',[])]))
"""
return set(json.loads(compose("exec", "-T", "dispatcher", "python", "-c", code)))
def main():
ready_api()
client = Client(base_url="http://127.0.0.1:18085", timeout=45)
actor, _, _, chat = client.bootstrap()
filename = "crash-" + uuid.uuid4().hex + ".png"
before = staging_keys()
sql(
"create function proof_upload_crash() returns trigger language plpgsql as $$ begin "
"if NEW.filename='"
+ filename
+ "' then perform pg_sleep(45); end if; return NEW; end; $$; "
"create trigger proof_upload_crash before insert on attachments "
"for each row execute function proof_upload_crash();"
)
try:
with ThreadPoolExecutor(max_workers=1) as pool:
request = pool.submit(
client.call,
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + filename,
202,
actor=actor,
raw=Path("tests/fixtures/sample.png").read_bytes(),
headers={"Content-Type": "image/png"},
schema="Attachment",
)
wait_for(
lambda: sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")
!= "0",
15,
"upload did not reach S3-before-COMMIT window",
)
orphan = staging_keys() - before
check(len(orphan) == 1, "no staged source before attachment COMMIT")
compose("kill", "-s", "SIGKILL", "api")
try:
request.result(timeout=20)
except Exception:
pass
else:
raise AssertionError("killed upload returned a confirmed attachment")
check(
sql("select count(*) from attachments where filename='" + filename + "';") == "0",
"uncommitted attachment survived process death",
)
for key in orphan:
check(
sql("select count(*) from attachments where staging_key='" + key + "';") == "0",
"orphan unexpectedly referenced",
)
finally:
sql("drop trigger proof_upload_crash on attachments; drop function proof_upload_crash();")
compose("start", "api")
ready_api()
attachment, body = client.attachment(actor, chat)
wait_ready(client, actor, attachment)
downloaded = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", 200, actor=actor
)
check(downloaded["bytes"] == body, "upload after API recovery corrupted")
print(
"PASS SIGKILL after S3 PUT before DB COMMIT: no confirmed response, DB rolled back, staged orphan unreferenced; same session uploads after recovery"
)
if __name__ == "__main__":
run(main)