Реализована лабораторная работа 5 на оценку 4

This commit is contained in:
MacBook
2026-11-03 14:05:38 +03:00
parent 276dbdad8a
commit 9db2fa724a
41 changed files with 4267 additions and 37 deletions
+82
View File
@@ -0,0 +1,82 @@
"""Local synthetic tests; credentials stay in memory and never enter evidence."""
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, run
def compose(*args, data=None):
result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
input=data, capture_output=True, text=True)
check(result.returncode == 0, 'compose command failed: ' + ' '.join(args[:3]))
return result.stdout.strip()
def psql(sql):
return compose('exec', '-T', 'postgres', 'psql', '-XAtq', '-v', 'ON_ERROR_STOP=1',
'-U', 'messenger', '-d', 'messenger', data=sql)
def wait_for(test, message, timeout=100):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
value = test()
if value:
return value
except Failure:
pass
time.sleep(.3)
raise Failure(message)
def ready(client):
wait_for(lambda: client.call('GET', '/health/ready', schema='Health'), 'API not ready')
def upload(client, actor, chat, raw=None):
if raw is None:
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
result = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=test.png',
202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(result['status'] == 'queued', '202 must contain queued snapshot')
return result
def state(client, actor, attachment):
return client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
def wait_state(client, actor, attachment, wanted='ready', timeout=100):
def poll():
result = state(client, actor, attachment)
if wanted == 'ready':
check(result['status'] != 'failed', 'job unexpectedly failed')
return result if result['status'] == wanted else None
return wait_for(poll, 'attachment did not become ' + wanted, timeout)
def fault(point):
compose('exec', '-T', 'api1', '/messenger', 'fault', 'arm', point)
def hit(point):
wait_for(lambda: psql("SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE point='" + point + "';") == 't',
'fault not reached: ' + point)
def dump_evidence(name, value):
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence' / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def start_only(service):
# Compose start can also start dependencies; fault tests need exactly this container.
container = compose('ps', '--all', '-q', service)
result = subprocess.run(['docker', 'start', container], capture_output=True, text=True)
check(result.returncode == 0, 'cannot start container ' + service)
+138
View File
@@ -0,0 +1,138 @@
"""Grade 4: durable acceptance, outbox, crashes, lease, retries, explicit replay."""
import hashlib
import json
import time
import uuid
from pipeline_helpers import *
def main():
client = Client(timeout=30)
ready(client)
actor, _, _, chat = client.bootstrap()
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
results = {}
try:
# Worker absent: no resize in API, accepted job survives real restarts.
compose('stop', 'worker')
attachment = upload(client, actor, chat)
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=actor)
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': '', 'attachment_ids': [attachment['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
services = ('api1', 'api2', 'broker')
def starts():
values = {}
for service in services:
container = compose('ps', '-q', service)
data = subprocess.run(['docker', 'inspect', container], capture_output=True, text=True, check=True)
values[service] = json.loads(data.stdout)[0]['State']['StartedAt']
return values
before = starts()
compose('restart', *services)
ready(client)
after = starts()
check(all(before[s] != after[s] for s in services), 'actual restart not observed')
check(state(client, actor, attachment)['status'] == 'queued', 'worker stopped but state changed')
start_only('worker')
result = wait_state(client, actor, attachment)
check({v['name'] for v in result['variants']} == {'thumbnail', 'crop', 'optimized'}, 'missing grade4 variants')
check(client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes'] == raw, 'original changed')
wait_for(lambda: psql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='" + attachment['id'] + "';") == 't', 'staging not cleaned')
results['stopped_worker_and_restart'] = dict(status='PASS', before=before, after=after)
# Committed outbox remains when dispatcher dies before XADD.
compose('stop', 'dispatcher')
fault('dispatcher_before_publish')
item = upload(client, actor, chat)
check(psql("SELECT count(*) FROM attachment_outbox WHERE job_id='" + item['id'] + "';") == '1', 'outbox absent')
compose('start', 'dispatcher')
hit('dispatcher_before_publish')
wait_state(client, actor, item)
results['commit_publish_gap'] = 'PASS: actual dispatcher exit 86 and automatic restart'
# Crash after S3 objects, before final PG COMMIT; reclaim expired processing.
fault('worker_after_objects')
item = upload(client, actor, chat)
hit('worker_after_objects')
check(psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'processing', 'crash did not leave processing')
started = time.monotonic()
result = wait_state(client, actor, item, timeout=110)
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '2', 'expired lease not recovered')
check(len(result['variants']) == 3, 'duplicate variant metadata')
results['crash_after_objects'] = dict(status='PASS', recovery_seconds=round(time.monotonic()-started, 3), attempts=2)
# COMMIT ready then death before ack: ready must never regress/reprocess.
fault('worker_before_ack')
item = upload(client, actor, chat)
hit('worker_before_ack')
result = wait_state(client, actor, item)
attempts = psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';")
duplicate = dict(schema_version=1, job_id=item['id'], type='attachment.process.v1', attachment_id=item['id'],
pipeline_version=1, attempt=1, created_at=item['created_at'])
# Use broker password only inside the container, never in evidence.
duplicate_id = compose('exec', '-T', 'broker', 'sh', '-ec',
'redis-cli --no-auth-warning -a "$(cat /run/secrets/broker_password)" XADD attachment.jobs.v1 "*" job "$1"',
'sh', json.dumps(duplicate))
wait_for(lambda: compose('exec', '-T', 'broker', 'sh', '-ec',
'redis-cli --raw --no-auth-warning -a "$(cat /run/secrets/broker_password)" XRANGE attachment.jobs.v1 "$1" "$1"',
'sh', duplicate_id) == '', 'ready duplicate was not acknowledged')
check(state(client, actor, item) == result, 'ready duplicate changed result')
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == attempts, 'ready duplicate processed again')
results['commit_before_ack_and_duplicate'] = 'PASS'
# Temporary S3 failure: attempt budget/backoff, failed registry, audited replay.
compose('stop', 'worker')
item = upload(client, actor, chat)
psql("UPDATE attachment_jobs SET max_attempts=2 WHERE id='" + item['id'] + "';")
compose('stop', 's3')
start_only('worker')
check(compose('ps', '--status', 'running', '-q', 's3') == '', 'fault test unexpectedly restarted S3')
wait_for(lambda: psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'failed', 'temporary errors did not exhaust retries', 100)
compose('start', 's3')
ready(client)
failed = state(client, actor, item)
check(failed['error_code'] == 'retry_exhausted', 'unsafe or missing final error')
client.call('GET', '/api/v1/attachments/' + item['id'] + '/content', 409, actor=actor)
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
body={'text':'failed', 'attachment_ids':[item['id']]}, headers={'Idempotency-Key':uuid.uuid4().hex})
registry = compose('exec', '-T', 'dispatcher', '/messenger', 'failed-jobs')
check(item['id'] in registry, 'failed registry missing job')
compose('exec', '-T', 'dispatcher', '/messenger', 'replay', item['id'])
wait_state(client, actor, item)
check(psql("SELECT count(*) FROM attachment_replays WHERE job_id='" + item['id'] + "';") == '1', 'replay audit missing')
proc = subprocess.run(['docker','compose','--env-file','.env','exec','-T','dispatcher','/messenger','replay',item['id']], cwd=ROOT, capture_output=True)
check(proc.returncode != 0, 'ready replay must be refused')
results['retry_failed_registry_replay'] = dict(status='PASS', exhausted_attempts=2, error_code='retry_exhausted', replay_audit_rows=1, ready_replay_rejected=True)
# Permanent invalid staging: no endless retries, safe machine error.
compose('stop', 'worker')
item = upload(client, actor, chat)
original_key = uuid.uuid4().hex
original_body = {'text':'accepted while queued', 'attachment_ids':[item['id']]}
original_message = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
# Integrity metadata mismatch represents invalid durable source.
psql("UPDATE attachments SET sha256=repeat('0',64) WHERE id='" + item['id'] + "';")
start_only('worker')
failed = wait_state(client, actor, item, 'failed')
check(failed['error_code'] == 'invalid_image', 'permanent invalid source must fail safely')
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '1', 'permanent error retried')
repeated = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
check(repeated == original_message, 'committed message replay changed after attachment failed')
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409,
actor=actor, body=original_body, headers={'Idempotency-Key':uuid.uuid4().hex})
results['permanent_error'] = 'PASS'
results['message_replay_after_attachment_failure'] = 'PASS'
results['crash_points'] = json.loads(psql("SELECT json_agg(json_build_object('point',point,'armed',armed,'hit_at',hit_at) ORDER BY point) FROM pipeline_faults WHERE hit_at IS NOT NULL;"))
dump_evidence('pipeline-grade4.json', results)
print('PASS:', json.dumps(results))
finally:
compose('start', 's3', 'broker', 'dispatcher', 'worker', 'api1', 'api2')
psql('DELETE FROM pipeline_faults;')
ready(client)
if __name__ == '__main__':
run(main)
+79
View File
@@ -0,0 +1,79 @@
"""Public persistence/failover hooks plus actual container restart evidence."""
import json
import subprocess
import uuid
from pipeline_helpers import *
def snapshots():
services=('postgres','redis','s3','broker','api1','api2','dispatcher','worker','cleanup','nginx')
result={}
for service in services:
container=compose('ps','-q',service)
info=subprocess.run(['docker','inspect',container],capture_output=True,text=True,check=True)
data=json.loads(info.stdout)[0]
result[service]=dict(id=data['Id'],started_at=data['State']['StartedAt'])
return result
def main():
client=Client();ready(client)
before=snapshots()
base=client.base
command=['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base]
result=subprocess.run(command,cwd=ROOT,capture_output=True,text=True)
check(result.returncode==0,'public persistence failed: '+result.stdout[-500:])
after=snapshots()
check(all(before[s]['started_at']!=after[s]['started_at'] for s in before),'hook did not restart all required services')
output={'persistence':dict(status='PASS',before=before,after=after),'failover':[]}
public=subprocess.run(['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh','BASE_URL='+base],cwd=ROOT,capture_output=True,text=True)
check(public.returncode==0,'public failover failed: '+public.stdout[-500:])
output['public_failover']=dict(status='PASS',output=public.stdout.strip())
try:
compose('start','api1','api2');ready(client)
actor,_,_,chat=client.bootstrap()
item=upload(client,actor,chat);wait_state(client,actor,item)
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
path='/api/v1/chats/'+chat['id']+'/messages'
for target in ('api-1','api-2'):
compose('start','api1','api2');ready(client)
seen=set()
wait_for(lambda: (seen.add(client.call('GET','/health/ready')['headers']['X-Instance-Id']) or len(seen)==2),'two replicas not visible')
process=subprocess.Popen([str(ROOT/'scripts/stop-one.sh')],cwd=ROOT,
env=dict(os.environ,TARGET_INSTANCE_ID=target),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
began=time.monotonic();deadline=began+8;first=None;confirmed=set();failures=0
key=uuid.uuid4().hex
while time.monotonic()<deadline:
try:
response=client.call('POST',path,201,actor=actor,body={'text':key},headers={'Idempotency-Key':key},schema='Message')
confirmed.add(response['json']['id'])
if process.poll() is not None and response['headers']['X-Instance-Id']!=target and first is None:
first=time.monotonic()-began
key=uuid.uuid4().hex
except Failure:
failures+=1
time.sleep(.1)
check(process.wait(timeout=10)==0,'stop hook failed')
check(first is not None and first<=10,'surviving API did not recover within 10 seconds')
service={'api-1':'api1','api-2':'api2'}[target]
check(not compose('ps','--status','running','-q',service),'target was not actually stopped')
page=client.call('GET',path+'?limit=100',actor=actor,schema='MessagePage')['json']
visible={m['id'] for m in page['items']}
# At most 80 requests per case: walk pages to include both cases.
while page['next_cursor']:
from urllib.parse import quote
page=client.call('GET',path+'?limit=100&cursor='+quote(page['next_cursor']),actor=actor,schema='MessagePage')['json']
visible.update(m['id'] for m in page['items'])
check(confirmed.issubset(visible),'confirmed messages lost')
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original lost on API failover')
output['failover'].append(dict(status='PASS',stopped_service=service,confirmed_messages=len(confirmed),
transient_failures=failures,first_survivor_seconds=round(first,3),original_preserved=True))
finally:
compose('start','api1','api2');ready(client)
dump_evidence('resilience.json',output)
print('PASS: all ten services restarted, same token/data/original preserved; both API failures covered')
if __name__=='__main__':
run(main)
+100
View File
@@ -0,0 +1,100 @@
"""Grade 4 image contract: actual decoding, EXIF, alpha, limits and private storage."""
import base64
import hashlib
import json
import struct
import uuid
import zlib
from pipeline_helpers import *
def make_fixture(kind):
code = '''
import base64,io,sys
from PIL import Image
kind=sys.argv[1]
if kind=='orientation':
im=Image.new('RGB',(320,200),'red');exif=Image.Exif();exif[274]=6;exif[315]='synthetic test';kw=dict(format='JPEG',exif=exif)
elif kind=='alpha':
im=Image.new('RGBA',(8,4),(255,0,0,0));kw=dict(format='PNG')
elif kind=='boundary':
im=Image.new('RGB',(8000,5000),'blue');kw=dict(format='PNG')
else:
im=Image.new('RGB',(1601,801),'blue');kw=dict(format='PNG')
b=io.BytesIO();im.save(b,**kw);print(base64.b64encode(b.getvalue()).decode())
'''
return base64.b64decode(compose('exec', '-T', 'worker', 'python3', '-c', code, kind))
def inspect_image(raw):
code = '''
import base64,io,json,sys
from PIL import Image
im=Image.open(io.BytesIO(base64.b64decode(sys.stdin.read())));im.load()
print(json.dumps(dict(format=im.format,width=im.width,height=im.height,exif=len(im.getexif()),pixel=list(im.convert('RGB').getpixel((0,0))))))
'''
return json.loads(compose('exec', '-T', 'worker', 'python3', '-c', code, data=base64.b64encode(raw).decode()))
def chunk(kind, payload):
return struct.pack('>I', len(payload)) + kind + payload + struct.pack('>I', zlib.crc32(kind+payload) & 0xffffffff)
def main():
client=Client(timeout=60)
actor, _, outsider, chat=client.bootstrap()
results={}
for kind in ('orientation','alpha','large','boundary'):
raw=make_fixture(kind)
content_type='image/jpeg' if kind=='orientation' else 'image/png'
item=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=synthetic',202,actor=actor,raw=raw,
headers={'Content-Type':content_type},schema='Attachment')['json']
result=wait_state(client,actor,item)
variants={v['name']:v for v in result['variants']}
expected={'orientation':(160,256),'alpha':(8,4),'large':(256,128),'boundary':(256,160)}[kind]
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==expected,'thumbnail dimensions/orientation')
check((variants['crop']['width'],variants['crop']['height'])==(128,128),'crop dimensions')
optimized={'orientation':(200,320),'alpha':(8,4),'large':(1280,640),'boundary':(1280,800)}[kind]
check((variants['optimized']['width'],variants['optimized']['height'])==optimized,'optimized fit dimensions')
for name,meta in variants.items():
blob=client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant='+name,actor=actor)['bytes']
check(hashlib.sha256(blob).hexdigest()==meta['sha256'] and len(blob)==meta['size_bytes'],'variant checksum/size')
decoded=inspect_image(blob)
check(decoded['format']==('WEBP' if name=='optimized' else 'JPEG'),'actual variant encoding')
check(decoded['exif']==0,'EXIF leaked into variant')
if kind=='alpha':
check(all(v>=250 for v in decoded['pixel']),'alpha not composited on white')
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
client.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider)
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=crop',404,actor=outsider)
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=missing',404,actor=actor)
results[kind]={'status':'PASS','variants':variants}
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
for size in (6294458,10485760):
extra=size-len(original)-12
raw=original[:-12]+chunk(b'paDd',bytes(extra))+original[-12:]
check(len(raw)==size,'fixture exact size')
item=upload(client,actor,chat,raw)
wait_state(client,actor,item)
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'large original changed')
path='/api/v1/chats/'+chat['id']+'/attachments?filename=bad.png'
client.call('POST',path,413,actor=actor,raw=bytes(10485761),headers={'Content-Type':'image/png'})
for raw in (original[:40],original[:-12],b'not an image'):
client.call('POST',path,415,actor=actor,raw=raw,headers={'Content-Type':'image/png'})
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',20000,10000,8,2,0,0,0))+chunk(b'IEND',b'')
client.call('POST',path,413,actor=actor,raw=huge,headers={'Content-Type':'image/png'})
results['byte_limits_corrupt_pixel_limits']='PASS'
item=upload(client,actor,chat)
wait_state(client,actor,item)
audit=compose('exec','-T','api1','/messenger','s3-audit','originals/'+item['id'])
check('PASS' in audit,'S3 credential audit failed')
results['private_bucket_limited_credentials']='PASS'
metrics=json.loads(compose('exec','-T','worker','/messenger','memory'))
check(metrics['memory.peak'] < metrics['memory.max'],'worker reached memory limit')
results['worker_memory_bytes']=metrics
dump_evidence('variants-grade4.json',results)
print('PASS: actual JPEG/WebP, EXIF orientation, white alpha, bounds, ACL, checksums, private S3')
if __name__=='__main__':
run(main)