lab5: асинхронная очередь, worker и идемпотентный pipeline
API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
This commit is contained in:
@@ -30,7 +30,7 @@ def main():
|
||||
response = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote('failover.png'),
|
||||
201,
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
@@ -40,6 +40,7 @@ def main():
|
||||
instance = response['headers'].get('X-Instance-Id')
|
||||
check(bool(instance), 'upload response has no X-Instance-Id')
|
||||
check(attachment['sha256'] == hashlib.sha256(content).hexdigest(), 'upload checksum mismatch')
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
|
||||
stop = subprocess.run(
|
||||
[str(ROOT / 'scripts/stop-one.sh')],
|
||||
|
||||
@@ -19,7 +19,7 @@ from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def upload(client, actor, chat, content, filename='sample.png', content_type='image/png', expected=201):
|
||||
def upload(client, actor, chat, content, filename='sample.png', content_type='image/png', expected=202):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(filename, safe='')
|
||||
return client.call('POST', path, expected, actor=actor, raw=content, headers={'Content-Type': content_type})
|
||||
|
||||
@@ -92,16 +92,18 @@ def main():
|
||||
)
|
||||
print('duplicate attachment ids: 400')
|
||||
|
||||
# The only variant in the lab4 contract is original; other values are 400.
|
||||
# Lab5 exposes the derived variants after ready; queued content is a conflict.
|
||||
own, content = client.attachment(alice, chat)
|
||||
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content?variant=thumbnail', 400, actor=alice)
|
||||
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content', 409, actor=alice)
|
||||
own = client.wait_ready(alice, own)
|
||||
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content?variant=thumbnail', 200, actor=alice)
|
||||
|
||||
# Attachment-only message is valid.
|
||||
client.message(alice, chat, '', attachments=[own['id']])
|
||||
print('attachment-only message: 201')
|
||||
|
||||
# Object keys are server-generated; anonymous direct access must be denied.
|
||||
key = 'attachments/' + chat['id'] + '/' + own['id']
|
||||
key = 'attachments/' + chat['id'] + '/' + own['id'] + '/original'
|
||||
request = urllib.request.Request('http://127.0.0.1:8333/messenger-attachments/' + key, method='GET')
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=5)
|
||||
|
||||
Executable
+92
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5: accepted work survives a stopped worker and a broker restart.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/lab5_async.py --base-url http://localhost:8080
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import ROOT, compose, psql # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def wait_state(client, actor, attachment, expected, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
current = client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
|
||||
check(current['status'] != 'failed', 'attachment failed: ' + str(current.get('error_code')))
|
||||
if current['status'] == expected:
|
||||
return current
|
||||
time.sleep(0.2)
|
||||
raise Failure('attachment did not reach ' + expected)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 async worker/broker durability')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
content = FIXTURE.read_bytes()
|
||||
|
||||
# 1. Worker down: API still accepts 202, content is 409, the message links.
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
check(attached['status'] == 'queued', '202 snapshot must be queued')
|
||||
queued = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
|
||||
check(queued['status'] == 'queued', 'worker stopped but attachment is not queued')
|
||||
client.call('GET', '/api/v1/attachments/' + attached['id'] + '/content', 409, actor=alice)
|
||||
client.message(alice, chat, '', attachments=[attached['id']])
|
||||
time.sleep(2)
|
||||
still = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
|
||||
check(still['status'] == 'queued', 'worker stopped but job was processed synchronously')
|
||||
print('worker down: 202 queued, content 409, queued attachment linked')
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
|
||||
ready = client.wait_ready(alice, attached)
|
||||
thumb = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content?variant=thumbnail', actor=bob)
|
||||
check(thumb['headers'].get_content_type() == 'image/jpeg', 'thumbnail content type mismatch')
|
||||
download = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
|
||||
check(download['bytes'] == content, 'original bytes changed')
|
||||
check(psql("select coalesce(staging_key, '') from attachments where id='%s'" % ready['id']) == '',
|
||||
'staging key was not cleared after ready')
|
||||
print('worker restarted: ready, thumbnail and original downloadable, staging cleared')
|
||||
|
||||
# 2. Broker restart with its volume: an intent accepted while the broker is
|
||||
# down is published by the relay after recovery.
|
||||
compose('stop', 'relay')
|
||||
compose('stop', 'broker')
|
||||
try:
|
||||
during, _ = client.attachment(alice, chat)
|
||||
check(during['status'] == 'queued', 'upload during broker outage must be queued')
|
||||
print('broker down: upload accepted into outbox')
|
||||
finally:
|
||||
compose('up', '-d', '--wait', '--no-deps', 'broker', check=False)
|
||||
compose('up', '-d', '--no-deps', 'relay', check=False)
|
||||
|
||||
ready = client.wait_ready(alice, during, wait_seconds=90)
|
||||
print('broker + relay recovered: queued job reached ready')
|
||||
|
||||
# 3. A full stack restart with volumes keeps ready data and the worker path.
|
||||
compose('restart', 'api', 'worker', 'relay')
|
||||
recovered = client.call('GET', '/api/v1/attachments/' + ready['id'], actor=bob, schema='Attachment')['json']
|
||||
check(recovered['status'] == 'ready', 'ready attachment lost across restart')
|
||||
body = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
|
||||
check(body['bytes'] == content, 'original lost across restart')
|
||||
print('stack restart: ready attachment and original preserved')
|
||||
|
||||
print('PASS: lab5 async worker/broker durability')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
run(main)
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', 'relay', check=False)
|
||||
Executable
+252
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5 level 4: retry, DLQ/replay, crash windows, lease takeover.
|
||||
|
||||
The stand must be running. The script temporarily recreates worker/relay with
|
||||
FAULTS_ENABLED=1 and targeted failpoints, then restores the normal services.
|
||||
|
||||
python3 student-tests/lab5_faults.py --base-url http://localhost:8080
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from tests_helpers import compose, jobctl, psql # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
WORKER = 'mtusi-messenger-lab5-worker-1'
|
||||
RELAY = 'mtusi-messenger-lab5-relay-1'
|
||||
|
||||
|
||||
def worker_with(**env):
|
||||
compose('up', '-d', '--force-recreate', '--no-deps', 'worker', env=env)
|
||||
|
||||
|
||||
def relay_with(**env):
|
||||
compose('up', '-d', '--force-recreate', '--no-deps', 'relay', env=env)
|
||||
|
||||
|
||||
def reset_worker():
|
||||
worker_with()
|
||||
|
||||
|
||||
def reset_relay():
|
||||
relay_with()
|
||||
|
||||
|
||||
def job_id(attachment_id):
|
||||
value = psql("select job_id from attachment_jobs where attachment_id = '%s'" % attachment_id)
|
||||
check(bool(value), 'job row is missing for ' + attachment_id)
|
||||
|
||||
return value.splitlines()[0]
|
||||
|
||||
|
||||
def wait_db(attachment_id, predicate, timeout=120, description=''):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = ''
|
||||
while time.monotonic() < deadline:
|
||||
rows = psql("select a.status || '|' || coalesce(a.error_code,'') || '|' || j.attempt from attachments a join attachment_jobs j on j.attachment_id=a.id where a.id='%s'" % attachment_id)
|
||||
if rows:
|
||||
last = rows.splitlines()[0]
|
||||
status, error, attempt = last.split('|')
|
||||
if predicate(status, error, int(attempt)):
|
||||
return status, error, int(attempt)
|
||||
time.sleep(0.2)
|
||||
raise Failure('timeout waiting for ' + description + ' (last=' + last + ')')
|
||||
|
||||
|
||||
def queue_messages(name):
|
||||
project = 'mtusi-messenger-lab5'
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', project + '-broker-1', 'rabbitmqctl', '-p', 'messenger', 'list_queues', 'name', 'messages'],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith(name):
|
||||
return int(line.split()[1])
|
||||
return 0
|
||||
|
||||
|
||||
def scenario_permanent_failure_and_replay(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='permanent')
|
||||
status, code, attempts = wait_db(attached['id'], lambda s, e, a: s == 'failed', 40, 'permanent failure')
|
||||
check(code == 'injected_failure', 'unexpected permanent error_code: ' + code)
|
||||
check(attempts == 1, 'a permanent error must not consume retries')
|
||||
meta = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment')['json']
|
||||
check(meta['status'] == 'failed' and meta['error_code'] == code, 'API did not expose failed/error_code')
|
||||
client.call('GET', '/api/v1/attachments/' + attached['id'] + '/content', 409, actor=alice)
|
||||
client.call(
|
||||
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [attached['id']]},
|
||||
headers={'Idempotency-Key': 'failed-link-' + attached['id']},
|
||||
)
|
||||
failed_view = jobctl('failed', '-limit', '20').stdout
|
||||
check(jid in failed_view, 'failed job is missing from the operator registry')
|
||||
print('permanent failure: failed/' + code + ', content 409, failed attachment not linkable, registry visible')
|
||||
|
||||
reset_worker()
|
||||
replay = jobctl('replay', '-job', jid)
|
||||
check(replay.returncode == 0, 'jobctl replay failed: ' + replay.stderr)
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=60)
|
||||
check(len([v for v in ready['variants'] if v['name'] == 'thumbnail']) == 1, 'replay created a duplicate thumbnail')
|
||||
print('replay: failed -> queued -> ready, one thumbnail')
|
||||
|
||||
# Replay of a ready job must be refused and must not create another effect.
|
||||
again = jobctl('replay', '-job', jid, check=False)
|
||||
check(again.returncode != 0, 'replay of a ready job must be refused')
|
||||
print('replay ready job: refused')
|
||||
|
||||
|
||||
def scenario_transient_exhaustion(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='transient',
|
||||
PROCESSING_RETRY_BASE='100ms', PROCESSING_RETRY_CAP='500ms',
|
||||
)
|
||||
status, code, attempts = wait_db(attached['id'], lambda s, e, a: s == 'failed', 120, 'retry exhaustion')
|
||||
check(attempts == 5, 'retry cap must be exactly 5, got ' + str(attempts))
|
||||
check(code == 'retry_exhausted', 'unexpected exhaustion code: ' + code)
|
||||
events = psql("select event || ':' || coalesce(attempt,0) from attachment_job_events where job_id='%s' order by id" % jid)
|
||||
check(events.count('retried:') == 4, 'expected four managed retries: ' + events)
|
||||
check(events.count('failed:') == 1, 'expected one terminal failure: ' + events)
|
||||
check(queue_messages('attachment.process.dead') >= 1, 'terminal failure did not reach the DLQ')
|
||||
print('transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present')
|
||||
|
||||
reset_worker()
|
||||
|
||||
|
||||
def scenario_crash_after_first_variant(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
relay_with(OUTBOX_REAPER_INTERVAL='2s')
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_AFTER_FIRST_VARIANT='exit',
|
||||
PROCESSING_LEASE_TTL='15s', PROCESSING_HEARTBEAT='3s', PROCESSING_JOB_TIMEOUT='10s',
|
||||
)
|
||||
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=90)
|
||||
status, _, attempts = wait_db(attached['id'], lambda s, e, a: s == 'ready', 10, 'crash recovery')
|
||||
check(attempts >= 2, 'crash recovery must use a new managed attempt, got ' + str(attempts))
|
||||
names = sorted(v['name'] for v in ready['variants'])
|
||||
check(names == ['crop', 'optimized', 'thumbnail'], 'duplicate/partial variant set: ' + str(names))
|
||||
print('crash after first variant: redelivered, same three variants, attempts=' + str(attempts))
|
||||
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_crash_after_commit(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_AFTER_COMMIT='exit')
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=60)
|
||||
check(ready['status'] == 'ready', 'job did not stay ready after commit/ack crash')
|
||||
check(psql("select attempt from attachment_jobs where job_id='%s'" % jid) == '1',
|
||||
'redelivery after ready must be a no-op, not a new attempt')
|
||||
print('crash after commit before ack: ready remains, redelivery is a no-op')
|
||||
|
||||
reset_worker()
|
||||
|
||||
|
||||
def scenario_crash_before_side_effect(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
relay_with(OUTBOX_REAPER_INTERVAL='2s')
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_AFTER_CLAIM='exit',
|
||||
PROCESSING_LEASE_TTL='15s', PROCESSING_HEARTBEAT='3s', PROCESSING_JOB_TIMEOUT='12s',
|
||||
)
|
||||
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=90)
|
||||
status, _, attempts = wait_db(attached['id'], lambda s, e, a: s == 'ready', 10, 'pre-effect crash recovery')
|
||||
check(attempts >= 2, 'pre-effect crash must use a new managed attempt, got ' + str(attempts))
|
||||
check(sorted(v['name'] for v in ready['variants']) == ['crop', 'optimized', 'thumbnail'],
|
||||
'pre-effect crash produced an incomplete variant set')
|
||||
print('crash after claim before side effect: requeued, attempts=' + str(attempts) + ', ready')
|
||||
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_outbox_gap(client, alice, chat):
|
||||
compose('stop', 'relay')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
unpublished = psql("select count(*) from outbox_messages where job_id='%s' and published_at is null" % jid)
|
||||
check(unpublished == '1', 'upload did not leave a durable outbox intent')
|
||||
|
||||
relay_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_OUTBOX_AFTER_COMMIT='exit')
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=90)
|
||||
check(psql("select count(*) from outbox_messages where job_id='%s' and published_at is null" % jid) == '0',
|
||||
'outbox row stayed unpublished after recovery')
|
||||
print('outbox gap: crash before publish recovered through the relay, outbox published, ready')
|
||||
reset_relay()
|
||||
|
||||
|
||||
def scenario_lease_takeover(client, alice, chat):
|
||||
compose('stop', 'worker')
|
||||
attached, _ = client.attachment(alice, chat)
|
||||
jid = job_id(attached['id'])
|
||||
|
||||
relay_with(OUTBOX_REAPER_INTERVAL='1s')
|
||||
worker_with(
|
||||
FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_SLEEP_AFTER_CLAIM='8s',
|
||||
PROCESSING_LEASE_TTL='15s', PROCESSING_HEARTBEAT='3s', PROCESSING_JOB_TIMEOUT='12s',
|
||||
)
|
||||
|
||||
wait_db(attached['id'], lambda s, e, a: s == 'processing', 20, 'processing claim')
|
||||
subprocess.run(['docker', 'pause', WORKER], check=True, capture_output=True)
|
||||
wait_db(attached['id'], lambda s, e, a: s == 'queued' and a >= 2, 30, 'lease expiry requeue')
|
||||
subprocess.run(['docker', 'unpause', WORKER], check=True, capture_output=True)
|
||||
ready = client.wait_ready(alice, attached, wait_seconds=60)
|
||||
check(len(ready['variants']) == 3, 'lease takeover produced an incomplete variant set')
|
||||
print('lease expiry: paused worker, reaper requeued, stale attempt fenced, ready')
|
||||
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 level 4 fault injection')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
scenarios = [
|
||||
scenario_permanent_failure_and_replay,
|
||||
scenario_transient_exhaustion,
|
||||
scenario_crash_after_first_variant,
|
||||
scenario_crash_after_commit,
|
||||
scenario_crash_before_side_effect,
|
||||
scenario_outbox_gap,
|
||||
scenario_lease_takeover,
|
||||
]
|
||||
|
||||
try:
|
||||
for scenario in scenarios:
|
||||
scenario(client, alice, chat)
|
||||
finally:
|
||||
reset_worker()
|
||||
reset_relay()
|
||||
|
||||
print('PASS: lab5 level 4 fault injection')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5: metadata, bytes and dimensions of all contract variants.
|
||||
|
||||
Run against a live stand:
|
||||
python3 student-tests/lab5_variants.py --base-url http://localhost:8080
|
||||
"""
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
from image_probe import jpeg_size # noqa: E402
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
|
||||
|
||||
|
||||
def webp_size(data):
|
||||
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'not a WebP container')
|
||||
|
||||
chunk = data[12:16]
|
||||
if chunk == b'VP8X':
|
||||
width = 1 + int.from_bytes(data[24:27], 'little')
|
||||
height = 1 + int.from_bytes(data[27:30], 'little')
|
||||
return width, height
|
||||
if chunk == b'VP8 ':
|
||||
start = data.index(b'\x9d\x01\x2a', 12) + 3
|
||||
width = int.from_bytes(data[start:start + 2], 'little') & 0x3fff
|
||||
height = int.from_bytes(data[start + 2:start + 4], 'little') & 0x3fff
|
||||
return width, height
|
||||
if chunk == b'VP8L':
|
||||
bits = int.from_bytes(data[21:25], 'little')
|
||||
width = (bits & 0x3fff) + 1
|
||||
height = ((bits >> 14) & 0x3fff) + 1
|
||||
return width, height
|
||||
raise Failure('unsupported WebP chunk ' + repr(chunk))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 variant contract')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
|
||||
attached, content = client.attachment(alice, chat)
|
||||
ready = client.wait_ready(alice, attached)
|
||||
|
||||
by_name = {variant['name']: variant for variant in ready['variants']}
|
||||
check(set(by_name) == {'thumbnail', 'crop', 'optimized'}, 'unexpected variant set: ' + str(sorted(by_name)))
|
||||
|
||||
expected = {
|
||||
'thumbnail': ('image/jpeg', (256, 160)),
|
||||
'crop': ('image/jpeg', (128, 128)),
|
||||
'optimized': ('image/webp', (320, 200)),
|
||||
}
|
||||
|
||||
for name, (content_type, dims) in expected.items():
|
||||
variant = by_name[name]
|
||||
response = client.call(
|
||||
'GET', '/api/v1/attachments/' + ready['id'] + '/content?variant=' + name, actor=bob,
|
||||
)
|
||||
data = response['bytes']
|
||||
check(response['headers'].get_content_type() == content_type, name + ' content type mismatch')
|
||||
check(variant['content_type'] == content_type, name + ' metadata content type mismatch')
|
||||
check(len(data) == variant['size_bytes'], name + ' size_bytes mismatch')
|
||||
check(hashlib.sha256(data).hexdigest() == variant['sha256'], name + ' sha256 mismatch')
|
||||
|
||||
if name == 'optimized':
|
||||
actual = webp_size(data)
|
||||
check(actual == dims, name + ' dimensions ' + str(actual))
|
||||
check(b'EXIF' not in data[:64], 'optimized WebP must not carry EXIF')
|
||||
else:
|
||||
actual = jpeg_size(data)
|
||||
check(actual == dims, name + ' dimensions ' + str(actual))
|
||||
check('Exif' not in data[:64].decode('latin-1', 'ignore'), name + ' must not carry EXIF')
|
||||
check((variant['width'], variant['height']) == dims, name + ' metadata dimensions mismatch')
|
||||
|
||||
original = client.call('GET', '/api/v1/attachments/' + ready['id'] + '/content', actor=bob)
|
||||
check(original['bytes'] == content, 'original bytes changed')
|
||||
check(original['headers'].get_content_type() == 'image/png', 'original content type changed')
|
||||
|
||||
print('variants: thumbnail 256x160, crop 128x128, optimized WebP 320x200; metadata == bytes')
|
||||
print('PASS: lab5 variant contract')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -52,10 +52,10 @@ def put(url, content, content_type='image/png'):
|
||||
return error.code
|
||||
|
||||
|
||||
def complete(client, actor, attachment_id, digest, expected=200):
|
||||
def complete(client, actor, attachment_id, digest, expected=202):
|
||||
return client.call(
|
||||
'POST', '/api/v1/attachments/' + attachment_id + '/complete', expected,
|
||||
actor=actor, body={'sha256': digest}, schema='Attachment' if expected == 200 else None,
|
||||
actor=actor, body={'sha256': digest}, schema='Attachment' if expected == 202 else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -73,7 +73,8 @@ def main():
|
||||
check(put(presigned['upload_url'], content) == 200, 'direct PUT failed')
|
||||
attachment = complete(client, alice, presigned['attachment_id'], digest)['json']
|
||||
check(attachment['sha256'] == digest and attachment['size_bytes'] == len(content), 'completed metadata mismatch')
|
||||
print('happy path: direct PUT 200, complete ready, checksum/size match')
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
print('happy path: direct PUT 200, complete queued, ready after worker')
|
||||
|
||||
client.message(alice, chat, '', attachments=[attachment['id']])
|
||||
download = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
|
||||
@@ -83,6 +84,7 @@ def main():
|
||||
# Completion is idempotent.
|
||||
again = complete(client, alice, presigned['attachment_id'], digest)['json']
|
||||
check(again['id'] == attachment['id'], 'repeated complete returned another attachment')
|
||||
check(again['status'] in ('queued', 'processing', 'ready'), 'repeated complete returned an invalid state')
|
||||
print('repeated complete is idempotent')
|
||||
|
||||
# A foreign user cannot complete someone else's pending upload.
|
||||
|
||||
@@ -10,15 +10,32 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
def compose(*args, check=True, env=None):
|
||||
command = [*os.environ.get('COMPOSE_BIN', 'docker compose').split(), '--env-file', '.env', '-f', 'compose.yaml', *args]
|
||||
environment = {**os.environ, **(env or {})}
|
||||
|
||||
return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, check=check)
|
||||
return subprocess.run(command, cwd=ROOT, capture_output=True, text=True, check=check, env=environment)
|
||||
|
||||
|
||||
def jobctl(*args, check=True):
|
||||
"""Run the operator CLI inside the worker image."""
|
||||
return compose('run', '--rm', '--entrypoint', '/usr/local/bin/jobctl', 'worker', *args, check=check)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Read a scalar/list from the stand database (operator evidence only)."""
|
||||
project = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab5')
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', project + '-postgres-1', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', sql],
|
||||
cwd=ROOT, capture_output=True, text=True, check=True,
|
||||
)
|
||||
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def containers_by_hostname(service='api'):
|
||||
"""{hostname: {id, name, status}} для контейнеров сервиса."""
|
||||
project = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab4')
|
||||
project = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab5')
|
||||
listed = subprocess.run(
|
||||
[
|
||||
'docker', 'ps', '-q',
|
||||
|
||||
Reference in New Issue
Block a user