forked from mtusi2026/mtusi2026lab5
готво 5
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
"""Replay concrete reviewer cases through real HTTP and controlled dependency freezes."""
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
|
||||
|
||||
|
||||
def png(width,height):
|
||||
# Complete PNG, including all scanlines and CRCs, without allocating a bitmap.
|
||||
def chunk(kind,data):
|
||||
return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data))
|
||||
compressor=zlib.compressobj()
|
||||
packed=io.BytesIO()
|
||||
row=b'\0'*(width+1)
|
||||
for _ in range(height): packed.write(compressor.compress(row))
|
||||
packed.write(compressor.flush())
|
||||
return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,0,0,0,0))
|
||||
+chunk(b'IDAT',packed.getvalue())+chunk(b'IEND',b''))
|
||||
|
||||
|
||||
DIRECT='''import json,sys,time,urllib.request,urllib.error
|
||||
p=json.load(sys.stdin);h={}
|
||||
if p.get('token'):h['Authorization']='Bearer '+p['token']
|
||||
r=urllib.request.Request('http://127.0.0.1:8080'+p['path'],headers=h)
|
||||
t=time.monotonic()
|
||||
try:r=urllib.request.urlopen(r,timeout=10)
|
||||
except urllib.error.HTTPError as e:r=e
|
||||
with r:
|
||||
data=json.load(r)
|
||||
if r.code>=400:
|
||||
assert data['error']['request_id']==r.headers['X-Request-Id']
|
||||
assert data['error']['code']=='unavailable'
|
||||
print(json.dumps({'status':r.code,'seconds':round(time.monotonic()-t,4),
|
||||
'request_id_present':bool(r.headers.get('X-Request-Id')),'instance_id_present':bool(r.headers.get('X-Instance-Id'))}))
|
||||
'''
|
||||
LOCKER='''import asyncio,sys,asyncpg
|
||||
from src.core.settings import settings
|
||||
async def f():
|
||||
c=await asyncpg.connect(settings.database_url.get_secret_value())
|
||||
await c.execute('BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE')
|
||||
print('LOCKED',flush=True)
|
||||
await asyncio.to_thread(sys.stdin.readline)
|
||||
await c.execute('ROLLBACK');await c.close()
|
||||
asyncio.run(f())
|
||||
'''
|
||||
PENDING='''import asyncio,asyncpg
|
||||
from src.core.settings import settings
|
||||
async def f():
|
||||
c=await asyncpg.connect(settings.database_url.get_secret_value())
|
||||
print(await c.fetchval("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type='Lock' AND query LIKE '%FROM messages%'"))
|
||||
await c.close()
|
||||
asyncio.run(f())
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('API reviewer regression scenarios')
|
||||
c=Client(args.base_url,args.ca_file,timeout=15)
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
history='/api/v1/chats/'+chat['id']+'/messages'
|
||||
c.message(alice,chat,'Контроль до отказов')
|
||||
results=[]
|
||||
for name in ('review123\n','review123\r','review123\x00','review123\t'):
|
||||
c.call('POST','/api/v1/users',400,body={'username':name,'display_name':'Review','password':'valid-password-123'})
|
||||
results.append({'case':'username_control_characters','result':'PASS','status':400})
|
||||
data=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
upload='/api/v1/chats/'+chat['id']+'/attachments'
|
||||
for label,filename,payload,mime,status in [
|
||||
('truncated_png','sample.png',data[:-12],'image/png',415),
|
||||
('header_only_png','sample.png',data[:33],'image/png',415),
|
||||
('mismatched_mime','sample.png',data,'image/jpeg',415),
|
||||
('DEL_filename','a%7F.png',data,'image/png',400),
|
||||
('missing_filename',None,data,'image/png',400),
|
||||
]:
|
||||
c.call('POST',upload+('' if filename is None else '?filename='+filename),status,
|
||||
actor=alice,raw=payload,headers={'Content-Type':mime})
|
||||
results.append({'case':label,'result':'PASS','status':status})
|
||||
for width,height,status in ((8000,5000,202),(8000,5001,413),(20000,10000,413)):
|
||||
payload=png(width,height)
|
||||
reply=c.call('POST',upload+'?filename=dimensions.png',status,actor=alice,raw=payload,
|
||||
headers={'Content-Type':'image/png'},schema='Attachment' if status==202 else None)
|
||||
if status==202:
|
||||
c.wait_ready(alice, reply['json'])
|
||||
check(c.call('GET','/api/v1/attachments/'+reply['json']['id']+'/content',actor=bob)['bytes']==payload,
|
||||
'40 MP original changed')
|
||||
results.append({'case':'pixels','dimensions':[width,height],'result':'PASS','status':status})
|
||||
api=compose('ps','-q','api').split()[0]
|
||||
# Actual application credentials must not permit creating unrelated buckets.
|
||||
code='''from src.core.storage import get_storage
|
||||
from minio.error import S3Error
|
||||
import uuid
|
||||
s=get_storage();b='forbidden-'+uuid.uuid4().hex
|
||||
try:s.make_bucket(b)
|
||||
except S3Error as e:assert e.code=='AccessDenied';print('PASS')
|
||||
else:s.remove_bucket(b);raise AssertionError('API can create foreign buckets')
|
||||
'''
|
||||
check(subprocess.check_output(['docker','exec',api,'python','-c',code],text=True).strip()=='PASS',
|
||||
'API has excessive S3 rights')
|
||||
results.append({'case':'API_cannot_create_foreign_bucket','result':'PASS'})
|
||||
def direct(path,token=None):
|
||||
reply=subprocess.run(['docker','exec','-i',api,'python','-c',DIRECT],
|
||||
input=json.dumps({'path':path,'token':token}),text=True,capture_output=True,timeout=13,check=True)
|
||||
return json.loads(reply.stdout)
|
||||
transfer_code="""import asyncio,http.client,json,sys,time
|
||||
from sqlalchemy import func,select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from src.core.db.session import create_engine
|
||||
from src.core.db.models import Attachment,UploadIntent
|
||||
p=json.load(sys.stdin)
|
||||
async def counts():
|
||||
e=create_engine();f=async_sessionmaker(e)
|
||||
try:
|
||||
async with f() as s:
|
||||
return [await s.scalar(select(func.count()).select_from(m)) for m in (Attachment,UploadIntent)]
|
||||
finally:await e.dispose()
|
||||
before=asyncio.run(counts())
|
||||
c=http.client.HTTPConnection('127.0.0.1',8080,timeout=8)
|
||||
c.putrequest('POST',p['path'])
|
||||
c.putheader('Authorization','Bearer '+p['token'])
|
||||
c.putheader('Content-Type','image/png');c.putheader('Content-Length','1000');c.endheaders()
|
||||
c.send(b'\\x89PNG\\r\\n\\x1a\\nshort');c.close();time.sleep(.3)
|
||||
assert before==asyncio.run(counts()),'interrupted client created durable state'
|
||||
c=http.client.HTTPConnection('127.0.0.1',8080,timeout=8)
|
||||
c.request('POST',p['path'],body=(b'x'*65536 for _ in range(161)),
|
||||
headers={'Authorization':'Bearer '+p['token'],'Content-Type':'image/png'},encode_chunked=True)
|
||||
r=c.getresponse();body=json.loads(r.read())
|
||||
assert r.status==413 and body['error']['code']=='payload_too_large'
|
||||
assert body['error']['request_id']==r.getheader('X-Request-Id')
|
||||
c.close();assert before==asyncio.run(counts()),'oversized chunked body created durable state'
|
||||
print('PASS')
|
||||
"""
|
||||
transfer=subprocess.run(['docker','exec','-i',api,'python','-c',transfer_code],
|
||||
input=json.dumps({'path':upload+'?filename=interrupted.png','token':alice['token']}),
|
||||
text=True,capture_output=True,timeout=20,check=True)
|
||||
check(transfer.stdout.strip()=='PASS','transfer limits failed')
|
||||
results.append({'case':'client_abort_and_oversized_chunked_body','result':'PASS',
|
||||
'oversized_status':413,'durable_state_unchanged':True})
|
||||
direct(history,alice['token'])
|
||||
# Start an actual history SELECT, hold it on a table lock, then freeze PG.
|
||||
locker=subprocess.Popen(['docker','exec','-i',api,'python','-u','-c',LOCKER],
|
||||
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
|
||||
check(locker.stdout.readline().strip()=='LOCKED','test table lock was not acquired')
|
||||
paused=False
|
||||
pool=ThreadPoolExecutor(max_workers=2)
|
||||
query=pool.submit(direct,history,alice['token'])
|
||||
try:
|
||||
deadline=time.monotonic()+2
|
||||
while True:
|
||||
pending=int(subprocess.check_output(['docker','exec',api,'python','-c',PENDING],text=True))
|
||||
if pending:break
|
||||
check(time.monotonic()<deadline,'history did not enter SQL before the freeze')
|
||||
time.sleep(.02)
|
||||
compose('pause','postgres');paused=True
|
||||
ready=pool.submit(direct,'/health/ready')
|
||||
history_result=query.result(timeout=8)
|
||||
readiness_result=ready.result(timeout=8)
|
||||
for result in (history_result,readiness_result):
|
||||
check(result['status']==503 and result['seconds']<7,'frozen PostgreSQL exceeded HTTP budget')
|
||||
check(result['request_id_present'] and result['instance_id_present'],'missing response headers')
|
||||
results.append({'case':'PostgreSQL_frozen_after_SQL_started','result':'PASS',
|
||||
'history':history_result,'readiness':readiness_result})
|
||||
finally:
|
||||
if paused:compose('unpause','postgres')
|
||||
try:locker.stdin.write('release\n');locker.stdin.flush()
|
||||
except BrokenPipeError:pass
|
||||
locker.wait(timeout=8)
|
||||
pool.shutdown(wait=True)
|
||||
deadline=time.monotonic()+12
|
||||
while True:
|
||||
try:
|
||||
response=direct(history,alice['token'])
|
||||
check(response['status']==200,'history did not recover')
|
||||
check(direct('/health/ready')['status']==200,'readiness did not recover')
|
||||
# Wait for HAProxy's rise checks as well as direct API recovery.
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
c.call('GET', history, actor=alice, schema='MessagePage')
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic()>deadline:raise
|
||||
time.sleep(.2)
|
||||
results.append({'case':'PostgreSQL_resume_without_API_restart','result':'PASS'})
|
||||
print(json.dumps({'result':'PASS','checks':results},ensure_ascii=False,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Stop the exact API replica which accepted the image; preserve original bytes."""
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment download after stopping the uploading replica')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
|
||||
202, actor=alice, raw=content, headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment')
|
||||
att = uploaded['json']
|
||||
c.message(alice, chat, '', attachments=[att['id']])
|
||||
c.wait_ready(alice, att)
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
subprocess.run(['scripts/stop-one.sh'], check=True,
|
||||
env=dict(os.environ, TARGET_INSTANCE_ID=target),
|
||||
stdout=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 15
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
|
||||
break
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.2)
|
||||
check(downloaded['bytes'] == content, 'original lost after uploader replica stopped')
|
||||
check(downloaded['headers']['X-Instance-Id'] != target, 'download used stopped replica')
|
||||
print('PASS: exact uploading replica stopped; another replica returns identical original')
|
||||
finally:
|
||||
# Restore the two-replica development stack for subsequent work.
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--wait', 'api'], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Lab4 black-box checks against the running Compose stack."""
|
||||
import hashlib
|
||||
import io
|
||||
import struct
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment originals, ACL, validation and message limits')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data=content, name='photo.png', mime='image/png', status=202, actor=alice):
|
||||
return c.call('POST', path + '/attachments?filename=' + name, status,
|
||||
actor=actor, raw=data, headers={'Content-Type': mime},
|
||||
schema='Attachment' if status == 202 else None)['json']
|
||||
|
||||
first = upload()
|
||||
second = upload() # Same display name must not overwrite the first object.
|
||||
check(first['id'] != second['id'], 'same filename overwrote attachment')
|
||||
jpg = io.BytesIO()
|
||||
Image.new('RGB', (31, 17), 'red').save(jpg, format='JPEG')
|
||||
jpeg = upload(jpg.getvalue(), 'photo.jpg', 'image/jpeg')
|
||||
for att, original in [(first, content), (second, content), (jpeg, jpg.getvalue())]:
|
||||
check(att['sha256'] == hashlib.sha256(original).hexdigest(), 'incorrect digest')
|
||||
att = c.wait_ready(alice, att)
|
||||
check({v['name'] for v in att['variants']} == {'thumbnail', 'crop', 'optimized'}, 'incorrect ready metadata')
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
||||
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
|
||||
check(downloaded['bytes'] == original, 'original changed')
|
||||
|
||||
ids = [first['id'], second['id'], jpeg['id']]
|
||||
key = uuid.uuid4().hex
|
||||
message = c.message(alice, chat, '', key=key, attachments=ids)['json']
|
||||
check(message['attachment_ids'] == ids, 'attachment order lost')
|
||||
check(c.message(alice, chat, '', key=key, attachments=ids)['json'] == message,
|
||||
'idempotency replay changed message')
|
||||
c.call('POST', path + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids[:1]}, headers={'Idempotency-Key': key})
|
||||
page = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']
|
||||
check(any(m == message for m in page['items']), 'history lost attachments')
|
||||
# The contract permits referencing the same accessible chat attachment again.
|
||||
c.message(bob, chat, 'same image', attachments=[first['id']])
|
||||
|
||||
for body in ({'text': '', 'attachment_ids': []},
|
||||
{'text': '', 'attachment_ids': [first['id']] * 2},
|
||||
{'text': '', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}):
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=body,
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('POST', path + '/messages', 404, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [str(uuid.uuid4())]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat')['json']
|
||||
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
upload(actor=eve, status=404)
|
||||
upload(name='..%2Fphoto.png', status=400)
|
||||
upload(name='a%00b.png', status=400)
|
||||
upload(data=b'not a PNG', status=415)
|
||||
upload(data=content[:30], status=415)
|
||||
upload(mime='image/jpeg', status=415)
|
||||
upload(mime='application/octet-stream', status=415)
|
||||
# Oversized dimensions with a valid PNG header; no huge bitmap allocation.
|
||||
header = struct.pack('>IIBBBBB', 10000, 5000, 8, 2, 0, 0, 0)
|
||||
bomb = (content[:8] + struct.pack('>I', len(header)) + b'IHDR' + header
|
||||
+ struct.pack('>I', zlib.crc32(b'IHDR' + header)) + content[33:])
|
||||
upload(data=bomb, status=413)
|
||||
upload(data=b'x' * (10485760 + 1), status=413)
|
||||
c.call('POST', path + '/attachments?filename=a.png', 401,
|
||||
raw=content, headers={'Content-Type': 'image/png'})
|
||||
|
||||
# Exactly 10 distinct attachments must remain valid, including after reading history.
|
||||
ten = ids + [upload()['id'] for _ in range(7)]
|
||||
check(len(c.message(alice, chat, '', attachments=ten)['json']['attachment_ids']) == 10,
|
||||
'10 attachments rejected')
|
||||
replay_key = uuid.uuid4().hex
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
responses = list(pool.map(lambda _: Client(args.base_url, args.ca_file).message(
|
||||
alice, chat, 'Concurrent image', key=replay_key, attachments=ids
|
||||
), range(8)))
|
||||
check(all(r['json'] == responses[0]['json'] for r in responses),
|
||||
'concurrent attachment retries differ')
|
||||
print('PASS: PNG/JPEG bytes, metadata, ACL, chat boundaries, limits and idempotency')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность, область ключей и повторная авторизация."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab3 concurrency and idempotency")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = uuid.uuid4().hex
|
||||
clients = [Client(args.base_url, args.ca_file) for _ in range(16)]
|
||||
barrier = threading.Barrier(len(clients))
|
||||
|
||||
def send(local):
|
||||
barrier.wait()
|
||||
return local.message(alice, chat, "Одна отправка 👋", key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(clients)) as pool:
|
||||
responses = list(pool.map(send, clients))
|
||||
instances = {r["headers"]["X-Instance-Id"] for r in responses}
|
||||
check(len(instances) >= 2, "Parallel repeats did not reach >=2 replicas")
|
||||
original = responses[0]["json"]
|
||||
check(all(r["json"] == original for r in responses), "Concurrent results differ")
|
||||
messages = c.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(messages == [original], "Concurrent retries duplicated message")
|
||||
# Missing attachment_ids and [] are semantically equal; raw JSON ordering too.
|
||||
replay = c.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
raw=b'{"attachment_ids":[],"text":"' + "Одна отправка 👋".encode() + b'"}',
|
||||
headers={"Idempotency-Key": key, "Content-Type": "application/json"},
|
||||
schema="Message",
|
||||
)
|
||||
check(replay["json"] == original, "Equivalent JSON did not replay")
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
409,
|
||||
actor=alice,
|
||||
body={"text": "Другой текст"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
other = c.message(bob, chat, "Другой отправитель", key=key)["json"]
|
||||
check(other["id"] != original["id"], "Key incorrectly shared across users")
|
||||
chat2 = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Другой чат", "member_ids": [alice["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
check(
|
||||
c.message(alice, chat2, "Другой чат", key=key)["json"]["id"] != original["id"],
|
||||
"Key scope includes wrong chat",
|
||||
)
|
||||
for invalid in [None, "", "bad key", "x" * 129, "bad/key"]:
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": "invalid"},
|
||||
headers={} if invalid is None else {"Idempotency-Key": invalid},
|
||||
)
|
||||
# Validation/access failures must not consume a key.
|
||||
retry_key = uuid.uuid4().hex
|
||||
c.call(
|
||||
"POST", path, 400, actor=alice, body={"text": ""}, headers={"Idempotency-Key": retry_key}
|
||||
)
|
||||
c.message(alice, chat, "После 400", key=retry_key)
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
404,
|
||||
actor=eve,
|
||||
body={"text": original["text"]},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
401,
|
||||
actor=alice,
|
||||
body={"text": original["text"]},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
for route in ["/health/live", "/health/ready", "/missing"]:
|
||||
c.call("GET", route, 404 if route == "/missing" else 200)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"parallel_repeats": len(responses),
|
||||
"instances": sorted(instances),
|
||||
"messages_created": 1,
|
||||
"checks": "normalization, conflict, key scope, invalid keys, access, logout, headers",
|
||||
"result": "PASS",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
"""Lab5 HTTP checks and real, opt-in Compose fault injection on an isolated stand."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def passed(name, **details):
|
||||
result = dict(case=name, result='PASS', **details)
|
||||
RESULTS.append(result)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
def wait(predicate, description, seconds=40):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(.25)
|
||||
raise AssertionError('Timeout: ' + description)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--faults', action='store_true')
|
||||
parser.add_argument('--project', default=os.environ.get('COMPOSE_PROJECT_NAME', ''))
|
||||
args = arguments(__doc__, configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
base = '/api/v1/attachments/'
|
||||
|
||||
def upload(data, mime='image/png'):
|
||||
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=image.png',
|
||||
202, actor=alice, raw=data, headers={'Content-Type': mime}, schema='Attachment')['json']
|
||||
check(att['status'] == 'queued' and att['variants'] == [], '202 must be a queued snapshot')
|
||||
return att
|
||||
|
||||
def fixture(size, mode='RGB', color='red', fmt='PNG', exif=None):
|
||||
data = io.BytesIO()
|
||||
options = {'exif': exif} if exif else {}
|
||||
Image.new(mode, size, color).save(data, fmt, **options)
|
||||
return data.getvalue()
|
||||
|
||||
cases = [((320, 200), (256, 160)), ((7, 3), (7, 3)), ((1001, 667), (256, 170)),
|
||||
((1600, 1000), (256, 160))]
|
||||
for size, thumb_size in cases:
|
||||
data = fixture(size)
|
||||
att = c.wait_ready(alice, upload(data))
|
||||
variants = {v['name']: v for v in att['variants']}
|
||||
check(set(variants) == {'thumbnail', 'crop', 'optimized'}, 'all variants required')
|
||||
check(c.call('GET', base + att['id'] + '/content', actor=bob)['bytes'] == data, 'original changed')
|
||||
for name, item in variants.items():
|
||||
response = c.call('GET', base + att['id'] + '/content?variant=' + name, actor=bob)
|
||||
encoded = response['bytes']
|
||||
check(hashlib.sha256(encoded).hexdigest() == item['sha256'], 'variant checksum')
|
||||
check(len(encoded) == item['size_bytes'], 'variant size')
|
||||
with Image.open(io.BytesIO(encoded)) as image:
|
||||
image.load()
|
||||
check(image.size == (item['width'], item['height']), 'reported dimensions')
|
||||
check(not image.getexif() and 'icc_profile' not in image.info, 'metadata leaked')
|
||||
check(image.format == ('WEBP' if name == 'optimized' else 'JPEG'), 'format')
|
||||
if name == 'thumbnail': check(image.size == thumb_size, 'floor/no-upscale')
|
||||
if name == 'crop': check(image.size == (128, 128), 'crop dimensions')
|
||||
if name == 'optimized':
|
||||
check(max(image.size) <= 1280 and image.width <= size[0] and image.height <= size[1], 'optimized bounds')
|
||||
c.call('GET', base + att['id'] + '/content?variant=' + name, 404, actor=eve)
|
||||
passed('variants', original=list(size), thumbnail=list(thumb_size))
|
||||
|
||||
alpha = upload(fixture((20, 10), 'RGBA', (255, 0, 0, 0)))
|
||||
alpha = c.wait_ready(alice, alpha)
|
||||
encoded = c.call('GET', base + alpha['id'] + '/content?variant=thumbnail', actor=bob)['bytes']
|
||||
with Image.open(io.BytesIO(encoded)) as image:
|
||||
check(min(image.getpixel((0, 0))) >= 250, 'alpha must be white')
|
||||
exif = Image.Exif(); exif[274] = 6; exif[270] = 'private metadata'
|
||||
rotated = c.wait_ready(alice, upload(fixture((200, 100), fmt='JPEG', exif=exif), 'image/jpeg'))
|
||||
thumbnail = next(v for v in rotated['variants'] if v['name'] == 'thumbnail')
|
||||
check((thumbnail['width'], thumbnail['height']) == (100, 200), 'EXIF orientation')
|
||||
stripes = Image.new('RGB', (300, 100), 'red')
|
||||
stripes.paste('green', (100, 0, 200, 100)); stripes.paste('blue', (200, 0, 300, 100))
|
||||
buf = io.BytesIO(); stripes.save(buf, 'PNG')
|
||||
cropped = c.wait_ready(alice, upload(buf.getvalue()))
|
||||
data = c.call('GET', base + cropped['id'] + '/content?variant=crop', actor=bob)['bytes']
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
red, green, blue = image.getpixel((64, 64))
|
||||
check(green > red + 50 and green > blue + 50, 'crop must be centered')
|
||||
passed('alpha_EXIF_metadata_center_crop')
|
||||
|
||||
if not args.faults:
|
||||
return
|
||||
check(bool(args.project) and args.project != ROOT.name, 'Fault tests require an explicitly named isolated project')
|
||||
override = Path(tempfile.mkdtemp(prefix='lab5-faults-')) / 'override.yaml'
|
||||
override.write_text('''services:
|
||||
worker:
|
||||
environment: &faults
|
||||
PIPELINE_FAULT_INJECTION: "true"
|
||||
JOB_LEASE_SECONDS: "5"
|
||||
JOB_MAX_ATTEMPTS: "3"
|
||||
JOB_TIMEOUT_SECONDS: "1"
|
||||
JOB_RETRY_BASE_SECONDS: "0.5"
|
||||
JOB_RETRY_CAP_SECONDS: "2"
|
||||
dispatcher:
|
||||
environment: *faults
|
||||
''')
|
||||
command = ['docker', 'compose', '--env-file', os.environ.get('ENV_FILE', '.env'), '-p', args.project, '-f', str(ROOT / 'compose.yaml'), '-f', str(override)]
|
||||
|
||||
def compose(*parts, input=None, expected=0):
|
||||
result = subprocess.run(command + list(parts), input=input, text=True, capture_output=True, timeout=100)
|
||||
check(result.returncode == expected, 'Compose action failed: ' + ' '.join(parts[:3]) + ' ' + result.stderr[-400:])
|
||||
return result.stdout.strip()
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'postgres', 'sh', '-c',
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At -v ON_ERROR_STOP=1', input=query)
|
||||
|
||||
def job(att):
|
||||
return json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + att['id'] + "';"))
|
||||
|
||||
def set_fault(att, value):
|
||||
sql("UPDATE attachment_jobs SET fault=" + ("'" + value + "'" if value else 'NULL') + " WHERE attachment_id='" + att['id'] + "';")
|
||||
|
||||
def exited(service, code):
|
||||
ids = compose('ps', '-aq', service).split()
|
||||
if not ids: return False
|
||||
inspect = subprocess.check_output(['docker', 'inspect', '--format', '{{json .State}}', ids[0]], text=True)
|
||||
state = json.loads(inspect)
|
||||
return state['Status'] == 'exited' and state['ExitCode'] == code
|
||||
|
||||
def pending():
|
||||
return int(compose('exec', '-T', 'broker', 'redis-cli', 'XPENDING', 'attachment-jobs-v1', 'image-workers-v1').splitlines()[0])
|
||||
|
||||
def objects(att):
|
||||
code = '''import json,sys
|
||||
from src.core.storage import make_storage
|
||||
from src.core.settings import settings
|
||||
s=make_storage(role='worker');i=sys.argv[1]
|
||||
print(json.dumps({o.object_name:o.etag for prefix in ['originals/'+i,'variants/'+i+'/'] for o in s.list_objects(settings.s3_bucket,prefix=prefix,recursive=True)}))'''
|
||||
return json.loads(compose('exec', '-T', 'dispatcher', 'python', '-c', code, att['id']))
|
||||
|
||||
def inject(att):
|
||||
j = job(att)
|
||||
payload = dict(schema_version=1, job_id=j['id'], type='attachment.process.v1', attachment_id=att['id'],
|
||||
pipeline_version=1, attempt=j['attempt'], created_at=j['created_at'])
|
||||
compose('exec', '-T', 'broker', 'redis-cli', 'XADD', 'attachment-jobs-v1', '*', 'job', json.dumps(payload))
|
||||
|
||||
try:
|
||||
compose('up', '-d', '--no-deps', '--force-recreate', 'worker', 'dispatcher')
|
||||
compose('stop', 'worker')
|
||||
att, data = c.attachment(alice, chat)
|
||||
c.message(alice, chat, '', attachments=[att['id']])
|
||||
c.call('GET', base + att['id'] + '/content', 409, actor=bob)
|
||||
c.message(alice, chat, 'API работает без worker')
|
||||
wait(lambda: job(att)['published_at'], 'publish while worker stopped')
|
||||
check(int(compose('exec', '-T', 'broker', 'redis-cli', 'XLEN', 'attachment-jobs-v1')) > 0, 'broker must contain work')
|
||||
compose('restart', 'api', 'broker')
|
||||
def ready():
|
||||
try:
|
||||
return c.call('GET', '/health/ready', [200, 503])['status'] == 200
|
||||
except Failure:
|
||||
return False
|
||||
wait(ready, 'API ready')
|
||||
compose('start', 'worker')
|
||||
c.wait_ready(alice, att)
|
||||
check(c.call('GET', base + att['id'] + '/content', actor=bob)['bytes'] == data, 'restart lost original')
|
||||
passed('stopped_worker_API_broker_restart', attachment_id=att['id'])
|
||||
|
||||
compose('stop', 'broker')
|
||||
unavailable = upload(fixture((324, 204)))
|
||||
check(c.call('GET', '/health/ready')['status'] == 200, 'broker outage must not block API')
|
||||
check(job(unavailable)['published_at'] is None, 'unsent job must remain in DB')
|
||||
compose('start', 'broker')
|
||||
c.wait_ready(alice, unavailable)
|
||||
passed('broker_unavailable_outbox_recovered')
|
||||
|
||||
# COMMIT is already durable; kill the actual relay before and after XADD.
|
||||
for fault, code in [('before_publish', 81), ('after_publish', 82)]:
|
||||
compose('stop', 'dispatcher', 'worker')
|
||||
att = upload(fixture((321, 201)))
|
||||
set_fault(att, fault)
|
||||
check(job(att)['published_at'] is None, 'must have unsent outbox')
|
||||
compose('start', 'dispatcher')
|
||||
wait(lambda: exited('dispatcher', code), fault)
|
||||
check(job(att)['published_at'] is None, 'relay crash must roll back sent flag')
|
||||
# Dispatcher is stopped; clear through postgres, then restore the same job.
|
||||
set_fault(att, None)
|
||||
compose('start', 'dispatcher', 'worker')
|
||||
c.wait_ready(alice, att)
|
||||
passed(fault + '_recovered', job_id=job(att)['id'])
|
||||
|
||||
for fault, code in [('after_objects', 83), ('after_commit', 84)]:
|
||||
compose('stop', 'worker')
|
||||
att = upload(fixture((322, 202)))
|
||||
set_fault(att, fault)
|
||||
compose('start', 'worker')
|
||||
wait(lambda: exited('worker', code), fault)
|
||||
before = objects(att)
|
||||
check(len(before) == 4, 'one original and three objects must exist')
|
||||
j = job(att)
|
||||
if fault == 'after_objects':
|
||||
check(j['state'] == 'processing', 'crash must leave a processing lease')
|
||||
else:
|
||||
check(j['state'] == 'ready', 'ready commit must precede ack')
|
||||
check(pending() > 0, 'crash must leave an unacked delivery')
|
||||
set_fault(att, None)
|
||||
compose('start', 'worker')
|
||||
c.wait_ready(alice, att)
|
||||
wait(lambda: pending() == 0, 'pending delivery recovery')
|
||||
check(objects(att) == before, 'redelivery changed/duplicated objects')
|
||||
stable = job(att)
|
||||
inject(att); inject(att)
|
||||
wait(lambda: pending() == 0 and int(compose('exec', '-T', 'broker', 'redis-cli', 'XLEN', 'attachment-jobs-v1')) == 0, 'duplicate ack')
|
||||
check(job(att)['attempt'] == stable['attempt'], 'ready duplicate must not start a new attempt')
|
||||
check(objects(att) == before, 'ready duplicate changed output')
|
||||
passed(fault + '_redelivery_idempotent', attempt=stable['attempt'], objects=len(before))
|
||||
|
||||
for fault in ['temporary', 'permanent', 'timeout']:
|
||||
compose('stop', 'worker')
|
||||
att = upload(fixture((323, 203)))
|
||||
set_fault(att, fault)
|
||||
compose('start', 'worker')
|
||||
failed = wait(lambda: (a if (a := c.call('GET', base + att['id'], actor=alice, schema='Attachment')['json'])['status'] == 'failed' else None), 'terminal failed')
|
||||
j = job(att)
|
||||
check(j['cycle_attempt'] == (1 if fault == 'permanent' else 3), 'retry budget/classification')
|
||||
check(failed['error_code'] == ('invalid_image' if fault == 'permanent' else 'retry_exhausted'), 'safe terminal code')
|
||||
c.call('GET', base + att['id'] + '/content', 409, actor=bob)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text':'', 'attachment_ids':[att['id']]}, headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
registry = json.loads(compose('exec', '-T', 'dispatcher', 'python', '-m', 'src.pipeline.admin', 'failed'))
|
||||
check(any(x['job_id'] == j['id'] for x in registry), 'failed registry missing')
|
||||
set_fault(att, None)
|
||||
compose('exec', '-T', 'dispatcher', 'python', '-m', 'src.pipeline.admin', 'replay', j['id'], '--operator', 'lab5-test', '--reason', 'dependency restored')
|
||||
c.wait_ready(alice, att)
|
||||
check(sql("SELECT count(*) FROM job_replays WHERE job_id='" + j['id'] + "';") == '1', 'audit missing')
|
||||
compose('exec', '-T', 'dispatcher', 'python', '-m', 'src.pipeline.admin', 'replay', j['id'], '--operator', 'lab5-test', '--reason', 'duplicate replay', expected=1)
|
||||
passed(fault + '_failed_audited_replay', attempts_before_replay=j['attempt'])
|
||||
|
||||
wait(lambda: sql("SELECT count(*) FROM attachments WHERE status='ready' AND staging_key IS NOT NULL;") == '0', 'ready staging cleanup')
|
||||
passed('staging_cleanup_after_ready')
|
||||
|
||||
compose('stop', 'worker')
|
||||
retained = upload(fixture((325, 205)))
|
||||
set_fault(retained, 'permanent')
|
||||
compose('start', 'worker')
|
||||
wait(lambda: job(retained)['state'] == 'failed', 'failed retention fixture')
|
||||
check(sql("SELECT staging_key IS NOT NULL FROM attachments WHERE id='" + retained['id'] + "';") == 't', 'fresh failed staging must remain')
|
||||
sql("UPDATE attachments SET updated_at=clock_timestamp()-interval '8 days' WHERE id='" + retained['id'] + "';")
|
||||
wait(lambda: sql("SELECT staging_key IS NULL FROM attachments WHERE id='" + retained['id'] + "';") == 't', 'failed retention cleanup')
|
||||
compose('exec', '-T', 'dispatcher', 'python', '-m', 'src.pipeline.admin', 'replay', job(retained)['id'], '--operator', 'lab5-test', '--reason', 'expired source', expected=1)
|
||||
passed('failed_retention_and_expired_replay_rejected')
|
||||
|
||||
compose('stop', 'worker')
|
||||
active = upload(fixture((326, 206)))
|
||||
sql("UPDATE attachments SET updated_at=clock_timestamp()-interval '8 days' WHERE id='" + active['id'] + "';")
|
||||
orphan = 'staging/' + str(uuid.uuid4())
|
||||
script = '''import io,sys
|
||||
from src.core.storage import make_storage
|
||||
from src.core.settings import settings
|
||||
make_storage(role='worker').put_object(settings.s3_bucket,sys.argv[1],io.BytesIO(b'orphan'),6)
|
||||
'''
|
||||
compose('exec', '-T', 'dispatcher', 'python', '-c', script, orphan)
|
||||
sql("INSERT INTO upload_intents(object_key,state,created_at) VALUES ('" + orphan + "','pending',clock_timestamp()-interval '8 days');")
|
||||
wait(lambda: sql("SELECT state FROM upload_intents WHERE object_key='" + orphan + "';") == 'abandoned', 'orphan staging cleanup')
|
||||
check(sql("SELECT staging_key IS NOT NULL FROM attachments WHERE id='" + active['id'] + "';") == 't', 'cleanup must protect queued work')
|
||||
compose('start', 'worker')
|
||||
c.wait_ready(alice, active)
|
||||
passed('abandoned_staging_cleaned_active_job_protected')
|
||||
|
||||
finally:
|
||||
# Disable every injection and restore the ordinary configuration even on failure.
|
||||
try:
|
||||
sql('UPDATE attachment_jobs SET fault=NULL WHERE fault IS NOT NULL;')
|
||||
finally:
|
||||
subprocess.run(['docker','compose','--env-file',os.environ.get('ENV_FILE','.env'),'-p',args.project,'up','-d','--no-deps','--force-recreate','worker','dispatcher'],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=100, check=True)
|
||||
override.unlink(missing_ok=True)
|
||||
override.parent.rmdir()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Run in Linux worker: actual decoder failures and configured resource ceilings."""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from src.core.settings import settings
|
||||
|
||||
|
||||
def main():
|
||||
with TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
source = root / 'input'
|
||||
def process(data, max_pixels=40000000, memory=768):
|
||||
source.write_bytes(data)
|
||||
return subprocess.run([sys.executable,'-m','src.pipeline.images',str(source),str(root),
|
||||
str(max_pixels),str(memory),'5'],capture_output=True,timeout=10,
|
||||
env=dict(os.environ, PIPELINE_TEST_IMAGE_DELAY='0')).returncode
|
||||
buffer = io.BytesIO()
|
||||
Image.new('RGB',(1000,1000),'red').save(buffer,'PNG')
|
||||
data = buffer.getvalue()
|
||||
assert process(b'not an image') == 2
|
||||
assert process(data[:33]) == 2
|
||||
assert process(data, max_pixels=100) == 2
|
||||
assert process(data, memory=1) != 0
|
||||
assert process(data) == 0
|
||||
# Non-square integer-ratio rounding and independent process are exercised
|
||||
# by HTTP tests. These values prove the actual stand configuration too.
|
||||
assert settings.worker_memory_mb == 768
|
||||
assert settings.worker_concurrency == 1
|
||||
print(json.dumps(dict(result='PASS', invalid_image_rejected=True,
|
||||
truncated_image_rejected=True, decoded_pixel_limit=True,
|
||||
address_space_limit=True, subprocess_memory_mb=settings.worker_memory_mb,
|
||||
wall_timeout_seconds=settings.job_timeout_seconds,
|
||||
concurrency=settings.worker_concurrency, prefetch_per_consumer=1)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Run inside worker: migrate a real lab4 database and process its existing file."""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
from PIL import Image
|
||||
from pydantic import SecretStr
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from src.core.db.models import Attachment, AttachmentJob
|
||||
from src.core.db.session import create_engine
|
||||
from src.core.settings import settings
|
||||
from src.core.storage import make_storage
|
||||
from src.pipeline.dispatcher import cleanup
|
||||
from src.pipeline.worker import Envelope, process_job
|
||||
|
||||
|
||||
async def main():
|
||||
previous = settings.database_url.get_secret_value()
|
||||
database = 'migration_' + uuid4().hex
|
||||
parts = urlsplit(previous)
|
||||
url = urlunsplit(parts._replace(path='/' + database))
|
||||
control = await asyncpg.connect(previous)
|
||||
storage = make_storage(role='worker')
|
||||
attachment_id, user_id, chat_id = uuid4(), uuid4(), uuid4()
|
||||
key = 'originals/' + str(attachment_id)
|
||||
engine = None
|
||||
try:
|
||||
await control.execute('CREATE DATABASE ' + database)
|
||||
env = dict(os.environ, DATABASE_URL=url)
|
||||
def migrate(target):
|
||||
result = subprocess.run(['alembic', 'upgrade', target], env=env, capture_output=True)
|
||||
assert result.returncode == 0, 'migration failed: ' + result.stderr.decode()[-500:]
|
||||
await asyncio.to_thread(migrate, '008')
|
||||
buffer = io.BytesIO()
|
||||
Image.new('RGB', (320, 200), 'orange').save(buffer, 'PNG')
|
||||
data = buffer.getvalue()
|
||||
await asyncio.to_thread(storage.put_object, settings.s3_bucket, key, io.BytesIO(data), len(data), 'image/png')
|
||||
connection = await asyncpg.connect(url)
|
||||
try:
|
||||
await connection.execute("INSERT INTO users (id,username,display_name,password_hash,created_at) VALUES ($1,'migration_user','Migration','unused',now())", user_id)
|
||||
await connection.execute("INSERT INTO chats (id,title,created_at) VALUES ($1,'Migration',now())", chat_id)
|
||||
await connection.execute("INSERT INTO chat_members (chat_id,user_id) VALUES ($1,$2)", chat_id, user_id)
|
||||
await connection.execute("""INSERT INTO attachments
|
||||
(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at)
|
||||
VALUES ($1,$2,$3,'legacy.png',$4,'image/png',$5,$6,now(),now())""",
|
||||
attachment_id, chat_id, user_id, key, len(data), hashlib.sha256(data).hexdigest())
|
||||
finally:
|
||||
await connection.close()
|
||||
await asyncio.to_thread(migrate, '009')
|
||||
settings.database_url = SecretStr(url)
|
||||
engine = create_engine()
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
async with factory() as session:
|
||||
attachment = await session.get(Attachment, attachment_id)
|
||||
job = await session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == attachment_id))
|
||||
assert attachment.status == 'queued' and attachment.staging_key == key
|
||||
message = Envelope(schema_version=1,job_id=str(job.id),type='attachment.process.v1',
|
||||
attachment_id=str(attachment_id),pipeline_version=1,attempt=1,created_at=job.created_at.isoformat())
|
||||
assert await process_job(factory, message)
|
||||
await cleanup(factory)
|
||||
async with factory() as session:
|
||||
attachment = await session.get(Attachment, attachment_id)
|
||||
assert attachment.status == 'ready' and len(attachment.variants) == 3
|
||||
assert attachment.staging_key is None
|
||||
response = storage.get_object(settings.s3_bucket, key)
|
||||
try:
|
||||
assert response.read() == data, 'cleanup removed/replaced legacy original'
|
||||
finally:
|
||||
response.close(); response.release_conn()
|
||||
print(json.dumps(dict(result='PASS', migration='008 -> 009', legacy_original_unchanged=True,
|
||||
variants=3, staging_cleanup_safe=True)))
|
||||
finally:
|
||||
settings.database_url = SecretStr(previous)
|
||||
if engine:
|
||||
await engine.dispose()
|
||||
await control.execute('DROP DATABASE IF EXISTS ' + database + ' WITH (FORCE)')
|
||||
await control.close()
|
||||
for object_key in [key] + ['variants/' + str(attachment_id) + '/v1/' + name for name in ('thumbnail','crop','optimized')]:
|
||||
await asyncio.to_thread(storage.remove_object, settings.s3_bucket, object_key)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user