forked from mtusi2026/mtusi2026lab2
Выполнила лабораторную 2
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Demonstrate that restarting lab1 clears the in-memory state."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def request(base_url, method, path, body=None, actor=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if actor:
|
||||
headers["X-User-Id"] = actor
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = Request(base_url + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
response = urlopen(request, timeout=3)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
if not response.headers.get("X-Request-Id"):
|
||||
raise RuntimeError("API response is missing X-Request-Id")
|
||||
return response.status, payload
|
||||
|
||||
|
||||
def wait_ready(base_url, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
status, _ = request(base_url, "GET", "/health/ready")
|
||||
if status == 200:
|
||||
return
|
||||
except (OSError, URLError, TimeoutError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("API did not become ready within %s seconds" % timeout)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
parser.add_argument("--container", default=os.environ.get("CONTAINER_NAME", "mtusi-messenger-lab1"))
|
||||
args = parser.parse_args()
|
||||
base_url = args.base_url.rstrip("/")
|
||||
|
||||
username = "lifecycle_" + uuid.uuid4().hex[:12]
|
||||
status, user = request(base_url, "POST", "/api/v1/users", {
|
||||
"username": username,
|
||||
"display_name": "Lifecycle demo",
|
||||
})
|
||||
if status != 201:
|
||||
raise RuntimeError("user creation returned HTTP %s" % status)
|
||||
|
||||
status, chat = request(base_url, "POST", "/api/v1/chats", {
|
||||
"title": "Lifecycle demo",
|
||||
"member_ids": [user["id"]],
|
||||
}, actor=user["id"])
|
||||
if status != 201:
|
||||
raise RuntimeError("chat creation returned HTTP %s" % status)
|
||||
|
||||
message_text = "persisted only while this process is alive"
|
||||
status, message = request(base_url, "POST", "/api/v1/chats/%s/messages" % chat["id"], {
|
||||
"text": message_text,
|
||||
}, actor=user["id"])
|
||||
if status != 201:
|
||||
raise RuntimeError("message creation returned HTTP %s" % status)
|
||||
|
||||
status, page = request(base_url, "GET", "/api/v1/chats/%s/messages" % chat["id"], actor=user["id"])
|
||||
if status != 200 or not any(item["id"] == message["id"] for item in page["items"]):
|
||||
raise RuntimeError("created message was not readable before restart")
|
||||
print("before restart: user_id=%s message_id=%s message_read=yes" % (user["id"], message["id"]))
|
||||
|
||||
subprocess.run(["docker", "restart", "--timeout", "5", args.container], check=True, capture_output=True, text=True)
|
||||
wait_ready(base_url)
|
||||
status, error = request(base_url, "GET", "/api/v1/users/me", actor=user["id"])
|
||||
if status != 401 or error.get("error", {}).get("code") != "unauthorized":
|
||||
raise RuntimeError("old X-User-Id should be rejected after restart; got HTTP %s" % status)
|
||||
print("after restart: old_user_id_status=%s code=%s state_reset=yes" % (status, error["error"]["code"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user