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

54 lines
1.9 KiB
Python

from concurrent.futures import ThreadPoolExecutor
import threading
import uuid
from client import Client, check, run
from pipeline_support import compose, ready_api, sql
def main():
ready_api()
client = Client(base_url="http://127.0.0.1:18085", timeout=30)
actor, _, _, chat = client.bootstrap()
limit = int(compose("exec", "-T", "api", "printenv", "MAX_MESSAGES_PER_CHAT"))
check(1 <= limit <= 10000, "unexpected test history capacity")
sql(
"insert into messages(id,chat_id,sender_id,text,created_at) "
"select gen_random_uuid(),'" + chat["id"] + "','" + actor["id"] + "','seed',now() "
"from generate_series(1," + str(limit - 1) + ");"
)
barrier = threading.Barrier(10)
def send(_):
barrier.wait()
return client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
[201, 413],
actor=actor,
body={"text": "last slot", "attachment_ids": []},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
with ThreadPoolExecutor(max_workers=10) as pool:
responses = list(pool.map(send, range(10)))
instances = {item["headers"].get("X-Instance-Id") for item in responses}
check(
len(instances) == 2 and None not in instances,
"last-slot race did not reach both API replicas",
)
confirmed = [item for item in responses if item["status"] == 201]
rejected = [item for item in responses if item["status"] == 413]
check(len(confirmed) == 1 and len(rejected) == 9, "history capacity raced across API replicas")
check(
int(sql("select count(*) from messages where chat_id='" + chat["id"] + "';")) == limit,
"history capacity exceeded in DB",
)
print(
"PASS history last-slot race: 10 simultaneous unique POSTs, exactly 1 committed and 9 rejected with 413; DB count equals configured limit"
)
if __name__ == "__main__":
run(main)