Лабораторная 6: наблюдаемость мессенджера

This commit is contained in:
2026-11-21 11:32:12 +03:00
parent 470d9d6f1e
commit 59a3f96a82
94 changed files with 6746 additions and 35 deletions
+106
View File
@@ -0,0 +1,106 @@
"""Run cleanup scenarios against a disposable PostgreSQL database."""
import os
import sys
from pathlib import Path
from uuid import uuid4
import psycopg2
from psycopg2 import sql
from psycopg2.extensions import make_dsn
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from messenger.config import Config
from messenger.db import Database
from messenger.errors import Unavailable
from messenger.store import Store
GRACE_SECONDS = 900
def unavailable(_key):
raise Unavailable('synthetic S3 failure')
def expect_unavailable(operation):
try:
operation()
except Unavailable:
return
raise AssertionError('Expected Unavailable')
def exercise(database):
store = Store(None, database, None)
user, chat = str(uuid4()), str(uuid4())
with database.cursor() as cur:
cur.execute("INSERT INTO users VALUES (%s,'cleanup','unused','Cleanup')", (user,))
cur.execute("INSERT INTO chats VALUES (%s,'Cleanup')", (chat,))
def reserve(expired=False):
aid = str(uuid4())
key = 'attachments/' + aid
store.reserve_attachment(aid, chat, user, 'x.png', 'image/png', 1, 'a' * 64, key)
if expired:
with database.cursor() as cur:
cur.execute("UPDATE attachments SET updated_at=now()-interval '16 minutes' WHERE id=%s", (aid,))
return aid, key
objects = set()
fresh, fresh_key = reserve()
objects.add(fresh_key)
ready, ready_key = reserve(expired=True)
store.finish_attachment(ready, objects.add)
with database.cursor() as cur:
cur.execute("UPDATE attachments SET updated_at=now()-interval '16 minutes' WHERE id=%s", (ready,))
active, active_key = reserve(expired=True)
def active_put(key):
objects.add(key)
assert not store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
store.finish_attachment(active, active_put)
failed, failed_key = reserve(expired=True)
def put_then_fail(key):
objects.add(key)
# Inject a failure after the object exists and before the ready update.
raise Unavailable('synthetic failure after PUT')
expect_unavailable(lambda: store.finish_attachment(failed, put_then_fail))
assert failed_key in objects
expect_unavailable(lambda: store.clean_pending_attachment(GRACE_SECONDS, unavailable))
with database.cursor() as cur:
cur.execute('SELECT status FROM attachments WHERE id=%s', (failed,))
assert cur.fetchone()['status'] == 'pending'
assert store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
assert objects == {fresh_key, ready_key, active_key}
reserve(expired=True) # Reservation whose PUT never created an object.
assert store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
assert not store.clean_pending_attachment(GRACE_SECONDS, objects.discard)
with database.cursor() as cur:
cur.execute('SELECT id::text AS id, status FROM attachments')
assert {row['id']: row['status'] for row in cur.fetchall()} == {
fresh: 'pending', ready: 'ready', active: 'ready',
}
print('PASS: PostgreSQL row lock protects active PUT; fresh and ready attachments preserved')
print('PASS: interrupted PUT and failure after PUT cleaned; S3 failure retries safely')
def main():
dsn = os.environ['LAB4_TEST_DATABASE_URL']
schema = 'cleanup_' + uuid4().hex
with psycopg2.connect(dsn) as conn, conn.cursor() as cur:
cur.execute(sql.SQL('CREATE SCHEMA {}').format(sql.Identifier(schema)))
config = Config.from_env({'DATABASE_URL': make_dsn(dsn, options='-csearch_path=' + schema)})
database = Database(config)
try:
database.open()
database.run_migrations()
exercise(database)
finally:
database.close()
with psycopg2.connect(dsn) as conn, conn.cursor() as cur:
cur.execute(sql.SQL('DROP SCHEMA {} CASCADE').format(sql.Identifier(schema)))
if __name__ == '__main__':
main()
+68
View File
@@ -0,0 +1,68 @@
"""Check upload errors through Nginx and exercise an actual S3 outage."""
from io import BytesIO
from pathlib import Path
import subprocess
import sys
import time
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=45)
alice, _, eve, chat = client.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
path = f"/api/v1/chats/{chat['id']}/attachments"
good = path + '?filename=sample.png'
item, _ = client.attachment(alice, chat)
content = f"/api/v1/attachments/{item['id']}/content"
def upload(url, payload, expected, mime='image/png', actor=alice):
return client.call('POST', url, expected, actor=actor, raw=payload,
headers={'Content-Type': mime})
huge = BytesIO()
Image.new('1', (8001, 5000)).save(huge, 'PNG')
for payload, expected, mime in [
(b'x' * (10 * 1024 * 1024 + 1), 413, 'image/png'),
(huge.getvalue(), 413, 'image/png'),
(data[:30], 415, 'image/png'),
(data, 415, 'image/jpeg'),
]:
upload(good, payload, expected, mime)
upload(path + '?filename=a%2Fb.png', data, 400)
upload(good, data, 404, actor=eve)
client.call('GET', content, 404, actor=eve)
print('PASS: size, pixel count, corruption, MIME, filename and chat ACL over Nginx')
def s3_command(action):
subprocess.run(['docker', 'compose', action, 's3'], cwd=ROOT, check=True, timeout=30)
try:
s3_command('stop')
upload(good, data, 503)
client.call('GET', content, 503, actor=alice)
client.message(alice, chat, 'Текст при недоступном S3')
finally:
s3_command('start')
started = time.monotonic()
for _ in range(40):
try:
downloaded = client.call('GET', content, actor=alice)
break
except Failure:
time.sleep(.25)
else:
raise Failure('S3 download did not recover after restart')
check(downloaded['bytes'] == data, 'original changed after S3 restart')
print(f'PASS: S3 outage returned 503, text remained available, original recovered in {time.monotonic()-started:.2f}s')
if __name__ == '__main__':
run(main)
+54
View File
@@ -0,0 +1,54 @@
"""Stop the actual upload replica and check original bytes after failover and restart."""
from hashlib import sha256
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=55)
alice, bob, _, chat = client.bootstrap()
path = f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png"
original = (ROOT / 'tests/fixtures/sample.png').read_bytes()
reply = client.call('POST', path, 201, actor=alice, raw=original,
headers={'Content-Type': 'image/png'}, schema='Attachment')
aid = reply['json']['id']
upload_instance = reply['headers']['X-Instance-Id']
digest = sha256(original).hexdigest()
content = '/api/v1/attachments/' + aid + '/content'
text = client.message(alice, chat, '', attachments=[aid])['json']
def verify():
received = client.call('GET', content, actor=bob)
check(received['bytes'] == original and sha256(received['bytes']).hexdigest() == digest,
'original changed')
history = client.call('GET', f"/api/v1/chats/{chat['id']}/messages",
actor=bob, schema='MessagePage')['json']
check(text in history['items'], 'message attachment link lost')
return received['headers']['X-Instance-Id']
start = time.monotonic()
try:
subprocess.run(['scripts/stop-one.sh'], cwd=ROOT, check=True, timeout=30,
env={**os.environ, 'TARGET_INSTANCE_ID': upload_instance})
instance = verify()
check(instance != upload_instance, 'download was served by the stopped uploader')
print(f'PASS: {upload_instance} -> {instance}, SHA-256 {digest}, {time.monotonic()-start:.2f}s')
finally:
subprocess.run([sys.executable, 'scripts/manage.py', 'restore'], cwd=ROOT, check=True, timeout=100)
start = time.monotonic()
subprocess.run(['scripts/restart.sh'], cwd=ROOT, check=True, timeout=100)
instance = verify()
print(f'PASS: after full restart via {instance}, SHA-256 {digest}, {time.monotonic()-start:.2f}s')
if __name__ == '__main__':
run(main)
+141
View File
@@ -0,0 +1,141 @@
from datetime import datetime, timezone
from hashlib import sha256
from io import BytesIO
import logging
import os
import http.client
import socket
from pathlib import Path
import threading
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import uuid4
import json
import sys
from botocore.response import StreamingBody
from PIL import Image
root = Path(__file__).resolve().parents[1]
os.environ['S3_BUCKET'] = 'test'
sys.path.insert(0, str(root / 'src'))
from messenger.api import Api
from messenger.config import Config
from messenger.security import hash_token
from messenger.server import build_server
from messenger.store import Store
chat, member, outsider = [str(uuid4()) for _ in range(3)]
class Metadata:
rows = {}
def get_session(self, token):
return {hash_token('member'): member, hash_token('outsider'): outsider}.get(token)
def user(self, uid):
return {'id': uid}
def chat(self, cid):
return {'id': cid} if cid == chat else None
def is_member(self, _chat, uid):
return uid == member
def reserve_attachment(self, aid, cid, uid, filename, mime, size, digest, key):
now = datetime.now(timezone.utc)
self.rows[aid] = dict(id=aid, chat_id=cid, owner_id=uid, filename=filename,
content_type=mime, size_bytes=size, sha256=digest,
object_key=key, status='pending', error_code=None,
created_at=now, updated_at=now)
def finish_attachment(self, aid, put_object):
put_object(self.rows[aid]['object_key'])
self.rows[aid]['status'] = 'ready'
return self.rows[aid]
def visible_attachment(self, aid, uid):
row = self.rows.get(aid)
if uid == member and row and row['status'] == 'ready':
return row
return None
public_attachment = staticmethod(Store.public_attachment)
class S3:
def __init__(self):
self.objects = {}
self.fail = False
def put_object(self, **kw):
if self.fail:
from botocore.exceptions import EndpointConnectionError
raise EndpointConnectionError(endpoint_url='http://s3.invalid')
data = kw['Body'].read()
assert len(data) == kw['ContentLength']
self.objects[kw['Key']] = data
def get_object(self, **kw):
data = self.objects[kw['Key']]
return {'ContentLength': len(data), 'Body': StreamingBody(BytesIO(data), len(data))}
config = Config.from_env({'APP_HOST':'127.0.0.1','APP_PORT':'8080'})
config.port = 0
api = Api(config, Metadata(), None)
s3 = S3()
api.attachments.client = s3
server = build_server(config, logging.getLogger('lab4-check'), api, None)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = 'http://127.0.0.1:' + str(server.server_address[1])
upload = f'/api/v1/chats/{chat}/attachments?filename=x.png'
def call(path, method='GET', data=None, mime='image/png', token='member'):
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': mime}
try:
response = urlopen(Request(base + path, data=data, headers=headers, method=method), timeout=12)
except HTTPError as exc:
response = exc
with response:
return response.code, response.headers, response.read()
try:
for image_format, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (10, 10), 'green').save(buf, format=image_format)
data = buf.getvalue()
status, _, raw = call(upload, 'POST', data, mime)
assert status == 201, (status, raw)
item = json.loads(raw)
assert item['status'] == 'ready' and item['sha256'] == sha256(data).hexdigest()
assert item['size_bytes'] == len(data) and 'object_key' not in item
path = '/api/v1/attachments/' + item['id']
assert json.loads(call(path)[2]) == item
status, headers, actual = call(path + '/content')
assert (status, headers['Content-Type'], actual) == (200, mime, data)
assert call(path, token='outsider')[0] == 404
assert call(path + '/content', token='outsider')[0] == 404
assert call(path + '/content?variant=thumbnail')[0] == 404
png = (root / 'tests/fixtures/sample.png').read_bytes()
assert call(upload, 'POST', png)[0] == 201
assert call(upload, 'POST', png, 'image/jpeg')[0] == 415
assert call(upload, 'POST', png[:30])[0] == 415
assert call(upload.replace('x.png','a%2Fb.png'), 'POST', png)[0] == 400
before = len(api.store.rows)
for length, partial, expected in [(10 * 1024 * 1024 + 1, b'', 413), (64, b'abc', 400)]:
conn = http.client.HTTPConnection(*server.server_address, timeout=5)
try:
conn.request('POST', upload, body=partial, headers={
'Authorization': 'Bearer member', 'Content-Type': 'image/png',
'Content-Length': str(length)})
if partial:
conn.sock.shutdown(socket.SHUT_WR)
with conn.getresponse() as response:
assert response.status == expected, response.status
response.read()
finally:
conn.close()
assert len(api.store.rows) == before
buf = BytesIO()
Image.new('1', (8001, 5000)).save(buf, 'PNG')
assert call(upload, 'POST', buf.getvalue())[0] == 413
s3.fail = True
assert call(upload, 'POST', png)[0] == 503
assert list(api.store.rows.values())[-1]['status'] == 'pending'
print('PASS: local HTTP PNG/JPEG round trip, checksum, metadata, ACL and missing variant')
print('PASS: malformed image, mismatched MIME, unsafe filename, byte/pixel limits and S3 error mapping')
print('NOTE: metadata and S3 are test substitutes; real Compose integration not exercised')
finally:
server.shutdown()
server.server_close()
thread.join()
+98
View File
@@ -0,0 +1,98 @@
"""Exercise broker persistence and kill a worker after S3 writes, before SQL commit/ACK."""
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def cmd(*args, capture=False):
return subprocess.run(args, cwd=ROOT, text=True, check=True, timeout=100,
stdout=subprocess.PIPE if capture else None).stdout
def compose(*args, capture=False):
return cmd('docker', 'compose', *args, capture=capture)
def wait_for(probe, timeout, label):
until = time.monotonic() + timeout
while time.monotonic() < until:
if probe():
return
time.sleep(.25)
raise RuntimeError(label)
def confirmed(aid):
count = compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger',
'-At', '-c', f"SELECT count(*) FROM attachment_outbox o JOIN attachment_jobs j "
f"ON j.id=o.job_id WHERE j.attachment_id='{aid}' AND o.published_at IS NOT NULL",
capture=True)
return int(count.strip()) > 0
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
marker = 'AFTER_S3_BEFORE_COMMIT'
fault_worker = 'lab5-fault-' + uuid4().hex[:10]
compose('stop', 'worker')
try:
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
client.message(alice, chat, '', attachments=[attachment['id']])
path = '/api/v1/attachments/' + attachment['id']
client.call('GET', path + '/content', 409, actor=bob)
wait_for(lambda: confirmed(attachment['id']), 30, 'no publisher confirm')
compose('restart', 'rabbitmq', 'api-a', 'api-b')
compose('up', '-d', '--no-build', '--no-deps', '--wait', 'api-a', 'api-b')
queued = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(queued['status'] == 'queued', 'job lost during restart')
compose('start', 'worker')
client.wait_ready(bob, attachment)
check(client.call('GET', path + '/content', actor=bob)['bytes'] == original, 'original lost')
print('PASS: worker stopped; after API and RabbitMQ restart the same attachment became ready', flush=True)
compose('stop', 'worker')
attachment, original = client.attachment(alice, chat)
path = '/api/v1/attachments/' + attachment['id']
code = """
import sys,time
from messenger import worker
commit = worker.complete
def pause(db, job, result=None, error_code=None):
if job['attachment_id'] == sys.argv[1] and result is not None:
print('AFTER_S3_BEFORE_COMMIT', flush=True)
time.sleep(120)
return commit(db, job, result, error_code)
worker.complete = pause
worker.main()
"""
compose('run', '-d', '--no-deps', '--name', fault_worker, 'worker',
'python', '-c', code, attachment['id'])
wait_for(lambda: marker in cmd('docker', 'logs', fault_worker, capture=True),
40, 'worker did not reach fault point')
cmd('docker', 'kill', fault_worker)
compose('start', 'worker')
start = time.monotonic()
def is_ready():
state = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(state['status'] != 'failed', 'processing failed after crash')
return state if state['status'] == 'ready' else None
wait_for(is_ready, 90, 'expired processing lease did not recover')
ready = is_ready()
check(len(ready['variants']) == 3, 'expected exactly one set of variants')
check(client.call('GET', path + '/content', actor=bob)['bytes'] == original, 'original changed')
print(f'PASS: worker killed after S3 write before COMMIT/ACK; recovered in {time.monotonic()-start:.2f}s')
finally:
subprocess.run(['docker', 'rm', '-f', fault_worker], cwd=ROOT, capture_output=True, timeout=15)
compose('start', 'worker')
if __name__ == '__main__':
run(main)
+24
View File
@@ -0,0 +1,24 @@
"""Regression: HTTP histogram includes response transmission."""
from email.message import Message
import logging
from types import SimpleNamespace
import time
from unittest.mock import Mock, patch
from messenger.server import ApiHandler
from messenger import telemetry
handler = object.__new__(ApiHandler)
handler.command = 'GET'
handler.path = '/api/v1/users/me'
handler.headers = Message()
handler.client_address = ('127.0.0.1', 1)
handler.server = SimpleNamespace(
shutting_down=False, config=SimpleNamespace(), logger=logging.getLogger('test'),
api=SimpleNamespace(dispatch=lambda _: (200, {})), enter=Mock(), leave=Mock())
handler._read_body = lambda: b''
handler._send = lambda *_: time.sleep(.08)
with patch.object(telemetry.http_duration, 'record') as record:
handler._handle_request()
assert record.call_args.args[0] >= .075, 'histogram omits response transmission'
handler.server.leave.assert_called_once()
print('PASS: HTTP histogram includes response transmission')
+89
View File
@@ -0,0 +1,89 @@
"""Exercise job fencing, failed replay and cleanup on the stage-5 stand."""
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
code = """
import sys
from messenger.attachments import AttachmentStorage
from messenger.config import Config
from messenger.db import Database
from messenger.errors import Conflict
import messenger.job_lifecycle as lifecycle
from messenger.worker import materialize, process
db = Database(Config.from_env())
db.open()
s3 = AttachmentStorage()
aid = sys.argv[1]
def delivery():
with db.cursor() as cur:
cur.execute('SELECT id AS job_id,attachment_id,pipeline_version,attempt FROM attachment_jobs WHERE attachment_id=%s', (aid,))
return cur.fetchone()
try:
first = delivery()
row = lifecycle.claim(db, first)
assert row['status'] == 'processing' and lifecycle.claim(db, first) is None
stale_result = materialize(row, s3, first['pipeline_version'], first['attempt'])
with db.cursor() as cur:
cur.execute("UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE id=%s", (first['job_id'],))
lifecycle.recover_expired(db)
second = delivery()
assert second['attempt'] == first['attempt'] + 1
assert not lifecycle.complete(db, first, result=stale_result)
assert lifecycle.claim(db, second)
lifecycle.MAX_ATTEMPTS = 2
assert lifecycle.complete(db, second)
with db.cursor() as cur:
cur.execute('SELECT status,error_code FROM attachments WHERE id=%s', (aid,))
assert cur.fetchone() == {'status':'failed','error_code':'retry_exhausted'}
assert lifecycle.replay(db, first['job_id'], 'stage5-test') == 3
third = delivery()
process(db, s3, third)
process(db, s3, third)
try:
lifecycle.replay(db, first['job_id'], 'stage5-test')
except Conflict:
pass
else:
raise AssertionError('ready job was replayed')
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM attachment_variants WHERE attachment_id=%s', (aid,))
assert cur.fetchone()['n'] == 3
cur.execute('SELECT count(*) AS n FROM attachment_replays WHERE job_id=%s', (first['job_id'],))
assert cur.fetchone()['n'] == 1
cur.execute("UPDATE attachment_outbox SET available_at=now()-interval '16 minutes' WHERE job_id=%s AND attempt=1",
(first['job_id'],))
# Check that the cleaner can remove an obsolete attempt even after replay succeeded.
removed = []
while lifecycle.clean_abandoned_outputs(db, lambda key: (s3.delete(key), removed.append(key))):
pass
assert stale_result[0] in removed, removed
while lifecycle.clean_staging(db, s3.delete):
pass
with db.cursor() as cur:
cur.execute('SELECT staging_cleaned_at,lease_until FROM attachment_jobs WHERE id=%s', (first['job_id'],))
row = cur.fetchone()
assert row['staging_cleaned_at'] is not None and row['lease_until'] is None
print('PASS: expired claim fenced, retry exhausted, audited replay, stale objects and staging cleaned')
finally:
db.close()
"""
subprocess.run(['docker', 'compose', 'exec', '-T', 'api-a', 'python', '-c',
code, attachment['id']], cwd=ROOT, check=True, timeout=45)
path = f"/api/v1/attachments/{attachment['id']}/content"
check(client.call('GET', path, actor=bob)['bytes'] == original, 'cleanup damaged original')
print('PASS: ready original survives cleanup and replay requests')
if __name__ == '__main__':
run(main)
+53
View File
@@ -0,0 +1,53 @@
"""Exercise attachment links and message replay over the running lab4 API."""
import sys
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Message attachment links and replay')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
first, _ = client.attachment(alice, chat)
second, _ = client.attachment(bob, chat)
ids = [second['id'], first['id']]
key = uuid.uuid4().hex
sent = client.message(bob, chat, '', key=key, attachments=ids)['json']
replay = client.message(bob, chat, '', key=key, attachments=ids)['json']
check(sent == replay and sent['attachment_ids'] == ids, 'ordered attachment replay mismatch')
path = f"/api/v1/chats/{chat['id']}/messages"
client.call('POST', path, 409, actor=bob, body={'text': '', 'attachment_ids': ids[::-1]},
headers={'Idempotency-Key': key})
for invalid in [[ids[0]] * 2, [str(uuid.uuid4()) for _ in range(11)], ['bad UUID'], None]:
client.call('POST', path, 400, actor=bob, body={'text': '', 'attachment_ids': invalid},
headers={'Idempotency-Key': uuid.uuid4().hex})
client.call('POST', path, 400, actor=bob, body={'text': ''},
headers={'Idempotency-Key': uuid.uuid4().hex})
client.call('POST', path, 404, actor=bob,
body={'text': '', 'attachment_ids': [str(uuid.uuid4())]},
headers={'Idempotency-Key': uuid.uuid4().hex})
other = client.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]},
schema='Chat')['json']
foreign, _ = client.attachment(alice, other)
client.call('POST', path, 404, actor=alice,
body={'text': '', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
plain_key = uuid.uuid4().hex
plain = client.message(alice, chat, 'Обычный текст', key=plain_key)['json']
check(client.message(alice, chat, 'Обычный текст', key=plain_key, attachments=[])['json'] == plain,
'omitted and empty attachment_ids must replay identically')
page = client.call('GET', path, actor=alice, schema='MessagePage')['json']
check([item for item in page['items'] if item['id'] == sent['id']] == [sent],
'ordered attachment IDs missing or duplicated in history')
print('PASS: ordered attachments, replay, invalid input, cross-chat rejection and history')
if __name__ == '__main__':
run(main)
+297
View File
@@ -0,0 +1,297 @@
"""Live lab6 checks. Fault modes restore every stopped service in finally."""
import argparse
import base64
from concurrent.futures import ThreadPoolExecutor
import json
import re
from pathlib import Path
import subprocess
import sys
import time
import uuid
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
PROM = 'http://localhost:19090'
LOKI = 'http://localhost:13100'
TEMPO = 'http://localhost:13200'
BASE = 'http://localhost:18083'
def get(url, headers=None):
with urlopen(Request(url, headers=headers or {}), timeout=8) as response:
return json.load(response)
def prom(query):
return get(PROM + '/api/v1/query?' + urlencode({'query': query}))['data']['result']
def eventually(function, timeout=75):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
try:
value = function()
if value:
return value
except OSError as exc:
last = type(exc).__name__
time.sleep(2)
raise AssertionError('condition timeout: ' + str(last or function.__name__))
def compose(*args):
subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
check=True, timeout=100, stdout=subprocess.DEVNULL)
def alert_firing(name):
alerts = get(PROM + '/api/v1/alerts')['data']['alerts']
return any(a['labels']['alertname'] == name and a['state'] == 'firing' for a in alerts)
def trace_spans(trace_id):
data = get(TEMPO + '/api/traces/' + trace_id, {'Accept': 'application/json'})
spans = []
def visit(item):
if isinstance(item, dict):
if 'spanId' in item and 'name' in item:
spans.append(item)
for child in item.values():
visit(child)
elif isinstance(item, list):
for child in item:
visit(child)
visit(data)
return spans
def upload(client, actor, chat):
original = (ROOT / 'tests/fixtures/sample.png').read_bytes()
incoming = uuid.uuid4().hex
reply = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
202, actor=actor, raw=original,
headers={'Content-Type': 'image/png',
'traceparent': '00-' + incoming + '-1234567890abcdef-01',
'tracestate': 'lab=lab6'}, schema='Attachment')
check(reply['headers']['X-Trace-Id'] == incoming, 'upload context lost')
return reply['json'], reply['headers']['X-Trace-Id']
def linked_trace(trace_id, attempts=1):
def ready():
spans = trace_spans(trace_id)
names = [s['name'] for s in spans]
if (any(n.startswith('POST /api/v1/chats/') for n in names)
and names.count('attachment.publish') >= attempts
and names.count('attachment.consume') >= attempts
and 's3.put' in names and 'postgresql.transaction' in names):
return spans
spans = eventually(ready)
ids = {s['spanId'] for s in spans}
for item in spans:
if item['name'] in ('attachment.publish', 'attachment.consume'):
check(item.get('parentSpanId') in ids, 'producer/consumer parent missing')
check(item.get('traceState') == 'lab=lab6', 'AMQP tracestate lost')
return spans
def correlated_logs(trace_id):
query = '{service_name=~"messenger-.*"} |= "' + trace_id + '"'
def available():
response = get(LOKI + '/loki/api/v1/query_range?' + urlencode({
'query': query, 'since': '1h', 'limit': 1000}))
rows = response['data']['result']
names = {r['stream'].get('service_name') for r in rows}
return rows if {'messenger-api', 'messenger-worker', 'messenger-publisher'} <= names else None
return eventually(available)
def smoke(client, alice, bob, chat):
att, tid = upload(client, alice, chat)
client.wait_ready(bob, att)
spans = linked_trace(tid)
logs = correlated_logs(tid)
required = ['messenger_http_requests_total', 'messenger_http_duration_seconds_bucket',
'messenger_queue_depth', 'messenger_queue_oldest_age_seconds',
'messenger_db_pool_used', 'messenger_worker_busy',
'messenger_job_duration_seconds_bucket', 'messenger_attachment_time_to_ready_seconds_bucket',
'messenger_process_memory_bytes', 'messenger_process_cpu_seconds_total']
for name in required:
eventually(lambda: prom(name))
# Validate propagation from an incoming W3C header, including header case normalization.
incoming_id = '1234567890abcdef1234567890abcdef'
reply = client.call('GET', '/api/v1/users/me', actor=alice,
headers={'traceparent': '00-' + incoming_id + '-1234567890abcdef-01',
'tracestate': 'lab=propagation'})
check(reply['headers']['X-Trace-Id'] == incoming_id, 'incoming trace context lost')
# Synthetic message and token must never appear in persisted telemetry.
canary = 'PRIVATE_BODY_' + tid
client.message(alice, chat, canary)
time.sleep(5)
for secret in (canary, alice['token']):
query = '{service_name=~"messenger-.*"} |= "' + secret + '"'
found = get(LOKI + '/loki/api/v1/query_range?' + urlencode({
'query': query, 'since': '1h', 'limit': 10}))['data']['result']
check(not found, 'private content found in telemetry')
password = (ROOT / 'secrets/grafana_password').read_text().strip()
auth = 'Basic ' + base64.b64encode(('admin:' + password).encode()).decode()
dashboard = get('http://localhost:13000/api/dashboards/uid/messenger', {'Authorization': auth})
check(len(dashboard['dashboard']['panels']) >= 12, 'dashboard not provisioned')
for panel in dashboard['dashboard']['panels']:
for target in panel.get('targets', []):
if 'expr' in target:
prom(target['expr'])
search = urlencode({'q': '{resource.service.name =~ "messenger-.*"}',
'start': int(time.time() - 900), 'end': int(time.time()), 'limit': 20})
traces = get('http://localhost:13000/api/datasources/proxy/uid/tempo/api/search?' + search,
{'Authorization': auth})
check(traces.get('traces'), 'Tempo search through Grafana failed')
return {'trace_id': tid, 'span_names': [s['name'] for s in spans],
'log_services': sorted({r['stream']['service_name'] for r in logs}),
'metric_names_checked': required, 'dashboard_panels': len(dashboard['dashboard']['panels']),
'dashboard_queries_valid': True, 'incoming_w3c_context': True, 'body_and_token_absent_from_logs': True}
def worker_stop(client, alice, bob, chat):
compose('stop', 'worker')
try:
att, tid = upload(client, alice, chat)
started = time.monotonic()
eventually(lambda: alert_firing('QueueLagGrowing'))
observation = {'seconds_to_firing': round(time.monotonic() - started, 2),
'oldest_job_age': prom('messenger_queue_oldest_age_seconds'),
'backlog': prom('messenger_queue_depth'),
'alerts_firing': get(PROM + '/api/v1/alerts')['data']['alerts']}
finally:
compose('start', 'worker')
client.wait_ready(bob, att)
eventually(lambda: not alert_firing('QueueLagGrowing'))
spans = linked_trace(tid)
observation.update(resolved=True, trace_id=tid, span_count=len(spans),
alerts_after=get(PROM + '/api/v1/alerts')['data']['alerts'])
return observation
def db_outage(client, alice):
# A held table lock makes actual PostgreSQL operations time out. Readiness SELECT 1 stays healthy.
locker = subprocess.Popen(['docker', 'compose', 'exec', '-T', 'postgres', 'psql',
'-U', 'messenger', '-d', 'messenger', '-v', 'ON_ERROR_STOP=1', '-c',
'BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(35); COMMIT;'],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
failures = []
try:
time.sleep(2)
def request(_):
reply = client.call('GET', '/api/v1/users/me', 503, actor=alice)
return reply['headers']['X-Trace-Id']
with ThreadPoolExecutor(max_workers=2) as executor:
failures = list(executor.map(request, range(8)))
eventually(lambda: alert_firing('HighApiErrorRate'))
error_spans = eventually(lambda: [s for s in trace_spans(failures[0])
if s['name'] == 'postgresql.transaction' and
s.get('status', {}).get('code') in (2, 'STATUS_CODE_ERROR')])
observation = {'firing': True, 'failed_requests': len(failures),
'trace_id': failures[0], 'db_error_spans': len(error_spans),
'alerts_firing': get(PROM + '/api/v1/alerts')['data']['alerts'],
'error_ratio': prom('sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / sum(rate(messenger_http_requests_total[1m]))')}
finally:
locker.wait(timeout=50)
eventually(lambda: client.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json'])
eventually(lambda: not alert_firing('HighApiErrorRate'), timeout=100)
observation['resolved'] = True
return observation
def retry(client, alice, bob, chat):
compose('stop', 'worker')
try:
att, tid = upload(client, alice, chat)
compose('stop', 's3')
# Compose start also starts dependencies in this version. Keep S3 stopped here.
subprocess.run(['docker', 'start', 'mtusi-lab6-worker-1'], check=True,
stdout=subprocess.DEVNULL)
def retried():
spans = trace_spans(tid)
return any(s['name'] == 'attachment.consume' and
s.get('status', {}).get('code') in (2, 'STATUS_CODE_ERROR') for s in spans)
eventually(retried, timeout=45)
finally:
compose('start', 's3', 'worker')
client.wait_ready(bob, att)
spans = linked_trace(tid, attempts=2)
return {'trace_id': tid, 'consumer_attempts': sum(s['name'] == 'attachment.consume' for s in spans),
'span_names': [s['name'] for s in spans], 'ready_after_retry': True}
def backend_outage(client, alice, bob, chat):
before = prom('sum(otelcol_exporter_send_failed_spans_total)')
tracked = ['mtusi-lab6-' + name + '-1' for name in
('api-a', 'api-b', 'worker', 'outbox-publisher', 'otel-collector')]
before_containers = json.loads(subprocess.check_output(['docker', 'inspect', *tracked], text=True))
outage_start = str(int(time.time()))
compose('stop', 'tempo')
count = 0
samples = []
try:
started = time.monotonic()
while time.monotonic() - started < 40:
client.message(alice, chat, 'telemetry-outage')
count += 1
if count % 15 == 0:
raw = subprocess.check_output(['docker', 'stats', '--no-stream', '--format',
'{{json .}}', *tracked], cwd=ROOT, text=True)
samples.extend(json.loads(line) for line in raw.splitlines())
time.sleep(.15)
att, _ = upload(client, alice, chat)
client.wait_ready(bob, att)
failures = prom('sum(otelcol_exporter_send_failed_spans_total)')
before_count = float(before[0]['value'][1]) if before else 0
check(failures and float(failures[0]['value'][1]) > before_count, 'no new exporter failures')
finally:
compose('start', 'tempo')
collector_logs = subprocess.check_output(['docker', 'compose', 'logs', '--since', outage_start,
'otel-collector'], cwd=ROOT, text=True)
dropped = sum(int(value) for value in re.findall(r'"dropped_items"\s*:\s*(\d+)', collector_logs))
after_containers = json.loads(subprocess.check_output(['docker', 'inspect', *tracked], text=True))
for before_item, after_item in zip(before_containers, after_containers):
check(after_item['State']['Running'] and not after_item['State']['OOMKilled'], 'container died')
check(before_item['RestartCount'] == after_item['RestartCount'], 'container restarted')
restored_att, restored_trace = upload(client, alice, chat)
client.wait_ready(bob, restored_att)
linked_trace(restored_trace)
correlated_logs(restored_trace)
return {'successful_messages': count, 'attachment_ready_during_outage': True,
'collector_reported_dropped_spans': dropped, 'export_failures_before': before, 'export_failures_after': failures,
'application_and_collector_stats': samples, 'no_oom_or_restarts': True, 'telemetry_restored_trace': restored_trace}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('mode', choices=['smoke', 'worker-stop', 'db-outage', 'retry', 'backend-outage'])
args = parser.parse_args()
client = Client(BASE, None, timeout=20)
alice, bob, _, chat = client.bootstrap()
if args.mode == 'smoke':
result = smoke(client, alice, bob, chat)
elif args.mode == 'worker-stop':
result = worker_stop(client, alice, bob, chat)
elif args.mode == 'db-outage':
result = db_outage(client, alice)
elif args.mode == 'retry':
result = retry(client, alice, bob, chat)
else:
result = backend_outage(client, alice, bob, chat)
path = ROOT / 'evidence' / ('observability-' + args.mode + '.json')
path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
print('PASS', args.mode, path.name)
if __name__ == '__main__':
main()
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Run against a lab5 stage-3 stand without a worker.
set -eu
cd "$(dirname "$0")/.."
base_url=${BASE_URL:-http://localhost:18082}
sql() {
docker compose exec -T postgres psql -U messenger -d messenger -At -v ON_ERROR_STOP=1 -c "$1"
}
docker compose stop outbox-publisher
trap 'docker compose start outbox-publisher >/dev/null' EXIT
upload=$(PYTHONDONTWRITEBYTECODE=1 python3 student-tests/queued_upload.py --base-url "$base_url")
printf '%s\n' "$upload"
aid=$(printf '%s\n' "$upload" | awk '/Attachment ID:/ {print $3}')
query="SELECT count(*) FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='$aid' AND o.published_at IS"
test "$(sql "$query NULL")" = 1
echo 'PASS: upload committed while publisher was stopped'
docker compose start outbox-publisher
trap - EXIT
for i in $(seq 1 40); do
if test "$(sql "$query NOT NULL")" = 1; then
echo 'PASS: same attachment job confirmed after publisher startup'
exit 0
fi
sleep 1
done
echo 'FAIL: outbox row not confirmed' >&2
exit 1
+27
View File
@@ -0,0 +1,27 @@
"""Verify durable handoff before a publisher or worker is enabled."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
attachment, _ = client.attachment(alice, chat)
path = '/api/v1/attachments/' + attachment['id']
check(attachment['status'] == 'queued', 'expected queued with worker disabled')
metadata = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(metadata == attachment, 'queued metadata differs')
client.call('GET', path, 404, actor=eve)
client.call('GET', path + '/content', 409, actor=bob)
sent = client.message(alice, chat, '', attachments=[attachment['id']])['json']
check(sent['attachment_ids'] == [attachment['id']], 'queued attachment not linked')
print('PASS: 202 queued, metadata ACL, 409 before ready, and queued attachment linked')
print('Attachment ID:', attachment['id'])
if __name__ == '__main__':
run(main)
+72
View File
@@ -0,0 +1,72 @@
"""Run via docker compose exec -T api-a python - with this file on stdin."""
from hashlib import sha256
from io import BytesIO
from uuid import uuid4
from botocore.exceptions import ClientError
from PIL import Image
from messenger.attachments import AttachmentStorage
from messenger.clean_attachments import GRACE_SECONDS, clean_batch
from messenger.config import Config
from messenger.db import Database
from messenger.errors import Unavailable
from messenger.store import Store
def main():
config = Config.from_env()
db = Database(config)
db.open()
store = Store(config, db, None)
s3 = AttachmentStorage()
user, chat, aid = [str(uuid4()) for _ in range(3)]
key = 'attachments/' + aid
payload = BytesIO()
Image.new('RGB', (2, 2), 'green').save(payload, format='PNG')
data = payload.getvalue()
try:
with db.cursor() as cur:
cur.execute('INSERT INTO users (id,username,password_hash,display_name) VALUES (%s,%s,%s,%s)',
(user, 'gc_' + user[:8], 'unused', 'Cleanup check'))
cur.execute("INSERT INTO chats (id,title) VALUES (%s,'Cleanup check')", (chat,))
store.reserve_attachment(aid, chat, user, 'probe.png', 'image/png',
len(data), sha256(data).hexdigest(), key)
def put_then_fail(object_key):
s3.put(object_key, BytesIO(data), len(data), 'image/png')
raise Unavailable('synthetic failure after successful PUT')
try:
store.finish_attachment(aid, put_then_fail)
except Unavailable as exc:
assert str(exc) == 'synthetic failure after successful PUT'
else:
raise AssertionError('fault did not run')
obj = s3.client.get_object(Bucket=s3.bucket, Key=key)
with obj['Body'] as body:
assert body.read() == data
with db.cursor() as cur:
cur.execute('SELECT status FROM attachments WHERE id=%s', (aid,))
assert cur.fetchone()['status'] == 'pending'
cur.execute("UPDATE attachments SET updated_at=now()-make_interval(secs => %s) WHERE id=%s",
(GRACE_SECONDS + 1, aid))
clean_batch(store, s3)
with db.cursor() as cur:
cur.execute('SELECT 1 FROM attachments WHERE id=%s', (aid,))
assert cur.fetchone() is None
try:
obj = s3.client.get_object(Bucket=s3.bucket, Key=key)
except ClientError as exc:
assert exc.response['ResponseMetadata']['HTTPStatusCode'] == 404, exc
else:
obj['Body'].close()
raise AssertionError('orphan object still exists')
print('PASS: actual MinIO object existed after failed commit and was removed by cleanup')
finally:
db.close()
if __name__ == '__main__':
main()
+20
View File
@@ -0,0 +1,20 @@
import sys,json,time,urllib.parse,subprocess
from pathlib import Path
sys.path.insert(0,'student-tests');import observability as o
trace_id=json.loads(Path('evidence/observability-smoke.json').read_text())['trace_id']
before=o.trace_spans(trace_id)
o.correlated_logs(trace_id)
stamp=time.time()-10
query=o.PROM+'/api/v1/query?'+urllib.parse.urlencode({'query':'sum(messenger_http_requests_total)','time':stamp})
old=o.get(query)['data']['result']
assert old
for service in ('otel-collector','prometheus','loki','tempo','grafana'):
o.compose('restart',service)
subprocess.run([sys.executable, 'scripts/wait_ready.py'], check=True)
o.eventually(lambda:o.trace_spans(trace_id),timeout=100)
o.correlated_logs(trace_id)
after=o.get(query)['data']['result']
assert after==old,'historical metric changed after restart'
assert {s['spanId'] for s in before}=={s['spanId'] for s in o.trace_spans(trace_id)},'trace history changed'
Path('evidence/telemetry-persistence.json').write_text(json.dumps({'trace_id':trace_id,'trace_spans_preserved':len(before),'api_worker_publisher_logs_preserved':True,'historical_metric_preserved':True,'restarted':['otel-collector','prometheus','loki','tempo','grafana']},indent=2)+'\n')
print('PASS metrics/logs/traces history survives backend restart')
+104
View File
@@ -0,0 +1,104 @@
"""Measure sampled cgroup memory during ten simultaneous HTTP uploads."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
from io import BytesIO
import json
import math
from pathlib import Path
import random
import subprocess
import sys
from threading import Barrier
import time
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
COUNT = 10
SAMPLER = """
import select, sys, time
from pathlib import Path
usage = Path('/sys/fs/cgroup/memory.current')
limit = Path('/sys/fs/cgroup/memory.max')
cpu = Path('/sys/fs/cgroup/cpu.stat')
print(limit.read_text().strip(), flush=True)
while True:
stats = dict(line.split() for line in cpu.read_text().splitlines())
print(usage.read_text().strip(), stats['usage_usec'], flush=True)
if select.select([sys.stdin], [], [], .05)[0]:
break
"""
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file, timeout=60)
alice, _, _, chat = client.bootstrap()
width = 1700
source = Image.frombytes('RGB', (width, width), random.Random(2026).randbytes(width * width * 3))
buffer = BytesIO()
source.save(buffer, format='PNG', compress_level=0)
payload = buffer.getvalue()
digest = hashlib.sha256(payload).hexdigest()
check(len(payload) <= 10 * 1024 * 1024, 'fixture exceeds upload size limit')
path = f"/api/v1/chats/{chat['id']}/attachments?filename=load.png"
barrier = Barrier(COUNT + 1)
samplers = {}
def upload():
local = Client(args.base_url, args.ca_file, timeout=60)
barrier.wait(timeout=30)
start = time.monotonic()
try:
reply = local.call('POST', path, 201, actor=alice, raw=payload,
headers={'Content-Type': 'image/png'}, schema='Attachment')
check(reply['json']['sha256'] == digest, 'upload hash mismatch')
return {'instance': reply['headers']['X-Instance-Id'], 'id': reply['json']['id'],
'seconds': time.monotonic() - start}
except Failure as exc:
return {'error': str(exc), 'seconds': time.monotonic() - start}
try:
for service in ('api-a', 'api-b'):
proc = subprocess.Popen(
['docker', 'compose', 'exec', '-T', service, 'python', '-u', '-c', SAMPLER],
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
samplers[service] = proc
with ThreadPoolExecutor(max_workers=COUNT) as pool:
futures = [pool.submit(upload) for _ in range(COUNT)]
limits = {service: int(proc.stdout.readline()) for service, proc in samplers.items()}
initial = {service: tuple(map(int, proc.stdout.readline().split()))
for service, proc in samplers.items()}
start = time.monotonic()
barrier.wait(timeout=30)
requests = [future.result() for future in futures]
elapsed = time.monotonic() - start
finally:
for proc in samplers.values():
if proc.poll() is None:
proc.stdin.close()
resources = {}
for service, proc in samplers.items():
samples = [initial[service]] + [tuple(map(int, line.split())) for line in proc.stdout]
check(proc.wait(timeout=10) == 0 and len(samples) > 1, 'memory sampler failed')
resources[service] = {
'baseline_bytes': samples[0][0], 'peak_sample_bytes': max(row[0] for row in samples),
'limit_bytes': limits[service], 'samples': len(samples),
'cpu_seconds': (samples[-1][1] - samples[0][1]) / 1e6,
}
successes = [row for row in requests if 'id' in row]
durations = sorted(row['seconds'] for row in successes)
percentiles = {f'p{p}': durations[math.ceil(p / 100 * len(durations)) - 1]
for p in (50, 95, 99)} if durations else {}
print(json.dumps({'concurrency': COUNT, 'payload_bytes': len(payload), 'sha256': digest,
'elapsed_seconds': elapsed, 'successful_rps': len(successes) / elapsed,
'latency_seconds': percentiles, 'requests': requests,
'memory_sample_interval_seconds': .05, 'resources': resources}, indent=2))
check(len({row['id'] for row in successes}) == COUNT, 'not all uploads succeeded uniquely')
if __name__ == '__main__':
run(main)
+62
View File
@@ -0,0 +1,62 @@
"""Verify worker effects through HTTP and MinIO with a direct job handoff."""
import hashlib
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
from image_probe import jpeg_size
def main():
args = arguments(__doc__)
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
code = """
from messenger.attachments import AttachmentStorage
from messenger.config import Config
from messenger.db import Database
from messenger.worker import process
import sys
db = Database(Config.from_env())
db.open()
try:
with db.cursor() as cur:
cur.execute('SELECT id AS job_id, attachment_id, pipeline_version, attempt '
'FROM attachment_jobs WHERE attachment_id=%s', (sys.argv[1],))
job = cur.fetchone()
storage = AttachmentStorage()
process(db, storage, job)
process(db, storage, job)
finally:
db.close()
"""
subprocess.run(['docker', 'compose', 'exec', '-T', 'api-a', 'python', '-c',
code, attachment['id']], cwd=ROOT, check=True, timeout=30)
path = '/api/v1/attachments/' + attachment['id']
ready = client.call('GET', path, actor=bob, schema='Attachment')['json']
check(ready['status'] == 'ready' and len(ready['variants']) == 3, 'expected three variants')
check(client.call('GET', path + '/content', actor=bob)['bytes'] == original, 'original changed')
expected = {'thumbnail': (256, 160, 'image/jpeg'), 'crop': (128, 128, 'image/jpeg'),
'optimized': (320, 200, 'image/webp')}
for item in ready['variants']:
width, height, mime = expected[item['name']]
reply = client.call('GET', path + '/content?variant=' + item['name'], actor=bob)
data = reply['bytes']
check((item['width'], item['height'], item['content_type']) == (width, height, mime),
'incorrect variant metadata')
check(reply['headers'].get_content_type() == mime and len(data) == item['size_bytes']
and hashlib.sha256(data).hexdigest() == item['sha256'], 'incorrect variant payload')
if mime == 'image/jpeg':
check(jpeg_size(data) == (width, height), 'invalid JPEG dimensions')
else:
check(data[:4] == b'RIFF' and data[8:12] == b'WEBP', 'invalid WebP signature')
print('PASS: original unchanged, thumbnail 256x160, crop 128x128, WebP 320x200')
print('PASS: processing the same committed job twice keeps one set of variants')
if __name__ == '__main__':
run(main)