ЛР 5: outbox, retry и versioned pipeline — Майорова БВТ2301
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
"""Stop worker, accept queued, restart API/broker, then complete the same attachment."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client,Failure
|
||||
|
||||
|
||||
def docker(*args):return subprocess.check_output(['docker',*args],text=True).strip()
|
||||
|
||||
|
||||
def main():
|
||||
c=Client();alice,bob,eve,chat=c.bootstrap();record={}
|
||||
before=json.loads(subprocess.check_output([sys.executable,'scripts/snapshot.py'],text=True))
|
||||
try:
|
||||
docker('compose','stop','worker','dispatcher')
|
||||
queued,raw=c.attachment(alice,chat)
|
||||
assert queued['status']=='queued'
|
||||
message=c.message(alice,chat,'accepted with worker stopped',attachments=[queued['id']])['json']
|
||||
c.call('GET','/api/v1/attachments/'+queued['id']+'/content',409,actor=bob)
|
||||
killed=docker('compose','ps','-q','api').splitlines()
|
||||
for container in killed:docker('kill','--signal=KILL',container)
|
||||
record['killed_api_containers']=killed
|
||||
docker('compose','up','-d','--wait','--no-deps','api')
|
||||
time.sleep(2)
|
||||
assert c.call('GET','/api/v1/attachments/'+queued['id'],actor=bob,schema='Attachment')['json']['status']=='queued'
|
||||
docker('compose','up','-d','--no-deps','dispatcher')
|
||||
deadline=time.monotonic()+10
|
||||
while int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))<1:
|
||||
assert time.monotonic()<deadline;time.sleep(.1)
|
||||
docker('compose','stop','dispatcher')
|
||||
length_before=int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))
|
||||
docker('compose','restart','broker')
|
||||
docker('compose','up','-d','--wait','--no-deps','broker')
|
||||
length_after=int(docker('compose','exec','-T','broker','redis-cli','XLEN','attachment-jobs'))
|
||||
assert length_after>=length_before>=1
|
||||
record['stream_entries_before_after_broker_restart']=[length_before,length_after]
|
||||
docker('compose','up','-d','--no-deps','worker','dispatcher')
|
||||
ready=c.wait_ready(bob,queued)
|
||||
assert c.call('GET','/api/v1/attachments/'+queued['id']+'/content',actor=bob)['bytes']==raw
|
||||
record.update(attachment_id=queued['id'],original_sha256=hashlib.sha256(raw).hexdigest(),status=ready['status'],variants=[v['name'] for v in ready['variants']],old_bearer_survived=True,message_attachment_retained=message['attachment_ids']==[queued['id']])
|
||||
finally:docker('compose','up','-d','--no-deps','worker','dispatcher')
|
||||
after=json.loads(subprocess.check_output([sys.executable,'scripts/snapshot.py'],text=True))
|
||||
record['before']=before;record['after']=after
|
||||
print(json.dumps(record,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Small deterministic PNG helpers; generation happens outside measurement."""
|
||||
import random
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
|
||||
def chunk(name, data):
|
||||
return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data) & 0xffffffff)
|
||||
|
||||
|
||||
def png(width, height, noise=False, rgb=True):
|
||||
channels = 3 if rgb else 1
|
||||
rand = random.Random(2301)
|
||||
encoded = zlib.compressobj(1)
|
||||
parts = []
|
||||
for _ in range(height):
|
||||
line = bytes(rand.getrandbits(8) for _ in range(width * channels)) if noise else b'\x7f' * (width * channels)
|
||||
parts.append(encoded.compress(b'\0' + line))
|
||||
parts.append(encoded.flush())
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 2 if rgb else 0, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def bomb():
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'x')) + chunk(b'IEND', b'')
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Real DB/S3/Redis fault injection. Stop production worker/dispatcher first."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path[:0]=['/app/src',str(Path.cwd()/'tests')]
|
||||
from PIL import Image
|
||||
from client import Client
|
||||
from pipeline import STREAM,GROUP,broker,connect,event,dispatch_once,process,ack
|
||||
from objects import Objects
|
||||
from postgres import setting
|
||||
from admin import replay,version,cleanup
|
||||
|
||||
|
||||
def main():
|
||||
c=Client();alice,bob,eve,chat=c.bootstrap()
|
||||
bus=broker(); objects=Objects(setting)
|
||||
report={'invariants':{},'faults':[]}
|
||||
def fetch(aid):
|
||||
with connect() as conn:
|
||||
a=conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s',(aid,)).fetchone()
|
||||
j=conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s',(a['current_job_id'],)).fetchone()
|
||||
return a,j
|
||||
def upload(raw=None,mime='image/png'):
|
||||
if raw is None: a,_=c.attachment(alice,chat)
|
||||
else:a=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=research.png',202,actor=alice,raw=raw,headers={'Content-Type':mime},schema='Attachment')['json']
|
||||
return a,fetch(a['id'])[1]
|
||||
def run_once(fault=None):
|
||||
args=[sys.executable,'/app/src/pipeline.py','work','--once']
|
||||
if fault:args+=['--fault-point',fault]
|
||||
return subprocess.run(args,capture_output=True,timeout=30).returncode
|
||||
def drain():
|
||||
for _ in range(200):
|
||||
batch=bus.xreadgroup(GROUP,'research-drain',{STREAM:'>'},count=1)
|
||||
if not batch:break
|
||||
for mid,data in batch[0][1]:process(json.loads(data['event']));ack(bus,mid)
|
||||
def expire(job):
|
||||
with connect() as conn:
|
||||
conn.execute("UPDATE attachment_jobs SET lease_until = clock_timestamp() - INTERVAL '1 second' WHERE 1=1 AND id = %s",(job['id'],))
|
||||
def recover(aid):
|
||||
until=time.monotonic()+20
|
||||
while time.monotonic()<until:
|
||||
dispatch_once(bus);drain()
|
||||
a,j=fetch(aid)
|
||||
if a['state']=='ready':return a,j
|
||||
time.sleep(.1)
|
||||
raise AssertionError('not recovered')
|
||||
for mid,data in bus.xautoclaim(STREAM,GROUP,'initial-recovery',min_idle_time=0,start_id='0-0',count=100)[1]:
|
||||
process(json.loads(data['event']));ack(bus,mid)
|
||||
# COMMIT -> no publisher yet: one queued row, no Redis message, then automatic outbox pass.
|
||||
a,j=upload()
|
||||
assert fetch(a['id'])[0]['state']=='queued'
|
||||
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',409,actor=bob)
|
||||
c.message(bob,chat,'queued is linkable',attachments=[a['id']])
|
||||
dispatch_once(bus);drain();assert fetch(a['id'])[0]['state']=='ready'
|
||||
report['invariants']['commit_before_publish_recovered']=True
|
||||
# Broker accepted XADD but publisher died before marking outbox: true exit(77).
|
||||
a,j=upload()
|
||||
code=subprocess.run([sys.executable,'/app/src/pipeline.py','dispatch','--once','--fault-point','after_publish'],capture_output=True,timeout=10).returncode
|
||||
assert code==77
|
||||
dispatch_once(bus);drain()
|
||||
assert fetch(a['id'])[0]['state']=='ready'
|
||||
report['invariants']['publish_before_marker_duplicate_safe']=True
|
||||
for point in ['before_side_effect','after_original','after_objects','after_commit']:
|
||||
a,j=upload();dispatch_once(bus)
|
||||
code=run_once(point);assert code==77,(point,code)
|
||||
before,job=fetch(a['id'])
|
||||
if point not in ('after_commit','before_side_effect'):expire(job)
|
||||
result,job=recover(a['id'])
|
||||
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',actor=bob)['bytes']==(Path.cwd()/'tests/fixtures/sample.png').read_bytes()
|
||||
reclaimed=bus.xautoclaim(STREAM,GROUP,'post-crash-redelivery',min_idle_time=0,start_id='0-0',count=100)[1]
|
||||
for mid,data in reclaimed:
|
||||
process(json.loads(data['event']));ack(bus,mid)
|
||||
assert bus.xpending(STREAM,GROUP)['pending']==0
|
||||
keys=objects.client.list_objects_v2(Bucket=objects.bucket,Prefix='results/'+a['id']+'/v1/').get('Contents',[])
|
||||
assert len(keys)==4,(point,len(keys))
|
||||
report['faults'].append({'point':point,'exit_code':code,'state_at_crash':before['state'],'recovered':result['state'],'attempts':job['attempt'],'result_objects':len(keys)})
|
||||
report['invariants']['crashes_before_after_side_effect_and_commit']=True
|
||||
bus.xadd(STREAM,{'event':json.dumps({'not':'a job'})})
|
||||
assert run_once()==0
|
||||
assert bus.xlen('rejected-jobs')>=1
|
||||
report['invariants']['invalid_envelope_observable_dlq']=True
|
||||
# Duplicate/reorder through broker on a completed job: no extra attempt/effect.
|
||||
a,j=upload();dispatch_once(bus);drain();before,done=fetch(a['id'])
|
||||
old=event(j)
|
||||
for attempt in [2,1,3,1,1]:bus.xadd(STREAM,{'event':json.dumps(dict(old,attempt=attempt))})
|
||||
drain();after,done2=fetch(a['id'])
|
||||
assert before['variants']==after['variants'] and done2['attempt']==done['attempt']
|
||||
report['invariants']['duplicate_and_reorder_no_second_effect']=True
|
||||
# Race two consumers with the SAME logical job, not just one serial duplicate.
|
||||
a,j=upload();e=event(j)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: results=list(pool.map(lambda _:process(e),range(2)))
|
||||
assert fetch(a['id'])[0]['state']=='ready' and sorted(results)==['noop','ready']
|
||||
report['invariants']['concurrent_duplicate_single_claim']=True
|
||||
# Pause actual old process after all immutable side effects, advance version and finish v2.
|
||||
a,j=upload();e=event(j)
|
||||
directory=Path('/tmp')/('fence-'+uuid.uuid4().hex);directory.mkdir();marker=directory/'paused';release=directory/'release'
|
||||
code="import sys,json,time;from pathlib import Path;sys.path.insert(0,'/app/src');from pipeline import process\ndef hook(point,job):\n if point=='after_objects':\n Path(sys.argv[2]).write_text('paused')\n while not Path(sys.argv[3]).exists():time.sleep(.05)\nprint(process(json.loads(sys.argv[1]),hook))"
|
||||
child=subprocess.Popen([sys.executable,'-c',code,json.dumps(e),str(marker),str(release)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
|
||||
try:
|
||||
deadline=time.monotonic()+20
|
||||
while not marker.exists():
|
||||
assert child.poll() is None
|
||||
assert time.monotonic()<deadline;time.sleep(.05)
|
||||
new=version(uuid.UUID(a['id']),2);newrow,newjob=fetch(a['id'])
|
||||
assert process(event(newjob))=='ready'
|
||||
current,finished=fetch(a['id']);signature=current['variants']
|
||||
release.write_text('go');stdout,stderr=child.communicate(timeout=10)
|
||||
assert child.returncode==0 and stdout.strip()=='fenced',(stdout,stderr)
|
||||
bus.xadd(STREAM,{'event':json.dumps(e)});drain()
|
||||
final,finished=fetch(a['id'])
|
||||
assert final['pipeline_version']==2 and final['variants']==signature and final['state']=='ready'
|
||||
assert all('/v2/' in v['object_key'] for v in final['variants'])
|
||||
report['invariants']['stale_running_version_fenced']=True
|
||||
report['invariants']['old_delivery_after_new_ready_no_overwrite']=True
|
||||
finally:
|
||||
release.write_text('go')
|
||||
if child.poll() is None:child.kill();child.wait()
|
||||
# Transient failures consume a finite budget; failed registry and explicit replay.
|
||||
a,j=upload()
|
||||
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
|
||||
# Exact staging copy saved externally; missing source is permanent and observable.
|
||||
raw=(Path.cwd()/'tests/fixtures/sample.png').read_bytes();objects.delete(j['source_key'])
|
||||
process(event(j));failed,fj=fetch(a['id']);assert failed['state']=='failed' and failed['error_code']=='source_missing'
|
||||
objects.put(j['source_key'],io.BytesIO(raw),len(raw),'image/png',hashlib.sha256(raw).hexdigest())
|
||||
replay(j['id']);fresh,fj=fetch(a['id']);assert process(event(fj))=='ready'
|
||||
try:replay(j['id']);raise AssertionError('replayed ready')
|
||||
except ValueError:pass
|
||||
report['invariants']['failed_registry_explicit_replay_and_ready_refusal']=True
|
||||
# Real S3 signature failures are transient, with two attempts and measured backoff.
|
||||
a,j=upload()
|
||||
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
|
||||
wrong=Path('/tmp/wrong-secret');wrong.write_text('synthetic-invalid-key-not-a-real-secret')
|
||||
env=dict(os.environ,S3_SECRET_ACCESS_KEY_FILE=str(wrong))
|
||||
transitions=[];started=time.monotonic()
|
||||
for _ in range(2):
|
||||
row,j=fetch(a['id'])
|
||||
delay=max(0,(j['next_attempt_at']-__import__('datetime').datetime.now(__import__('datetime').timezone.utc)).total_seconds())
|
||||
time.sleep(delay+.01)
|
||||
code="import sys,json;sys.path.insert(0,'/app/src');from pipeline import process;print(process(json.loads(sys.argv[1])))"
|
||||
run=subprocess.run([sys.executable,'-c',code,json.dumps(event(j))],env=env,capture_output=True,timeout=10)
|
||||
assert run.returncode==0
|
||||
row,j=fetch(a['id']);transitions.append({'state':j['state'],'attempt':j['attempt'],'error_code':j['error_code']})
|
||||
assert row['state']=='failed' and row['error_code']=='retry_exhausted' and j['attempt']==2
|
||||
replay(j['id']);row,j=fetch(a['id']);assert process(event(j))=='ready'
|
||||
report['retry']={'transitions':transitions,'seconds':round(time.monotonic()-started,3),'replayed_attempt':fetch(a['id'])[1]['attempt']}
|
||||
report['invariants']['transient_backoff_exhaustion_then_replay']=True
|
||||
# Real corrupted JPEG whose header is valid: heavy decoder fails safely in worker.
|
||||
jpg=io.BytesIO();Image.new('RGB',(320,200),'blue').save(jpg,format='JPEG');truncated=jpg.getvalue()[:-100]
|
||||
a,j=upload(truncated,'image/jpeg');process(event(j));bad,_=fetch(a['id'])
|
||||
assert bad['state']=='failed' and bad['error_code']=='invalid_image'
|
||||
report['invariants']['invalid_decode_permanent_failed']=True
|
||||
# EXIF, alpha, small image and all on-disk variants checked by the real decoder.
|
||||
transforms=[]
|
||||
for kind in ['alpha','exif','small']:
|
||||
out=io.BytesIO()
|
||||
if kind=='alpha':
|
||||
Image.new('RGBA',(20,10),(255,0,0,0)).save(out,format='PNG');mime='image/png'
|
||||
elif kind=='exif':
|
||||
image=Image.new('RGB',(200,320),'green');exif=Image.Exif();exif[274]=6;image.save(out,format='JPEG',exif=exif);mime='image/jpeg'
|
||||
else:Image.new('RGB',(5,3),'yellow').save(out,format='PNG');mime='image/png'
|
||||
a,j=upload(out.getvalue(),mime);assert process(event(j))=='ready'
|
||||
r=c.call('GET','/api/v1/attachments/'+a['id']+'/content?variant=thumbnail',actor=bob)
|
||||
with Image.open(io.BytesIO(r['bytes'])) as thumb:
|
||||
expected=(20,10) if kind=='alpha' else (256,160) if kind=='exif' else (5,3)
|
||||
assert thumb.size==expected
|
||||
assert not thumb.getexif()
|
||||
if kind=='alpha':assert min(thumb.getpixel((0,0)))>=250
|
||||
transforms.append({'kind':kind,'size':thumb.size,'exif_removed':not bool(thumb.getexif())})
|
||||
report['transforms']=transforms
|
||||
pending,pending_job=upload()
|
||||
dry=cleanup(False);fixed=cleanup(True);repeat=cleanup(True)
|
||||
assert fetch(pending['id'])[0]['state']=='queued' and objects.head(pending_job['source_key']) is not None
|
||||
report['invariants']['cleanup_preserves_current_and_fresh_failed']=True
|
||||
assert repeat['counts']['ready_staging']==0
|
||||
report['invariants']['ready_staging_cleanup_idempotent']=True
|
||||
report['cleanup']=[dry,fixed,repeat]
|
||||
print(json.dumps(report,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Figures from real accepted/ready and cgroup samples, no synthetic results."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
r=Path(__file__).resolve().parents[1]/'evidence'
|
||||
x=json.loads((r/'resources.json').read_text())['experiments']
|
||||
fig,axes=plt.subplots(1,2,figsize=(11,4.3),layout='constrained')
|
||||
labels=['320×200\n1,3 KiB','1800×1400\n7,21 MiB','10000×4000\n0,51 MiB']
|
||||
a=[max(v['accepted_seconds'] for v in e['replies']) for e in x]
|
||||
b=[max(v['ready_seconds'] for v in e['replies']) for e in x]
|
||||
axes[0].bar([i-.18 for i in range(3)],a,.36,label='p95 до 202')
|
||||
axes[0].bar([i+.18 for i in range(3)],b,.36,label='p95 до ready')
|
||||
axes[0].set(xticks=range(3),xticklabels=labels,ylabel='Секунды',title='10 одновременных загрузок · worker=1')
|
||||
axes[0].legend()
|
||||
peak=[int(e['after']['memory.peak'])/1048576 for e in x]
|
||||
anon=[max(int(dict(line.split() for line in s['worker']['memory.stat'].splitlines())['anon']) for s in e['samples'])/1048576 for e in x]
|
||||
axes[1].bar([i-.18 for i in range(3)],peak,.36,label='cgroup memory.peak')
|
||||
axes[1].bar([i+.18 for i in range(3)],anon,.36,label='Пик resident anon')
|
||||
axes[1].axhline(768,color='#d62728',linestyle='--',label='Лимит worker')
|
||||
axes[1].set(xticks=range(3),xticklabels=labels,ylabel='MiB',title='Worker + дочерний декодер')
|
||||
axes[1].legend(fontsize=8)
|
||||
for ax in axes:ax.grid(axis='y',alpha=.2);ax.set_axisbelow(True)
|
||||
fig.suptitle('ЛР 5 · реальные измерения · concurrency=1, prefetch=1')
|
||||
fig.savefig(r/'pipeline.png',dpi=150)
|
||||
fig.savefig(r/'pipeline.svg')
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Finite simultaneous jobs including 40 MP; record actual worker cgroup peak/RSS."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client
|
||||
from images import png
|
||||
|
||||
|
||||
def docker(*args):return subprocess.check_output(['docker',*args],text=True).strip()
|
||||
|
||||
|
||||
def memory(container):
|
||||
code="import json;from pathlib import Path;p=Path('/sys/fs/cgroup');print(json.dumps({k:(p/k).read_text().strip() for k in ['memory.current','memory.peak','memory.events','memory.stat','cpu.stat']}))"
|
||||
return json.loads(docker('exec',container,'python','-c',code))
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(timeout=30);a,b,e,chat=c.bootstrap()
|
||||
profiles=[(320,200,False),(1800,1400,True),(10000,4000,False)]
|
||||
result=[]
|
||||
for w,h,noise in profiles:
|
||||
content=png(w,h,noise=noise)
|
||||
docker('compose','restart','worker');container=docker('compose','ps','-q','worker')
|
||||
before=memory(container);samples=[];done=threading.Event();start=time.monotonic()
|
||||
def sample():
|
||||
while not done.is_set():
|
||||
samples.append({'seconds':round(time.monotonic()-start,4),'worker':memory(container)})
|
||||
done.wait(.05)
|
||||
sampler=threading.Thread(target=sample);sampler.start()
|
||||
barrier=threading.Barrier(10)
|
||||
def upload(i):
|
||||
barrier.wait();t=time.monotonic()
|
||||
r=Client(timeout=30).call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=load.png',202,actor=a,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
accepted=time.monotonic()-t
|
||||
ready=Client(timeout=30).wait_ready(b,r['json'])
|
||||
assert ready['sha256']==hashlib.sha256(content).hexdigest()
|
||||
return {'index':i,'accepted_seconds':accepted,'ready_seconds':time.monotonic()-t,'status':ready['status']}
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: replies=list(pool.map(upload,range(10)))
|
||||
finally:done.set();sampler.join()
|
||||
after=memory(container);assert 'oom_kill 0' in after['memory.events']
|
||||
result.append({'width':w,'height':h,'bytes':len(content),'clients':10,'before':before,'after':after,'samples':samples,'replies':replies,'seconds':time.monotonic()-start})
|
||||
print(json.dumps({'method':'10 simultaneous uploads, worker concurrency=1; cgroup v2 samples include child renderer; anon is resident anonymous memory, memory.peak includes tmpfs/kernel/cache','experiments':result},indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Private S3 and job envelopes do not expose source bytes or credentials."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
sys.path[:0]=['/app/src',str(Path.cwd()/'tests')]
|
||||
from client import Client
|
||||
from pipeline import connect,validate,event
|
||||
from objects import Objects
|
||||
from postgres import setting
|
||||
|
||||
c=Client();a,b,e,chat=c.bootstrap();att,raw=c.attachment(a,chat);ready=c.wait_ready(b,att)
|
||||
with connect() as conn:
|
||||
row=conn.execute('SELECT object_key, current_job_id FROM attachments WHERE 1=1 AND id = %s',(att['id'],)).fetchone()
|
||||
job=conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s',(row['current_job_id'],)).fetchone()
|
||||
message=event(job);message['attempt']=max(1,job['attempt'])
|
||||
assert validate(message)
|
||||
assert set(message)=={'schema_version','job_id','type','attachment_id','pipeline_version','attempt','created_at'}
|
||||
assert len(json.dumps(message))<1024
|
||||
for path in ('/'+Objects(setting).bucket+'/'+row['object_key'],'/'+Objects(setting).bucket+'?list-type=2'):
|
||||
try:urllib.request.urlopen('http://s3:8333'+path,timeout=2);raise AssertionError('anonymous access')
|
||||
except urllib.error.HTTPError as error:assert error.code==403
|
||||
for key in ['schema_version','pipeline_version','attempt']:
|
||||
bad=dict(message);bad[key]=True;assert not validate(bad)
|
||||
for body in [dict(message,extra='x'),dict(message,created_at='bad'),dict(message,traceparent='bad')]:assert not validate(body)
|
||||
print(json.dumps({'anonymous_object_and_list_403':True,'job_fields':sorted(message),'job_bytes':len(json.dumps(message)),'no_source_bytes_or_credentials_in_envelope':True,'strict_invalid_envelope_checks':True},indent=2))
|
||||
@@ -0,0 +1,32 @@
|
||||
"""A continuously trickling client still reaches the absolute upload deadline."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import select
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
target = urlsplit(c.base)
|
||||
connection = socket.create_connection((target.hostname, target.port), timeout=3)
|
||||
header = 'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=slow_' + uuid.uuid4().hex + '.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer ' + alice['token'] + '\r\nContent-Type: image/png\r\nContent-Length: 10485760\r\nConnection: close\r\n\r\n'
|
||||
started = time.monotonic()
|
||||
connection.sendall(header.encode())
|
||||
response = b''
|
||||
while time.monotonic() - started < 20:
|
||||
if select.select([connection], [], [], .15)[0]:
|
||||
response += connection.recv(4096)
|
||||
if b'\r\n\r\n' in response:
|
||||
break
|
||||
connection.sendall(b'x')
|
||||
connection.close()
|
||||
elapsed = time.monotonic() - started
|
||||
assert response.startswith(b'HTTP/1.1 400') or response.startswith(b'HTTP/1.0 400'), response[:100]
|
||||
assert 14 <= elapsed < 19
|
||||
assert b'x-instance-id:' in response.lower() and b'x-request-id:' in response.lower()
|
||||
print(json.dumps({'trickle_seconds': round(elapsed, 3), 'http_status': 400, 'absolute_deadline_enforced': True}))
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Extra black-box tests, without changing the course's public tests."""
|
||||
import concurrent.futures
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client as PublicClient, LAB
|
||||
|
||||
|
||||
class Client(PublicClient):
|
||||
def call(self, method, path, *args, headers=None, **kwargs):
|
||||
headers = dict(headers or {})
|
||||
if method == 'POST' and path.endswith('/messages'):
|
||||
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
|
||||
return super().call(method, path, *args, headers=headers, **kwargs)
|
||||
|
||||
|
||||
class APIContract(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = '/api/v1/chats/' + self.chat['id']
|
||||
|
||||
def test_malformed_json_and_extra_fields(self):
|
||||
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
|
||||
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
|
||||
|
||||
def test_unicode_limits(self):
|
||||
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
|
||||
self.assertEqual(result['text'], '👩' * 4000)
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
|
||||
|
||||
def test_unicode_nul_round_trip(self):
|
||||
import base64
|
||||
value = 'A\x00B\\u0000👩'
|
||||
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
|
||||
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
|
||||
self.assertEqual(user['display_name'], value)
|
||||
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
self.assertEqual(session['user'], user)
|
||||
actor = {'id': user['id'], 'token': session['token']}
|
||||
# Exercise the database path and then the Redis profile cache.
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
|
||||
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
|
||||
self.assertEqual(chat['title'], value)
|
||||
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
|
||||
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
|
||||
for content in contents:
|
||||
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
|
||||
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
|
||||
self.assertEqual([message['text'] for message in history['items']], contents)
|
||||
|
||||
def test_foreign_chat(self):
|
||||
for suffix in ('', '/messages'):
|
||||
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
|
||||
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
|
||||
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
|
||||
|
||||
def test_registration_race(self):
|
||||
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
|
||||
def register(_):
|
||||
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
statuses = list(executor.map(register, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
|
||||
def test_invalid_chat_creation(self):
|
||||
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
|
||||
for member_ids in members:
|
||||
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
|
||||
|
||||
def test_cursor_scope_and_validation(self):
|
||||
for i in range(3):
|
||||
self.client.message(self.alice, self.chat, str(i))
|
||||
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
|
||||
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
||||
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
|
||||
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
|
||||
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
|
||||
|
||||
def test_concurrent_messages_and_pagination(self):
|
||||
def send(i):
|
||||
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
sent = list(executor.map(send, range(100)))
|
||||
found = []
|
||||
cursor = None
|
||||
while True:
|
||||
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
|
||||
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
|
||||
found.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(found), 100)
|
||||
self.assertEqual(len({v['id'] for v in found}), 100)
|
||||
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
|
||||
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
|
||||
|
||||
def test_idempotency_concurrent_replicas(self):
|
||||
key = uuid.uuid4().hex
|
||||
def send(_):
|
||||
return Client().message(self.alice, self.chat, 'Один раз\x00👩', key=key)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
|
||||
replies = list(executor.map(send, range(32)))
|
||||
self.assertGreaterEqual(len({v['headers']['X-Instance-Id'] for v in replies}), 2)
|
||||
self.assertTrue(all(v['json'] == replies[0]['json'] for v in replies))
|
||||
page = self.client.call('GET', self.path + '/messages', actor=self.bob, schema='MessagePage')['json']
|
||||
self.assertEqual(page['items'], [replies[0]['json']])
|
||||
self.client.call('POST', self.path + '/messages', 409, actor=self.alice, body={'text': 'different'}, headers={'Idempotency-Key': key})
|
||||
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=self.alice)
|
||||
self.client.call('POST', self.path + '/messages', 401, actor=self.alice, body={'text': 'Один раз\x00👩'}, headers={'Idempotency-Key': key})
|
||||
|
||||
def test_protocol_error_headers(self):
|
||||
self.client.call('TRACE', '/api/v1/users/me', 400, actor=self.alice)
|
||||
|
||||
def test_idempotency_scope(self):
|
||||
key = uuid.uuid4().hex
|
||||
one = self.client.message(self.alice, self.chat, 'same', key=key)['json']
|
||||
two = self.client.message(self.bob, self.chat, 'same', key=key)['json']
|
||||
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'scope', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
|
||||
three = self.client.message(self.alice, other, 'same', key=key)['json']
|
||||
self.assertEqual(len({one['id'], two['id'], three['id']}), 3)
|
||||
|
||||
def test_idempotency_semantic_body(self):
|
||||
key = uuid.uuid4().hex
|
||||
one = self.client.message(self.alice, self.chat, 'semantic', key=key)['json']
|
||||
two = self.client.call('POST', self.path + '/messages', 201, actor=self.alice, body={'attachment_ids': [], 'text': 'semantic'}, headers={'Idempotency-Key': key}, schema='Message')['json']
|
||||
self.assertEqual(one, two)
|
||||
|
||||
def test_idempotency_invalid_keys(self):
|
||||
for key in (None, '', 'x' * 129, 'space key', 'bad,key', 'slash/key'):
|
||||
headers = {} if key is None else {'Idempotency-Key': key}
|
||||
PublicClient().call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': 'valid'}, headers=headers)
|
||||
for raw in (b'{"text":true}', b'{"text":"ok","extra":1}', b'{"text":"ok","attachment_ids":false}'):
|
||||
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
|
||||
def test_idempotency_conflicting_race(self):
|
||||
key = uuid.uuid4().hex
|
||||
def send(i):
|
||||
return Client().call('POST', self.path + '/messages', [201, 409], actor=self.alice, body={'text': str(i % 2)}, headers={'Idempotency-Key': key}, schema=None)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
|
||||
replies = list(executor.map(send, range(32)))
|
||||
self.assertEqual(sum(v['status'] == 201 for v in replies), 16)
|
||||
self.assertEqual(sum(v['status'] == 409 for v in replies), 16)
|
||||
page = self.client.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
|
||||
self.assertEqual(len(page['items']), 1)
|
||||
|
||||
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
|
||||
def test_unicode_password_basic_and_logout(self):
|
||||
import base64
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
|
||||
self.client.call('POST', '/api/v1/users', 201, body=registration)
|
||||
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
headers = {'Authorization': 'Basic ' + encoded}
|
||||
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
|
||||
actor = {'id': session['user']['id'], 'token': session['token']}
|
||||
self.client.call('GET', '/api/v1/users/me', actor=actor)
|
||||
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
|
||||
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
|
||||
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
|
||||
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Independent tests for async image metadata, transformations and access."""
|
||||
import io
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'tests')]
|
||||
from client import Client
|
||||
from images import bomb
|
||||
|
||||
|
||||
class Images(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c=Client(); self.alice,self.bob,self.eve,self.chat=self.c.bootstrap()
|
||||
self.path='/api/v1/chats/'+self.chat['id']
|
||||
self.raw=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def test_async_variants_and_replay(self):
|
||||
queued,_=self.c.attachment(self.alice,self.chat)
|
||||
self.assertEqual(queued['status'],'queued')
|
||||
key=uuid.uuid4().hex
|
||||
one=self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json']
|
||||
self.assertEqual(self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json'],one)
|
||||
ready=self.c.wait_ready(self.alice,queued)
|
||||
self.assertEqual({v['name'] for v in ready['variants']},{'thumbnail','crop','optimized'})
|
||||
dimensions={v['name']:(v['width'],v['height']) for v in ready['variants']}
|
||||
self.assertEqual(dimensions,{'thumbnail':(256,160),'crop':(128,128),'optimized':(320,200)})
|
||||
for v in ready['variants']:
|
||||
import hashlib
|
||||
r=self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant='+v['name'],actor=self.bob)
|
||||
self.assertEqual(hashlib.sha256(r['bytes']).hexdigest(),v['sha256'])
|
||||
self.assertEqual(len(r['bytes']),v['size_bytes'])
|
||||
self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant=absent',404,actor=self.bob)
|
||||
|
||||
def test_mime_bytes_pixels_and_filename(self):
|
||||
path=self.path+'/attachments?filename=test.png'
|
||||
for raw,mime,status in [(b'not image','image/png',415),(self.raw[:20],'image/png',415),(self.raw,'image/jpeg',415),(bomb(),'image/png',413),(b'x'*(10485760+1),'image/png',413)]:
|
||||
self.c.call('POST',path,status,actor=self.alice,raw=raw,headers={'Content-Type':mime})
|
||||
for name in ('../x.png','a\\x.png','a\0.png','a\n.png','a'*256,''):
|
||||
self.c.call('POST',self.path+'/attachments?filename='+quote(name,safe=''),400,actor=self.alice,raw=self.raw,headers={'Content-Type':'image/png'})
|
||||
|
||||
def test_private_and_cross_chat(self):
|
||||
att,_=self.c.attachment(self.alice,self.chat)
|
||||
for suffix in ('','/content'):
|
||||
self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=self.eve)
|
||||
self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,401)
|
||||
other=self.c.call('POST','/api/v1/chats',201,actor=self.alice,body={'title':'other','member_ids':[self.alice['id']]},schema='Chat')['json']
|
||||
self.c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=self.alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
|
||||
|
||||
if __name__=='__main__': unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user