Выполнение lab4 на 4

This commit is contained in:
Daria0w0
2026-11-06 17:35:48 +03:00
parent 9197e151ba
commit 879463c947
89 changed files with 5551 additions and 108 deletions
+83
View File
@@ -0,0 +1,83 @@
"""Message attachment ACL, validation and idempotency. Synthetic data only."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Messages with attachments')
base = args.base_url or 'http://127.0.0.1:8084'
c = Client(base, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
first, _ = c.attachment(alice, chat)
second, _ = c.attachment(alice, chat)
path = '/api/v1/chats/' + chat['id'] + '/messages'
ids = [second['id'], first['id']]
key = uuid.uuid4().hex
created = c.message(bob, chat, '', key=key, attachments=ids)['json']
check(created['attachment_ids'] == ids and created['text'] == '', 'attachment-only message/order lost')
replay = c.call('POST', path, 201, actor=bob,
body={'attachment_ids': ids, 'text': ''}, headers={'Idempotency-Key': key}, schema='Message')['json']
check(replay == created, 'JSON field order changed replay')
c.call('POST', path, 409, actor=bob, body={'text': '', 'attachment_ids': list(reversed(ids))}, headers={'Idempotency-Key': key})
c.call('POST', path, 409, actor=bob, body={'text': '', 'attachment_ids': ids[:1]}, headers={'Idempotency-Key': key})
print('PASS: attachment-only message, non-owner participant, list order, replay and changed-list 409')
text_key = uuid.uuid4().hex
text = c.message(alice, chat, 'text-only', key=text_key)['json']
check(text['attachment_ids'] == [], 'text-only attachment_ids must be []')
check(c.message(alice, chat, 'text-only', key=text_key, attachments=[])['json'] == text,
'omitted attachment_ids differs from []')
print('PASS: text-only compatibility; omitted attachment_ids and [] replay identically')
invalid_bodies = [
{'text': ''}, {'text': ' \t\n', 'attachment_ids': []},
{'text': '', 'attachment_ids': [first['id'], first['id']]},
{'text': '', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]},
{'text': '', 'attachment_ids': ['not-uuid']},
{'text': 'x', 'attachment_ids': None}, {'text': 'x', 'attachment_ids': 'wrong'},
{'text': 'x', 'attachment_ids': [None]}, {'text': 'x', 'unexpected': True},
]
for body in invalid_bodies:
c.call('POST', path, 400, actor=alice, body=body, headers={'Idempotency-Key': uuid.uuid4().hex})
print('PASS: empty message, duplicates, >10 IDs, bad UUID/types/null/unknown fields return 400')
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Other chat', 'member_ids': [alice['id'], eve['id']]}, schema='Chat')['json']
foreign, _ = c.attachment(alice, other)
retry_key = uuid.uuid4().hex
for attachment_id in (foreign['id'], str(uuid.uuid4())):
c.call('POST', path, 404, actor=alice, body={'text': '', 'attachment_ids': [attachment_id]},
headers={'Idempotency-Key': retry_key})
c.message(alice, chat, 'corrected retry', key=retry_key, attachments=[first['id']])
c.call('POST', path, 404, actor=eve, body={'text': '', 'attachment_ids': [first['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
print('PASS: foreign-chat/unknown attachment and outsider return 404; rejected request does not consume key')
ten_ids = ids + [c.attachment(alice, chat)[0]['id'] for _ in range(8)]
ten = c.message(alice, chat, '', attachments=ten_ids)['json']
check(ten['attachment_ids'] == ten_ids, 'ten attachments were not preserved')
print('PASS: exactly ten distinct attachments are accepted')
concurrent_key = uuid.uuid4().hex
def send(_):
local = Client(base, args.ca_file)
return local.message(alice, chat, 'concurrent', key=concurrent_key, attachments=[first['id']])
with ThreadPoolExecutor(max_workers=8) as executor:
results = list(executor.map(send, range(16)))
check(all(result['json'] == results[0]['json'] for result in results), 'concurrent replies differ')
instances = {result['headers']['X-Instance-Id'] for result in results}
check(len(instances) >= 2, 'concurrent replay did not reach two replicas')
history = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
check(len(history) == 5, 'rejected requests or retries left extra messages')
matching = [message for message in history if message['id'] == results[0]['json']['id']]
check(len(matching) == 1, 'concurrent retry created duplicates in history')
check(next(message for message in history if message['id'] == created['id']) == created, 'history lost attachments')
print('PASS: 16 concurrent retries across two replicas return one message, history preserves attachment order')
print('PASS: message attachment checks completed')
if __name__ == '__main__':
run(main)
+216
View File
@@ -0,0 +1,216 @@
"""Explicit local failures; preserves volumes and restores API/S3 in finally."""
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def docker(*args, check_code=True):
result = subprocess.run(['docker', *args], cwd=ROOT, text=True, capture_output=True, timeout=120)
if check_code:
check(result.returncode == 0, 'Docker operation failed: ' + args[0])
return result
def compose(*args, **kwargs):
return docker('compose', '--env-file', '.env', *args, **kwargs)
def snapshot(label):
ids = compose('ps', '-a', '-q').stdout.split()
template = ('{"id":{{json .Id}},"name":{{json .Name}},'
'"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
'"status":{{json .State.Status}},"started_at":{{json .State.StartedAt}},'
'"pid":{{json .State.Pid}},"image_id":{{json .Image}},"mounts":{{json .Mounts}}}')
records = []
for container in ids:
item = json.loads(docker('inspect', '--format', template, container).stdout)
item['volumes'] = [{'name': m['Name'], 'destination': m['Destination']}
for m in item.pop('mounts') if m['Type'] == 'volume']
records.append(item)
record = {'stage': label, 'utc': dt.datetime.now(dt.timezone.utc).isoformat(), 'containers': records}
with (ROOT / 'evidence' / 'attachment-resilience-containers.jsonl').open('a', encoding='utf-8') as out:
out.write(json.dumps(record, ensure_ascii=False) + '\n')
return records
def wait_ready(c, seconds=60):
deadline = time.monotonic() + seconds
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
check(time.monotonic() < deadline, 'readiness did not recover')
time.sleep(0.3)
def restore(c):
# Compose start also visits depends_on (bootstrap/migrate). Restore only
# the stopped processes, without reapplying credentials during the test.
for container in compose('ps', '-a', '-q', 's3', 'api').stdout.split():
if docker('inspect', '--format', '{{.State.Running}}', container).stdout.strip() != 'true':
docker('start', container)
deadline = time.monotonic() + 60
observed, consecutive = set(), 0
while True:
try:
response = c.call('GET', '/health/ready', schema='Health')
observed.add(response['headers']['X-Instance-Id'])
consecutive += 1
if len(observed) == 2 and consecutive >= 8:
return
except Failure:
observed, consecutive = set(), 0
check(time.monotonic() < deadline, 'two API replicas did not return to stable LB rotation')
time.sleep(0.2)
def download(c, actor, attachment, original):
response = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)
check(response['bytes'] == original, 'original bytes changed')
check(hashlib.sha256(response['bytes']).hexdigest() == attachment['sha256'], 'checksum changed')
return response
def public_test(c, mode):
env = dict(os.environ, LAB_PYTHON=sys.executable)
hook = 'scripts/restart.cmd' if mode == 'persistence' else 'scripts/stop-one.cmd'
before = snapshot('before-public-' + mode)
result = subprocess.run([sys.executable, '-X', 'utf8', 'tests/resilience.py', '--mode', mode,
'--action-script', hook, '--base-url', c.base],
cwd=ROOT, env=env, text=True, capture_output=True, timeout=200)
(ROOT / 'evidence' / ('lab4-' + mode + '.txt')).write_text(result.stdout + result.stderr, encoding='utf-8')
after = snapshot('after-public-' + mode)
check(result.returncode == 0, 'public ' + mode + ' failed; inspect its evidence file')
if mode == 'persistence':
previous = {item['name']: item for item in before}
for item in after:
if item['service'] in ('api', 'lb', 'postgres', 'redis', 's3'):
check(item['started_at'] != previous[item['name']]['started_at'], 'component was not restarted: ' + item['service'])
check(item['volumes'] == previous[item['name']]['volumes'], 'persistent volume changed')
print('PASS: public persistence; API/LB/PostgreSQL/Redis/S3 restarted, named volumes unchanged')
else:
check(sum(item['service'] == 'api' and item['status'] == 'exited' for item in after) == 1,
'failover hook did not leave exactly one API stopped')
print('PASS: public failover; one API stopped, in-flight messages/session/original preserved')
restore(c)
def uploader_failovers(c):
alice, bob, _, chat = c.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
containers = compose('ps', '-q', 'api').stdout.split()
check(len(containers) == 2, 'expected exactly two running API replicas')
aliases = {container: docker('exec', container, '/server', 'instance-id').stdout.strip() for container in containers}
for index, target in enumerate(containers, 1):
expected = aliases[target]
uploaded = None
for _ in range(40):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
if response['headers']['X-Instance-Id'] == expected:
uploaded = response['json']
break
check(uploaded is not None, 'target API did not receive upload')
c.message(alice, chat, '', attachments=[uploaded['id']])
snapshot('before-uploader-stop-' + str(index))
docker('stop', '--time', '1', target)
snapshot('after-uploader-stop-' + str(index))
started = time.monotonic()
failures = 0
while True:
try:
response = download(c, bob, uploaded, data)
check(response['headers']['X-Instance-Id'] != expected, 'stopped uploader still served download')
break
except Failure:
failures += 1
check(time.monotonic() - started < 10, 'download did not recover within 10 seconds')
time.sleep(0.2)
print(json.dumps({'scenario': 'uploader-failover', 'replica': index,
'recovery_seconds_after_stop': round(time.monotonic()-started, 3),
'transient_failures': failures, 'checksum_match': True}))
restore(c)
# Ensure the restored process is ready before selecting it as the next target.
deadline = time.monotonic() + 30
while True:
result = docker('exec', target, '/server', 'healthcheck', check_code=False)
if result.returncode == 0:
break
check(time.monotonic() < deadline, 'restored API did not become ready')
time.sleep(0.2)
aliases[target] = docker('exec', target, '/server', 'instance-id').stdout.strip()
print('PASS: upload -> stop exact uploader -> other API downloads identical original, for both replicas')
def s3_outage(c):
alice, bob, _, chat = c.bootstrap()
attachment, data = c.attachment(alice, chat)
original_message = c.message(alice, chat, 'survive S3 outage', attachments=[attachment['id']])['json']
before = snapshot('before-s3-outage')
compose('stop', '--timeout', '1', 's3')
snapshot('during-s3-outage')
try:
api_containers = compose('ps', '-q', 'api').stdout.split()
for container in api_containers:
probe = docker('exec', container, '/server', 'healthcheck', check_code=False)
check(probe.returncode != 0 and 'status=503' in probe.stderr, 'API readiness did not return 503')
live = compose('run', '--rm', '--no-deps', '--entrypoint', '/bin/sh', 's3-bootstrap',
'-c', 'wget -qO- http://api:8080/health/live').stdout
check(json.loads(live)['status'] == 'ok', 'API liveness failed during S3 outage')
# LB may withdraw all API after readiness failure and generate its own 503.
req = urllib.request.Request(c.base + '/api/v1/attachments/' + attachment['id'] + '/content',
headers={'Authorization': 'Bearer ' + bob['token']})
try:
response = c.opener.open(req, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
check(response.code == 503, 'download did not fail with 503 during S3 outage')
print('PASS: real S3 stop; both API ready=503, live=200, public download=503 (API or LB)')
finally:
compose('start', 's3')
wait_ready(c)
download(c, bob, attachment, data)
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json']
check(original_message in page['items'], 'message lost during S3 outage')
c.attachment(alice, chat)
after = snapshot('after-s3-outage')
previous = {item['name']: item for item in before}
for item in after:
if item['service'] == 'api':
check(item['started_at'] == previous[item['name']]['started_at'], 'API restarted during S3 outage')
print('PASS: S3 restored; original/message/session preserved, new upload works, API processes did not restart')
def main():
args = arguments('Explicit attachment failover, restart and S3 outage')
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file, timeout=3)
evidence = ROOT / 'evidence/attachment-resilience-containers.jsonl'
evidence.write_text('', encoding='utf-8')
try:
restore(c)
snapshot('initial')
public_test(c, 'failover')
uploader_failovers(c)
public_test(c, 'persistence')
s3_outage(c)
print('PASS: attachment resilience checks completed')
finally:
restore(c)
snapshot('final-restored')
if __name__ == '__main__':
run(main)
+62
View File
@@ -0,0 +1,62 @@
\set ON_ERROR_STOP on
BEGIN;
-- All synthetic rows are rolled back, including on test failure.
INSERT INTO users(id, username, display_name, password_hash)
VALUES ('10000000-0000-4000-8000-000000000001', 'schema_attachment_test', 'Test', 'not-a-login-fixture');
INSERT INTO chats(id, title) VALUES
('20000000-0000-4000-8000-000000000001', 'First'),
('20000000-0000-4000-8000-000000000002', 'Second');
INSERT INTO chat_members(chat_id, user_id)
SELECT id, '10000000-0000-4000-8000-000000000001'::uuid FROM chats
WHERE id IN ('20000000-0000-4000-8000-000000000001', '20000000-0000-4000-8000-000000000002');
INSERT INTO messages(id, chat_id, sender_id, text) VALUES
('30000000-0000-4000-8000-000000000001', '20000000-0000-4000-8000-000000000001',
'10000000-0000-4000-8000-000000000001', 'schema test');
INSERT INTO attachments(id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256)
SELECT id, chat_id, '10000000-0000-4000-8000-000000000001'::uuid,
'attachments/' || id::text, 'photo.png', 'image/png', 10, repeat('a', 64)
FROM (VALUES
('40000000-0000-4000-8000-000000000001'::uuid, '20000000-0000-4000-8000-000000000001'::uuid),
('40000000-0000-4000-8000-000000000002'::uuid, '20000000-0000-4000-8000-000000000002'::uuid)
) AS fixture(id, chat_id);
INSERT INTO message_attachments VALUES
('30000000-0000-4000-8000-000000000001', '40000000-0000-4000-8000-000000000001',
'20000000-0000-4000-8000-000000000001', 0);
DO $$
BEGIN
BEGIN
INSERT INTO message_attachments VALUES
('30000000-0000-4000-8000-000000000001', '40000000-0000-4000-8000-000000000002',
'20000000-0000-4000-8000-000000000001', 1);
RAISE EXCEPTION 'FAIL: cross-chat attachment accepted';
EXCEPTION WHEN foreign_key_violation THEN
RAISE NOTICE 'PASS: cross-chat attachment rejected';
END;
BEGIN
UPDATE message_attachments SET position = 10;
RAISE EXCEPTION 'FAIL: attachment position 10 accepted';
EXCEPTION WHEN check_violation THEN
RAISE NOTICE 'PASS: attachment position limited to 0..9';
END;
BEGIN
UPDATE attachments SET size_bytes = 10485761;
RAISE EXCEPTION 'FAIL: oversized metadata accepted';
EXCEPTION WHEN check_violation THEN
RAISE NOTICE 'PASS: oversized metadata rejected';
END;
BEGIN
UPDATE attachments SET filename = '../photo.png';
RAISE EXCEPTION 'FAIL: path filename accepted';
EXCEPTION WHEN check_violation THEN
RAISE NOTICE 'PASS: filename path rejected';
END;
BEGIN
UPDATE attachments SET sha256 = 'wrong';
RAISE EXCEPTION 'FAIL: invalid checksum accepted';
EXCEPTION WHEN check_violation THEN
RAISE NOTICE 'PASS: invalid checksum rejected';
END;
END $$;
ROLLBACK;
\echo 'PASS: attachment schema checks completed; fixtures rolled back.'
+63
View File
@@ -0,0 +1,63 @@
"""Attachment endpoints only; synthetic users and one PNG, no tokens in output."""
import hashlib
from pathlib import Path
import struct
import sys
from urllib.parse import quote
import uuid
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Attachment upload, metadata, content and validation')
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file)
alice, bob, eve, chat = c.bootstrap()
attachment, content = c.attachment(alice, chat)
path = '/api/v1/attachments/' + attachment['id']
check(attachment['variants'] == [] and attachment['error_code'] is None, 'invalid ready metadata')
fetched = c.call('GET', path, actor=bob, schema='Attachment')['json']
check(fetched == attachment, 'metadata changed between replicas')
download = c.call('GET', path + '/content', actor=bob)
check(download['bytes'] == content, 'original changed')
check(download['headers'].get_content_type() == 'image/png', 'wrong MIME')
check(hashlib.sha256(download['bytes']).hexdigest() == attachment['sha256'], 'checksum mismatch')
print('PASS: upload 201 ready; participant metadata/download; original and checksum match')
for suffix in ('', '/content'):
c.call('GET', path + suffix, 404, actor=eve)
c.call('GET', path + suffix, 401)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()), 404, actor=alice)
c.call('GET', path + '/content?variant=thumbnail', 404, actor=alice)
print('PASS: unauthorized 401, outsider/unknown attachment 404, missing variant 404')
upload = '/api/v1/chats/' + chat['id'] + '/attachments?filename=photo.png'
c.call('POST', upload, 404, actor=eve, raw=content, headers={'Content-Type': 'image/png'})
c.call('POST', upload, 401, raw=content, headers={'Content-Type': 'image/png'})
for label, raw, mime, expected in (
('corrupt', b'not an image', 'image/png', 415),
('truncated', content[:33], 'image/png', 415),
('spoofed MIME', content, 'image/jpeg', 415),
('unsupported MIME', content, 'text/plain', 415),
):
c.call('POST', upload, expected, actor=alice, raw=raw, headers={'Content-Type': mime})
print('PASS:', label, 'returns', expected)
huge = bytearray(content)
huge[16:24] = struct.pack('>II', 40001, 1000)
huge[29:33] = struct.pack('>I', zlib.crc32(huge[12:29]))
c.call('POST', upload, 413, actor=alice, raw=bytes(huge), headers={'Content-Type': 'image/png'})
print('PASS: excessive pixel dimensions return 413')
for name in ('', '../photo.png', 'a\\photo.png', 'a\x00.png', 'a\n.png', 'я' * 256):
c.call('POST', upload.split('?')[0] + '?filename=' + quote(name, safe=''), 400,
actor=alice, raw=content, headers={'Content-Type': 'image/png'})
print('PASS: invalid filenames return 400')
# Declared length is rejected before attempting an unbounded body read.
c.call('POST', upload, 413, actor=alice, raw=b'',
headers={'Content-Type': 'image/png', 'Content-Length': str(10485761)})
print('PASS: declared byte length above 10 MiB returns 413')
print('PASS: attachment HTTP checks completed; message attachment_ids not tested yet')
if __name__ == '__main__':
run(main)
+19
View File
@@ -0,0 +1,19 @@
services:
s3-client-test:
profiles: [checks]
build:
context: .
target: s3-client-test
environment:
S3_INTEGRATION: "1"
S3_ENDPOINT: http://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
secrets: [s3_access_key_id, s3_secret_access_key]
cpus: 1.0
mem_limit: 512m
depends_on:
s3-bootstrap:
condition: service_completed_successfully
+32
View File
@@ -0,0 +1,32 @@
// Generate a deterministic synthetic JPEG without third-party dependencies.
package main
import (
"image"
"image/color"
"image/jpeg"
"log"
"os"
)
func main() {
if err := os.MkdirAll("data/upload-fixtures", 0755); err != nil {
log.Fatal(err)
}
file, err := os.Create("data/upload-fixtures/synthetic.jpg")
if err != nil {
log.Fatal(err)
}
img := image.NewRGBA(image.Rect(0, 0, 1024, 768))
for y := 0; y < 768; y++ {
for x := 0; x < 1024; x++ {
img.SetRGBA(x, y, color.RGBA{uint8(x*7 + y), uint8(y*11 + x), uint8(x ^ y), 255})
}
}
if err := jpeg.Encode(file, img, &jpeg.Options{Quality: 90}); err != nil {
log.Fatal(err)
}
if err := file.Close(); err != nil {
log.Fatal(err)
}
}
+58
View File
@@ -0,0 +1,58 @@
"""Exact byte limit and chunked overflow using a valid PNG ancillary chunk."""
import hashlib
import http.client
import json
from pathlib import Path
import struct
import sys
from urllib.parse import urlsplit
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run, shape
def main():
args = arguments('Exact 10 MiB and chunked overflow')
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file, timeout=65)
alice, bob, _, chat = c.bootstrap()
base = (ROOT / 'tests/fixtures/sample.png').read_bytes()
limit = 10485760
# Insert a real tEXt chunk before IEND; no trailing bytes after the PNG end.
size = limit - len(base) - 12
text = b'padding\0' + b'x' * (size - 8)
chunk = struct.pack('>I', size) + b'tEXt' + text + struct.pack('>I', zlib.crc32(b'tEXt' + text))
data = base[:-12] + chunk + base[-12:]
check(len(data) == limit, 'incorrect boundary fixture size')
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=limit.png'
a = c.call('POST', path, 201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(a['size_bytes'] == limit and a['sha256'] == hashlib.sha256(data).hexdigest(), 'boundary metadata mismatch')
downloaded = c.call('GET', '/api/v1/attachments/' + a['id'] + '/content', actor=bob)
check(downloaded['bytes'] == data, '10 MiB original changed')
print('PASS: real PNG exactly 10 MiB accepted; original bytes/checksum preserved')
target = urlsplit(c.base)
check(target.scheme == 'http', 'chunked boundary scenario is local HTTP only')
def pieces():
for offset in range(0, len(data), 32768):
yield data[offset:offset+32768]
yield b'x'
connection = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=65)
try:
connection.request('POST', path, body=pieces(), encode_chunked=True,
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'})
response = connection.getresponse()
body = json.loads(response.read())
check(response.status == 413, 'chunked size overflow did not return 413')
shape(body, 'Error')
check(body['error']['request_id'] == response.headers.get('X-Request-Id'), 'request ID mismatch')
check(bool(response.headers.get('X-Instance-Id')), 'missing API instance ID')
finally:
connection.close()
print('PASS: chunked stream without Content-Length, 10 MiB+1 byte, returns 413 from API')
if __name__ == '__main__':
run(main)
+144
View File
@@ -0,0 +1,144 @@
"""Explicit local fault injection. Ages only its own synthetic upload intent."""
import json
from pathlib import Path
import socket
import subprocess
import sys
import uuid
from urllib.parse import urlsplit
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def compose(*args, input=None):
result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
input=input, text=True, capture_output=True, timeout=90)
check(result.returncode == 0, 'Compose operation failed: ' + args[0])
return result.stdout.strip()
def sql(query):
return compose('exec', '-T', 'postgres', 'psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1',
'-U', 'messenger', '-d', 'messenger', input=query)
def s3_exists(object_id):
# Shell text contains no credential values; they are read inside the container.
script = ('mc alias set api http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" '
'"$(cat /run/secrets/s3_secret_access_key)" >/dev/null 2>&1; '
'mc --json stat "api/$S3_BUCKET/attachments/' + object_id + '"')
result = subprocess.run(['docker', 'compose', '--env-file', '.env', 'run', '--rm',
'--entrypoint', '/bin/sh', 's3-bootstrap', '-c', script],
cwd=ROOT, text=True, capture_output=True, timeout=30)
lines = [json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]
check(bool(lines), 'S3 stat returned no JSON')
item = lines[-1]
if item.get('status') == 'success':
return True
# Missing and authorization/network errors must not be confused.
message = json.dumps(item).lower()
check('does not exist' in message or 'specified key' in message or 'nosuchkey' in message,
'unexpected S3 stat error')
return False
def age(object_id):
sql("UPDATE upload_intents SET created_at=clock_timestamp()-INTERVAL '11 minutes', "
"expires_at=clock_timestamp()-INTERVAL '1 minute', next_cleanup_at=clock_timestamp()-INTERVAL '1 minute' "
"WHERE id='" + object_id + "';")
def cleanup(dry=False):
options = ('--dry-run',) if dry else ()
return json.loads(compose('exec', '-T', 'api', '/server', 'cleanup', *options))
def main():
args = arguments('Upload compensation / grace period checks')
c = Client(args.base_url or 'http://127.0.0.1:8084', args.ca_file)
alice, bob, _, chat = c.bootstrap()
ready, data = c.attachment(alice, chat)
c.message(alice, chat, '', attachments=[ready['id']])
check(sql("SELECT count(*) FROM upload_intents WHERE id='" + ready['id'] + "';") == '0',
'successful publication left an intent')
marker = 'cleanup_test_' + uuid.uuid4().hex
filename = marker + '.png'
create_trigger = f"""
CREATE FUNCTION {marker}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.filename='{filename}' THEN RAISE EXCEPTION 'synthetic metadata failure'; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER {marker} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {marker}();
"""
sql(create_trigger)
failed_id = None
try:
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
503, actor=alice, raw=data, headers={'Content-Type': 'image/png'})
failed_id = sql("SELECT id::text FROM upload_intents WHERE owner_id='" + alice['id'] + "';")
uuid.UUID(failed_id)
check(sql("SELECT count(*) FROM attachments WHERE id='" + failed_id + "';") == '0', 'failed publication committed metadata')
check(s3_exists(failed_id), 'fault was not injected after successful S3 PUT')
print('PASS: real S3 PUT followed by injected INSERT failure returns 503; durable intent remains')
cleanup()
check(s3_exists(failed_id), 'fresh upload removed before grace period')
print('PASS: cleanup preserves fresh failed upload during 10-minute grace period')
age(failed_id)
preview = cleanup(True)
check(preview['would_delete'] >= 1 and s3_exists(failed_id), 'dry-run modified object or missed intent')
unavailable = subprocess.run(['docker', 'compose', '--env-file', '.env', 'exec', '-T',
'-e', 'S3_ENDPOINT=http://127.0.0.1:1', 'api', '/server', 'cleanup'],
cwd=ROOT, text=True, capture_output=True, timeout=30)
check(unavailable.returncode != 0 and json.loads(unavailable.stdout)['errors'] >= 1,
'cleanup failed to report unavailable S3')
check(sql("SELECT state FROM upload_intents WHERE id='" + failed_id + "';") == 'pending',
'failed deletion discarded pending intent')
print('PASS: unavailable cleanup endpoint reports error and preserves intent for retry')
cleanup()
check(not s3_exists(failed_id), 'expired failed upload remains in S3')
check(sql("SELECT state FROM upload_intents WHERE id='" + failed_id + "';") == 'abandoned', 'tombstone missing')
print('PASS: aged intent detected; dry-run preserves object; cleanup removes it and retains tombstone')
# Simulate a late PUT arriving after the first deletion.
script = ('mc alias set api http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" '
'"$(cat /run/secrets/s3_secret_access_key)" >/dev/null 2>&1; '
'printf late | mc pipe "api/$S3_BUCKET/attachments/' + failed_id + '" >/dev/null')
compose('run', '--rm', '--entrypoint', '/bin/sh', 's3-bootstrap', '-c', script)
age(failed_id)
cleanup()
check(not s3_exists(failed_id), 'late PUT not cleaned')
age(failed_id)
cleanup()
print('PASS: late PUT removed on retry; repeat DELETE of absent object succeeds')
check(c.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)['bytes'] == data,
'cleanup damaged published attachment')
sql("INSERT INTO upload_intents(id,chat_id,owner_id) VALUES('" + ready['id'] + "','" + chat['id'] + "','" + alice['id'] + "');")
age(ready['id'])
cleanup()
check(sql("SELECT count(*) FROM upload_intents WHERE id='" + ready['id'] + "';") == '0', 'stale ready intent not removed')
check(c.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)['bytes'] == data,
'stale intent caused published object deletion')
print('PASS: published attachment referenced by message remains byte-identical')
# A client disconnects before a complete image is received: no S3 PUT starts.
target = urlsplit(c.base)
check(target.scheme == 'http', 'disconnect check is local HTTP only')
request = (f'POST /api/v1/chats/{chat["id"]}/attachments?filename=interrupted.png HTTP/1.1\r\n'
f'Host: {target.netloc}\r\nAuthorization: Bearer {alice["token"]}\r\n'
'Content-Type: image/png\r\nContent-Length: 100000\r\n\r\n').encode() + data[:20]
with socket.create_connection((target.hostname, target.port or 80), timeout=5) as sock:
sock.sendall(request)
sock.shutdown(socket.SHUT_WR)
while sock.recv(4096):
pass
check(sql("SELECT count(*) FROM upload_intents WHERE owner_id='" + alice['id'] + "' AND state='pending';") == '0',
'interrupted client created a pending S3 upload')
print('PASS: disconnected partial HTTP upload never reaches S3 intent stage')
finally:
sql(f'DROP TRIGGER IF EXISTS {marker} ON attachments; DROP FUNCTION IF EXISTS {marker}();')
print('PASS: upload compensation checks completed; grace aging was explicit SQL simulation')
if __name__ == '__main__':
run(main)
+60
View File
@@ -0,0 +1,60 @@
"""Deterministic streaming PNG generation; no third-party Python packages."""
import hashlib
from pathlib import Path
import random
import struct
import zlib
ROOT = Path(__file__).resolve().parents[1]
DIRECTORY = ROOT / 'data/upload-fixtures'
def chunk(file, kind, data):
file.write(struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)))
def png(name, width, height, bit_depth, color_type, noisy=False):
path = DIRECTORY / (name + '.png')
channels = {2: 3, 6: 4}[color_type]
row_bytes = width * channels * (bit_depth // 8)
compressor = zlib.compressobj(level=1)
random_source = random.Random(20261106)
pattern = b'\x12\x34\x56\x78\x9a\xbc\xde\xf0' * 8192
with path.open('wb') as file:
file.write(b'\x89PNG\r\n\x1a\n')
chunk(file, b'IHDR', struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0))
for _ in range(height):
compressed = compressor.compress(b'\0')
if compressed:
chunk(file, b'IDAT', compressed)
remaining = row_bytes
while remaining:
size = min(remaining, 65536)
block = random_source.randbytes(size) if noisy else pattern[:size]
compressed = compressor.compress(block)
if compressed:
chunk(file, b'IDAT', compressed)
remaining -= size
chunk(file, b'IDAT', compressor.flush())
chunk(file, b'IEND', b'')
return {'name': name, 'path': str(path), 'content_type': 'image/png', 'width': width,
'height': height, 'bit_depth': bit_depth, 'color_type': color_type,
'size_bytes': path.stat().st_size, 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
def generate():
DIRECTORY.mkdir(parents=True, exist_ok=True)
fixtures = [png('rgb8_1mp', 1024, 768, 8, 2, noisy=True),
png('rgba16_40mp', 8000, 5000, 16, 6),
png('rgba16_wide_40mp', 40000000, 1, 16, 6)]
jpeg = DIRECTORY / 'synthetic.jpg'
if jpeg.exists():
fixtures.append({'name': 'jpeg_1mp', 'path': str(jpeg), 'content_type': 'image/jpeg',
'width': 1024, 'height': 768, 'size_bytes': jpeg.stat().st_size,
'sha256': hashlib.sha256(jpeg.read_bytes()).hexdigest()})
return fixtures
if __name__ == '__main__':
import json
print(json.dumps(generate(), indent=2))
+211
View File
@@ -0,0 +1,211 @@
"""Bounded upload experiment. Recreates only API; preserves all data volumes."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import threading
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check
from upload_fixtures import generate
def docker(*args, required=True):
result = subprocess.run(['docker', *args], cwd=ROOT, capture_output=True, text=True, timeout=120)
if required:
check(result.returncode == 0, 'Docker operation failed: ' + args[0])
return result
def compose(*args):
return docker('compose', '--env-file', '.env', *args).stdout.strip()
def wait_two(c, ids):
aliases = {docker('exec', cid, '/server', 'instance-id').stdout.strip() for cid in ids}
deadline = time.monotonic() + 60
seen, stable = set(), 0
while True:
try:
alias = c.call('GET', '/health/ready', schema='Health')['headers']['X-Instance-Id']
check(alias in aliases, 'old API still in LB')
seen.add(alias)
stable += 1
if seen == aliases and stable >= 8:
return
except Failure:
seen, stable = set(), 0
check(time.monotonic() < deadline, 'two new API did not become ready')
time.sleep(0.2)
def resources(ids):
result = []
for cid in ids:
state = json.loads(docker('inspect', '--format', '{{json .State}}', cid).stdout)
item = {'container_id': cid, 'status': state['Status'], 'oom_killed': state['OOMKilled']}
probe = docker('exec', cid, '/resourceprobe', required=False)
if probe.returncode == 0:
item.update(json.loads(probe.stdout))
else:
item['cgroup_unavailable'] = True
result.append(item)
return result
def percentile(values, percentile):
ordered = sorted(values)
if not ordered:
return None
index = (len(ordered)-1) * percentile / 100
low = int(index)
return round(ordered[low] + (ordered[min(low+1, len(ordered)-1)] - ordered[low]) * (index-low), 4)
def experiment(args, fixture):
c = Client(args.base_url, timeout=65)
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', '--wait-timeout', '60', 'api')
ids = compose('ps', '-q', 'api').split()
check(len(ids) == 2, 'expected two API')
wait_two(c, ids)
alice, bob, _, chat = c.bootstrap()
for _ in range(2):
c.attachment(alice, chat) # Same small warmup for every profile.
payload = Path(fixture['path']).read_bytes()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + Path(fixture['path']).name
samples, stop = [], threading.Event()
def monitor():
while not stop.is_set():
observation = docker('stats', '--no-stream', '--format', '{{json .}}', *ids, required=False)
if observation.returncode == 0:
for line in observation.stdout.splitlines():
item = json.loads(line)
item['elapsed_seconds'] = round(time.monotonic() - observation_start, 3)
samples.append(item)
stop.wait(0.2)
observation_start = time.monotonic()
before = resources(ids)
check(all('memory_peak_bytes' in item for item in before), 'cgroup v2 measurement unavailable')
thread = threading.Thread(target=monitor, daemon=True)
thread.start()
results, batches = [], []
lock = threading.Lock()
active = maximum_active = 0
try:
for repeat in range(args.repeats):
barrier = threading.Barrier(args.concurrency)
def send(_):
nonlocal active, maximum_active
local = Client(args.base_url, timeout=65)
barrier.wait(timeout=15)
started = time.monotonic()
with lock:
active += 1
maximum_active = max(maximum_active, active)
try:
response = local.call('POST', path, 201, actor=alice, raw=payload,
headers={'Content-Type': fixture['content_type']}, schema='Attachment')
return {'ok': True, 'seconds': time.monotonic()-started, 'attachment': response['json'],
'instance': response['headers']['X-Instance-Id']}
except (Failure, OSError, TimeoutError) as exc:
return {'ok': False, 'seconds': time.monotonic()-started, 'error': str(exc)[:200]}
finally:
with lock:
active -= 1
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
batch = list(executor.map(send, range(args.concurrency)))
batches.append({'repeat': repeat+1, 'seconds': round(time.monotonic()-started, 4),
'successes': sum(item['ok'] for item in batch),
'errors': sum(not item['ok'] for item in batch)})
results.extend(batch)
after = resources(ids)
observation_seconds = time.monotonic() - observation_start
finally:
stop.set()
thread.join(timeout=5)
successes = [item for item in results if item['ok']]
verified = 0
for item in successes:
a = item['attachment']
check(a['sha256'] == fixture['sha256'] and a['size_bytes'] == len(payload), 'upload checksum/size mismatch')
response = c.call('GET', '/api/v1/attachments/' + a['id'] + '/content', actor=bob)
check(response['bytes'] == payload and hashlib.sha256(response['bytes']).hexdigest() == fixture['sha256'], 'download mismatch')
check(response['headers'].get_content_type() == fixture['content_type'], 'download MIME mismatch')
verified += 1
timed_seconds = sum(batch['seconds'] for batch in batches)
result = {
'fixture': {key: value for key, value in fixture.items() if key != 'path'},
'concurrency': args.concurrency, 'max_client_in_flight': maximum_active, 'repeats': args.repeats,
'warmup': '2 sample.png uploads after fresh API start', 'batches': batches,
'successful_requests': len(successes), 'error_count': len(results)-len(successes),
'error_fraction': (len(results)-len(successes))/len(results),
'errors': [item['error'] for item in results if not item['ok']],
'http_upload_seconds': round(timed_seconds, 4),
'successful_rps': round(len(successes)/timed_seconds, 3),
'latency_success_seconds': {f'p{p}': percentile([item['seconds'] for item in successes], p) for p in (50, 95, 99)},
'serving_instances': len({item['instance'] for item in successes}), 'downloads_verified': verified,
'resources_before': before, 'resources_after': after,
'resource_observation_seconds': round(observation_seconds, 4), 'docker_stats_samples': samples,
}
for first, last in zip(before, after):
if 'cpu_usage_usec' in last:
last['cpu_mean_percent_one_core'] = round((last['cpu_usage_usec']-first['cpu_usage_usec']) / (observation_seconds*10000), 2)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://127.0.0.1:8084')
parser.add_argument('--profiles', nargs='+', default=['rgb8_1mp', 'jpeg_1mp', 'rgba16_40mp', 'rgba16_wide_40mp'])
parser.add_argument('--concurrency', type=int, default=10)
parser.add_argument('--repeats', type=int, default=3)
parser.add_argument('--output', default='evidence/upload-memory.json')
args = parser.parse_args()
check(1 <= args.concurrency <= 32 and 1 <= args.repeats <= 5, 'invalid experiment bounds')
fixtures = {item['name']: item for item in generate()}
check(all(name in fixtures for name in args.profiles), 'missing fixture; run go run ./student-tests/fixturegen first')
engine = json.loads(docker('info', '--format', '{{json .}}').stdout)
report = {'utc': dt.datetime.now(dt.timezone.utc).isoformat(), 'python': sys.version.split()[0],
'docker': {'server': engine['ServerVersion'], 'cpus': engine['NCPU'], 'memory_bytes': engine['MemTotal']},
'method': 'synchronized finite batches, fresh API per profile, kernel peak since cgroup creation including warmup/probes; no upload retries',
'profiles': []}
output = ROOT / args.output
for name in args.profiles:
result = experiment(args, fixtures[name])
report['profiles'].append(result)
output.write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps({'profile': name, 'successes': result['successful_requests'], 'errors': result['error_count'],
'peak_MiB': [round(item.get('memory_peak_bytes', 0)/1048576, 2) for item in result['resources_after']],
'oom_killed': [item['oom_killed'] for item in result['resources_after']]}), flush=True)
# Restore stopped API after a diagnostic failure without changing data volumes.
stopped = docker('compose', '--env-file', '.env', 'ps', '-a', '-q', 'api').stdout.split()
for cid in stopped:
if docker('inspect', '--format', '{{.State.Running}}', cid).stdout.strip() != 'true':
docker('start', cid)
check(all(profile['error_count'] == 0 for profile in report['profiles']), 'upload failures recorded; inspect JSON')
for profile in report['profiles']:
check(all(not item['oom_killed'] and item.get('oom_kills', 0) == 0 and item.get('swap_limit_bytes') == 0
for item in profile['resources_after']), 'OOM or unexpected swap configuration')
if args.concurrency >= 10:
check(profile['max_client_in_flight'] >= 10 and profile['serving_instances'] == 2,
'experiment did not reach ten overlapping uploads and both API')
print('PASS: upload concurrency/memory experiment and original-byte verification')
if __name__ == '__main__':
try:
main()
except (Failure, OSError, ValueError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)