[+] add project

This commit is contained in:
2026-11-17 02:09:04 +03:00
parent ec540a1a72
commit 1fdd40bb42
42 changed files with 2963 additions and 52 deletions
+13
View File
@@ -55,3 +55,16 @@ make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.
## Что ещё остаётся доказать
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
## Дополнительные проверки lab4
```sh
make test-grade4
make test-s3-failure
make test-upload-load OUTPUT=evidence/upload-load.json
make test-reconcile
```
`test-grade4` проверяет слишком большой файл, повреждение, MIME-подмену, пиксельный лимит, опасное имя, cross-chat привязку, чужое вложение и конкурентную идемпотентность. `test-s3-failure` временно останавливает локальный Compose S3 и обязательно поднимает его обратно. `test-upload-load` отправляет десять параллельных синтетических JPEG и семплирует память API через `docker stats`; частота замеров ограничивает точность пика.
Reconciler `python scripts/reconcile.py` по умолчанию работает только в режиме dry-run и использует grace period 24 часа. Он рассматривает для удаления только старые объекты `attachments/`, для которых нет metadata, и старые missing metadata без ссылок в сообщениях. `--apply` включает исправление; уменьшать grace period до нуля можно лишь на disposable synthetic стенде. Ссылочные вложения и свежие объекты сохраняются. Missing object у используемого вложения выводится как защищённое несоответствие для ручного восстановления, автоматическое удаление metadata не выполняется. `make test-reconcile` создаёт синтетические сбои и демонстрирует dry-run, grace period, исправление и повторный запуск; команда не подходит для production или ценных данных.
View File
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Concurrent idempotency and replica-distribution checks."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import uuid
from client import Client, Failure, arguments, check, run
from image_fixture import solid_gray_png
def main():
args = arguments("Concurrent shared-idempotency and API-replica check")
client = Client(args.base_url, args.ca_file, timeout=5)
alice, bob, eve, chat = client.bootstrap()
key = uuid.uuid4().hex
body = {"text": "parallel-idempotency-" + key}
def send(_):
return Client(args.base_url, args.ca_file, timeout=5).call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
201,
body=body,
actor=alice,
headers={"Idempotency-Key": key},
schema="Message",
)
with ThreadPoolExecutor(max_workers=12) as executor:
responses = list(executor.map(send, range(12)))
messages = [response["json"] for response in responses]
check(all(message == messages[0] for message in messages), "concurrent replay differed")
conflict = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
409,
body={"text": "different body"},
actor=alice,
headers={"Idempotency-Key": key},
)
check(conflict["status"] == 409, "same key with a different body was accepted")
instances = {
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"][
"X-Instance-Id"
]
for _ in range(80)
}
check(len(instances) >= 2, "load balancer did not expose two API instances")
upload_path = "/api/v1/chats/" + chat["id"] + "/attachments"
fixture = (Path(__file__).parent / "fixtures" / "sample.png").read_bytes()
client.call(
"POST",
upload_path + "?filename=too-large.png",
413,
actor=alice,
raw=b"x" * (10 * 1024 * 1024 + 1),
headers={"Content-Type": "image/png"},
)
client.call(
"POST",
upload_path + "?filename=broken.png",
415,
actor=alice,
raw=b"\x89PNG\r\n\x1a\nnot-an-image",
headers={"Content-Type": "image/png"},
)
client.call(
"POST",
upload_path + "?filename=mime.jpg",
415,
actor=alice,
raw=fixture,
headers={"Content-Type": "image/jpeg"},
)
client.call(
"POST",
upload_path + "?filename=pixels.png",
413,
actor=alice,
raw=solid_gray_png(6401, 6251),
headers={"Content-Type": "image/png"},
)
client.call(
"POST",
upload_path + "?filename=..%2Fprivate.png",
400,
actor=alice,
raw=fixture,
headers={"Content-Type": "image/png"},
)
attachment, _ = client.attachment(alice, chat)
other_chat = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Другой чат", "member_ids": [alice["id"], bob["id"]]},
schema="Chat",
)["json"]
client.call(
"POST",
"/api/v1/chats/" + other_chat["id"] + "/messages",
404,
actor=alice,
body={"text": "", "attachment_ids": [attachment["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
for path in (
"/api/v1/attachments/" + attachment["id"],
"/api/v1/attachments/" + attachment["id"] + "/content",
):
client.call("GET", path, 404, actor=eve)
print("PASS: concurrent idempotency returned one message; observed %d API replicas" % len(instances))
print("PASS: level-4 attachment error, pixel limit, chat binding and outsider checks.")
if __name__ == "__main__":
run(main)
+36
View File
@@ -0,0 +1,36 @@
"""Small deterministic PNG builders for standard-library-only acceptance tests."""
import random
import struct
import zlib
def _chunk(name, data):
kind = name.encode("ascii")
return (
struct.pack(">I", len(data))
+ kind
+ data
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
)
def solid_gray_png(width, height):
row_size = (width + 7) // 8
raw = (b"\x00" + bytes(row_size)) * height
image_header = struct.pack(">IIBBBBB", width, height, 1, 0, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _chunk("IHDR", image_header) + _chunk(
"IDAT", zlib.compress(raw)
) + _chunk("IEND", b"")
def noisy_rgb_png(width, height, seed=42024):
image_header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
compressor = zlib.compressobj(level=1)
compressed = bytearray()
rng = random.Random(seed)
for _ in range(height):
compressed.extend(compressor.compress(b"\x00" + rng.randbytes(width * 3)))
compressed.extend(compressor.flush())
return b"\x89PNG\r\n\x1a\n" + _chunk("IHDR", image_header) + _chunk(
"IDAT", bytes(compressed)
) + _chunk("IEND", b"")
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Inject safe synthetic S3/DB inconsistencies and verify reconciliation."""
import json
import os
import subprocess
import sys
import uuid
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
from botocore import UNSIGNED
from client import Client, check
def reconcile(*options):
result = subprocess.run(
[sys.executable, "scripts/reconcile.py", *options],
capture_output=True,
text=True,
check=False,
)
check(result.returncode == 0, "reconciler command failed: " + result.stderr.strip())
return json.loads(result.stdout)
def upload(client, alice, chat):
return client.attachment(alice, chat)[0]
def main():
base_url = os.environ.get("RECONCILE_TEST_BASE_URL", "http://load_balancer:8080")
client = Client(base_url)
alice, _, _, chat = client.bootstrap()
linked = upload(client, alice, chat)
client.message(alice, chat, "", attachments=[linked["id"]])
missing_referenced = upload(client, alice, chat)
client.message(alice, chat, "", attachments=[missing_referenced["id"]])
missing_unreferenced = upload(client, alice, chat)
with open(os.environ["S3_ACCESS_KEY_ID_FILE"], encoding="utf-8") as file:
access_key = file.read().strip()
with open(os.environ["S3_SECRET_ACCESS_KEY_FILE"], encoding="utf-8") as file:
secret_key = file.read().strip()
s3 = boto3.client(
"s3",
endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
region_name=os.environ.get("S3_REGION", "us-east-1"),
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
config=Config(signature_version="s3v4", connect_timeout=2, read_timeout=5),
)
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
for attachment in (missing_referenced, missing_unreferenced):
s3.delete_object(Bucket=bucket, Key="attachments/" + attachment["id"])
fresh_orphan = "attachments/" + str(uuid.uuid4())
with open("tests/fixtures/sample.png", "rb") as file:
fixture = file.read()
s3.put_object(
Bucket=bucket,
Key=fresh_orphan,
Body=fixture,
ContentType="image/png",
)
denied = boto3.client(
"s3",
endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
region_name=os.environ.get("S3_REGION", "us-east-1"),
config=Config(signature_version=UNSIGNED, connect_timeout=2, read_timeout=5),
)
try:
denied.get_object(Bucket=bucket, Key="attachments/" + linked["id"])
raise AssertionError("private S3 bucket allowed an anonymous object read")
except ClientError as error:
check(
error.response["ResponseMetadata"]["HTTPStatusCode"] in {403, 404},
"anonymous S3 request did not fail as private access",
)
dry_run = reconcile("--grace-hours", "24")
check(dry_run["mode"] == "dry-run", "default reconciliation must be dry-run")
check(dry_run["orphan_fresh_preserved"] >= 1, "fresh orphan was not protected")
check(
dry_run["missing_referenced_or_fresh_preserved"] >= 2,
"referenced/fresh missing metadata was not protected",
)
applied_grace = reconcile("--apply", "--grace-hours", "24")
check(applied_grace["objects_deleted"] == 0, "grace run deleted fresh object")
check(applied_grace["metadata_deleted"] == 0, "grace run deleted fresh metadata")
s3.head_object(Bucket=bucket, Key=fresh_orphan)
s3.head_object(Bucket=bucket, Key="attachments/" + linked["id"])
repaired = reconcile("--apply", "--grace-hours", "0")
check(repaired["objects_deleted"] >= 1, "stale orphan object was not removed")
check(repaired["metadata_deleted"] >= 1, "stale unreferenced missing row was not removed")
check(
repaired["missing_referenced_or_fresh_preserved"] >= 1,
"missing referenced attachment was not protected",
)
repeated = reconcile("--apply", "--grace-hours", "0")
check(repeated["objects_deleted"] == 0, "repeated run was not idempotent for objects")
check(repeated["metadata_deleted"] == 0, "repeated run was not idempotent for metadata")
check(
client.call("GET", "/api/v1/attachments/" + linked["id"], actor=alice)["status"] == 200,
"reconciler removed a used attachment",
)
downloaded = client.call(
"GET", "/api/v1/attachments/" + linked["id"] + "/content", actor=alice
)
check(downloaded["bytes"] == fixture, "reconciler damaged a used attachment")
client.call(
"GET",
"/api/v1/attachments/" + missing_referenced["id"],
200,
actor=alice,
schema="Attachment",
)
client.call(
"GET",
"/api/v1/attachments/" + missing_unreferenced["id"],
404,
actor=alice,
)
print(
json.dumps(
{
"private_bucket_anonymous_read": "denied",
"dry_run_elapsed_seconds": dry_run["elapsed_seconds"],
"objects_scanned": dry_run["objects_scanned"],
"metadata_scanned": dry_run["metadata_scanned"],
"dry_run_orphan_candidates": dry_run["orphan_old_candidates"],
"fresh_orphan_preserved": applied_grace["orphan_fresh_preserved"],
"apply_deleted_objects": repaired["objects_deleted"],
"apply_deleted_unreferenced_metadata": repaired["metadata_deleted"],
"referenced_missing_metadata_preserved": True,
"repeat_deleted_objects": repeated["objects_deleted"],
"repeat_deleted_metadata": repeated["metadata_deleted"],
"used_attachment_preserved": True,
},
sort_keys=True,
)
)
if __name__ == "__main__":
main()
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""Fail one explicitly selected replica and write sanitized evidence."""
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
from urllib.parse import quote
from client import Client, Failure, arguments, check, run
def history(client, actor, chat):
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
messages = []
seen = set()
while True:
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
messages.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return messages
check(cursor not in seen, "history cursor cycle")
seen.add(cursor)
path = (
"/api/v1/chats/"
+ chat["id"]
+ "/messages?limit=100&cursor="
+ quote(cursor, safe="")
)
def main():
def configure(parser):
parser.add_argument("--target-id", required=True)
parser.add_argument("--action-script", required=True)
parser.add_argument("--output")
args = arguments("Targeted API failover evidence", configure)
target = args.target_id
script = Path(args.action_script).expanduser().resolve()
check(script.is_file() and os.access(script, os.X_OK), "action script must be executable")
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, _, chat = client.bootstrap()
observed_before = {
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"][
"X-Instance-Id"
]
for _ in range(40)
}
check(len(observed_before) >= 2, "fewer than two API replicas observed")
check(target in observed_before, "target ID is not a currently observed API replica")
original = None
for _ in range(20):
original = client.message(
alice, chat, "pre-failure-" + uuid.uuid4().hex, key=uuid.uuid4().hex
)
if original["headers"]["X-Instance-Id"] == target:
break
check(original["headers"]["X-Instance-Id"] == target, "could not select requested replica")
env = dict(os.environ)
env["TARGET_INSTANCE_ID"] = target
process = subprocess.Popen(
[str(script)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
started = time.monotonic()
recovered_at = None
successful_writes = []
failed_writes = 0
failed_reads = 0
served_after = []
key = uuid.uuid4().hex
text = "during-failover-" + key
try:
while time.monotonic() - started < 15:
status = process.poll()
check(status is None or status == 0, "action script failed")
check(status is not None or time.monotonic() - started < 10, "action script exceeded 10s")
try:
read = client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
served_after.append(read["headers"]["X-Instance-Id"])
except Failure:
failed_reads += 1
time.sleep(0.1)
continue
try:
response = client.message(alice, chat, text, key=key)
successful_writes.append(response["json"])
if status == 0 and recovered_at is None:
recovered_at = time.monotonic() - started
key = uuid.uuid4().hex
text = "during-failover-" + key
except Failure:
failed_writes += 1
time.sleep(0.1)
check(process.poll() == 0, "action script did not finish successfully")
check(recovered_at is not None and recovered_at <= 10, "writes did not recover within 10s")
check(len(successful_writes) >= 5, "too few successful writes after the failure")
check(target not in served_after[-5:], "stopped replica still serves requests")
all_messages = history(client, bob, chat)
ids = [message["id"] for message in all_messages]
texts = [message["text"] for message in all_messages]
check(len(ids) == len(set(ids)), "duplicate message IDs in history")
check(len(texts) == len(set(texts)), "retry created duplicate message bodies")
check(original["json"] in all_messages, "confirmed pre-failure message was lost")
for message in successful_writes:
check(message in all_messages, "confirmed failover write was lost")
elapsed = time.monotonic() - started
total_attempts = len(successful_writes) + failed_writes
result = {
"target_instance_id": target,
"observed_instances_before": len(observed_before),
"instances_serving_after": sorted(set(served_after)),
"duration_seconds": round(elapsed, 3),
"successful_writes": len(successful_writes),
"failed_write_attempts": failed_writes,
"failed_read_attempts": failed_reads,
"successful_rps": round(len(successful_writes) / elapsed, 3),
"write_error_ratio": round(failed_writes / total_attempts, 6),
"recovery_seconds": round(recovered_at, 3),
"confirmed_data_preserved": True,
"duplicate_messages": 0,
}
rendered = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(rendered, encoding="utf-8")
print(rendered, end="")
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
if __name__ == "__main__":
run(main)
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Verify uploads return an explicit 503 while the Compose S3 service is stopped."""
import json
from pathlib import Path
import subprocess
import time
from client import Client, ROOT, arguments, check, run
def compose(*args):
subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def healthy_api_container():
result = subprocess.run(
["docker", "compose", "ps", "-q", "api"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
for container in result.stdout.split():
health = subprocess.run(
["docker", "inspect", "--format", "{{.State.Health.Status}}", container],
check=True,
capture_output=True,
text=True,
)
if health.stdout.strip() == "healthy":
return container
raise AssertionError("no healthy API replica is available")
def main():
args = arguments("S3 outage behavior; stops and restores the local Compose S3 service")
client = Client(args.base_url, args.ca_file, timeout=15)
alice, _, _, chat = client.bootstrap()
fixture = (Path(__file__).parent / "fixtures" / "sample.png").read_bytes()
api_container = healthy_api_container()
stopped = False
try:
compose("stop", "s3")
stopped = True
payload = json.dumps(
{"alice": alice, "chat": chat, "fixture": fixture.hex()}
)
worker = subprocess.run(
[
"docker",
"exec",
"-i",
api_container,
"python",
"tests/s3_failure_worker.py",
],
cwd=ROOT,
input=payload,
text=True,
capture_output=True,
check=False,
)
check(worker.returncode == 0, "S3 failure worker failed: " + worker.stderr.strip())
check(worker.stdout.strip() == "PASS", "API did not return 503 for unavailable S3")
finally:
if stopped:
compose("up", "-d", "s3")
compose("run", "--rm", "--no-deps", "s3-bootstrap")
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
break
except AssertionError:
time.sleep(1)
else:
raise AssertionError("API did not become ready after S3 recovery")
print("PASS: upload returned 503 during S3 outage; bucket and API recovered with volumes intact.")
if __name__ == "__main__":
run(main)
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Internal worker for tests/s3_failure.py; reads auth data only from stdin."""
import json
import sys
import urllib.error
import urllib.request
def main():
payload = json.load(sys.stdin)
alice = payload["alice"]
chat = payload["chat"]
content = bytes.fromhex(payload["fixture"])
request = urllib.request.Request(
"http://127.0.0.1:8080/api/v1/chats/"
+ chat["id"]
+ "/attachments?filename=s3-down.png",
data=content,
headers={
"Authorization": "Bearer " + alice["token"],
"Content-Type": "image/png",
},
method="POST",
)
try:
urllib.request.urlopen(request, timeout=15)
except urllib.error.HTTPError as response:
if response.code != 503:
raise AssertionError("expected HTTP 503, received " + str(response.code))
body = json.loads(response.read())
request_id = response.headers.get("X-Request-Id")
if body.get("error", {}).get("code") != "unavailable":
raise AssertionError("expected unavailable error response")
if not request_id or body["error"].get("request_id") != request_id:
raise AssertionError("error request ID does not match response header")
if not response.headers.get("X-Instance-Id"):
raise AssertionError("missing API instance ID")
else:
raise AssertionError("expected HTTP 503 during the S3 outage")
print("PASS")
if __name__ == "__main__":
main()
+39
View File
@@ -0,0 +1,39 @@
import unittest
from datetime import datetime, timedelta, timezone
from scripts.reconcile import plan_reconciliation
class ReconcilePlanTests(unittest.TestCase):
def test_only_stale_orphans_and_old_unreferenced_rows_are_candidates(self):
now = datetime.now(timezone.utc)
old = now - timedelta(days=2)
fresh = now - timedelta(minutes=2)
metadata = [
{"id": "used", "object_key": "attachments/used", "created_at": old, "referenced": True},
{"id": "unreferenced", "object_key": "attachments/missing", "created_at": old, "referenced": False},
{"id": "fresh", "object_key": "attachments/fresh-missing", "created_at": fresh, "referenced": False},
]
objects = [
{"Key": "attachments/used", "LastModified": old},
{"Key": "attachments/orphan-old", "LastModified": old},
{"Key": "attachments/orphan-fresh", "LastModified": fresh},
{"Key": "unrelated/keep", "LastModified": old},
]
plan = plan_reconciliation(metadata, objects, now, timedelta(hours=24))
self.assertEqual(plan["orphan_old"], ["attachments/orphan-old"])
self.assertEqual(plan["orphan_fresh"], ["attachments/orphan-fresh"])
self.assertEqual(plan["missing_unreferenced_old"], ["unreferenced"])
self.assertEqual(plan["missing_protected"], ["fresh"])
def test_repeat_after_repair_has_no_candidates(self):
now = datetime.now(timezone.utc)
plan = plan_reconciliation([], [], now, timedelta(hours=24))
self.assertEqual(plan["orphan_old"], [])
self.assertEqual(plan["missing_unreferenced_old"], [])
if __name__ == "__main__":
unittest.main()
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Upload 10+ valid images concurrently and sample API container memory."""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
import re
import subprocess
import threading
import time
from client import Client, check
from image_fixture import noisy_rgb_png
def memory_bytes(value):
match = re.match(r"\s*([\d.]+)\s*([KMG]i?B)", value)
if not match:
return 0
amount = float(match.group(1))
unit = match.group(2).upper()
return int(
amount
* {
"KB": 1000,
"MB": 1000**2,
"GB": 1000**3,
"KIB": 1024,
"MIB": 1024**2,
"GIB": 1024**3,
}[unit]
)
def compose_api_ids():
result = subprocess.run(
["docker", "compose", "ps", "-q", "api"],
check=True,
capture_output=True,
text=True,
)
healthy_ids = []
for container_id in result.stdout.split():
health = subprocess.run(
["docker", "inspect", "--format", "{{.State.Health.Status}}", container_id],
check=True,
capture_output=True,
text=True,
)
if health.stdout.strip() == "healthy":
healthy_ids.append(container_id)
check(len(healthy_ids) >= 2, "need at least two healthy API containers for the measurement")
return healthy_ids
def sample_memory(ids, stop, peak):
while not stop.is_set():
for container_id in ids:
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", container_id],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
used = memory_bytes(result.stdout.split("/", 1)[0])
peak[container_id] = max(peak.get(container_id, 0), used)
stop.wait(0.5)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--concurrency", type=int, default=10)
parser.add_argument("--output", default=None)
args = parser.parse_args()
if args.concurrency < 10:
parser.error("--concurrency must be at least 10")
bootstrap = Client(args.base_url)
alice, _, _, chat = bootstrap.bootstrap()
content = noisy_rgb_png(1200, 1200)
check(0 < len(content) <= 10 * 1024 * 1024, "generated PNG must be within 10 MiB")
api_ids = compose_api_ids()
stop = threading.Event()
peak = {}
sampler = threading.Thread(target=sample_memory, args=(api_ids, stop, peak), daemon=True)
sampler.start()
started = time.monotonic()
attachment_ids = []
try:
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
tasks = [
executor.submit(
Client(args.base_url).call,
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=load.png",
201,
None,
alice,
{"Content-Type": "image/png"},
content,
"Attachment",
)
for _ in range(args.concurrency)
]
for task in as_completed(tasks):
attachment_ids.append(task.result()["json"]["id"])
finally:
stop.set()
sampler.join()
result = {
"concurrency": args.concurrency,
"upload_bytes_each": len(content),
"uploads_succeeded": len(attachment_ids),
"elapsed_seconds": round(time.monotonic() - started, 3),
"api_container_peak_memory_bytes": peak,
"api_container_ids": api_ids,
"notes": "Peak sampled every 0.5s using docker stats; excludes database, LB, and client memory.",
}
if len(attachment_ids) != args.concurrency:
raise SystemExit("not every upload succeeded")
output = json.dumps(result, indent=2, sort_keys=True)
if args.output:
with open(args.output, "w", encoding="utf-8") as file:
file.write(output + "\n")
print(output)
if __name__ == "__main__":
main()