173 lines
7.3 KiB
Python
173 lines
7.3 KiB
Python
"""Exercise the dedicated local Compose project using synthetic attachments."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, Failure, check
|
|
from image_probe import jpeg_size
|
|
|
|
|
|
def compose(*args):
|
|
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, encoding="utf-8")
|
|
|
|
|
|
def wait_for(action, description):
|
|
deadline = time.monotonic() + 70
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
result = action()
|
|
if result:
|
|
return result
|
|
except (Failure, subprocess.CalledProcessError):
|
|
pass
|
|
time.sleep(0.5)
|
|
raise Failure(description)
|
|
|
|
|
|
def queue_depth():
|
|
output = subprocess.check_output(
|
|
["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues",
|
|
"name", "messages_ready", "messages_unacknowledged"],
|
|
cwd=ROOT, text=True, encoding="utf-8", stderr=subprocess.PIPE,
|
|
)
|
|
for line in output.splitlines():
|
|
fields = line.split()
|
|
if fields and fields[0] == "attachment.process.v1":
|
|
return tuple(map(int, fields[1:]))
|
|
return None
|
|
|
|
|
|
def api_instances(client):
|
|
instances = {client.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"]
|
|
for _ in range(4)}
|
|
return instances if len(instances) == 2 else None
|
|
|
|
|
|
def duplicate(attachment_id):
|
|
code = """
|
|
import sys
|
|
from src.jobs import broker, database, publish
|
|
with database() as db, broker() as connection:
|
|
job = db.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s', (sys.argv[1],)).fetchone()
|
|
channel = connection.channel()
|
|
channel.confirm_delivery()
|
|
publish(channel, job, job['attempts'])
|
|
"""
|
|
compose("exec", "-T", "dispatcher", "python", "-c", code, attachment_id)
|
|
|
|
|
|
def check_retry_limit(client, alice, bob, chat):
|
|
compose("stop", "worker")
|
|
attachment, _ = client.attachment(alice, chat)
|
|
path = "/api/v1/attachments/" + attachment["id"]
|
|
# Remove only the staging object created for this synthetic case.
|
|
code = """
|
|
import sys
|
|
from uuid import UUID
|
|
from src.objects import Objects
|
|
objects = Objects()
|
|
try:
|
|
objects.delete('staging/' + UUID(sys.argv[1]).hex)
|
|
finally:
|
|
objects.close()
|
|
"""
|
|
compose("run", "--rm", "--no-deps", "-T", "worker", "python", "-c", code, attachment["id"])
|
|
compose("start", "worker")
|
|
|
|
def failed():
|
|
result = client.call("GET", path, actor=bob, schema="Attachment")["json"]
|
|
return result if result["status"] == "failed" else None
|
|
|
|
terminal = wait_for(failed, "Missing staging object did not reach failed")
|
|
check(terminal["error_code"] == "retry_exhausted", "Unexpected final error")
|
|
client.call("GET", path + "/content", 409, actor=bob)
|
|
code = """
|
|
import sys
|
|
from src.jobs import MAX_ATTEMPTS, database
|
|
with database() as db:
|
|
job = db.execute('SELECT attempts,publish_at FROM attachment_jobs WHERE attachment_id=%s',
|
|
(sys.argv[1],)).fetchone()
|
|
assert job['attempts'] == MAX_ATTEMPTS and job['publish_at'] is None
|
|
print(job['attempts'])
|
|
"""
|
|
attempts = int(compose("exec", "-T", "worker", "python", "-c", code, attachment["id"]).strip())
|
|
return {"attachment_id": attachment["id"], "attempts": attempts,
|
|
"status": terminal["status"], "error_code": terminal["error_code"]}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", default="https://localhost:8443")
|
|
parser.add_argument("--ca-file", default=str(ROOT / "secrets/pki/ca.crt"))
|
|
parser.add_argument("--output", type=Path)
|
|
args = parser.parse_args()
|
|
client = Client(args.base_url, args.ca_file)
|
|
alice, bob, _, chat = client.bootstrap()
|
|
compose("stop", "worker")
|
|
try:
|
|
check(queue_depth() == (0, 0), "Expected an idle lab queue before the test")
|
|
attachment, original = client.attachment(alice, chat)
|
|
path = "/api/v1/attachments/" + attachment["id"]
|
|
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
|
client.call("GET", path + "/content", 409, actor=bob)
|
|
wait_for(lambda: queue_depth() == (1, 0), "RabbitMQ did not receive the job")
|
|
compose("stop", "dispatcher")
|
|
old_instances = wait_for(lambda: api_instances(client), "Expected two ready API replicas")
|
|
compose("restart", "api1", "api2", "broker")
|
|
new_instances = wait_for(lambda: api_instances(client), "Both API replicas did not come back")
|
|
check(old_instances.isdisjoint(new_instances), "An API process did not restart")
|
|
wait_for(lambda: queue_depth() == (1, 0), "Job did not survive RabbitMQ restart")
|
|
client.call("GET", path + "/content", 409, actor=bob)
|
|
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob,
|
|
schema="MessagePage")["json"]
|
|
check(message in history["items"], "Message missing after API restart")
|
|
compose("start", "worker")
|
|
ready = client.wait_ready(bob, attachment)
|
|
downloaded = client.call("GET", path + "/content", actor=bob)["bytes"]
|
|
check(downloaded == original, "Original bytes changed")
|
|
thumbnail_path = path + "/content?variant=thumbnail"
|
|
image = client.call("GET", thumbnail_path, actor=bob)["bytes"]
|
|
check(jpeg_size(image) == (256, 160), "Unexpected thumbnail dimensions")
|
|
check(len(ready["variants"]) == 1, "Expected exactly one variant")
|
|
check(ready["variants"][0]["sha256"] == hashlib.sha256(image).hexdigest(), "Thumbnail checksum mismatch")
|
|
wait_for(lambda: queue_depth() == (0, 0), "Worker did not acknowledge the job")
|
|
compose("stop", "worker")
|
|
compose("start", "dispatcher")
|
|
duplicate(attachment["id"])
|
|
wait_for(lambda: queue_depth() == (1, 0), "Duplicate was not published")
|
|
compose("start", "worker")
|
|
wait_for(lambda: queue_depth() == (0, 0), "Duplicate was not acknowledged")
|
|
check(client.call("GET", path, actor=bob, schema="Attachment")["json"] == ready,
|
|
"Duplicate changed ready metadata")
|
|
check(client.call("GET", thumbnail_path, actor=bob)["bytes"] == image, "Duplicate changed JPEG")
|
|
result = {
|
|
"attachment_id": attachment["id"], "message_id": message["id"], "upload_status": 202,
|
|
"content_while_queued": 409, "queued_jobs_after_broker_restart_with_dispatcher_stopped": 1,
|
|
"api_instance_ids_before": sorted(old_instances), "api_instance_ids_after": sorted(new_instances),
|
|
"message_preserved_after_restart": True, "final_status": ready["status"],
|
|
"original_bytes_match": True, "thumbnail": ready["variants"][0], "duplicate_acknowledged": True,
|
|
"duplicate_preserved_metadata_and_bytes": True,
|
|
"retry_limit": check_retry_limit(client, alice, bob, chat),
|
|
}
|
|
rendered = json.dumps(result, indent=2)
|
|
if args.output:
|
|
args.output.write_text(rendered + "\n", encoding="utf-8")
|
|
print(rendered)
|
|
finally:
|
|
compose("start", "dispatcher", "worker")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
for variable in ("NO_PROXY", "no_proxy"):
|
|
os.environ[variable] = ",".join(filter(None, (os.environ.get(variable), "127.0.0.1", "localhost")))
|
|
main()
|