add lab5
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit local Docker tests: private bucket, uploader failover, S3 outage."""
|
||||
import json
|
||||
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, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(['docker', 'compose', *args], cwd=ROOT, input=input,
|
||||
text=True, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'stack did not recover')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--mode', required=True, choices=['private', 'failover', 's3-outage'])
|
||||
args = arguments(__doc__, configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
att = uploaded['json']
|
||||
content_path = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
if args.mode == 'private':
|
||||
script = '''import sys, urllib.request, urllib.error
|
||||
url = "http://s3:8333/messenger-attachments/originals/" + sys.stdin.read().strip()
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403, error.code
|
||||
print("PASS: anonymous S3 GET returns 403 for an existing object")
|
||||
else:
|
||||
raise AssertionError("private object leaked")
|
||||
'''
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script, input=att['id']).strip())
|
||||
elif args.mode == 'failover':
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
service = None
|
||||
for candidate in ('api-a', 'api-b'):
|
||||
container = compose('ps', '-q', candidate).strip()
|
||||
hostname = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
|
||||
if hostname == target:
|
||||
service = candidate
|
||||
check(service is not None, 'uploading replica not found')
|
||||
try:
|
||||
compose('stop', service)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
download = c.call('GET', content_path, actor=bob)
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'download did not recover')
|
||||
time.sleep(0.5)
|
||||
check(download['headers']['X-Instance-Id'] != target, 'download used stopped uploader')
|
||||
check(download['bytes'] == data, 'original changed after stopping uploader')
|
||||
print('PASS: uploaded via ' + service + '; stopped that container; original downloaded through another replica')
|
||||
finally:
|
||||
compose('start', service)
|
||||
wait_ready(c)
|
||||
else:
|
||||
try:
|
||||
compose('stop', 's3')
|
||||
# Direct API request inside the network: LB excludes unready backends.
|
||||
script = '''import json, sys, urllib.request, urllib.error
|
||||
payload = json.load(sys.stdin)
|
||||
for method, path, body, headers in [
|
||||
("GET", "/health/ready", None, {}),
|
||||
("GET", payload["path"], None, {"Authorization": "Bearer " + payload["token"]}),
|
||||
("POST", payload["upload_path"], bytes.fromhex(payload["bytes"]),
|
||||
{"Authorization": "Bearer " + payload["token"], "Content-Type": "image/png"}),
|
||||
]:
|
||||
req = urllib.request.Request("http://localhost:8080" + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
document = json.load(error)
|
||||
assert document["error"]["code"] == "unavailable"
|
||||
assert document["error"]["request_id"] == error.headers["X-Request-Id"]
|
||||
else:
|
||||
raise AssertionError("S3 outage was not reported")
|
||||
assert urllib.request.urlopen("http://localhost:8080/health/live").status == 200
|
||||
print("PASS: S3 outage gives 503 for readiness, download and upload; liveness stays 200")
|
||||
'''
|
||||
payload = {'path': content_path, 'token': bob['token'], 'bytes': data.hex(),
|
||||
'upload_path': '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'}
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script,
|
||||
input=json.dumps(payload)).strip())
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
# HeadBucket/read recovery alone does not prove the write path is ready.
|
||||
# Use the same write-probing bootstrap as the documented restart hook.
|
||||
compose('run', '--rm', '--no-deps', 's3-init')
|
||||
wait_ready(c)
|
||||
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after-recovery.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
print('PASS: original available and new upload accepted after S3 restart/bootstrap')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attachment contract checks against the running lab5 stack."""
|
||||
import hashlib
|
||||
import http.client
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data, mime='image/png', filename='photo.png', status=202, actor=alice):
|
||||
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
|
||||
headers={'Content-Type': mime}, schema='Attachment' if status == 202 else None)
|
||||
|
||||
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
|
||||
data = buf.getvalue()
|
||||
att = upload(data, mime)['json']
|
||||
check(att['variants'] == [] and att['status'] == 'queued', 'wrong attachment state')
|
||||
att = c.wait_ready(bob, att)
|
||||
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
|
||||
content_path = '/api/v1/attachments/' + att['id']
|
||||
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
|
||||
'metadata changed')
|
||||
check(c.call('GET', content_path + '/content', actor=bob)['bytes'] == data, 'bytes changed')
|
||||
c.call('GET', content_path, 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 401)
|
||||
c.call('GET', content_path + '/content?variant=thumbnail', actor=bob)
|
||||
message = c.message(bob, chat, '', attachments=[att['id']])['json']
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
actor=alice, schema='MessagePage')['json']['items']
|
||||
check(message in history, 'attachment message missing in history')
|
||||
print('PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL')
|
||||
|
||||
for name in ('../x.png', 'x/y.png', 'x\\y.png', 'x\x00.png', 'x\n.png', 'x\x7f.png', ' ', 'x' * 256):
|
||||
upload(png, filename=name, status=400)
|
||||
upload(png, mime='image/jpeg', status=415)
|
||||
upload(b'not an image', status=415)
|
||||
upload(png[:30], status=415)
|
||||
upload(png, mime='application/octet-stream', status=415)
|
||||
upload(png, status=404, actor=eve)
|
||||
upload(b'x' * (10485760 + 1), status=413)
|
||||
|
||||
# Valid PNG header with an oversized canvas: reject before attempting pixel decoding.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8001, 5000, 8, 2, 0, 0, 0))
|
||||
huge += chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'')
|
||||
upload(huge, status=413)
|
||||
|
||||
# No Content-Length: limits must also work for chunked requests.
|
||||
url = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
|
||||
connection.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161),
|
||||
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'},
|
||||
encode_chunked=True)
|
||||
response = connection.getresponse()
|
||||
check(response.status == 413, 'chunked upload bypassed byte limit')
|
||||
response.read()
|
||||
connection.close()
|
||||
print('PASS: filename, MIME, malformed image, byte/pixel and chunked limits')
|
||||
|
||||
att = upload(png)['json']
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
for target, ids, code in ((chat, [str(uuid.uuid4())], 404),
|
||||
(other_chat, [att['id']], 404),
|
||||
(chat, [att['id'], att['id']], 400)):
|
||||
c.call('POST', '/api/v1/chats/' + target['id'] + '/messages', code, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, 'same', key=key)['json']
|
||||
check(c.message(alice, chat, 'same', key=key, attachments=[])['json'] == first,
|
||||
'omitted and empty attachment_ids differ')
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, '', key=key, attachments=[att['id']])['json']
|
||||
check(c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] == first, 'replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
|
||||
print('PASS: attachment scope, duplicates and idempotency normalization')
|
||||
|
||||
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
|
||||
exact = png + b'\0' * (10485760 - len(png))
|
||||
att = upload(exact)['json']
|
||||
c.wait_ready(bob, att)
|
||||
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
|
||||
'10 MiB original changed')
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (8000, 5000)).save(buf, 'PNG')
|
||||
att = upload(buf.getvalue())['json']
|
||||
check(att['size_bytes'] == len(buf.getvalue()), '40M pixel upload failed')
|
||||
print('PASS: inclusive 10 MiB and 40 million pixel boundaries')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Один ключ одновременно через LB создаёт ровно одно сообщение."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = "concurrent idempotency " + key
|
||||
|
||||
def send(_number: int):
|
||||
return Client().message(alice, chat, text, key=key)["json"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
check(all(reply == replies[0] for reply in replies), "replays returned different messages")
|
||||
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
history = client.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
|
||||
check(sum(message["id"] == replies[0]["id"] for message in history) == 1, "concurrent retries created duplicates")
|
||||
print("PASS: concurrent idempotency through load balancer")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check real producer payloads and redeliver a complete persisted message."""
|
||||
import json
|
||||
import time
|
||||
from jsonschema import Draft202012Validator, FormatChecker
|
||||
from pipeline_integration import ROOT, Client, remote, duplicate, snapshot, wait, check
|
||||
|
||||
|
||||
def main():
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
att, _ = c.attachment(actor, chat)
|
||||
wait(c, actor, att)
|
||||
payloads = remote('''rows = await db.pool.fetch('SELECT payload FROM attachment_outbox')
|
||||
print(json.dumps([json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload'] for row in rows]))''')
|
||||
validator = Draft202012Validator(json.loads((ROOT / 'contracts/jobs.schema.json').read_text()), format_checker=FormatChecker())
|
||||
for payload in payloads:
|
||||
validator.validate(payload)
|
||||
before = snapshot(att)
|
||||
duplicate(att)
|
||||
duplicate(att)
|
||||
time.sleep(3)
|
||||
check(snapshot(att) == before, 'persisted redelivery changed result')
|
||||
result = dict(status='PASS', validated_outbox_payloads=len(payloads),
|
||||
extra_payload_fields=False, persisted_redelivery_noop=True)
|
||||
(ROOT / 'evidence/job-contract.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Offline regression checks for delivery and terminal-state safety."""
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.worker import process_locked as process, settle_delivery
|
||||
from concurrent.futures import Future
|
||||
from src.broker import _publish_to
|
||||
|
||||
|
||||
class CriticalTests(unittest.IsolatedAsyncioTestCase):
|
||||
def test_failed_or_unrecorded_work_is_requeued(self):
|
||||
for result in (False, None, RuntimeError('database unavailable')):
|
||||
future, channel = Future(), MagicMock()
|
||||
if isinstance(result, Exception):
|
||||
future.set_exception(result)
|
||||
else:
|
||||
future.set_result(result)
|
||||
settle_delivery(channel, 7, future)
|
||||
channel.basic_ack.assert_not_called()
|
||||
channel.basic_nack.assert_called_once_with(7, requeue=True)
|
||||
|
||||
def test_durable_success_is_acked(self):
|
||||
future, channel = Future(), MagicMock()
|
||||
future.set_result(True)
|
||||
settle_delivery(channel, 7, future)
|
||||
channel.basic_ack.assert_called_once_with(7)
|
||||
channel.basic_nack.assert_not_called()
|
||||
|
||||
async def test_outbox_decodes_jsonb(self):
|
||||
store = PostgresStore('unused')
|
||||
store._pool = AsyncMock()
|
||||
payload = {'type': 'attachment.process.v1', 'attachment_id': str(uuid4())}
|
||||
store.pool.fetch.return_value = [{'id': uuid4(), 'payload': json.dumps(payload)}]
|
||||
event, = await store.due_outbox_events()
|
||||
self.assertEqual(json.loads(json.dumps(event['payload'])), payload)
|
||||
|
||||
async def run_processing(self, committed):
|
||||
store, s3 = AsyncMock(), AsyncMock()
|
||||
stamp = datetime.now(timezone.utc)
|
||||
store.claim_attachment_job.return_value = {
|
||||
'claim_time': stamp, 'staging_key': 'staging/test',
|
||||
'content_type': 'image/png', 'size_bytes': 1, 'sha256': 'unused',
|
||||
}
|
||||
store.complete_attachment_job.return_value = committed
|
||||
s3.settings = SimpleNamespace(max_pixels=40000000)
|
||||
s3.download_key.return_value = b'fixture'
|
||||
s3.delete.side_effect = RuntimeError('storage temporarily unavailable')
|
||||
payload = {'attachment_id': str(uuid4())}
|
||||
with patch('src.worker.render_isolated', return_value=[('thumbnail', b'jpeg', 'image/jpeg', 1, 1)]):
|
||||
await process(store, s3, payload, 60)
|
||||
self.assertEqual(store.complete_attachment_job.call_args.args[-1], stamp)
|
||||
return store, s3
|
||||
|
||||
async def test_cleanup_error_does_not_retry_ready(self):
|
||||
store, s3 = await self.run_processing(True)
|
||||
s3.delete.assert_awaited_once()
|
||||
store.retry_attachment_job.assert_not_awaited()
|
||||
|
||||
async def test_stale_completion_keeps_staging(self):
|
||||
_, s3 = await self.run_processing(False)
|
||||
s3.delete.assert_not_awaited()
|
||||
|
||||
async def test_stale_claim_cannot_publish_metadata(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchval.return_value = None
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
self.assertFalse(await store.complete_attachment_job(uuid4(), 'original', [], datetime.now(timezone.utc)))
|
||||
connection.execute.assert_not_awaited()
|
||||
|
||||
async def test_retry_of_terminal_or_stale_attempt_is_noop(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchrow.return_value = None
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
self.assertFalse(await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc)))
|
||||
connection.execute.assert_not_awaited()
|
||||
|
||||
def test_dlq_waits_for_publisher_confirm(self):
|
||||
connection = MagicMock()
|
||||
with patch('src.broker._connection', return_value=connection):
|
||||
_publish_to('dlq', {'failure': 'invalid_job'})
|
||||
connection.channel.return_value.confirm_delivery.assert_called_once()
|
||||
self.assertTrue(connection.channel.return_value.basic_publish.call_args.kwargs['mandatory'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Destructive-to-availability tests on the local lab stack; volumes preserved.
|
||||
|
||||
Only synthetic attachments created here are mutated. Tokens stay in memory.
|
||||
Run sequentially, never alongside load or another fault test.
|
||||
"""
|
||||
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
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def compose(*args, env=None, source=None):
|
||||
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT,
|
||||
env=dict(os.environ, **(env or {})), input=source,
|
||||
text=True, capture_output=True, timeout=150)
|
||||
check(result.returncode == 0, 'compose failed: ' + ' '.join(args[:4]) + '\n' + result.stderr[-1000:])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def remote(body, **values):
|
||||
source = '''import asyncio, json, os
|
||||
from uuid import UUID
|
||||
from src.config import load_settings
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.storage.s3 import S3Store, S3Settings
|
||||
from src.broker import publish
|
||||
V = json.loads(%r)
|
||||
async def main():
|
||||
db = PostgresStore(load_settings().database_url)
|
||||
await db.connect()
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
%s
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
asyncio.run(main())
|
||||
''' % (json.dumps(values), '\n'.join(' ' + line for line in body.splitlines()))
|
||||
return json.loads(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-', source=source))
|
||||
|
||||
|
||||
def record(name, **facts):
|
||||
RESULTS.append(dict(test=name, status='PASS', **facts))
|
||||
print('PASS: ' + name, flush=True)
|
||||
(ROOT / 'evidence/pipeline-integration.json').write_text(json.dumps(RESULTS, indent=2) + '\n')
|
||||
|
||||
|
||||
def ready(c):
|
||||
deadline = time.monotonic() + 90
|
||||
successes = 0
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
successes += 1
|
||||
if successes >= 5:
|
||||
return
|
||||
time.sleep(.5)
|
||||
except Failure:
|
||||
successes = 0
|
||||
time.sleep(.5)
|
||||
raise Failure('API did not recover')
|
||||
|
||||
|
||||
def wait(c, actor, att, status='ready', timeout=120):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
|
||||
except Failure:
|
||||
time.sleep(.25)
|
||||
continue
|
||||
if value['status'] == status:
|
||||
return value
|
||||
check(value['status'] != 'failed' or status == 'failed', 'unexpected failed attachment')
|
||||
time.sleep(.25)
|
||||
raise Failure('attachment did not reach ' + status)
|
||||
|
||||
|
||||
def snapshot(att):
|
||||
return remote('''row = await db.pool.fetchrow("SELECT a.status, j.attempt, j.job_id, a.original_key, a.staging_key FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1", UUID(V['id']))
|
||||
objects = sorted(list(await s3.list('originals/' + V['id'] + '/')) + list(await s3.list('variants/' + V['id'] + '/')))
|
||||
print(json.dumps(dict(row) | {'objects': objects}, default=str))''', id=att['id'])
|
||||
|
||||
|
||||
def duplicate(att):
|
||||
return remote('''payload = await db.pool.fetchval("SELECT o.payload FROM attachment_outbox o JOIN attachment_jobs j ON j.job_id=o.job_id WHERE j.attachment_id=$1 ORDER BY o.created_at LIMIT 1", UUID(V['id']))
|
||||
await publish(json.loads(payload) if isinstance(payload, str) else payload)
|
||||
print('true')''', id=att['id'])
|
||||
|
||||
|
||||
def main():
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
|
||||
# No worker: HTTP admission and message creation must remain asynchronous.
|
||||
compose('stop', '-t', '2', 'worker')
|
||||
att, data = c.attachment(alice, chat)
|
||||
check(att['status'] == 'queued', 'upload is not queued with stopped worker')
|
||||
c.message(alice, chat, 'queued attachment', attachments=[att['id']])
|
||||
time.sleep(2)
|
||||
compose('restart', 'broker')
|
||||
compose('up', '-d', '--no-deps', '--wait', 'broker')
|
||||
compose('restart', 'api-a', 'api-b')
|
||||
ready(c)
|
||||
compose('start', 'worker')
|
||||
completed = wait(c, bob, att)
|
||||
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == data, 'original changed')
|
||||
check({v['name'] for v in completed['variants']} == {'thumbnail', 'crop', 'optimized'}, 'variants missing')
|
||||
record('stopped worker, queued message, broker/API restart, ready', attachment_id=att['id'])
|
||||
|
||||
before = snapshot(att)
|
||||
duplicate(att)
|
||||
duplicate(att)
|
||||
time.sleep(3)
|
||||
check(snapshot(att) == before, 'duplicate changed result or created S3 objects')
|
||||
refused = remote("print(json.dumps(await db.replay_failed_attachment(UUID(V['id']))))", id=att['id'])
|
||||
check(refused is False, 'ready replay accepted')
|
||||
record('duplicate delivery and replay of ready are no-ops', object_count=len(before['objects']))
|
||||
|
||||
# Pause publication so the API crash is demonstrably before any publish.
|
||||
compose('stop', '-t', '2', 'outbox')
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b', env={'OUTBOX_FAULT_AFTER_COMMIT': '1'})
|
||||
ready(c)
|
||||
fault_actor, _, _, fault_chat = c.bootstrap()
|
||||
try:
|
||||
c.attachment(fault_actor, fault_chat)
|
||||
raise AssertionError('crash hook did not interrupt upload')
|
||||
except Failure:
|
||||
pass
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b')
|
||||
ready(c)
|
||||
row = remote('''rows = await db.pool.fetch("SELECT a.id, o.published_at FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id JOIN attachment_outbox o ON o.job_id=j.job_id WHERE a.chat_id=$1", UUID(V['chat']))
|
||||
assert len(rows) == 1 and rows[0]['published_at'] is None
|
||||
print(json.dumps({'id': str(rows[0]['id'])}))''', chat=fault_chat['id'])
|
||||
compose('start', 'outbox')
|
||||
wait(c, fault_actor, row)
|
||||
record('crash after COMMIT before publish recovered from existing outbox', attachment_id=row['id'])
|
||||
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'WORKER_FAULT_AFTER_S3_PUT': '1', 'JOB_TIMEOUT_SECONDS': '10'})
|
||||
att, _ = c.attachment(alice, chat)
|
||||
wait(c, alice, att)
|
||||
snap = snapshot(att)
|
||||
check(snap['attempt'] >= 2 and len(snap['objects']) >= 8, 'side effect crash/lease retry not observed')
|
||||
marker = compose('exec', '-T', 'worker', 'cat', '/tmp/worker-fault-after-s3')
|
||||
check(marker == att['id'], 'wrong fault target')
|
||||
record('worker crash after S3 before commit/ack, lease recovery', attempt=snap['attempt'], objects_before_cleanup=len(snap['objects']))
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker')
|
||||
|
||||
# Select only this test's unreferenced attempt keys for cleanup.
|
||||
cleaned = remote('''from argparse import Namespace
|
||||
from src.reconcile import run
|
||||
keys = V['keys']
|
||||
result = await run(Namespace(apply=True, grace_seconds=0, object_key=keys))
|
||||
print(json.dumps(result['deleted']))''', keys=snap['objects'])
|
||||
check(len(cleaned) == 4, 'stale attempt objects not cleaned safely')
|
||||
check(len(snapshot(att)['objects']) == 4, 'live attempt affected by cleanup')
|
||||
wait(c, alice, att)
|
||||
record('targeted orphan cleanup preserves committed attempt', deleted=len(cleaned))
|
||||
|
||||
# Lose only this synthetic staging object to exercise transient retry exhaustion.
|
||||
compose('stop', '-t', '2', 'worker')
|
||||
att, data = c.attachment(alice, chat)
|
||||
remote("await s3.delete('staging/' + V['id'] + '/original')\nprint('true')", id=att['id'])
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'JOB_MAX_ATTEMPTS': '2'})
|
||||
failed = wait(c, alice, att, 'failed')
|
||||
snap = snapshot(att)
|
||||
check(snap['attempt'] == 2 and failed['error_code'] == 'retry_exhausted', 'unbounded/wrong retry')
|
||||
# Restore exactly the bytes originally accepted, then explicit failed-only replay.
|
||||
import base64
|
||||
replayed = remote('''from io import BytesIO
|
||||
import base64
|
||||
content = base64.b64decode(V['data'])
|
||||
await s3.put('staging/' + V['id'] + '/original', BytesIO(content), len(content), 'image/png')
|
||||
print(json.dumps(await db.replay_failed_attachment(UUID(V['id']))))''', id=att['id'], data=base64.b64encode(data).decode())
|
||||
check(replayed, 'failed replay refused')
|
||||
wait(c, alice, att)
|
||||
record('bounded transient retry, failed registry and explicit replay', attempts_before_replay=snap['attempt'])
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker')
|
||||
|
||||
# Real Linux child with deliberately insufficient address space.
|
||||
memory = remote('''import subprocess
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
buf = BytesIO(); Image.new('RGB', (2400, 2400)).save(buf, 'PNG')
|
||||
env = dict(os.environ, RENDER_MEMORY_MB='120')
|
||||
p = subprocess.run(['/app/.venv/bin/python', '-m', 'src.render'], input=buf.getvalue(), capture_output=True, env=env, timeout=30)
|
||||
print(json.dumps({'returncode': p.returncode}))''')
|
||||
check(memory['returncode'] == 21, 'Linux memory limit did not produce bounded resource failure')
|
||||
record('Linux renderer memory limit', **memory)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b', 'worker', 'outbox')
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real PostgreSQL/S3/RabbitMQ invariant and security checks, synthetic data only."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
from pipeline_integration import Client, check, compose, remote, wait, ROOT
|
||||
|
||||
|
||||
def main():
|
||||
results = []
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
att, _ = c.attachment(alice, chat)
|
||||
wait(c, bob, att)
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
for name, fmt, bound in (('thumbnail', 'JPEG', 256), ('crop', 'JPEG', 128), ('optimized', 'WEBP', 1280)):
|
||||
content = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + name, actor=bob)['bytes']
|
||||
with Image.open(BytesIO(content)) as image:
|
||||
check(image.format == fmt and max(image.size) <= bound and not image.getexif(), 'variant format/size/EXIF')
|
||||
if name == 'crop':
|
||||
check(image.size == (128, 128), 'crop dimensions')
|
||||
results.append('actual thumbnail/crop/WebP formats, dimensions and removed EXIF')
|
||||
# Verify actual private object key, not a nonexistent legacy key.
|
||||
private = remote('''import urllib.request, urllib.error
|
||||
key = await db.pool.fetchval('SELECT original_key FROM attachments WHERE id=$1', UUID(V['id']))
|
||||
try:
|
||||
urllib.request.urlopen('http://s3:8333/' + s3.settings.bucket + '/' + key, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403, error.code
|
||||
else:
|
||||
raise AssertionError('anonymous object leaked')
|
||||
print('true')''', id=att['id'])
|
||||
check(private, 'private S3 check failed')
|
||||
for variant in ('thumbnail', 'crop', 'optimized'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + variant, 404, actor=eve)
|
||||
results.append('anonymous S3 403 on existing object; variant ACL 404')
|
||||
|
||||
lock = remote('''import time
|
||||
entered = asyncio.Event()
|
||||
async def writer():
|
||||
async with db.attachment_transaction():
|
||||
entered.set()
|
||||
await asyncio.sleep(1)
|
||||
task = asyncio.create_task(writer())
|
||||
await entered.wait()
|
||||
started = time.monotonic()
|
||||
async with db.attachment_transaction(maintenance=True):
|
||||
waited = time.monotonic() - started
|
||||
await task
|
||||
assert waited >= .9, waited
|
||||
print(json.dumps({'maintenance_wait_seconds': waited}))''')
|
||||
results.append(lock)
|
||||
|
||||
# Poison staging only for a newly created synthetic attachment and update its
|
||||
# digest so invalid-image classification (not transport checksum) is exercised.
|
||||
compose('stop', '-t', '2', 'worker')
|
||||
guarded, _ = c.attachment(alice, chat)
|
||||
fence = remote('''key = UUID(V['id'])
|
||||
job_id = await db.pool.fetchval('SELECT job_id FROM attachment_jobs WHERE attachment_id=$1', key)
|
||||
before = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id)
|
||||
await db.pool.execute("UPDATE attachment_jobs SET updated_at=now()-interval '61 seconds' WHERE attachment_id=$1", key)
|
||||
await db.schedule_due_jobs()
|
||||
after = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id)
|
||||
assert after == before + 1, 'unclaimed published job stranded'
|
||||
assert await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', key) == 1
|
||||
await db.schedule_due_jobs()
|
||||
assert await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id) == after, 'watchdog floods outbox'
|
||||
first = await db.claim_attachment_job(key, 30)
|
||||
assert first is not None
|
||||
assert await db.retry_attachment_job(key, 5, 30, first['claim_time'])
|
||||
assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed retry delay'
|
||||
await db.pool.execute("UPDATE attachment_jobs SET next_attempt_at=now() WHERE attachment_id=$1", key)
|
||||
await db.schedule_due_jobs()
|
||||
second = await db.claim_attachment_job(key, 30)
|
||||
assert second is not None and second['attempt'] == 2
|
||||
assert not await db.complete_attachment_job(key, 'invalid-stale-key', [], first['claim_time'])
|
||||
assert not await db.retry_attachment_job(key, 5, 0, first['claim_time'])
|
||||
await db.pool.execute("UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE attachment_id=$1", key)
|
||||
assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed lease attempt accounting'
|
||||
await db.schedule_due_jobs()
|
||||
third = await db.claim_attachment_job(key, 30)
|
||||
assert third['attempt'] == 3
|
||||
assert await db.retry_attachment_job(key, 5, 0, third['claim_time'])
|
||||
print('true')''', id=guarded['id'])
|
||||
check(fence, 'SQL fencing/backoff invariant')
|
||||
results.append('real SQL: queued watchdog republishes without attempt increment/flood; duplicate respects backoff; expired lease counted; stale completion/retry fenced')
|
||||
att, _ = c.attachment(alice, chat)
|
||||
remote('''from io import BytesIO
|
||||
from hashlib import sha256
|
||||
data = b'invalid image payload'
|
||||
await s3.put('staging/' + V['id'] + '/original', BytesIO(data), len(data), 'image/png')
|
||||
await db.pool.execute('UPDATE attachments SET size_bytes=$2, sha256=$3 WHERE id=$1', UUID(V['id']), len(data), sha256(data).hexdigest())
|
||||
print('true')''', id=att['id'])
|
||||
compose('start', 'worker')
|
||||
wait(c, alice, guarded)
|
||||
failed = wait(c, alice, att, 'failed')
|
||||
check(failed['error_code'] == 'invalid_image', 'permanent classification failed')
|
||||
attempt = remote("print(await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', UUID(V['id'])))", id=att['id'])
|
||||
check(attempt == 1, 'permanent error retried')
|
||||
results.append('permanent invalid_image reaches failed on attempt 1')
|
||||
|
||||
# DLQ uses confirmed persistent publication; count change avoids consuming
|
||||
# messages belonging to a different test.
|
||||
dlq = remote('''from src.broker import _connection, _publish, DLQ
|
||||
connection = _connection(); channel = connection.channel()
|
||||
before = channel.queue_declare(queue=DLQ, durable=True).method.message_count
|
||||
connection.close()
|
||||
_publish({'malformed': True})
|
||||
print(json.dumps({'before': before}))''')
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
count = remote('''from src.broker import _connection, DLQ
|
||||
connection = _connection()
|
||||
print(connection.channel().queue_declare(queue=DLQ, durable=True).method.message_count)
|
||||
connection.close()''')
|
||||
if count > dlq['before']:
|
||||
break
|
||||
time.sleep(.5)
|
||||
check(count == dlq['before'] + 1, 'invalid job not delivered to DLQ')
|
||||
results.append('malformed broker message delivered to DLQ')
|
||||
|
||||
# Actual Linux child timeout: no renderer can finish within this deadline.
|
||||
timeout = remote('''from src.worker import render_isolated
|
||||
try:
|
||||
render_isolated(b'x', .000001)
|
||||
except TimeoutError:
|
||||
print('true')
|
||||
else:
|
||||
raise AssertionError('timeout not enforced')''')
|
||||
check(timeout, 'timeout missing')
|
||||
results.append('Linux render subprocess killed/reaped on deadline')
|
||||
(ROOT / 'evidence/pipeline-invariants.json').write_text(json.dumps(results, indent=2) + '\n')
|
||||
print(json.dumps(results, indent=2), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker')
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Запрет БД только для api-a через pg_hba; восстановление в finally."""
|
||||
import ipaddress
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d",
|
||||
"messenger", "-v", "ON_ERROR_STOP=1", "-Atc", statement)
|
||||
|
||||
|
||||
def ready(service):
|
||||
code = """import urllib.request, urllib.error
|
||||
try:
|
||||
print(urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=7).status)
|
||||
except urllib.error.HTTPError as error:
|
||||
print(error.code)
|
||||
"""
|
||||
return compose("exec", "-T", service, "/app/.venv/bin/python", "-c", code)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client()
|
||||
container = json.loads(subprocess.check_output(
|
||||
["docker", "inspect", compose("ps", "-q", "api-a")], text=True))[0]
|
||||
addresses = list(container["NetworkSettings"]["Networks"].values())
|
||||
check(len(addresses) == 1, "test expects one API network")
|
||||
address = str(ipaddress.IPv4Address(addresses[0]["IPAddress"]))
|
||||
bad_id = container["Config"]["Hostname"]
|
||||
before = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(40)}
|
||||
check(len(before) == 2 and bad_id in before, "both API replicas must be reachable")
|
||||
check(ready("api-a") == ready("api-b") == "200", "both APIs must be ready")
|
||||
# Сохраняем исходный pg_hba; чужую оставшуюся резервную копию не перезаписываем.
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'test ! -e "$PGDATA/pg_hba.conf.readiness-backup"; '
|
||||
'cp -p "$PGDATA/pg_hba.conf" "$PGDATA/pg_hba.conf.readiness-backup"')
|
||||
try:
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'{ printf "host all all %s/32 reject\\n" "$1"; '
|
||||
'cat "$PGDATA/pg_hba.conf.readiness-backup"; } > "$PGDATA/pg_hba.conf"',
|
||||
"sh", address)
|
||||
sql("SELECT pg_reload_conf()")
|
||||
time.sleep(0.5)
|
||||
sql(f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE client_addr = '{address}'::inet")
|
||||
check(ready("api-a") == "503", "api-a must be unready")
|
||||
check(ready("api-b") == "200", "api-b must remain ready")
|
||||
# 2s interval + 2s check timeout, с запасом на планировщик Docker Desktop.
|
||||
time.sleep(6)
|
||||
for _ in range(40):
|
||||
result = client.call("GET", "/health/live", 200)
|
||||
check(result["headers"]["X-Instance-Id"] != bad_id, "LB selected unready api-a")
|
||||
for _ in range(20):
|
||||
result = client.call("POST", "/api/v1/users", 201, body={
|
||||
"username": "r_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Readiness regression",
|
||||
"password": "Test-password-" + uuid.uuid4().hex,
|
||||
}, schema="User")
|
||||
check(result["headers"]["X-Instance-Id"] != bad_id, "registration reached api-a")
|
||||
print("PASS: api-a ready=503, api-b ready=200; 40/40 live and 20/20 registrations use api-b")
|
||||
finally:
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'mv "$PGDATA/pg_hba.conf.readiness-backup" "$PGDATA/pg_hba.conf"')
|
||||
sql("SELECT pg_reload_conf()")
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
observed = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(10)}
|
||||
if observed == before:
|
||||
check(ready("api-a") == "200", "restored api-a must be ready")
|
||||
print("PASS: database access restored; both API replicas returned to LB")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("api-a did not return to LB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка 503 readiness при остановленном PostgreSQL."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
Client().call("GET", "/health/ready", 503)
|
||||
print("PASS: readiness rejects unavailable PostgreSQL")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject S3/DB disagreement and prove dry-run, grace period and safe repair."""
|
||||
import json
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None, env=None) -> str:
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
|
||||
input=input, env=env)
|
||||
|
||||
|
||||
def reconcile(*args) -> dict:
|
||||
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile", *args)
|
||||
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
|
||||
|
||||
|
||||
def s3_code(action: str, key: str, data: bytes | None = None) -> None:
|
||||
code = """from src.storage.s3 import S3Settings, S3Store
|
||||
import base64, json, sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
payload = json.load(sys.stdin)
|
||||
key = payload['key']
|
||||
try:
|
||||
if sys.argv[1] == 'put':
|
||||
s3.client.put_object(Bucket=s3.settings.bucket, Key=key,
|
||||
Body=base64.b64decode(payload.get('data', 'b3JwaGFu')))
|
||||
else:
|
||||
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
payload = {"key": key}
|
||||
if data is not None:
|
||||
payload["data"] = base64.b64encode(data).decode()
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
|
||||
input=json.dumps(payload))
|
||||
|
||||
|
||||
def wait_ready(client: Client, env=None) -> None:
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "stack did not recover")
|
||||
time.sleep(.5)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
|
||||
def upload(name, expected=201):
|
||||
return client.call("POST", path + name, expected, actor=alice, raw=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
# A reference object must survive an apply sweep, even with zero grace.
|
||||
protected = upload("protected.png")["json"]
|
||||
message = client.message(alice, chat, "protected", attachments=[protected["id"]])["json"]
|
||||
orphan = "originals/test-orphan-" + uuid.uuid4().hex
|
||||
s3_code("put", orphan)
|
||||
|
||||
report = reconcile("--grace-seconds", "3600")
|
||||
check(orphan in report["fresh_unreferenced"], "fresh orphan missing from dry-run")
|
||||
check(not report["deleted"], "dry-run deleted an object")
|
||||
report = reconcile("--apply", "--grace-seconds", "3600", "--object-key", orphan)
|
||||
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
|
||||
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
|
||||
check(orphan not in report["deleted"] and orphan not in report["orphan_candidates"],
|
||||
"second repair run was not idempotent")
|
||||
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"reconciler deleted a referenced object")
|
||||
|
||||
# This models loss after metadata has committed: report it, do not delete metadata.
|
||||
missing = upload("missing.png")["json"]
|
||||
missing_key = "originals/" + missing["id"]
|
||||
s3_code("delete", missing_key)
|
||||
try:
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", missing_key)
|
||||
expected = {"attachment_id": missing["id"], "object_key": missing_key}
|
||||
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
|
||||
client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
|
||||
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
|
||||
finally:
|
||||
s3_code("put", missing_key, image)
|
||||
check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"test object was not restored")
|
||||
report = reconcile("--grace-seconds", "0")
|
||||
check(expected not in report["missing_objects"], "restored object remained missing on second scan")
|
||||
print("PASS: S3-side missing object, dry-run, grace period and idempotent orphan repair", flush=True)
|
||||
|
||||
# Inject a process-equivalent failure after PUT directly into the configured
|
||||
# replica. The public load balancer may correctly select the healthy peer,
|
||||
# which would not exercise this boundary.
|
||||
environment = dict(__import__("os").environ, UPLOAD_FAULT_AFTER_S3_PUT="1")
|
||||
before_fault = set(reconcile("--grace-seconds", "0")["orphan_candidates"])
|
||||
try:
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
|
||||
wait_ready(client, environment)
|
||||
fault = """import base64, json, sys, urllib.error, urllib.request
|
||||
payload = json.load(sys.stdin)
|
||||
request = urllib.request.Request('http://127.0.0.1:8080/api/v1/chats/' + payload['chat_id'] +
|
||||
'/attachments?filename=fault-after-put.png', data=base64.b64decode(payload['image']),
|
||||
method='POST', headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
assert json.load(error)['error']['code'] == 'unavailable'
|
||||
else:
|
||||
raise AssertionError('fault injection unexpectedly returned success')
|
||||
"""
|
||||
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", fault,
|
||||
input=json.dumps({"chat_id": chat["id"], "token": alice["token"],
|
||||
"image": base64.b64encode(image).decode()}))
|
||||
report = reconcile("--grace-seconds", "0")
|
||||
injected = sorted(set(report["orphan_candidates"]) - before_fault)
|
||||
check(len(injected) == 1, "fault must create exactly one new orphan; run without other writers")
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", injected[0])
|
||||
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
|
||||
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]
|
||||
check(message in history["items"], "message reference was lost")
|
||||
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"used original was lost")
|
||||
print("PASS: injected pre-INSERT failure repaired; message and used original survive", flush=True)
|
||||
finally:
|
||||
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--force-recreate", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real database rejection, concurrent commit, interrupted upload and pagination."""
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, run
|
||||
|
||||
PROBE = r'''
|
||||
import asyncio, base64, hashlib, http.client, json, sys, urllib.request, urllib.error
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID, uuid4
|
||||
from src.config import load_settings
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.storage.s3 import S3Store, S3Settings
|
||||
from src.reconcile import run as reconcile, scan
|
||||
|
||||
payload = json.load(sys.stdin)
|
||||
image = base64.b64decode(payload['image'])
|
||||
chat_id, user_id = UUID(payload['chat_id']), UUID(payload['user_id'])
|
||||
|
||||
def upload(filename):
|
||||
req = urllib.request.Request('http://api-a:8080/api/v1/chats/' + str(chat_id) +
|
||||
'/attachments?filename=' + filename, data=image, method='POST',
|
||||
headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
return response.status, json.load(response)
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, json.load(error)
|
||||
|
||||
async def main():
|
||||
db = PostgresStore(load_settings().database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await db.connect()
|
||||
def args(key):
|
||||
return SimpleNamespace(apply=True, grace_seconds=0, object_key=[key])
|
||||
try:
|
||||
# A failed metadata inventory must not authorize any S3 deletion.
|
||||
key = 'originals/audit-inventory-' + uuid4().hex
|
||||
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
|
||||
class BrokenInventory:
|
||||
async def attachment_keys(self):
|
||||
# Real SQL failure, not an empty inventory on error.
|
||||
return await db.pool.fetch('SELECT * FROM audit_missing_table_' + uuid4().hex)
|
||||
try:
|
||||
async with db.attachment_transaction(maintenance=True):
|
||||
try:
|
||||
await scan(args(key), BrokenInventory(), s3)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('failed inventory did not abort')
|
||||
assert key in await s3.list('originals/')
|
||||
finally:
|
||||
await s3.delete(key)
|
||||
print('PASS: failed PostgreSQL inventory aborts apply without deleting the orphan', flush=True)
|
||||
|
||||
# An actual PostgreSQL trigger rejects only this test chat's INSERT.
|
||||
suffix = uuid4().hex
|
||||
name = 'audit_reject_' + suffix
|
||||
before = await s3.list('originals/')
|
||||
await db.pool.execute(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.chat_id = '{chat_id}'::uuid THEN
|
||||
RAISE EXCEPTION 'synthetic audit rejection' USING ERRCODE = '23514';
|
||||
END IF; RETURN NEW; END $$""")
|
||||
try:
|
||||
await db.pool.execute(f'CREATE TRIGGER {name} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {name}()')
|
||||
status, body = await asyncio.to_thread(upload, 'db-failure.png')
|
||||
assert status == 503 and body['error']['code'] == 'unavailable', (status, body)
|
||||
assert await db.pool.fetchval('SELECT count(*) FROM attachments WHERE chat_id=$1', chat_id) == 0
|
||||
finally:
|
||||
await db.pool.execute(f'DROP TRIGGER IF EXISTS {name} ON attachments')
|
||||
await db.pool.execute(f'DROP FUNCTION {name}()')
|
||||
created = set(await s3.list('originals/')) - set(before)
|
||||
assert len(created) == 1, created
|
||||
key = created.pop()
|
||||
report = await reconcile(SimpleNamespace(apply=False, grace_seconds=0, object_key=[key]))
|
||||
assert key in report['orphan_candidates'] and not report['deleted']
|
||||
assert (await reconcile(args(key)))['deleted'] == [key]
|
||||
assert not (await reconcile(args(key)))['deleted']
|
||||
print('PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op', flush=True)
|
||||
|
||||
# Writer holds a shared lock after PUT; cleanup must wait for COMMIT.
|
||||
identifier = uuid4()
|
||||
key = 'originals/' + str(identifier)
|
||||
async with db.attachment_transaction() as connection:
|
||||
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
|
||||
sweep = asyncio.create_task(reconcile(args(key)))
|
||||
for _ in range(40):
|
||||
waiting = await db.pool.fetchval("SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=41004 AND objid=1 AND NOT granted")
|
||||
if waiting:
|
||||
break
|
||||
await asyncio.sleep(.05)
|
||||
assert waiting and not sweep.done(), 'maintenance failed to wait for active writer'
|
||||
await db.create_attachment(identifier, chat_id, user_id, 'concurrent.png', 'image/png',
|
||||
len(image), hashlib.sha256(image).hexdigest(), key, connection=connection)
|
||||
report = await sweep
|
||||
assert key not in report['deleted'] and key not in report['orphan_candidates']
|
||||
row = await db.attachment_for_member(identifier, user_id)
|
||||
assert await s3.download(row) == image
|
||||
print('PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives', flush=True)
|
||||
|
||||
# Abrupt client close before all bytes arrive must not persist a file.
|
||||
before = await s3.list('originals/')
|
||||
rows = await db.attachment_keys()
|
||||
def interrupt():
|
||||
conn = http.client.HTTPConnection('api-a', 8080, timeout=10)
|
||||
conn.putrequest('POST', '/api/v1/chats/' + str(chat_id) + '/attachments?filename=interrupted.png')
|
||||
conn.putheader('Authorization', 'Bearer ' + payload['token'])
|
||||
conn.putheader('Content-Type', 'image/png')
|
||||
conn.putheader('Content-Length', str(len(image) + 100000))
|
||||
conn.endheaders()
|
||||
conn.send(image[:32])
|
||||
conn.close()
|
||||
await asyncio.to_thread(interrupt)
|
||||
await asyncio.sleep(1)
|
||||
assert await db.attachment_keys() == rows
|
||||
assert await s3.list('originals/') == before
|
||||
status, body = await asyncio.to_thread(upload, 'after-disconnect.png')
|
||||
assert status == 201, (status, body)
|
||||
print('PASS: interrupted upload leaves no metadata/object and next upload succeeds', flush=True)
|
||||
|
||||
# Exercise pagination on real S3 without adding thousands of fixtures.
|
||||
original_call = s3.call
|
||||
async def small_pages(method, **kwargs):
|
||||
if method == 'list_objects_v2':
|
||||
kwargs['MaxKeys'] = 7
|
||||
return await original_call(method, **kwargs)
|
||||
expected = await s3.list('originals/')
|
||||
s3.call = small_pages
|
||||
actual, pages = await s3.list_with_pages('originals/')
|
||||
assert actual == expected and pages > 1
|
||||
print(f'PASS: S3 pagination: {len(actual)} keys across {pages} pages, no missing/duplicate keys', flush=True)
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
asyncio.run(main())
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
payload = {"chat_id": chat["id"], "user_id": alice["id"], "token": alice["token"],
|
||||
"image": base64.b64encode((ROOT / "tests/fixtures/sample.png").read_bytes()).decode()}
|
||||
subprocess.run(["docker", "compose", "--profile", "maintenance", "run", "--rm", "--no-deps",
|
||||
"--entrypoint", "/app/.venv/bin/python", "reconcile", "-c", PROBE],
|
||||
cwd=ROOT, input=json.dumps(payload), text=True, check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure repeatable reconciler inventory cost for two controlled S3 sizes."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None) -> str:
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, input=input)
|
||||
|
||||
|
||||
def reconcile() -> dict:
|
||||
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile",
|
||||
"--grace-seconds", "3600")
|
||||
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
|
||||
|
||||
|
||||
def mutate(action: str, keys: list[str]) -> None:
|
||||
code = """from src.storage.s3 import S3Settings, S3Store
|
||||
import json, sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
for key in json.load(sys.stdin):
|
||||
if sys.argv[1] == 'put':
|
||||
s3.client.put_object(Bucket=s3.settings.bucket, Key=key, Body=b'track-2-benchmark')
|
||||
else:
|
||||
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
|
||||
input=json.dumps(keys))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
arguments(__doc__) # Keeps the common --base-url/--ca-file command interface.
|
||||
results = []
|
||||
for requested in (32, 128):
|
||||
prefix = f"originals/track2-benchmark-{uuid.uuid4().hex}-"
|
||||
keys = [prefix + str(index) for index in range(requested)]
|
||||
try:
|
||||
mutate("put", keys)
|
||||
reports = [reconcile() for _ in range(3)]
|
||||
for report in reports:
|
||||
check(set(keys).issubset(report["fresh_unreferenced"]),
|
||||
"benchmark objects were not included in the inventory")
|
||||
check(not set(keys) & set(report["orphan_candidates"]),
|
||||
"grace period classified fresh benchmark objects as deletable")
|
||||
seconds = [report["scan_metrics"]["total_seconds"] for report in reports]
|
||||
results.append({
|
||||
"added_unreferenced_objects": requested,
|
||||
"runs": 3,
|
||||
"s3_objects_scanned": reports[-1]["s3_objects"],
|
||||
"metadata_rows_scanned": reports[-1]["metadata_rows"],
|
||||
"s3_list_pages": reports[-1]["scan_metrics"]["s3_list_pages"],
|
||||
"seconds": seconds,
|
||||
"median_seconds": round(statistics.median(seconds), 6),
|
||||
})
|
||||
finally:
|
||||
mutate("delete", keys)
|
||||
print(json.dumps({"method": "three dry-run inventories per controlled size", "results": results},
|
||||
sort_keys=True))
|
||||
print("PASS: reconciler cost measured for 32 and 128 added S3 objects; fixtures removed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Contract, isolated-render and benchmark regressions without Docker."""
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import importlib.util
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from PIL import Image
|
||||
from src.worker import variants, render_isolated, PermanentFailure
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.reconcile import scan
|
||||
from src.errors import ApiError
|
||||
|
||||
|
||||
def png(width, height):
|
||||
buffer = BytesIO()
|
||||
Image.new('RGBA', (width, height), (255, 0, 0, 0)).save(buffer, 'PNG')
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class Regressions(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_failed_attachment_is_rejected(self):
|
||||
store, connection = PostgresStore('unused'), AsyncMock()
|
||||
connection.fetchval.side_effect = [1, 1, 1]
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
with self.assertRaises(ApiError) as error:
|
||||
await store.create_message_idempotent(uuid4(), uuid4(), '', 'key', 86400, [uuid4()])
|
||||
self.assertEqual(error.exception.status_code, 409)
|
||||
connection.fetchrow.assert_not_awaited()
|
||||
|
||||
def test_floor_and_small_images(self):
|
||||
self.assertEqual(variants(png(300, 200))[0][3:], (256, 170))
|
||||
self.assertEqual(variants(png(200, 300))[0][3:], (170, 256))
|
||||
self.assertEqual(variants(png(10, 8))[0][3:], (10, 8))
|
||||
for name, data, mime, width, height in variants(png(300, 200)):
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
self.assertEqual(image.size, (width, height))
|
||||
self.assertTrue(all(value > 240 for value in image.convert('RGB').getpixel((0, 0))))
|
||||
|
||||
def test_renderer_success_and_permanent_error(self):
|
||||
self.assertEqual(render_isolated(png(300, 200), 10)[0][3:], (256, 170))
|
||||
with self.assertRaises(PermanentFailure):
|
||||
render_isolated(b'not an image', 10)
|
||||
|
||||
def test_renderer_is_killed_on_deadline(self):
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(TimeoutError):
|
||||
render_isolated(png(300, 200), .0001)
|
||||
self.assertLess(time.monotonic() - started, 2)
|
||||
|
||||
async def test_cleanup_retains_active_and_failed_staging(self):
|
||||
old = datetime.now(timezone.utc) - timedelta(days=2)
|
||||
db, s3 = AsyncMock(), AsyncMock()
|
||||
db.attachment_keys.return_value = {'staging/active': uuid4(), 'staging/failed': uuid4(), 'originals/ready': uuid4()}
|
||||
s3.list_with_pages.side_effect = [({'staging/active': old, 'staging/failed': old, 'staging/orphan': old}, 1),
|
||||
({'originals/ready': old}, 1), ({'variants/orphan': old}, 1)]
|
||||
report = await scan(SimpleNamespace(grace_seconds=60, apply=True, object_key=[]), db, s3)
|
||||
self.assertEqual(report['deleted'], ['staging/orphan', 'variants/orphan'])
|
||||
|
||||
async def test_permanent_failure_is_atomic_and_not_retried(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchrow.return_value = {'attempt': 1}
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
result = await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc), 'invalid_image')
|
||||
self.assertFalse(result)
|
||||
self.assertEqual(connection.execute.await_count, 2)
|
||||
for call in connection.execute.call_args_list:
|
||||
self.assertIn("status='failed'", call.args[0])
|
||||
self.assertEqual(call.args[2], 'invalid_image')
|
||||
|
||||
def test_benchmark_partial_batch_and_recovery(self):
|
||||
spec = importlib.util.spec_from_file_location('track1', ROOT / 'scripts/track1.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
jobs, lock = {}, threading.Lock()
|
||||
class FakeClient:
|
||||
def __init__(self, *args, **kwargs): pass
|
||||
def bootstrap(self): return {}, {}, {}, {'id': str(uuid4())}
|
||||
def call(self, method, path, *args, **kwargs):
|
||||
if method == 'POST':
|
||||
key = str(uuid4())
|
||||
with lock: jobs[key] = {'id': key, 'status': 'ready', 'queue_wait_seconds': .01}
|
||||
return {'status': 202, 'json': {'id': key}}
|
||||
return {'json': {'status': 'ready'}}
|
||||
def attachment(self, *args): return {}, b''
|
||||
def wait_ready(self, *args, **kwargs): return {}
|
||||
def metrics(_):
|
||||
with lock:
|
||||
return {'jobs': list(jobs.values()), 'pending': 0, 'rss_bytes': 1000, 'concurrency': 2, 'prefetch': 2}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
destination = str(Path(directory) / 'result.json')
|
||||
args = SimpleNamespace(run_name='test', workers=2, prefetch=2, max_pending=20, images=10,
|
||||
concurrency=8, size=8, max_ready_seconds=2, require_backpressure=False,
|
||||
output=destination, base_url=None, ca_file=None)
|
||||
info = {'Config': {'Env': ['MAX_PENDING_JOBS=20']}, 'HostConfig': {'Memory': 4096, 'NanoCpus': 2}}
|
||||
with patch.object(module, 'arguments', return_value=args), patch.object(module, 'Client', FakeClient), \
|
||||
patch.object(module, 'metrics', side_effect=metrics), patch.object(module, 'container_info', return_value=info), \
|
||||
patch.object(module, 'broker_depth', return_value={'messages_ready': 0, 'messages_unacknowledged': 0}):
|
||||
module.main()
|
||||
report = json.loads(Path(destination).read_text())
|
||||
self.assertEqual(report['results']['ready'], 10)
|
||||
self.assertTrue(report['results']['recovery_upload_ready'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии ревью: не-ASCII Bearer и невалидная кодировка JSON через LB."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
for path in ("/api/v1/users/me", "/api/v1/auth/sessions/current"):
|
||||
method = "DELETE" if path.endswith("/current") else "GET"
|
||||
result = client.call(method, path, 401,
|
||||
headers={"Authorization": "Bearer é"}, schema="Error")
|
||||
check(result["headers"].get("WWW-Authenticate", "").startswith("Bearer"),
|
||||
"missing Bearer challenge")
|
||||
check(result["json"]["error"]["code"] == "unauthorized", "wrong error code")
|
||||
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
|
||||
"request IDs differ")
|
||||
for raw in (b"\xff", b"{", b'{"username":'):
|
||||
result = client.call("POST", "/api/v1/users", 400, raw=raw,
|
||||
headers={"Content-Type": "application/json"}, schema="Error")
|
||||
check(result["json"]["error"]["code"] == "invalid_request", "wrong JSON error code")
|
||||
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
|
||||
"request IDs differ")
|
||||
print("PASS: non-ASCII Bearer returns 401/challenge; malformed JSON returns contract Error/400")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove that the API identity is bucket-scoped and lacks admin operations."""
|
||||
import subprocess
|
||||
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 compose(*args, input=None):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
|
||||
input=input, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=permission.png", 202,
|
||||
actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
bucket = "permission-probe-" + uuid.uuid4().hex
|
||||
code = """from botocore.exceptions import ClientError
|
||||
from src.storage.s3 import S3Settings, S3Store
|
||||
import sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
try:
|
||||
s3.client.create_bucket(Bucket=sys.stdin.read().strip())
|
||||
except ClientError as error:
|
||||
assert error.response['Error']['Code'] in {'AccessDenied', 'Unauthorized'}, error.response
|
||||
else:
|
||||
raise AssertionError('API S3 identity unexpectedly has admin bucket creation')
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", code, input=bucket)
|
||||
admin = """from src.storage.s3 import S3Settings, S3Store
|
||||
import sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
s3.client.list_buckets()
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", admin)
|
||||
print("PASS: API identity cannot create buckets; maintenance identity has separate admin access")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка expiry; запускается при SESSION_TTL_SECONDS=2."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
actor = client.user("expiry")
|
||||
time.sleep(3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: expired Bearer session was rejected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ten concurrent bounded uploads, with API-container peak memory sampling."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import http.client
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
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 api_memory() -> dict[str, int]:
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api-a", "api-b"], cwd=ROOT, text=True).split()
|
||||
return {container[:12]: int(subprocess.check_output(
|
||||
["docker", "exec", container, "cat", "/sys/fs/cgroup/memory.current"], text=True))
|
||||
for container in ids}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument("--output", default="evidence/upload-memory.json")
|
||||
parser.add_argument("--size-mib", type=int, default=5)
|
||||
args = arguments(__doc__, configure)
|
||||
check(1 <= args.size_mib <= 10, "--size-mib must be 1..10")
|
||||
client = Client(args.base_url, args.ca_file, timeout=60)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
seed = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
payload = seed + b"\0" * (args.size_mib * 1024 * 1024 - len(seed))
|
||||
baseline, peak, samples, stop = api_memory(), {}, [], threading.Event()
|
||||
check(len(baseline) == 2, "memory experiment requires two running APIs")
|
||||
sampling_errors = []
|
||||
timestamps = []
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def sampler():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
values = api_memory()
|
||||
check(set(values) == set(baseline), "API containers changed during measurement")
|
||||
except Exception as error:
|
||||
sampling_errors.append(type(error).__name__)
|
||||
return
|
||||
timestamps.append(time.monotonic())
|
||||
samples.append(values)
|
||||
for name, value in values.items():
|
||||
peak[name] = max(peak.get(name, 0), value)
|
||||
time.sleep(.1)
|
||||
|
||||
def upload(index):
|
||||
barrier.wait(timeout=15)
|
||||
parsed = urlsplit(client.base)
|
||||
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=60)
|
||||
|
||||
def chunks():
|
||||
for offset in range(0, len(payload), 512 * 1024):
|
||||
yield payload[offset:offset + 512 * 1024]
|
||||
# Keep all ten client streams open long enough for multiple memory samples.
|
||||
time.sleep(.5)
|
||||
|
||||
connection.request("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(f"load-{index}.png"),
|
||||
body=chunks(), encode_chunked=True,
|
||||
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"})
|
||||
response = connection.getresponse()
|
||||
body = response.read()
|
||||
connection.close()
|
||||
check(response.status == 201, "upload %s returned %s: %s" % (index, response.status, body[:200]))
|
||||
return json.loads(body)
|
||||
|
||||
started = time.monotonic()
|
||||
thread = threading.Thread(target=sampler, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
attachments = list(pool.map(upload, range(10)))
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join(timeout=5)
|
||||
elapsed = time.monotonic() - started
|
||||
check(len({item["id"] for item in attachments}) == 10, "uploads were not distinct")
|
||||
check(not sampling_errors and len(samples) >= 2 and not thread.is_alive(),
|
||||
"memory sampler failed or did not collect enough samples: " + repr(sampling_errors))
|
||||
report = {
|
||||
"uploads": 10, "file_bytes": len(payload), "concurrency": 10,
|
||||
"api_upload_concurrency_limit": 1, "elapsed_seconds": round(elapsed, 3),
|
||||
"baseline_memory_bytes": baseline, "peak_memory_bytes": peak,
|
||||
"peak_growth_bytes": {name: peak.get(name, 0) - baseline.get(name, 0) for name in baseline},
|
||||
"samples": len(samples),
|
||||
"sample_intervals_seconds": [round(b-a, 3) for a, b in zip(timestamps, timestamps[1:])],
|
||||
"method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous.",
|
||||
}
|
||||
destination = ROOT / args.output
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
check(all(value <= 512 * 1024 * 1024 for value in peak.values()), "API exceeded configured memory limit")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user