лаба 4 на оценку 5

This commit is contained in:
2026-10-30 12:27:49 +03:00
parent 7860d81fa1
commit f9444a3965
59 changed files with 4696 additions and 90 deletions
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Black-box attachment validation and exact contract-boundary checks."""
import os
import struct
import zlib
from attachment_memory import cleanup, noisy_png, png_chunk
from client import Client, check, run
MAX_BYTES = 10 * 1024 * 1024
def exact_size_png(sample, target_size=MAX_BYTES):
check(sample.endswith(png_chunk(b"IEND", b"")), "sample PNG has no final IEND")
prefix, iend = sample[:-12], sample[-12:]
filler_size = target_size - len(prefix) - len(iend) - 12
check(filler_size >= 0, "sample PNG is larger than boundary")
result = prefix + png_chunk(b"ruSt", bytes(filler_size)) + iend
check(len(result) == target_size, "exact-size PNG construction failed")
return result
def exact_pixel_png(width=10_000, height=4_000):
compressor = zlib.compressobj(level=9)
row = bytes(1 + width * 3)
parts = []
for _ in range(height):
chunk = compressor.compress(row)
if chunk:
parts.append(chunk)
parts.append(compressor.flush())
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", b"".join(parts))
+ png_chunk(b"IEND", b"")
)
def config_only_png(width, height):
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
)
def upload(client, actor, chat, filename, payload, expected, schema=None):
return client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename),
expected,
actor=actor,
raw=payload,
headers={"Content-Type": "image/png"},
schema=schema,
)
def main():
client = Client(os.environ.get("BASE_URL"), None, timeout=30)
alice, bob, eve, chat = client.bootstrap()
users = [alice["id"], bob["id"], eve["id"]]
sample = open(os.path.join(os.path.dirname(__file__), "fixtures", "sample.png"), "rb").read()
try:
boundary = exact_size_png(sample)
response = upload(client, alice, chat, "exact-10mib.png", boundary, 201, "Attachment")
attachment = response["json"]
check(attachment["size_bytes"] == MAX_BYTES, "10 MiB boundary size changed")
downloaded = client.call(
"GET", "/api/v1/attachments/%s/content" % attachment["id"],
200, actor=alice,
)["bytes"]
check(downloaded == boundary, "10 MiB original changed after round trip")
pixels = exact_pixel_png()
upload(client, alice, chat, "exact-40m-pixels.png", pixels, 201, "Attachment")
upload(client, alice, chat, "over-pixels.png", config_only_png(20_000, 10_000), 413)
upload(client, alice, chat, "truncated.png", sample[:33], 415)
corrupted = noisy_png()
check(len(corrupted) > 70_000, "corruption fixture is too small")
corrupted = bytearray(corrupted)
corrupted[70_000] ^= 0xff
upload(client, alice, chat, "corrupt-after-prefix.png", bytes(corrupted), 415)
upload(client, alice, chat, "%20%20%20", sample, 400)
upload(client, alice, chat, "c1%C2%85.png", sample, 400)
upload(client, alice, chat, "invalid-%FF.png", sample, 400)
print("PASS: exact byte/pixel boundaries, complete decode, and filename validation are correct.")
finally:
cleanup(chat["id"], users)
if __name__ == "__main__":
run(main)
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Concurrent real PNG uploads with Docker API-container memory sampling."""
import concurrent.futures
import json
import os
import struct
import subprocess
import threading
import time
import uuid
import zlib
from client import Client, check, run
def png_chunk(kind, payload):
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload))
def noisy_png(width=2048, height=1024):
rows = bytearray()
for _ in range(height):
rows.append(0)
rows.extend(os.urandom(width * 3))
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", zlib.compress(bytes(rows), level=0))
+ png_chunk(b"IEND", b"")
)
def bytes_from_docker(value):
number, unit = value.split()[0], value.split()[0][-3:]
if unit in {"KiB", "MiB", "GiB"}:
number = value.split()[0][:-3]
else:
unit = "B"
factor = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}[unit]
return int(float(number) * factor)
def api_container_ids():
result = subprocess.run(
["docker", "compose", "ps", "-q", "api"],
check=True, text=True, capture_output=True,
)
return [line for line in result.stdout.splitlines() if line]
def sample_memory(container_ids, stop_event, peaks):
while not stop_event.is_set():
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}", *container_ids],
check=False, text=True, capture_output=True,
)
if result.returncode == 0:
for line in result.stdout.splitlines():
name, usage = line.split("\t", 1)
current = bytes_from_docker(usage.split(" / ", 1)[0])
peaks[name] = max(peaks.get(name, 0), current)
stop_event.wait(0.05)
def cleanup(chat_id, user_ids):
object_script = (
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mc rm --recursive --force "local/${S3_BUCKET}/attachments/' + chat_id + '/" >/dev/null 2>&1 || true\n'
)
subprocess.run(
["docker", "compose", "run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", object_script],
check=True,
)
quoted_users = ",".join("'%s'" % value for value in user_ids)
sql = f"""
BEGIN;
DELETE FROM messages WHERE chat_id = '{chat_id}';
DELETE FROM attachments WHERE chat_id = '{chat_id}';
DELETE FROM sessions WHERE user_id IN ({quoted_users});
DELETE FROM chat_members WHERE chat_id = '{chat_id}';
DELETE FROM chats WHERE id = '{chat_id}';
DELETE FROM users WHERE id IN ({quoted_users});
COMMIT;
"""
subprocess.run(
["docker", "compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger"],
input=sql, text=True, check=True,
)
def main():
concurrency = 12
base_url = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
client = Client(base_url, None, timeout=30)
alice, bob, eve, chat = client.bootstrap()
users = [alice["id"], bob["id"], eve["id"]]
payload = noisy_png()
stop_event = threading.Event()
peaks = {}
sampler = threading.Thread(
target=sample_memory,
args=(api_container_ids(), stop_event, peaks),
daemon=True,
)
sampler.start()
started = time.monotonic()
def upload(index):
response = client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=memory-%02d.png" % (chat["id"], index),
201,
actor=alice,
raw=payload,
headers={"Content-Type": "image/png", "X-Load-Id": uuid.uuid4().hex},
schema="Attachment",
)
return response["headers"]["X-Instance-Id"]
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
instances = list(pool.map(upload, range(concurrency)))
elapsed = time.monotonic() - started
stop_event.set()
sampler.join(timeout=10)
check(len(set(instances)) >= 2, "uploads did not exercise both API replicas")
check(len(peaks) >= 2, "memory was not sampled for both API replicas")
summary = {
"concurrency": concurrency,
"payload_bytes": len(payload),
"total_uploaded_bytes": len(payload) * concurrency,
"elapsed_seconds": round(elapsed, 3),
"successful_uploads": len(instances),
"api_instances_observed": len(set(instances)),
"peak_memory_bytes_by_container": peaks,
}
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
print("PASS: concurrent attachment uploads remained within configured API memory limits.")
finally:
stop_event.set()
sampler.join(timeout=10)
cleanup(chat["id"], users)
if __name__ == "__main__":
run(main)
+52
View File
@@ -0,0 +1,52 @@
#!/bin/sh
set -eu
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_root"
api_containers=$(docker compose ps -q api)
if [ -z "$api_containers" ]; then
printf "%s\n" "no running API containers found" >&2
exit 1
fi
for container_id in $api_containers; do
docker exec "$container_id" sh -ec '
test ! -e /run/secrets/minio_root_user
test ! -e /run/secrets/minio_root_password
! env | grep -Eq "^MINIO_ROOT_(USER|PASSWORD)="
'
done
docker compose run --rm --entrypoint /bin/sh minio-bootstrap -ec '
root_user="$(cat /run/secrets/minio_root_user)"
root_password="$(cat /run/secrets/minio_root_password)"
api_user="$(cat /run/secrets/s3_access_key_id)"
api_password="$(cat /run/secrets/s3_secret_access_key)"
probe_key="policy-probe/object.txt"
mc alias set admin http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null
mc alias set limited http://minio:9000 "$api_user" "$api_password" --api S3v4 >/dev/null
cleanup() {
mc rm --force "admin/${S3_BUCKET}/${probe_key}" >/dev/null 2>&1 || true
mc rb --force "admin/forbidden-policy-probe" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM
printf private-probe | mc pipe "limited/${S3_BUCKET}/${probe_key}" >/dev/null
mc stat "limited/${S3_BUCKET}/${probe_key}" >/dev/null
mc cat "limited/${S3_BUCKET}/${probe_key}" >/dev/null
if mc mb "limited/forbidden-policy-probe" >/dev/null 2>&1; then
printf "%s\n" "limited API credentials unexpectedly created another bucket" >&2
exit 1
fi
if wget -qO- "http://minio:9000/${S3_BUCKET}/${probe_key}" >/dev/null 2>&1; then
printf "%s\n" "anonymous HTTP GET unexpectedly read a private object" >&2
exit 1
fi
mc rm --force "limited/${S3_BUCKET}/${probe_key}" >/dev/null
trap - EXIT INT TERM
printf "%s\n" "PASS: API has no MinIO root credentials; limited policy permits object IO only in the private bucket; anonymous GET is denied."
'
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Inject isolated DB/S3 inconsistencies and prove reconciler dry-run/apply/repeat."""
import json
import os
import subprocess
import time
USER_ID = "90000000-0000-4000-8000-000000000001"
CHAT_ID = "90000000-0000-4000-8000-000000000002"
MISSING_ID = "90000000-0000-4000-8000-000000000011"
PROTECTED_ID = "90000000-0000-4000-8000-000000000012"
PENDING_ID = "90000000-0000-4000-8000-000000000013"
MESSAGE_ID = "90000000-0000-4000-8000-000000000021"
PREFIX = "attachments/reconcile-integration"
ORPHAN_KEY = PREFIX + "/orphan"
PENDING_KEY = PREFIX + "/pending"
def run(command, *, input_text=None, capture=False):
result = subprocess.run(
command,
input=input_text,
text=True,
check=False,
capture_output=capture,
env=os.environ.copy(),
)
if result.returncode != 0:
details = result.stderr.strip() if capture else "see command output"
raise RuntimeError("command failed: %s: %s" % (command[0], details))
return result.stdout if capture else ""
def compose(*arguments, capture=False, input_text=None):
return run(
["docker", "compose", *arguments],
input_text=input_text,
capture=capture,
)
def database(sql):
compose(
"exec", "-T", "postgres",
"psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger",
input_text=sql,
)
def object_command(script):
compose(
"run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap",
"-ec", script,
)
def clean_objects():
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mc rm --force "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null 2>&1 || true\n'
'mc rm --force "local/${S3_BUCKET}/' + PENDING_KEY + '" >/dev/null 2>&1 || true\n'
)
def clean_database():
database(f"""
BEGIN;
DELETE FROM messages WHERE id = '{MESSAGE_ID}';
DELETE FROM attachments WHERE id IN ('{MISSING_ID}', '{PROTECTED_ID}', '{PENDING_ID}');
DELETE FROM chat_members WHERE chat_id = '{CHAT_ID}';
DELETE FROM chats WHERE id = '{CHAT_ID}';
DELETE FROM users WHERE id = '{USER_ID}';
COMMIT;
""")
def inject_database():
database(f"""
BEGIN;
INSERT INTO users (id, username, display_name, password_hash)
VALUES ('{USER_ID}', 'reconcile_fixture', 'Reconcile Fixture', 'not-used');
INSERT INTO chats (id, title) VALUES ('{CHAT_ID}', 'Reconcile Integration');
INSERT INTO chat_members (chat_id, user_id, position) VALUES ('{CHAT_ID}', '{USER_ID}', 0);
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, width, height, status, created_at, updated_at
) VALUES
('{MISSING_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/missing', 'missing.png', 'image/png',
7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', now() - interval '2 hours', now() - interval '2 hours'),
('{PROTECTED_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/protected-missing', 'protected.png', 'image/png',
7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', now() - interval '2 hours', now() - interval '2 hours'),
('{PENDING_ID}', '{CHAT_ID}', '{USER_ID}', '{PENDING_KEY}', 'pending.png', 'image/png',
7, decode(repeat('00', 32), 'hex'), 1, 1, 'pending', now() - interval '2 hours', now() - interval '2 hours');
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{USER_ID}', 'protected attachment reference');
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{PROTECTED_ID}', 0);
COMMIT;
""")
def inject_objects():
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'printf orphan | mc pipe "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null\n'
'printf pending | mc pipe "local/${S3_BUCKET}/' + PENDING_KEY + '" >/dev/null\n'
)
def reconcile(apply=False):
command = [
"run", "--rm", "--entrypoint", "/app/reconciler", "api",
"--grace-period", "1s",
]
if apply:
command.append("--apply")
output = compose(*command, capture=True)
return json.loads(output)
def kinds(result):
return {issue["kind"] for issue in result["issues"]}
def main():
clean_objects()
clean_database()
try:
inject_database()
inject_objects()
time.sleep(2)
dry_run = reconcile(False)
expected = {
"orphan_object", "missing_object", "referenced_missing_object", "stale_pending",
}
if not expected.issubset(kinds(dry_run)):
raise RuntimeError("dry-run did not detect all injected inconsistencies")
if dry_run["deleted_objects"] or dry_run["failed_attachments"]:
raise RuntimeError("dry-run performed mutations")
applied = reconcile(True)
if applied["deleted_objects"] != 2 or applied["failed_attachments"] != 2:
raise RuntimeError("apply mutation counts differ: %s" % applied)
repeated = reconcile(True)
if repeated["deleted_objects"] or repeated["failed_attachments"]:
raise RuntimeError("repeated apply was not mutation-idempotent")
protected = [issue for issue in repeated["issues"] if issue.get("protected")]
if len(protected) != 1 or protected[0]["action"] != "manual_repair_required":
raise RuntimeError("referenced missing attachment was not protected")
print(json.dumps({
"dry_run_issues": len(dry_run["issues"]),
"apply_deleted_objects": applied["deleted_objects"],
"apply_failed_attachments": applied["failed_attachments"],
"repeat_mutations": repeated["deleted_objects"] + repeated["failed_attachments"],
"protected_manual_issues": len(protected),
"scanned_attachments": applied["scanned_attachments"],
"scanned_objects": applied["scanned_objects"],
"duration_ms": applied["duration_ms"],
}, ensure_ascii=False))
print("PASS: real PostgreSQL/MinIO reconciliation is dry-run safe, idempotent and reference-aware.")
finally:
clean_objects()
clean_database()
if __name__ == "__main__":
main()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Measure real PostgreSQL/MinIO reconciler traversal at two inventory sizes."""
import json
import subprocess
import time
PREFIX = "attachments/reconcile-scale"
def compose(*arguments, capture=False):
result = subprocess.run(
["docker", "compose", *arguments],
check=False,
text=True,
capture_output=capture,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() if capture else "docker compose command failed")
return result.stdout if capture else ""
def object_command(script):
compose("run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", script)
def clean():
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mc rm --recursive --force "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null 2>&1 || true\n'
)
def create(count):
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mkdir -p /tmp/reconcile-scale\n'
'index=0\n'
'while [ "$index" -lt ' + str(count) + ' ]; do\n'
' printf x > "/tmp/reconcile-scale/object-${index}"\n'
' index=$((index + 1))\n'
'done\n'
'mc cp --recursive /tmp/reconcile-scale/ "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null\n'
)
def dry_run():
started = time.monotonic()
output = compose(
"run", "--rm", "--entrypoint", "/app/reconciler", "api",
"--grace-period", "1s",
capture=True,
)
elapsed = time.monotonic() - started
result = json.loads(output)
return {
"scanned_attachments": result["scanned_attachments"],
"scanned_objects": result["scanned_objects"],
"issues": len(result["issues"]),
"reconciler_duration_ms": result["duration_ms"],
"container_start_and_run_ms": round(elapsed * 1000),
}
def main():
measurements = []
clean()
try:
for count in (100, 1000):
clean()
create(count)
time.sleep(2)
measurement = dry_run()
measurement["injected_orphan_objects"] = count
if measurement["issues"] < count:
raise RuntimeError("reconciler did not observe all scale fixtures")
measurements.append(measurement)
print(json.dumps({"measurements": measurements}, ensure_ascii=False))
print("PASS: reconciler traversal cost measured on real PostgreSQL/MinIO inventories.")
finally:
clean()
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Verify contract responses and original durability during a real MinIO outage."""
import json
import os
import subprocess
import time
from attachment_memory import cleanup
from client import Client, Failure, check, run
def compose(*arguments, **kwargs):
return subprocess.run(["docker", "compose", *arguments], check=True, **kwargs)
def wait_for_status(client, path, expected, timeout=20):
deadline = time.monotonic() + timeout
last_error = None
while time.monotonic() < deadline:
try:
return client.call("GET", path, expected=expected)
except Failure as error:
last_error = error
time.sleep(0.25)
raise Failure("%s did not reach %d: %s" % (path, expected, last_error))
def restore_storage(client):
compose("up", "-d", "--wait", "minio")
compose("run", "--rm", "minio-bootstrap")
wait_for_status(client, "/health/ready", 200, timeout=30)
def main():
client = Client(os.environ.get("BASE_URL"), None, timeout=15)
alice, bob, eve, chat = client.bootstrap()
users = [alice["id"], bob["id"], eve["id"]]
attachment, original = client.attachment(alice, chat)
storage_stopped = False
try:
compose("stop", "minio")
storage_stopped = True
readiness = wait_for_status(client, "/health/ready", 503)
check(readiness["elapsed"] < 5, "readiness exceeded its bounded timeout")
started = time.monotonic()
failure = client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=outage.png" % chat["id"],
503,
actor=alice,
raw=original,
headers={"Content-Type": "image/png"},
)
elapsed = time.monotonic() - started
check(failure["json"]["error"]["code"] == "unavailable", "wrong S3 outage error code")
check(elapsed < 15, "upload outage response exceeded API/client timeout")
restore_storage(client)
storage_stopped = False
downloaded = client.call(
"GET", "/api/v1/attachments/%s/content" % attachment["id"],
200, actor=alice,
)["bytes"]
check(downloaded == original, "existing original changed across MinIO outage")
print(json.dumps({
"readiness_503_seconds": round(readiness["elapsed"], 3),
"upload_503_seconds": round(elapsed, 3),
"original_bytes_verified": len(original),
}, sort_keys=True))
print("PASS: MinIO outage returns bounded JSON 503 and preserves existing originals.")
finally:
if storage_stopped:
restore_storage(client)
cleanup(chat["id"], users)
if __name__ == "__main__":
run(main)