ЛР 5: очередь и асинхронная обработка изображений

This commit is contained in:
2026-11-11 19:59:42 +03:00
parent 276dbdad8a
commit af485c93d4
54 changed files with 1966 additions and 34 deletions
+5
View File
@@ -0,0 +1,5 @@
@echo off
setlocal
cd /d "%~dp0.."
docker compose --env-file .env restart db s3 broker api1 api2 dispatcher worker lb
exit /b %ERRORLEVEL%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env restart db s3 broker api1 api2 dispatcher worker lb
+5
View File
@@ -0,0 +1,5 @@
@echo off
setlocal
cd /d "%~dp0.."
docker compose --env-file .env up -d --no-deps --wait --wait-timeout 55 api1 api2
exit /b %ERRORLEVEL%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env start api1 api2
+40
View File
@@ -0,0 +1,40 @@
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
if (!(Test-Path -LiteralPath '.env')) {
Copy-Item -LiteralPath '.env.example' -Destination '.env'
}
New-Item -ItemType Directory -Path 'secrets' -Force | Out-Null
function New-SecretFile([string]$Name, [int]$Length) {
$path = Join-Path (Get-Location) "secrets/$Name"
if (!(Test-Path -LiteralPath $path)) {
$bytes = [byte[]]::new($Length)
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try {
$rng.GetBytes($bytes)
} finally {
$rng.Dispose()
}
$value = [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
[IO.File]::WriteAllText($path, $value, [Text.Encoding]::ASCII)
}
}
New-SecretFile 'db_password' 24
New-SecretFile 's3_root_access' 10
New-SecretFile 's3_root_secret' 20
New-SecretFile 's3_access_key_id' 10
New-SecretFile 's3_secret_access_key' 20
New-SecretFile 'broker_password' 24
$brokerPassword = (Get-Content -LiteralPath 'secrets/broker_password' -Raw).Trim()
[IO.File]::WriteAllText((Join-Path (Get-Location) 'secrets/broker_url'), "amqp://messenger:${brokerPassword}@broker:5672/%2F", [Text.Encoding]::ASCII)
[IO.File]::WriteAllText((Join-Path (Get-Location) 'secrets/rabbitmq_config'), "default_user = messenger`ndefault_pass = ${brokerPassword}`n", [Text.Encoding]::ASCII)
if (!(Test-Path -LiteralPath 'secrets/database_url')) {
$password = (Get-Content -LiteralPath 'secrets/db_password' -Raw).TrimEnd([char]10)
$encoded = [Uri]::EscapeDataString($password)
$url = "postgresql://messenger:${encoded}@db:5432/messenger"
[IO.File]::WriteAllText((Join-Path (Get-Location) 'secrets/database_url'), $url, [Text.Encoding]::ASCII)
}
Write-Host 'Local secrets are ready.'
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
if [ ! -e .env ]; then cp .env.example .env; fi
mkdir -p secrets
if [ ! -e secrets/db_password ]; then
python3 -c 'import secrets;print(secrets.token_urlsafe(36),end="")' > secrets/db_password
fi
if [ ! -e secrets/database_url ]; then
python3 -c 'from pathlib import Path;from urllib.parse import quote; p=Path("secrets/db_password").read_text().strip();print("postgresql://messenger:"+quote(p,safe="")+"@db:5432/messenger",end="")' > secrets/database_url
fi
python3 - <<'PYGEN'
from pathlib import Path
import secrets
root=Path('secrets')
for name,length in [('s3_root_access',10),('s3_root_secret',20),('s3_access_key_id',10),('s3_secret_access_key',20),('broker_password',24)]:
file=root/name
if not file.exists():
file.write_bytes(secrets.token_hex(length).encode('ascii'))
password=(root/'broker_password').read_text().strip()
(root/'broker_url').write_text('amqp://messenger:'+password+'@broker:5672/%2F')
(root/'rabbitmq_config').write_text('default_user = messenger\ndefault_pass = '+password+'\n')
PYGEN
chmod 600 secrets/* .env
printf 'Local secrets prepared (values not displayed).\n'
+10
View File
@@ -0,0 +1,10 @@
@echo off
setlocal
cd /d "%~dp0.."
if /I "%TARGET_INSTANCE_ID%"=="api1" goto stop
if /I "%TARGET_INSTANCE_ID%"=="api2" goto stop
echo Invalid TARGET_INSTANCE_ID; refusing to stop an arbitrary service 1>&2
exit /b 2
:stop
docker compose --env-file .env stop -t 2 %TARGET_INSTANCE_ID%
exit /b %ERRORLEVEL%
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
case "${TARGET_INSTANCE_ID:-}" in
api1|api2) exec docker compose --env-file .env stop -t 2 "$TARGET_INSTANCE_ID" ;;
*) echo 'Unknown TARGET_INSTANCE_ID; refusing to stop an arbitrary service' >&2; exit 2 ;;
esac
+140
View File
@@ -0,0 +1,140 @@
"""Reproducible level-3 failure scenarios; synthetic data, no tokens in output."""
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tests'))
from client import Client, check
from image_probe import jpeg_size
def compose(*args):
result = subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
capture_output=True, text=True)
if result.returncode:
raise RuntimeError('compose action failed: '+ ' '.join(args[:3]))
return result.stdout.strip()
def internal(code):
return compose('exec','-T','dispatcher','python','-c',code)
def queue_count():
output = compose('exec','-T','broker','rabbitmqctl','list_queues','name','messages_ready','--silent')
for line in output.splitlines():
fields = line.split()
if len(fields)==2 and fields[0]=='attachments.v1':
return int(fields[1])
return 0
def started_at(service):
ident = compose('ps','-q',service)
return subprocess.check_output(['docker','inspect','--format','{{.State.StartedAt}}',ident],
text=True).strip()
def eventually(predicate, seconds=65):
deadline = time.monotonic()+seconds
while time.monotonic()<deadline:
try:
result = predicate()
if result:
return result
except Exception:
pass
time.sleep(0.5)
raise AssertionError('condition did not recover before deadline')
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8085')
args = parser.parse_args()
client = Client(args.base_url)
results = []
compose('stop','worker')
try:
alice,bob,eve,chat = client.bootstrap()
attachment, raw = client.attachment(alice,chat)
ident = attachment['id']
path = '/api/v1/attachments/'+ident
check(attachment['status']=='queued', 'upload snapshot must be queued')
client.call('GET',path+'/content',409,actor=alice)
linked = client.message(alice,chat,'',attachments=[ident])['json']
client.message(bob,chat,'Worker is stopped; messages still work')
eventually(lambda: queue_count()>0)
# Freeze publisher so broker persistence is observed without republishing.
compose('stop','dispatcher')
queued_before = queue_count()
started_before = {name:started_at(name) for name in ('api1','api2','broker')}
compose('restart','api1','api2','broker')
eventually(lambda: client.call('GET','/health/ready',schema='Health'))
queued_after = eventually(lambda: queue_count())
started_after = {name:started_at(name) for name in ('api1','api2','broker')}
check(all(started_before[name]!=started_after[name] for name in started_before), 'process did not actually restart')
check(queued_after==queued_before, 'broker lost durable queued messages')
pending = client.call('GET',path,actor=alice,schema='Attachment')['json']
check(pending['status']=='queued', 'API performed synchronous processing')
compose('start','dispatcher','worker')
start = time.monotonic()
ready = client.wait_ready(bob,attachment)
check(client.call('GET',path+'/content',actor=alice)['bytes']==raw, 'original changed')
thumbnail = client.call('GET',path+'/content?variant=thumbnail',actor=bob)['bytes']
check(jpeg_size(thumbnail)==(256,160), 'invalid thumbnail')
results.append(dict(scenario='stopped_worker_and_api_broker_restart', attachment_id=ident,
message_id=linked['id'], queued_before=queued_before, queued_after=queued_after,
broker_restart_verified=True, started_before=started_before, started_after=started_after,
ready_seconds=round(time.monotonic()-start,3),
thumbnail=[256,160], result='PASS'))
# Publish the exact same logical job five more times, with confirms.
snapshot = internal(f"""
import json
from app.storage import db
from app.broker import connect,QUEUE
from app.models.time_format import utc_z
import pika
with db() as c:
j=c.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s',('{ident}',)).fetchone()
body=dict(schema_version=1,job_id=str(j['job_id']),type='attachment.process.v1',attachment_id='{ident}',pipeline_version=1,attempt=1,created_at=utc_z(j['created_at']))
connection,ch=connect()
for _ in range(5):
ch.basic_publish('',QUEUE,json.dumps(body),pika.BasicProperties(delivery_mode=2),mandatory=True)
connection.close()
print(j['attempts'])
""")
eventually(lambda: queue_count()==0)
# Queue empty can mean delivered but unacked; wait for all acknowledgements.
eventually(lambda: 'attachments.v1\t0' in compose('exec','-T','broker','rabbitmqctl','list_queues','name','messages','--silent'))
check(client.call('GET',path,actor=alice,schema='Attachment')['json']==ready, 'duplicate changed ready metadata')
attempts = internal(f"from app.storage import db\nwith db() as c:\n print(c.execute('SELECT attempts FROM attachment_jobs WHERE attachment_id=%s',('{ident}',)).fetchone()['attempts'])")
check(attempts==snapshot, 'duplicate reran successful job')
check(client.call('GET',path+'/content?variant=thumbnail',actor=bob)['bytes']==thumbnail,'duplicate changed variant')
objects = json.loads(internal(f"from app.s3 import s3_client,bucket\nimport json\nprint(json.dumps([o['Key'] for o in s3_client().list_objects_v2(Bucket=bucket(),Prefix='results/{ident}/')['Contents']]))"))
check(len(objects)==2,'duplicate created extra objects')
results.append(dict(scenario='five_duplicate_deliveries',attachment_id=ident,attempts=int(attempts),
final_objects=objects, unchanged_metadata=True, result='PASS'))
# Transient storage failure: controlled, nonexistent staging key of a new test job.
compose('stop','worker')
failed, _ = client.attachment(alice,chat)
fid = failed['id']
internal(f"from app.storage import db\nwith db() as c:\n c.execute(\"UPDATE attachments SET object_key=%s WHERE id=%s\",('staging/missing-{fid}','{fid}'))")
compose('start','worker')
fpath = '/api/v1/attachments/'+fid
final = eventually(lambda: (lambda a:a if a['status']=='failed' else None)(client.call('GET',fpath,actor=alice,schema='Attachment')['json']))
check(final['error_code']=='retry_exhausted','unsafe or wrong failure code')
attempts = int(internal(f"from app.storage import db\nwith db() as c:\n print(c.execute('SELECT attempts FROM attachment_jobs WHERE attachment_id=%s',('{fid}',)).fetchone()['attempts'])"))
check(attempts==5,'retry bound not respected')
client.call('GET',fpath+'/content',409,actor=alice)
client.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,
body={'text':'','attachment_ids':[fid]},headers={'Idempotency-Key':'failed-'+fid})
client.call('GET',fpath,404,actor=eve)
results.append(dict(scenario='bounded_retry',attachment_id=fid,attempts=attempts,
error_code=final['error_code'], download_status=409, attach_status=409,result='PASS'))
finally:
compose('start','dispatcher','worker')
(ROOT/'evidence'/'pipeline.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print(json.dumps(results,indent=2))
print('PASS: lab5 durable queue, restart, redelivery and retry scenarios')
if __name__=='__main__':
main()
+62
View File
@@ -0,0 +1,62 @@
"""Run unchanged public resilience checks and record actual container restarts."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def docker(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True).strip()
def states():
ids = docker('compose','ps','-q').splitlines()
rows = json.loads(docker('inspect',*ids))
return {row['Config']['Labels']['com.docker.compose.service']:
dict(id=row['Id'][:12],started_at=row['State']['StartedAt'],image=row['Config']['Image'])
for row in rows}
def main():
base = sys.argv[1] if len(sys.argv)>1 else 'http://localhost:8085'
suffix = '.cmd' if os.name=='nt' else '.sh'
if os.name!='nt':
for name in ('restart','stop-one'):
(ROOT/'scripts'/(name+suffix)).chmod(0o755)
before = states()
command = [sys.executable,'tests/resilience.py','--base-url',base]
result = subprocess.run(command+['--mode','persistence','--action-script','scripts/restart'+suffix],
cwd=ROOT,capture_output=True,text=True)
print(result.stdout,end='')
(ROOT/'evidence/persistence.txt').write_text(result.stdout+result.stderr,encoding='utf-8')
after = states()
services = ('api1','api2','db','s3','broker','worker','dispatcher','lb')
changed = {name:before[name]['started_at']!=after[name]['started_at'] for name in services}
(ROOT/'evidence/persistence-runtime.json').write_text(json.dumps(dict(before=before,after=after,restarted=changed),indent=2)+'\n',encoding='utf-8')
if result.returncode or not all(changed.values()):
raise RuntimeError('persistence verification failed; see evidence')
failover_results = []
try:
for number in range(2):
result = subprocess.run(command+['--mode','failover','--action-script','scripts/stop-one'+suffix],
cwd=ROOT,capture_output=True,text=True)
print(result.stdout,end='')
failover_results.append(f'Run {number+1}\n'+result.stdout+result.stderr)
docker('compose','up','-d','--no-deps','api1','api2')
if result.returncode:
raise RuntimeError('failover verification failed; see evidence')
finally:
docker('compose','up','-d','--no-deps','api1','api2')
(ROOT/'evidence/failover.txt').write_text('\n'.join(failover_results),encoding='utf-8')
runtime = dict(python=platform.python_version(),host=platform.platform(),
docker=json.loads(docker('version','--format','{{json .}}')),
engine=json.loads(docker('info','--format','{{json .}}')),
containers=states())
# Keep only non-sensitive hardware/version fields from Docker info.
runtime['engine']={key:runtime['engine'][key] for key in ('NCPU','MemTotal','OSType','Architecture','OperatingSystem')}
(ROOT/'evidence/runtime.json').write_text(json.dumps(runtime,indent=2)+'\n',encoding='utf-8')
print('PASS: persistence and two API failover runs; actual process restarts recorded')
if __name__=='__main__':
main()
+11
View File
@@ -0,0 +1,11 @@
param([string]$BaseUrl = 'http://localhost:8085')
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
function Invoke-Check([string[]]$Arguments) {
& py @Arguments
if ($LASTEXITCODE -ne 0) { throw "Verification failed: $($Arguments[0])" }
}
Invoke-Check -Arguments @('scripts/check_contract.py')
Invoke-Check -Arguments @('tests/smoke.py', '--base-url', $BaseUrl)
Invoke-Check -Arguments @('scripts/verify-lab5.py', '--base-url', $BaseUrl)
Invoke-Check -Arguments @('tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.cmd', '--base-url', $BaseUrl)