feat: process attachments asynchronously with RabbitMQ and a worker
Upload answers 202 after staging, a queued job in PostgreSQL and a broker confirm; a separate worker publishes the original and a thumbnail with bounded retries. Adds the job and variant tables, the broker service, the worker S3 user, cleanup and reconcile support for staging and variants, the failure stand with broker and worker, bench and driver updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,9 +13,12 @@ from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from contract import assert_ok
|
||||
from contract import assert_accepted, assert_ok
|
||||
|
||||
API = "/api/v1"
|
||||
# срок ожидания готовности вложения — как у публичного smoke, и шаг опроса
|
||||
READY_TIMEOUT_S = 60
|
||||
READY_POLL_S = 0.2
|
||||
SESSIONS = f"{API}/auth/sessions"
|
||||
# защита от бесконечного обхода, если next_cursor никогда не станет null
|
||||
MAX_PAGES = 1000
|
||||
@@ -291,7 +294,7 @@ class Api:
|
||||
content_type: str = "image/png",
|
||||
filename: str = "image.png",
|
||||
) -> dict[str, Any]:
|
||||
"""Успешная загрузка: 201 и `Attachment` с размером и SHA-256."""
|
||||
"""Принятая загрузка: 202 и снимок `queued` с размером и SHA-256."""
|
||||
resp = self.post_attachment(
|
||||
actor,
|
||||
chat_id,
|
||||
@@ -299,7 +302,7 @@ class Api:
|
||||
content_type=content_type,
|
||||
filename=filename,
|
||||
)
|
||||
attachment = assert_ok(resp, 201, "Attachment")
|
||||
attachment = assert_accepted(resp)
|
||||
assert attachment["size_bytes"] == len(data), "size_bytes differs"
|
||||
assert attachment["sha256"] == hashlib.sha256(data).hexdigest(), (
|
||||
"sha256 differs"
|
||||
@@ -309,6 +312,57 @@ class Api:
|
||||
assert attachment["filename"] == filename, "filename changed"
|
||||
return attachment
|
||||
|
||||
def wait_attachment(
|
||||
self,
|
||||
actor: Actor,
|
||||
attachment_id: str,
|
||||
*,
|
||||
status: str = "ready",
|
||||
timeout: float = READY_TIMEOUT_S,
|
||||
) -> dict[str, Any]:
|
||||
"""Метаданные вложения, когда оно в статусе `status`: опрос раз в
|
||||
0,2 с. Истёк срок или вложение стало `failed`, а ждали другое —
|
||||
падение с последним состоянием (спек `student-tests`, «Готовность
|
||||
вложения в тестах»)."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
meta = assert_ok(
|
||||
self.attachment_meta(actor, attachment_id),
|
||||
200,
|
||||
"Attachment",
|
||||
)
|
||||
if meta["status"] == status:
|
||||
return meta
|
||||
assert meta["status"] != "failed", (
|
||||
f"attachment {attachment_id} became failed "
|
||||
f"({meta['error_code']}), waited for {status}"
|
||||
)
|
||||
assert time.monotonic() < deadline, (
|
||||
f"attachment {attachment_id} did not become {status} in "
|
||||
f"{timeout} s, last status {meta['status']}: is the worker "
|
||||
"running?"
|
||||
)
|
||||
time.sleep(READY_POLL_S)
|
||||
|
||||
def upload_ready(
|
||||
self,
|
||||
actor: Actor,
|
||||
chat_id: str,
|
||||
data: bytes,
|
||||
*,
|
||||
content_type: str = "image/png",
|
||||
filename: str = "image.png",
|
||||
) -> dict[str, Any]:
|
||||
"""Загрузка и ожидание `ready`: метаданные готового вложения."""
|
||||
accepted = self.upload(
|
||||
actor,
|
||||
chat_id,
|
||||
data,
|
||||
content_type=content_type,
|
||||
filename=filename,
|
||||
)
|
||||
return self.wait_attachment(actor, accepted["id"])
|
||||
|
||||
def attachment_meta(
|
||||
self,
|
||||
actor: Actor | None,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Проверка ответов по `contracts/openapi.json` и форматам контракта."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping
|
||||
@@ -130,6 +131,16 @@ def assert_ok(resp: httpx.Response, status: int, schema: str) -> Any:
|
||||
return body
|
||||
|
||||
|
||||
def assert_accepted(resp: httpx.Response) -> dict[str, Any]:
|
||||
"""Принятая загрузка: 202 и снимок на момент приёма по схеме контракта
|
||||
(спек `student-tests`, «Готовность вложения в тестах»)."""
|
||||
attachment = assert_ok(resp, 202, "Attachment")
|
||||
assert attachment["status"] == "queued", describe(resp, "not queued")
|
||||
assert attachment["variants"] == [], describe(resp, "has variants")
|
||||
assert attachment["error_code"] is None, describe(resp, "has error_code")
|
||||
return attachment
|
||||
|
||||
|
||||
def assert_error(resp: httpx.Response, status: int) -> dict[str, Any]:
|
||||
"""Ошибка в формате контракта; `code` соответствует статусу."""
|
||||
assert resp.status_code == status, describe(resp, f"expected {status}")
|
||||
@@ -226,6 +237,37 @@ def assert_content(
|
||||
)
|
||||
|
||||
|
||||
def assert_variant_content(
|
||||
resp: httpx.Response,
|
||||
variant: Mapping[str, Any],
|
||||
) -> bytes:
|
||||
"""Байты варианта: те же заголовки, что у оригинала, размер и SHA-256 —
|
||||
поля варианта в метаданных. Возвращает байты."""
|
||||
check_body(dict(variant), "Variant")
|
||||
assert resp.status_code == 200, describe(resp, "expected 200")
|
||||
assert resp.headers.get("X-Request-Id", "").strip(), describe(
|
||||
resp,
|
||||
"no X-Request-Id",
|
||||
)
|
||||
assert_instance_id(resp)
|
||||
assert resp.headers.get("Content-Type") == variant["content_type"], (
|
||||
describe(resp, f"Content-Type is not {variant['content_type']}")
|
||||
)
|
||||
assert resp.headers.get("Content-Length") == str(variant["size_bytes"]), (
|
||||
describe(resp, f"Content-Length is not {variant['size_bytes']}")
|
||||
)
|
||||
assert resp.headers.get("X-Content-Type-Options") == "nosniff", describe(
|
||||
resp,
|
||||
"no X-Content-Type-Options: nosniff",
|
||||
)
|
||||
assert_no_storage_traces(resp)
|
||||
assert len(resp.content) == variant["size_bytes"], "size_bytes differs"
|
||||
assert hashlib.sha256(resp.content).hexdigest() == variant["sha256"], (
|
||||
"sha256 of variant differs"
|
||||
)
|
||||
return resp.content
|
||||
|
||||
|
||||
def assert_instance_id(resp: httpx.Response) -> str:
|
||||
"""Непустой `X-Instance-Id` допустимого формата; возвращает значение."""
|
||||
instance_id = resp.headers.get("X-Instance-Id", "")
|
||||
|
||||
@@ -37,6 +37,20 @@ services:
|
||||
stop_grace_period: 2s
|
||||
haproxy:
|
||||
ports: !reset []
|
||||
# свой брокер со своим volume, порт AMQP не публикуется
|
||||
rabbitmq:
|
||||
ports: !reset []
|
||||
# worker со сроками, сравнимыми со временем теста, и без перезапуска: его
|
||||
# останавливают и убивают сами проверки (design change async-attachments,
|
||||
# решение 15). Сумма пауз 3 × 5 с больше возврата S3 (~8 с): «Временная
|
||||
# ошибка» успевает. Значения run_failures.py передаёт тестам (FAULT_WORKER_*)
|
||||
worker:
|
||||
restart: "no"
|
||||
environment:
|
||||
WORKER__MAX_ATTEMPTS: "4"
|
||||
WORKER__RETRY_DELAY_SECONDS: "5"
|
||||
WORKER__JOB_TIMEOUT_SECONDS: "10"
|
||||
WORKER__GRACEFUL_SHUTDOWN_SECONDS: "2"
|
||||
# уборщик с grace и интервалом, сравнимыми со временем теста (design
|
||||
# change upload-consistency, решение 10). Grace 20 с больше границы живой
|
||||
# загрузки при сроках по умолчанию (2 × 6 + 5 = 17 с): занижать сроки ради
|
||||
|
||||
+350
-37
@@ -39,18 +39,48 @@
|
||||
s3). Каталог `<id>` без файла не считается:
|
||||
после DELETE SeaweedFS убирает его лишь
|
||||
через ~2 мин
|
||||
fail-attachments insert|ready|stall|commit|outlive|undeletable <filename>
|
||||
staging-ids то же под `<база>/staging/<id>/`
|
||||
variant-object-count <id> сколько у вложения объектов вариантов
|
||||
(`<база>/attachments/<id>/v<N>-<имя>`)
|
||||
job <attachment_id> строка задания вложения: JSON с id, state,
|
||||
attempt, last_error_code, next_attempt_at,
|
||||
published_at; нет задания — пусто
|
||||
fail-attachments insert|queued|stall|commit|outlive|undeletable <filename>
|
||||
триггеры на вложения с этим filename (сбой —
|
||||
SQLSTATE 08006, для API это отказ БД, 503):
|
||||
insert — вставка строки падает; ready —
|
||||
перевод в ready падает до COMMIT; stall —
|
||||
перевод в ready ждёт pg_sleep(4); commit —
|
||||
перевод в ready падает на COMMIT (исход для
|
||||
insert — вставка строки падает; queued —
|
||||
перевод в queued падает до COMMIT; stall —
|
||||
перевод в queued ждёт pg_sleep(4); commit —
|
||||
перевод в queued падает на COMMIT (исход для
|
||||
API неизвестен); outlive — строка
|
||||
вставляется на час старше (уборщик берёт её
|
||||
сразу), а перевод в ready ждёт до 4,5 с, пока
|
||||
сразу), а перевод в queued ждёт до 4,5 с, пока
|
||||
строка pending не исчезнет; undeletable — как
|
||||
outlive, и удаление строки падает
|
||||
fail-attachments ready-fail|ready-stall <filename>
|
||||
фиксация worker: перевод в ready падает
|
||||
(08006) или ждёт pg_sleep(4)
|
||||
stop|start|pause|unpause|kill|recreate rabbitmq
|
||||
брокер стенда; recreate — up --force-recreate
|
||||
на том же volume; после start, recreate и
|
||||
unpause — ожидание ответа брокера
|
||||
stop|start|kill worker worker стенда; start — docker start контейнера
|
||||
worker-state JSON: running, restart_count, oom_killed,
|
||||
exit_code
|
||||
worker-log журнал контейнера worker (stdout), все
|
||||
запуски подряд
|
||||
queue-state JSON очереди: messages, messages_ready,
|
||||
messages_unacknowledged, consumers, durable;
|
||||
очереди нет — null
|
||||
peek-job тело одного сообщения очереди, прочитанного
|
||||
без подтверждения (возвращается в очередь);
|
||||
JSON с полями body (JSON-строка), delivery_mode;
|
||||
сообщения нет — пусто. Python в контейнере API
|
||||
его настройками: пароль в hook не попадает
|
||||
publish-job сообщение с телом из stdin в очередь,
|
||||
persistent; тот же контейнер
|
||||
delete-queue удалить очередь (rabbitmqctl в контейнере
|
||||
брокера); отсутствие — не ошибка
|
||||
fail-attachments mark <filename>
|
||||
пометка потерянного оригинала (UPDATE
|
||||
lost_at) вложения с этим filename падает
|
||||
@@ -65,13 +95,15 @@
|
||||
стенда мимо API: botocore в контейнере
|
||||
обычного API его ключами из окружения
|
||||
контейнера. Ключ — только под
|
||||
`<FAULT_DATABASE>/attachments/`, символы
|
||||
`<FAULT_DATABASE>/attachments/` или
|
||||
`<FAULT_DATABASE>/staging/`, символы
|
||||
[A-Za-z0-9._/-]
|
||||
delete-object <ключ> удалить объект мимо шлюза S3: `weed shell
|
||||
fs.rm /buckets/<bucket>/<ключ>`; ключ — с той
|
||||
же проверкой
|
||||
delete-row <id> удалить строку вложения (неиспользуемого:
|
||||
ссылку сообщения не даст удалить FK)
|
||||
delete-row <id> удалить строку вложения с его заданием и
|
||||
вариантами (неиспользуемого: ссылку
|
||||
сообщения не даст удалить FK)
|
||||
set-size <id> <байт> изменить size_bytes строки
|
||||
age-row <id> <секунд> сдвинуть created_at и updated_at строки
|
||||
назад на одно и то же время: CHECK и
|
||||
@@ -107,9 +139,10 @@ FAULT_DATABASE, их задаёт run_failures.py. Пароли и ключи н
|
||||
не печатает: valkey-cli берёт пароль из VALKEYCLI_AUTH контейнера, psql
|
||||
работает от POSTGRES_USER контейнера, weed shell — с ключом подписи из
|
||||
окружения контейнера s3, put-object — ключами API из окружения
|
||||
контейнера API. Только stdlib. Действия вложений — design change
|
||||
`upload-consistency`, решение 10; расхождения хранилищ и сверка — design
|
||||
change `track2-reconciler`, решение 11.
|
||||
контейнера API, peek-job и publish-job — настройками брокера там же. Только
|
||||
stdlib. Действия вложений — design change `upload-consistency`, решение 10;
|
||||
расхождения хранилищ и сверка — design change `track2-reconciler`, решение
|
||||
11; брокер, worker и задания — design change `async-attachments`, решение 15.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -129,7 +162,7 @@ COMPOSE_FILES = (
|
||||
ROOT / "student-tests" / "failures.compose.yml",
|
||||
)
|
||||
PROJECT_SUFFIX = "-failures"
|
||||
SERVICES = ("postgres", "valkey", "s3")
|
||||
SERVICES = ("postgres", "valkey", "s3", "rabbitmq")
|
||||
# та же проверка, что в healthcheck сервиса в docker-compose.yml. У
|
||||
# PostgreSQL стенда отказов healthcheck переопределён на базу postgres
|
||||
# (failures.compose.yml), а проба после start / unpause ходит в базу
|
||||
@@ -146,6 +179,7 @@ PROBES = {
|
||||
"grep -qF '\"DataNodes\":[{' && "
|
||||
"wget -q -O /dev/null http://127.0.0.1:8888/healthz && "
|
||||
'wget -q -O /dev/null "http://127.0.0.1:$S3_PORT/healthz"',
|
||||
"rabbitmq": "rabbitmq-diagnostics -q check_port_connectivity",
|
||||
}
|
||||
PROBE_TIMEOUT_S = 30
|
||||
# начало ключа карточки — копия CACHE_KEY_PREFIX из src/utils/constants.py:
|
||||
@@ -259,15 +293,16 @@ ORDER BY created_at DESC, id DESC LIMIT 1;
|
||||
# (connection_failure) приложение считает отказом БД: 503, а не 500
|
||||
# (design change upload-consistency, пробы). Три триггера, каждый
|
||||
# срабатывает только в своих режимах:
|
||||
# - fault_fail_attachments (строка, BEFORE): insert, ready, stall; в outlive
|
||||
# - fault_fail_attachments (строка, BEFORE): insert, queued, stall; в outlive
|
||||
# и undeletable вставка «на час старше» — created_at и updated_at вместе,
|
||||
# строка остаётся непомеченной (mark_ready требует updated_at =
|
||||
# created_at); в undeletable удаление строки падает;
|
||||
# строка остаётся непомеченной (mark_queued требует updated_at =
|
||||
# created_at); в undeletable удаление строки падает; ready-fail и
|
||||
# ready-stall — перевод worker в ready;
|
||||
# - fault_fail_attachments_commit (отложенный триггер ограничения, AFTER
|
||||
# UPDATE): commit — перевод в ready падает на COMMIT, исход для API
|
||||
# UPDATE): commit — перевод в queued падает на COMMIT, исход для API
|
||||
# неизвестен;
|
||||
# - fault_wait_attachments (оператор, BEFORE UPDATE OF status): outlive и
|
||||
# undeletable — перевод в ready ждёт, пока строка pending с этим
|
||||
# undeletable — перевод в queued ждёт, пока строка pending с этим
|
||||
# filename не исчезнет, но не дольше WAIT. На уровне оператора строка ещё
|
||||
# не заблокирована, уборщик её берёт. UPDATE OF status: пометку уборщика
|
||||
# (меняет только updated_at) ожидание не задерживает.
|
||||
@@ -297,15 +332,24 @@ BEGIN
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF OLD.status = 'pending' AND NEW.status = 'ready' THEN
|
||||
IF TG_ARGV[0] = 'ready' THEN
|
||||
RAISE EXCEPTION 'fault injected: attachment ready'
|
||||
IF OLD.status = 'pending' AND NEW.status = 'queued' THEN
|
||||
IF TG_ARGV[0] = 'queued' THEN
|
||||
RAISE EXCEPTION 'fault injected: attachment queued'
|
||||
USING ERRCODE = '08006';
|
||||
END IF;
|
||||
IF TG_ARGV[0] = 'stall' THEN
|
||||
PERFORM pg_sleep(4);
|
||||
END IF;
|
||||
END IF;
|
||||
IF OLD.status <> 'ready' AND NEW.status = 'ready' THEN
|
||||
IF TG_ARGV[0] = 'ready-fail' THEN
|
||||
RAISE EXCEPTION 'fault injected: attachment ready'
|
||||
USING ERRCODE = '08006';
|
||||
END IF;
|
||||
IF TG_ARGV[0] = 'ready-stall' THEN
|
||||
PERFORM pg_sleep(4);
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
@@ -313,8 +357,8 @@ CREATE OR REPLACE FUNCTION fault_fail_attachments_commit() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_ARGV[0] = 'commit' AND NEW.filename = TG_ARGV[1]
|
||||
AND OLD.status = 'pending' AND NEW.status = 'ready' THEN
|
||||
RAISE EXCEPTION 'fault injected: attachment ready commit'
|
||||
AND OLD.status = 'pending' AND NEW.status = 'queued' THEN
|
||||
RAISE EXCEPTION 'fault injected: attachment queued commit'
|
||||
USING ERRCODE = '08006';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
@@ -384,8 +428,14 @@ DROP FUNCTION IF EXISTS fault_fail_attachments_mark();
|
||||
"""
|
||||
# расхождения хранилищ (design change track2-reconciler, решение 11):
|
||||
# значения — переменные psql (:'title' — id, :'mode' — число)
|
||||
# задание и варианты ссылаются на строку без каскада: у готового вложения
|
||||
# метаданные удаляются вместе с ними
|
||||
DELETE_ROW_SQL = """\
|
||||
BEGIN;
|
||||
DELETE FROM attachment_variants WHERE attachment_id = :'title'::uuid;
|
||||
DELETE FROM attachment_jobs WHERE attachment_id = :'title'::uuid;
|
||||
DELETE FROM attachments WHERE id = :'title'::uuid RETURNING id;
|
||||
COMMIT;
|
||||
"""
|
||||
SET_SIZE_SQL = """\
|
||||
UPDATE attachments SET size_bytes = :'mode'::integer
|
||||
@@ -404,6 +454,79 @@ WHERE id = :'title'::uuid RETURNING id;
|
||||
LOST_IDS_SQL = """\
|
||||
SELECT id FROM attachments WHERE lost_at IS NOT NULL ORDER BY id;
|
||||
"""
|
||||
JOB_SQL = """\
|
||||
SELECT row_to_json(j) FROM (
|
||||
SELECT id, state, attempt, last_error_code, next_attempt_at,
|
||||
lease_expires_at, published_at
|
||||
FROM attachment_jobs WHERE attachment_id = :'title'::uuid
|
||||
) j;
|
||||
"""
|
||||
# брокер — настройками процесса в контейнере API: пароль в hook не попадает.
|
||||
# Соединение прямо на сообщение, без подтверждения (peek): закрытие
|
||||
# соединения возвращает его в очередь. Очередь — из имени базы процесса
|
||||
PEEK_JOB_PY = """\
|
||||
import asyncio
|
||||
import json
|
||||
import aio_pika
|
||||
from src.config import settings
|
||||
from src.infra.broker import queue_name
|
||||
async def main():
|
||||
broker = settings.broker
|
||||
connection = await aio_pika.connect(
|
||||
host=broker.host, port=broker.port, login=broker.user,
|
||||
password=broker.password.get_secret_value(), timeout=5,
|
||||
)
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
queue = await channel.declare_queue(
|
||||
queue_name(settings.database.name), durable=True,
|
||||
)
|
||||
message = await queue.get(no_ack=False, fail=False, timeout=5)
|
||||
if message is None:
|
||||
return
|
||||
print(json.dumps({
|
||||
"body": message.body.decode(),
|
||||
"delivery_mode": message.delivery_mode,
|
||||
}))
|
||||
await message.nack(requeue=True)
|
||||
asyncio.run(main())
|
||||
"""
|
||||
PUBLISH_JOB_PY = """\
|
||||
import asyncio
|
||||
import sys
|
||||
import aio_pika
|
||||
from src.config import settings
|
||||
from src.infra.broker import queue_name
|
||||
async def main():
|
||||
broker = settings.broker
|
||||
connection = await aio_pika.connect(
|
||||
host=broker.host, port=broker.port, login=broker.user,
|
||||
password=broker.password.get_secret_value(), timeout=5,
|
||||
)
|
||||
async with connection:
|
||||
channel = await connection.channel(publisher_confirms=True)
|
||||
name = queue_name(settings.database.name)
|
||||
await channel.declare_queue(name, durable=True)
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
sys.stdin.buffer.read(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
),
|
||||
routing_key=name,
|
||||
)
|
||||
asyncio.run(main())
|
||||
"""
|
||||
# поля list_queues; очередь — точное имя из FAULT_DATABASE
|
||||
QUEUE_COLUMNS = (
|
||||
"name",
|
||||
"messages",
|
||||
"messages_ready",
|
||||
"messages_unacknowledged",
|
||||
"consumers",
|
||||
"durable",
|
||||
)
|
||||
# копия ATTACHMENT_QUEUE_SUFFIX из src/utils/constants.py
|
||||
QUEUE_SUFFIX = "attachment.process.v1"
|
||||
# объект мимо API: botocore образа (зависимость aiobotocore) с адресом,
|
||||
# регионом и ключами из настроек процесса в контейнере API — ключи в hook
|
||||
# не попадают. Ключ — argv[1], тело — stdin
|
||||
@@ -437,11 +560,13 @@ SCHEDULED_CLEANER_ENV = "RECONCILER__INTERVAL_SECONDS=1"
|
||||
SCHEDULED_CLEANER_MAX_S = 60
|
||||
FAIL_ATTACHMENTS_MODES = (
|
||||
"insert",
|
||||
"ready",
|
||||
"queued",
|
||||
"stall",
|
||||
"commit",
|
||||
"outlive",
|
||||
"undeletable",
|
||||
"ready-fail",
|
||||
"ready-stall",
|
||||
)
|
||||
# как S3_BUCKET_NAME_PATTERN в src/utils/constants.py; имя базы — как в
|
||||
# run_isolated.py: путь filer собирается только из проверенных имён
|
||||
@@ -453,7 +578,10 @@ ATTACHMENT_DIR_RE = re.compile(
|
||||
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||||
)
|
||||
ATTACHMENT_KEY_PREFIX = "attachments"
|
||||
ATTACHMENT_STAGING_PREFIX = "staging"
|
||||
ATTACHMENT_ORIGINAL = "original"
|
||||
# объект варианта в каталоге вложения: v<версия>-<имя>
|
||||
VARIANT_FILE_RE = re.compile(r"^v[1-9][0-9]*-(thumbnail|crop|optimized)$")
|
||||
# строка fs.tree: отступ по 4 символа на уровень («│ » или « »), затем
|
||||
# «├──» или «└──» и имя
|
||||
TREE_LINE_RE = re.compile(r"^((?:[│ ] {3})*)[├└]──\s*(.*?)\s*$")
|
||||
@@ -697,11 +825,31 @@ def ids_with_original(tree: str) -> list[str]:
|
||||
return found
|
||||
|
||||
|
||||
def object_ids(project: str) -> str:
|
||||
"""`id` вложений с объектом в bucket стенда, строка на `id`. Нет
|
||||
префикса — пусто."""
|
||||
def variant_files(tree: str, attachment_id: str) -> list[str]:
|
||||
"""Файлы вариантов в каталоге `attachment_id` вывода `fs.tree`."""
|
||||
found: list[str] = []
|
||||
current = ""
|
||||
for line in tree.splitlines():
|
||||
match = TREE_LINE_RE.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
depth = len(match.group(1)) // 4 + 1
|
||||
name = match.group(2)
|
||||
if depth == 1:
|
||||
current = name
|
||||
elif (
|
||||
depth == 2
|
||||
and current == attachment_id
|
||||
and VARIANT_FILE_RE.fullmatch(name)
|
||||
):
|
||||
found.append(name)
|
||||
return found
|
||||
|
||||
|
||||
def tree_of(project: str, prefix: str) -> str:
|
||||
"""`fs.tree` каталога `<база>/<prefix>` bucket стенда; нет — пусто."""
|
||||
bucket, database = storage_names()
|
||||
tree = compose(
|
||||
return compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
@@ -709,11 +857,141 @@ def object_ids(project: str) -> str:
|
||||
"sh",
|
||||
"-c",
|
||||
"exec weed shell -master=127.0.0.1:9333 2>&1",
|
||||
stdin=(
|
||||
f"fs.tree /buckets/{bucket}/{database}/{ATTACHMENT_KEY_PREFIX}\n"
|
||||
),
|
||||
stdin=f"fs.tree /buckets/{bucket}/{database}/{prefix}\n",
|
||||
)
|
||||
return "\n".join(ids_with_original(tree))
|
||||
|
||||
|
||||
def object_ids(project: str, prefix: str = ATTACHMENT_KEY_PREFIX) -> str:
|
||||
"""`id` вложений с объектом `original` под префиксом bucket стенда,
|
||||
строка на `id`. Нет префикса — пусто."""
|
||||
return "\n".join(ids_with_original(tree_of(project, prefix)))
|
||||
|
||||
|
||||
def variant_object_count(project: str, attachment_id: str) -> str:
|
||||
wanted = str(uuid.UUID(attachment_id))
|
||||
tree = tree_of(project, ATTACHMENT_KEY_PREFIX)
|
||||
return str(len(variant_files(tree, wanted)))
|
||||
|
||||
|
||||
def queue() -> str:
|
||||
_, database = storage_names()
|
||||
return f"{database}.{QUEUE_SUFFIX}"
|
||||
|
||||
|
||||
def queue_state(project: str) -> str:
|
||||
"""Состояние очереди стенда JSON-ом или `null`: `rabbitmqctl` в контейнере
|
||||
брокера, без management API."""
|
||||
output = compose(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"rabbitmq",
|
||||
"rabbitmqctl",
|
||||
"-q",
|
||||
"list_queues",
|
||||
*QUEUE_COLUMNS,
|
||||
"--formatter",
|
||||
"json",
|
||||
)
|
||||
for item in json.loads(output or "[]"):
|
||||
if item["name"] == queue():
|
||||
return json.dumps(item)
|
||||
return "null"
|
||||
|
||||
|
||||
def delete_queue(project: str) -> str:
|
||||
"""Удалить очередь стенда; её отсутствие — не ошибка."""
|
||||
result = compose_run(
|
||||
project,
|
||||
"exec",
|
||||
"-T",
|
||||
"rabbitmq",
|
||||
"rabbitmqctl",
|
||||
"-q",
|
||||
"delete_queue",
|
||||
queue(),
|
||||
)
|
||||
if result.returncode != 0 and "No such queue" not in (
|
||||
result.stdout + result.stderr
|
||||
):
|
||||
sys.stderr.write(result.stderr)
|
||||
raise SystemExit(result.returncode)
|
||||
return ""
|
||||
|
||||
|
||||
def api_python(project: str, code: str, stdin: bytes | None = None) -> str:
|
||||
"""Код в контейнере обычного API: настройки процесса, а не hook, знают
|
||||
пароль брокера."""
|
||||
result = subprocess.run(
|
||||
["docker", "exec", "-i", api_container(project), "python", "-c", code],
|
||||
input=b"" if stdin is None else stdin,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
tail = result.stderr.decode(errors="replace").strip().splitlines()[-1:]
|
||||
raise HookError(f"api python failed: {tail}")
|
||||
# лишние записи настройки логгера в stdout: строка результата — последняя
|
||||
lines = result.stdout.decode(errors="replace").strip().splitlines()
|
||||
return lines[-1] if lines else ""
|
||||
|
||||
|
||||
def worker_container(project: str) -> str:
|
||||
container = compose(project, "ps", "-a", "-q", "worker")
|
||||
if not container:
|
||||
raise HookError("worker container of the stand not found")
|
||||
return container
|
||||
|
||||
|
||||
def worker_action(project: str, action: str) -> str:
|
||||
"""`start` — тот же контейнер, `docker start`, как у уборщика: у compose
|
||||
start нет контейнера одноразовых зависимостей."""
|
||||
if action == "stop":
|
||||
return compose(project, "stop", "worker")
|
||||
docker(action, worker_container(project))
|
||||
return ""
|
||||
|
||||
|
||||
def worker_state(project: str) -> str:
|
||||
fields = docker(
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{.State.Running}} {{.RestartCount}} {{.State.OOMKilled}} "
|
||||
"{{.State.ExitCode}}",
|
||||
worker_container(project),
|
||||
).split()
|
||||
return json.dumps(
|
||||
{
|
||||
"running": fields[0] == "true",
|
||||
"restart_count": int(fields[1]),
|
||||
"oom_killed": fields[2] == "true",
|
||||
"exit_code": int(fields[3]),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def broker_action(project: str, action: str) -> str:
|
||||
"""Действия брокера; ждёт ответа после возврата."""
|
||||
if action in ("stop", "pause"):
|
||||
compose(project, action, "rabbitmq")
|
||||
return ""
|
||||
if action == "kill":
|
||||
docker("kill", compose(project, "ps", "-q", "rabbitmq"))
|
||||
return ""
|
||||
if action == "start":
|
||||
docker("start", compose(project, "ps", "-a", "-q", "rabbitmq"))
|
||||
elif action == "unpause":
|
||||
compose(project, "unpause", "rabbitmq")
|
||||
else:
|
||||
compose(
|
||||
project,
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--force-recreate",
|
||||
"rabbitmq",
|
||||
)
|
||||
return wait_answers(project, "rabbitmq")
|
||||
|
||||
|
||||
def fail_attachments(project: str, mode: str, filename: str) -> str:
|
||||
@@ -739,16 +1017,22 @@ def storage_names() -> tuple[str, str]:
|
||||
|
||||
|
||||
def object_key(key: str) -> str:
|
||||
"""Ключ объекта вложений базы стенда; иначе — отказ (код 2)."""
|
||||
"""Ключ объекта вложений или staging базы стенда; иначе — отказ (код
|
||||
2)."""
|
||||
_, database = storage_names()
|
||||
prefix = f"{database}/{ATTACHMENT_KEY_PREFIX}/"
|
||||
prefixes = (
|
||||
f"{database}/{ATTACHMENT_KEY_PREFIX}/",
|
||||
f"{database}/{ATTACHMENT_STAGING_PREFIX}/",
|
||||
)
|
||||
if (
|
||||
not key.startswith(prefix)
|
||||
or len(key) == len(prefix)
|
||||
not any(
|
||||
key.startswith(prefix) and len(key) > len(prefix)
|
||||
for prefix in prefixes
|
||||
)
|
||||
or not OBJECT_KEY_RE.fullmatch(key)
|
||||
or ".." in key.split("/")
|
||||
):
|
||||
raise HookError(f"object key must be under {prefix}: {key!r}")
|
||||
raise HookError(f"object key must be under {prefixes}: {key!r}")
|
||||
return key
|
||||
|
||||
|
||||
@@ -975,6 +1259,35 @@ def run(project: str, action: str, args: list[str]) -> str:
|
||||
"""Выполнить действие; синтаксис без match: hook запускают и 3.9."""
|
||||
if action in ("stop", "start") and args == ["cleaner"]:
|
||||
return cleaner_action(project, action)
|
||||
if action in ("stop", "start", "kill") and args == ["worker"]:
|
||||
return worker_action(project, action)
|
||||
if action in (
|
||||
"stop",
|
||||
"start",
|
||||
"pause",
|
||||
"unpause",
|
||||
"kill",
|
||||
"recreate",
|
||||
) and args == ["rabbitmq"]:
|
||||
return broker_action(project, action)
|
||||
if action == "worker-state" and not args:
|
||||
return worker_state(project)
|
||||
if action == "worker-log" and not args:
|
||||
return docker("logs", worker_container(project))
|
||||
if action == "queue-state" and not args:
|
||||
return queue_state(project)
|
||||
if action == "delete-queue" and not args:
|
||||
return delete_queue(project)
|
||||
if action == "peek-job" and not args:
|
||||
return api_python(project, PEEK_JOB_PY)
|
||||
if action == "publish-job" and not args:
|
||||
return api_python(project, PUBLISH_JOB_PY, sys.stdin.buffer.read())
|
||||
if action == "job" and len(args) == 1:
|
||||
return psql(project, JOB_SQL, title=str(uuid.UUID(args[0])))
|
||||
if action == "staging-ids" and not args:
|
||||
return object_ids(project, ATTACHMENT_STAGING_PREFIX)
|
||||
if action == "variant-object-count" and len(args) == 1:
|
||||
return variant_object_count(project, args[0])
|
||||
if action in ("stop", "pause") and len(args) == 1:
|
||||
return compose(project, action, service(args[0]))
|
||||
if action == "start" and len(args) == 1:
|
||||
|
||||
@@ -267,6 +267,74 @@ def jpeg_empty_scan(data: bytes | None = None) -> bytes:
|
||||
return data[: _jpeg_header(data)[-1][2]] + JPEG_EOI
|
||||
|
||||
|
||||
def jpeg_precision_12() -> bytes:
|
||||
"""JPEG с 12 битами на компоненту в SOF: структура верна, а Pillow такой
|
||||
не декодирует (спек `attachment-processing`, «Изображение не
|
||||
декодируется»)."""
|
||||
data = bytearray(jpeg())
|
||||
sof = data.index(b"\xff\xc0")
|
||||
data[sof + 4] = 12
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def jpeg_halves(
|
||||
orientation: int | None = None,
|
||||
size: tuple[int, int] = (400, 200),
|
||||
) -> bytes:
|
||||
"""JPEG: левая половина красная, правая синяя; EXIF orientation —
|
||||
необязательно."""
|
||||
from PIL import Image # noqa: PLC0415
|
||||
|
||||
width, height = size
|
||||
image = Image.new("RGB", size, (255, 0, 0))
|
||||
image.paste((0, 0, 255), (width // 2, 0, width, height))
|
||||
save: dict[str, object] = {"quality": 95}
|
||||
if orientation is not None:
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = orientation
|
||||
save["exif"] = exif
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "JPEG", **save)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def png_half_transparent(size: tuple[int, int] = (200, 100)) -> bytes:
|
||||
"""PNG RGBA: левая половина чёрная и непрозрачная, правая прозрачная."""
|
||||
from PIL import Image # noqa: PLC0415
|
||||
|
||||
width, height = size
|
||||
image = Image.new("RGBA", size, (0, 0, 0, 255))
|
||||
image.paste((0, 0, 0, 0), (width // 2, 0, width, height))
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def png_palette_transparent(size: tuple[int, int] = (200, 100)) -> bytes:
|
||||
"""PNG с палитрой и tRNS: левая половина — чёрный цвет палитры, правая —
|
||||
прозрачный."""
|
||||
from PIL import Image # noqa: PLC0415
|
||||
|
||||
width, height = size
|
||||
image = Image.new("P", size, 0)
|
||||
image.putpalette([0, 0, 0, 0, 0, 0])
|
||||
image.paste(1, (width // 2, 0, width, height))
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "PNG", transparency=bytes((255, 0)))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def png_rgba_large(width: int = 8000, height: int = 5000) -> bytes:
|
||||
"""PNG RGBA на 40 млн пикселей: пик памяти декодирования — как у
|
||||
настоящего, файл мал и собирается быстро."""
|
||||
from PIL import Image # noqa: PLC0415
|
||||
|
||||
image = Image.new("RGBA", (width, height), (10, 20, 30, 128))
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "PNG", compress_level=1)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def png_variants() -> dict[str, bytes]:
|
||||
"""Разновидности PNG спека: палитра, альфа, серый с альфой, 16 и 1
|
||||
бит, Adam7."""
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
"""`make failure_checks`: проверки отказов на отдельном стенде.
|
||||
|
||||
Поднимает тот же `docker-compose.yml` под проектом `<рабочий>-failures`
|
||||
с override `student-tests/failures.compose.yml`: свои PostgreSQL, Valkey и
|
||||
S3 со своими volumes, порты хранилищ не публикуются. Затем:
|
||||
с override `student-tests/failures.compose.yml`: свои PostgreSQL, Valkey,
|
||||
S3 и брокер со своими volumes, порты хранилищ не публикуются. Затем:
|
||||
- собирает образ из рабочего дерева, применяет миграции и bootstrap S3;
|
||||
- запускает уборщика незавершённых загрузок с grace 20 с и интервалом
|
||||
1 с (`failures.compose.yml`; design change `upload-consistency`,
|
||||
решение 10) без плановой сверки (design change `track2-reconciler`,
|
||||
решение 9) и передаёт значения тестам; уборщика с плановой сверкой
|
||||
`<проект>-cleaner-scheduled` запускает hook и убирает этот скрипт;
|
||||
- запускает worker с короткими сроками и малым числом попыток (design
|
||||
change `async-attachments`, решение 15) и передаёт значения тестам;
|
||||
- запускает четыре контейнера API: обычный (с `MAX_UPLOAD_BYTES=1` и
|
||||
`MAX_IMAGE_PIXELS=1` в окружении — лимиты вложений от них не зависят),
|
||||
«тесный» (сроки сессии и ключа идемпотентности 2 с, пул из одного
|
||||
@@ -17,8 +19,8 @@ S3 со своими volumes, порты хранилищ не публикую
|
||||
«с коротким сроком S3» (срок вызова S3 1 с; change
|
||||
`fix-upload-put-flake`);
|
||||
- прогоняет тесты с маркером `fault` (`pytest -m fault`), передав им hook
|
||||
`student-tests/fault_hook.py`; при падении печатает журналы API и
|
||||
уборщика;
|
||||
`student-tests/fault_hook.py`; при падении печатает журналы API, уборщика
|
||||
и worker;
|
||||
- после тестов читает журнал PostgreSQL стенда: печатает сводку и падает
|
||||
на признаках аварийного перезапуска (решение 12 design change
|
||||
`fix-known-issues`);
|
||||
@@ -184,6 +186,27 @@ def cleaner_timings(project: str) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def worker_timings(project: str) -> dict[str, str]:
|
||||
"""Сроки и попытки worker стенда — из конфигурации compose
|
||||
(`failures.compose.yml`): тесты ждут по ним."""
|
||||
config = dc(project, "config", "--format", "json", quiet=True)
|
||||
environment = json.loads(config.stdout)["services"]["worker"][
|
||||
"environment"
|
||||
]
|
||||
return {
|
||||
"FAULT_WORKER_MAX_ATTEMPTS": environment["WORKER__MAX_ATTEMPTS"],
|
||||
"FAULT_WORKER_RETRY_DELAY_S": environment[
|
||||
"WORKER__RETRY_DELAY_SECONDS"
|
||||
],
|
||||
"FAULT_WORKER_JOB_TIMEOUT_S": environment[
|
||||
"WORKER__JOB_TIMEOUT_SECONDS"
|
||||
],
|
||||
"FAULT_WORKER_GRACEFUL_S": environment[
|
||||
"WORKER__GRACEFUL_SHUTDOWN_SECONDS"
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def env_pairs(env: dict[str, str]) -> str:
|
||||
"""`KEY=value` через пробел: так окружение API получают тесты."""
|
||||
return " ".join(f"{key}={value}" for key, value in env.items())
|
||||
@@ -339,8 +362,17 @@ def main() -> int:
|
||||
try:
|
||||
say("build image")
|
||||
dc(project, "build", "api")
|
||||
say("start postgres, valkey and s3")
|
||||
dc(project, "up", "-d", "--wait", "postgres", "valkey", "s3")
|
||||
say("start postgres, valkey, s3 and rabbitmq")
|
||||
dc(
|
||||
project,
|
||||
"up",
|
||||
"-d",
|
||||
"--wait",
|
||||
"postgres",
|
||||
"valkey",
|
||||
"s3",
|
||||
"rabbitmq",
|
||||
)
|
||||
say("migrations")
|
||||
dc(project, "run", "--rm", "migrate")
|
||||
# --wait одноразовый сервис считает готовым уже запущенным: код
|
||||
@@ -362,6 +394,14 @@ def main() -> int:
|
||||
f"{timings['FAULT_RECONCILER_INTERVAL_S']} s (0 — off)",
|
||||
)
|
||||
dc(project, "up", "-d", "--no-deps", "cleaner")
|
||||
workers = worker_timings(project)
|
||||
say(
|
||||
f"start worker: attempts {workers['FAULT_WORKER_MAX_ATTEMPTS']}, "
|
||||
f"retry delay {workers['FAULT_WORKER_RETRY_DELAY_S']} s, "
|
||||
f"job timeout {workers['FAULT_WORKER_JOB_TIMEOUT_S']} s, "
|
||||
f"graceful {workers['FAULT_WORKER_GRACEFUL_S']} s",
|
||||
)
|
||||
dc(project, "up", "-d", "--no-deps", "worker")
|
||||
say("start api containers")
|
||||
base_url = start_api(project, default_name, free_port(), LIMITS_ENV)
|
||||
tight_url = start_api(project, tight_name, free_port(), TIGHT_ENV)
|
||||
@@ -391,6 +431,7 @@ def main() -> int:
|
||||
}
|
||||
| storage_names(project)
|
||||
| timings
|
||||
| workers
|
||||
)
|
||||
say("pytest -m fault")
|
||||
results["fault"] = run(
|
||||
@@ -426,16 +467,17 @@ def main() -> int:
|
||||
name,
|
||||
check=False,
|
||||
)
|
||||
say(f"last {LOG_TAIL_LINES} lines of cleaner")
|
||||
dc(
|
||||
project,
|
||||
"logs",
|
||||
"--no-log-prefix",
|
||||
"--tail",
|
||||
str(LOG_TAIL_LINES),
|
||||
"cleaner",
|
||||
check=False,
|
||||
)
|
||||
for service in ("cleaner", "worker"):
|
||||
say(f"last {LOG_TAIL_LINES} lines of {service}")
|
||||
dc(
|
||||
project,
|
||||
"logs",
|
||||
"--no-log-prefix",
|
||||
"--tail",
|
||||
str(LOG_TAIL_LINES),
|
||||
service,
|
||||
check=False,
|
||||
)
|
||||
say("cleanup")
|
||||
if not cleanup(project, containers):
|
||||
say("cleanup failed")
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
"""`make test_isolated`: образ на временной базе `test_<db>`.
|
||||
|
||||
Создаёт базу в Postgres стенда, накатывает на неё миграции сервисом
|
||||
`migrate`, поднимает отдельный контейнер `api` из определения compose с
|
||||
подменой только `DATABASE__NAME`, прогоняет `make test` и
|
||||
`migrate`, поднимает отдельные контейнеры `api` и `worker` из определений
|
||||
compose с подменой только `DATABASE__NAME`, прогоняет `make test` и
|
||||
`make student_test` (`EXPECT_REPLICAS=1`: один процесс без
|
||||
балансировщика, тесты реплик пропускаются), затем удаляет контейнер и
|
||||
балансировщика, тесты реплик пропускаются), затем удаляет контейнеры и
|
||||
базу — при любом исходе, в том числе по Ctrl+C. Рабочая база и рабочие
|
||||
контейнеры стенда не трогаются. Valkey стенда общий: ключи кэша включают имя базы, и
|
||||
карточки тестового прогона не смешиваются с рабочими. S3 стенда тоже
|
||||
общий: ключи объектов начинаются с имени базы, и префикс `test_<db>/`
|
||||
bucket удаляется в начале (хвост прошлого прогона) и в уборке через
|
||||
`weed shell` в контейнере `s3` (design change `s3-storage`, решение 9).
|
||||
Только stdlib: всё через docker compose и make. Решение 12 design change
|
||||
Брокер стенда общий: задания идут через очередь `<база>.attachment.process.v1`,
|
||||
и очередь временной базы удаляется в начале и в уборке (design change
|
||||
`async-attachments`, решение 15). Только stdlib: всё через docker compose и make. Решение 12 design change
|
||||
`postgres-storage`.
|
||||
|
||||
Запускается напрямую `$(PYTHON)`, как проверки skeleton, а не через
|
||||
@@ -46,6 +48,9 @@ DEFAULT_BUCKET = "messenger"
|
||||
WEED_NO_ENTRY = "no entry is found"
|
||||
READY_TIMEOUT_S = 60
|
||||
LOG_TAIL_LINES = 50
|
||||
# копия ATTACHMENT_QUEUE_SUFFIX из src/utils/constants.py; скрипт на stdlib и
|
||||
# код приложения не импортирует
|
||||
QUEUE_SUFFIX = "attachment.process.v1"
|
||||
|
||||
|
||||
def say(message: str) -> None:
|
||||
@@ -122,6 +127,37 @@ def object_prefix(bucket: str, test_db: str) -> str:
|
||||
return f"/buckets/{bucket}/{test_db}"
|
||||
|
||||
|
||||
def queue_of(test_db: str) -> str:
|
||||
"""Очередь временной базы; другое имя — отказ, как у префикса: ошибка не
|
||||
может удалить рабочую очередь."""
|
||||
if not TEST_DB_NAME_RE.fullmatch(test_db):
|
||||
raise ValueError(f"not a test database name: {test_db}")
|
||||
return f"{test_db}.{QUEUE_SUFFIX}"
|
||||
|
||||
|
||||
def remove_queue(queue: str) -> None:
|
||||
"""Удалить очередь `rabbitmqctl` в контейнере брокера; её отсутствие — не
|
||||
ошибка. Иначе — `RuntimeError`."""
|
||||
result = run(
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"rabbitmq",
|
||||
"rabbitmqctl",
|
||||
"-q",
|
||||
"delete_queue",
|
||||
queue,
|
||||
check=False,
|
||||
quiet=True,
|
||||
)
|
||||
output = result.stdout + result.stderr
|
||||
if result.returncode != 0 and "No such queue" not in output:
|
||||
raise RuntimeError(
|
||||
f"queue {queue} not removed: {output.strip()[:200]}",
|
||||
)
|
||||
|
||||
|
||||
def weed_shell(command: str) -> str:
|
||||
"""Одна команда `weed shell` в контейнере `s3`: ключ подписи — в его
|
||||
окружении, master и filer — на его loopback. Вывод — stdout и stderr
|
||||
@@ -205,23 +241,29 @@ def main() -> int:
|
||||
return 2
|
||||
try:
|
||||
prefix = object_prefix(env.get("S3__BUCKET", DEFAULT_BUCKET), test_db)
|
||||
queue = queue_of(test_db)
|
||||
except ValueError as e:
|
||||
say(str(e))
|
||||
return 2
|
||||
port = env["TEST_APP_PORT"]
|
||||
app_port = env.get("APP__PORT", "8080")
|
||||
container = f"{compose_project()}-test-api"
|
||||
project = compose_project()
|
||||
container = f"{project}-test-api"
|
||||
worker = f"{project}-test-worker"
|
||||
containers = (container, worker)
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
|
||||
say(
|
||||
f"database={test_db} objects={prefix}/ container={container} "
|
||||
f"base_url={base_url}",
|
||||
f"database={test_db} objects={prefix}/ queue={queue} "
|
||||
f"containers={container} {worker} base_url={base_url}",
|
||||
)
|
||||
remove_container(container)
|
||||
for name in containers:
|
||||
remove_container(name)
|
||||
drop_database(test_db)
|
||||
say(f"remove objects {prefix}/")
|
||||
say(f"remove objects {prefix}/ and queue {queue}")
|
||||
try:
|
||||
remove_objects(prefix)
|
||||
remove_queue(queue)
|
||||
except (subprocess.CalledProcessError, RuntimeError) as e:
|
||||
say(f"setup failed: {e}")
|
||||
return 1
|
||||
@@ -261,6 +303,20 @@ def main() -> int:
|
||||
quiet=True,
|
||||
)
|
||||
wait_ready(f"{base_url}/health/ready", container)
|
||||
say("start worker container")
|
||||
run(
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
worker,
|
||||
"-e",
|
||||
f"DATABASE__NAME={test_db}",
|
||||
"worker",
|
||||
quiet=True,
|
||||
)
|
||||
say("ready")
|
||||
for target in ("test", "student_test"):
|
||||
say(f"make {target}")
|
||||
@@ -284,25 +340,31 @@ def main() -> int:
|
||||
# повторный Ctrl+C не должен оборвать уборку на полпути
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
if failed:
|
||||
say(f"last {LOG_TAIL_LINES} lines of {container}")
|
||||
run(
|
||||
"docker",
|
||||
"logs",
|
||||
"--tail",
|
||||
str(LOG_TAIL_LINES),
|
||||
container,
|
||||
check=False,
|
||||
)
|
||||
for name in containers:
|
||||
say(f"last {LOG_TAIL_LINES} lines of {name}")
|
||||
run(
|
||||
"docker",
|
||||
"logs",
|
||||
"--tail",
|
||||
str(LOG_TAIL_LINES),
|
||||
name,
|
||||
check=False,
|
||||
)
|
||||
say("cleanup")
|
||||
run("docker", "stop", container, check=False, quiet=True)
|
||||
remove_container(container)
|
||||
for name in containers:
|
||||
run("docker", "stop", name, check=False, quiet=True)
|
||||
remove_container(name)
|
||||
try:
|
||||
if args.keep_db:
|
||||
say(f"kept database {test_db} and objects {prefix}/")
|
||||
say(
|
||||
f"kept database {test_db}, objects {prefix}/ and queue "
|
||||
f"{queue}",
|
||||
)
|
||||
else:
|
||||
drop_database(test_db)
|
||||
say(f"remove objects {prefix}/")
|
||||
say(f"remove objects {prefix}/ and queue {queue}")
|
||||
remove_objects(prefix)
|
||||
remove_queue(queue)
|
||||
except (subprocess.CalledProcessError, RuntimeError) as e:
|
||||
say(f"cleanup failed: {e}")
|
||||
results["cleanup"] = 1
|
||||
|
||||
@@ -27,6 +27,9 @@ CAPABILITIES = (
|
||||
# уборщик: все сценарии — проверки отказов (design change
|
||||
# upload-consistency, решение 10)
|
||||
"storage-consistency",
|
||||
# с лабы 5 (design change async-attachments, решение 15)
|
||||
"attachment-processing",
|
||||
"message-broker",
|
||||
)
|
||||
SCENARIO_RE = re.compile(r"^#### Scenario: (.+?)\s*$", re.MULTILINE)
|
||||
|
||||
@@ -151,6 +154,39 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
"разные хэши одинаковых паролей, пароля нет в pg_dump базы — "
|
||||
"evidence/auth/passwords-and-tokens.md",
|
||||
),
|
||||
("message-broker", "Сервис брокера запущен"): Exclusion(
|
||||
reason="образ, volume и порты контейнера видны только в Docker",
|
||||
check="driver.py --port <LB> broker-check: образ с тегом и digest, "
|
||||
"именованный volume, docker port только AMQP на 127.0.0.1 — "
|
||||
"evidence/broker/stand.md",
|
||||
),
|
||||
("message-broker", "Предел памяти брокера"): Exclusion(
|
||||
reason="предел памяти виден только в статусе брокера",
|
||||
check="driver.py --port <LB> broker-check: предел памяти из "
|
||||
"rabbitmqctl status меньше лимита контейнера — "
|
||||
"evidence/broker/stand.md",
|
||||
),
|
||||
("message-broker", "Остановка брокера"): Exclusion(
|
||||
reason="код выхода и время остановки контейнера видны только в "
|
||||
"Docker, а проверка плавной остановки — на рабочем стенде",
|
||||
check="driver.py --port <LB> broker-check: docker compose stop "
|
||||
"брокера — код 0 раньше срока — evidence/broker/stand.md",
|
||||
),
|
||||
("message-broker", "Очереди разных баз разделены"): Exclusion(
|
||||
reason="прогон на временной базе и взгляд на очереди брокера, а "
|
||||
"набор не знает, на какой базе работает",
|
||||
check="make test_isolated KEEP_TEST_DB=1, driver.py --port <LB> "
|
||||
"broker-check --require-test-queue, make test_isolated: очередь "
|
||||
"временной базы есть после первого прогона и нет после второго — "
|
||||
"evidence/broker/isolated.md",
|
||||
),
|
||||
("data-storage", "Ограничения обработки в схеме"): Exclusion(
|
||||
reason="нужна прямая вставка в таблицы PostgreSQL, а тесты ходят по "
|
||||
"HTTP",
|
||||
check="driver.py --port <LB> attachment-storage: пробы ограничений "
|
||||
"обработки в откатываемой транзакции — "
|
||||
"evidence/attachments/storage.md",
|
||||
),
|
||||
}
|
||||
# ссылка исключения на доказательство в репозитории лабы
|
||||
EVIDENCE_RE = re.compile(r"evidence/[\w./-]+\.md")
|
||||
|
||||
@@ -451,7 +451,7 @@ def test_attachment_ids_in_upper_case(
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
attachment = api.upload(alice, chat["id"], data)
|
||||
attachment = api.upload_ready(alice, chat["id"], data)
|
||||
upper = attachment["id"].upper()
|
||||
meta = assert_ok(api.attachment_meta(alice, upper), 200, "Attachment")
|
||||
assert meta == attachment
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Спек `attachment-processing`: то, что видно по HTTP на любом стенде с worker.
|
||||
|
||||
Thumbnail, скачивание варианта, готовность и `failed` от недекодируемого
|
||||
изображения. Сценарии с остановкой worker, брокера и S3 — проверки отказов
|
||||
(`test_failures.py`).
|
||||
"""
|
||||
|
||||
import io
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
import images
|
||||
from api_client import Actor, Api
|
||||
from contract import (
|
||||
assert_error,
|
||||
assert_instance_id,
|
||||
assert_ok,
|
||||
assert_replicas,
|
||||
assert_variant_content,
|
||||
)
|
||||
|
||||
# сколько раз читать метаданные через LB, чтобы увидеть другую реплику
|
||||
REPLICA_ATTEMPTS = 20
|
||||
# допуск к цвету пикселя: JPEG теряет, но красный, синий и белый различимы
|
||||
COLOR_TOLERANCE = 40
|
||||
RED = (255, 0, 0)
|
||||
BLUE = (0, 0, 255)
|
||||
WHITE = (255, 255, 255)
|
||||
BLACK = (0, 0, 0)
|
||||
|
||||
|
||||
def thumbnail_of(
|
||||
api: Api,
|
||||
actor: Actor,
|
||||
attachment: dict[str, Any],
|
||||
) -> Image.Image:
|
||||
"""Вариант из метаданных готового вложения: скачан, сверен и открыт
|
||||
как настоящий JPEG; настоящие размеры равны полям варианта."""
|
||||
assert [item["name"] for item in attachment["variants"]] == ["thumbnail"]
|
||||
variant = attachment["variants"][0]
|
||||
data = assert_variant_content(
|
||||
api.attachment_content(actor, attachment["id"], variant="thumbnail"),
|
||||
variant,
|
||||
)
|
||||
image = Image.open(io.BytesIO(data))
|
||||
assert image.format == "JPEG"
|
||||
assert image.size == (variant["width"], variant["height"])
|
||||
assert variant["content_type"] == "image/jpeg"
|
||||
return image
|
||||
|
||||
|
||||
def assert_color(
|
||||
image: Image.Image,
|
||||
position: tuple[int, int],
|
||||
color: tuple[int, int, int],
|
||||
) -> None:
|
||||
got = image.convert("RGB").getpixel(position)
|
||||
assert all(
|
||||
abs(a - b) <= COLOR_TOLERANCE for a, b in zip(got, color, strict=True)
|
||||
), f"pixel {position}: {got}, expected about {color}"
|
||||
|
||||
|
||||
def thumbnail_size(
|
||||
api: Api,
|
||||
actor: Actor,
|
||||
chat_id: str,
|
||||
data: bytes,
|
||||
) -> tuple[int, int]:
|
||||
attachment = api.upload_ready(actor, chat_id, data)
|
||||
return thumbnail_of(api, actor, attachment).size
|
||||
|
||||
|
||||
@pytest.mark.spec("attachment-processing", "Вложение становится готовым")
|
||||
def test_attachment_becomes_ready(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
accepted = api.upload(alice, chat["id"], data, filename="sample.png")
|
||||
started = time.monotonic()
|
||||
ready = api.wait_attachment(alice, accepted["id"])
|
||||
print(f"ready in {time.monotonic() - started:.2f} s")
|
||||
assert ready["error_code"] is None
|
||||
assert [item["name"] for item in ready["variants"]] == ["thumbnail"]
|
||||
|
||||
|
||||
@pytest.mark.spec("attachment-processing", "Fixture 320 × 200")
|
||||
def test_thumbnail_fixture(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
attachment = api.upload_ready(alice, chat["id"], images.sample_png())
|
||||
assert thumbnail_of(api, alice, attachment).size == (256, 160)
|
||||
|
||||
|
||||
@pytest.mark.spec(
|
||||
"attachment-processing",
|
||||
"Маленькое изображение не увеличивается",
|
||||
)
|
||||
def test_thumbnail_not_enlarged(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
for size in ((100, 50), (256, 256)):
|
||||
data = images.png(*size)
|
||||
assert thumbnail_size(api, alice, chat["id"], data) == size
|
||||
|
||||
|
||||
@pytest.mark.spec("attachment-processing", "Округление вниз и минимум")
|
||||
def test_thumbnail_rounding(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
for size, expected in (
|
||||
((1000, 601), (256, 153)),
|
||||
((601, 1000), (153, 256)),
|
||||
((5000, 10), (256, 1)),
|
||||
((10, 5000), (1, 256)),
|
||||
):
|
||||
data = images.png(*size)
|
||||
assert thumbnail_size(api, alice, chat["id"], data) == expected, size
|
||||
|
||||
|
||||
@pytest.mark.spec("attachment-processing", "EXIF orientation")
|
||||
def test_thumbnail_exif_orientation(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
attachment = api.upload_ready(
|
||||
alice,
|
||||
chat["id"],
|
||||
images.jpeg_halves(orientation=6),
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
image = thumbnail_of(api, alice, attachment)
|
||||
assert image.size == (128, 256)
|
||||
assert_color(image, (64, 32), RED)
|
||||
assert_color(image, (64, 224), BLUE)
|
||||
|
||||
|
||||
def test_thumbnail_every_orientation(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
"""Спек `attachment-processing`, «EXIF orientation»: все восемь значений —
|
||||
где оказывается красная половина показанного изображения."""
|
||||
# значение → размер и точки красного и синего: левая половина файла
|
||||
# красная, правая синяя
|
||||
wide, tall = (256, 128), (128, 256)
|
||||
left, right = (32, 64), (224, 64)
|
||||
top, bottom = (64, 32), (64, 224)
|
||||
expected = {
|
||||
1: (wide, left, right),
|
||||
2: (wide, right, left),
|
||||
3: (wide, right, left),
|
||||
4: (wide, left, right),
|
||||
5: (tall, top, bottom),
|
||||
6: (tall, top, bottom),
|
||||
7: (tall, bottom, top),
|
||||
8: (tall, bottom, top),
|
||||
}
|
||||
for orientation, (size, red, blue) in expected.items():
|
||||
attachment = api.upload_ready(
|
||||
alice,
|
||||
chat["id"],
|
||||
images.jpeg_halves(orientation=orientation),
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
image = thumbnail_of(api, alice, attachment)
|
||||
assert image.size == size, orientation
|
||||
assert_color(image, red, RED)
|
||||
assert_color(image, blue, BLUE)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachment-processing", "Alpha на белый")
|
||||
def test_thumbnail_alpha(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
for data in (
|
||||
images.png_half_transparent(),
|
||||
images.png_palette_transparent(),
|
||||
):
|
||||
attachment = api.upload_ready(alice, chat["id"], data)
|
||||
image = thumbnail_of(api, alice, attachment)
|
||||
assert_color(image, (20, image.height // 2), BLACK)
|
||||
assert_color(image, (image.width - 20, image.height // 2), WHITE)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachment-processing", "Разновидности форматов")
|
||||
def test_thumbnail_format_variants(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
kinds = [
|
||||
("image/png", name, data)
|
||||
for name, data in images.png_variants().items()
|
||||
] + [
|
||||
("image/jpeg", name, data)
|
||||
for name, data in images.jpeg_variants().items()
|
||||
]
|
||||
for content_type, name, data in kinds:
|
||||
attachment = api.upload_ready(
|
||||
alice,
|
||||
chat["id"],
|
||||
data,
|
||||
content_type=content_type,
|
||||
filename=f"{name}.img",
|
||||
)
|
||||
thumbnail_of(api, alice, attachment)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Скачивание thumbnail")
|
||||
def test_download_thumbnail(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
attachment = api.upload_ready(alice, chat["id"], images.sample_png())
|
||||
resp = api.attachment_content(
|
||||
bob,
|
||||
attachment["id"],
|
||||
variant="thumbnail",
|
||||
)
|
||||
assert not resp.is_redirect
|
||||
assert_variant_content(resp, attachment["variants"][0])
|
||||
assert resp.headers["Content-Type"] == "image/jpeg"
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Отсутствующий вариант")
|
||||
def test_missing_variant(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
attachment = api.upload_ready(alice, chat["id"], images.sample_png())
|
||||
for variant in ("crop", "optimized"):
|
||||
assert_error(
|
||||
api.attachment_content(alice, attachment["id"], variant=variant),
|
||||
404,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Вариант для постороннего")
|
||||
def test_variant_outsider(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
eve: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
attachment = api.upload_ready(alice, chat["id"], images.sample_png())
|
||||
outsider = assert_error(
|
||||
api.attachment_content(eve, attachment["id"], variant="thumbnail"),
|
||||
404,
|
||||
)
|
||||
unknown = assert_error(
|
||||
api.attachment_content(
|
||||
alice,
|
||||
"00000000-0000-4000-8000-000000000000",
|
||||
variant="thumbnail",
|
||||
),
|
||||
404,
|
||||
)
|
||||
assert outsider["message"] == unknown["message"]
|
||||
|
||||
|
||||
@pytest.mark.spec("messages", "Вложение failed")
|
||||
def test_message_with_failed_attachment(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
accepted = api.upload(
|
||||
alice,
|
||||
chat["id"],
|
||||
images.jpeg_precision_12(),
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
failed = api.wait_attachment(alice, accepted["id"], status="failed")
|
||||
assert failed["error_code"] == "invalid_image"
|
||||
assert failed["variants"] == []
|
||||
key = "failed-attachment-key"
|
||||
assert_error(
|
||||
api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
json={"text": "x", "attachment_ids": [failed["id"]]},
|
||||
key=key,
|
||||
),
|
||||
409,
|
||||
)
|
||||
assert_error(
|
||||
api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
json={
|
||||
"text": "x",
|
||||
"attachment_ids": [
|
||||
failed["id"],
|
||||
"00000000-0000-4000-8000-000000000000",
|
||||
],
|
||||
},
|
||||
key=key,
|
||||
),
|
||||
404,
|
||||
)
|
||||
assert api.all_messages(alice, chat["id"]) == []
|
||||
# откат освободил ключ: то же значение годится для другого тела
|
||||
sent = api.send_message(alice, chat["id"], "без вложения", key=key)
|
||||
assert sent["attachment_ids"] == []
|
||||
|
||||
|
||||
@pytest.mark.spec("data-storage", "Принятое вложение видно сразу")
|
||||
def test_accepted_attachment_visible_on_other_replica(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
bob: Actor,
|
||||
chat: dict[str, Any],
|
||||
replicas: int,
|
||||
) -> None:
|
||||
upload = api.post_attachment(alice, chat["id"], images.sample_png())
|
||||
assert upload.status_code == 202, upload.text
|
||||
accepted = upload.json()
|
||||
uploaded_via = assert_instance_id(upload)
|
||||
seen = {uploaded_via}
|
||||
for _ in range(REPLICA_ATTEMPTS):
|
||||
resp = api.attachment_meta(bob, accepted["id"])
|
||||
meta = assert_ok(resp, 200, "Attachment")
|
||||
assert meta["id"] == accepted["id"]
|
||||
seen.add(assert_instance_id(resp))
|
||||
if len(seen) > 1:
|
||||
break
|
||||
assert_replicas(seen, replicas)
|
||||
@@ -21,6 +21,7 @@ import images
|
||||
from api_client import API, Actor, Api
|
||||
from contract import (
|
||||
BEARER_CHALLENGE,
|
||||
assert_accepted,
|
||||
assert_content,
|
||||
assert_error,
|
||||
assert_errors,
|
||||
@@ -29,8 +30,20 @@ from contract import (
|
||||
assert_ok,
|
||||
assert_replicas,
|
||||
assert_unauthorized,
|
||||
assert_variant_content,
|
||||
)
|
||||
|
||||
# поля оригинала: не меняются после ответа на загрузку
|
||||
ORIGINAL_FIELDS = (
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"created_at",
|
||||
)
|
||||
# больше лимита в 3 раза: 30 MiB
|
||||
BIG_BYTES = 30 * 1024 * 1024
|
||||
# сколько скачиваний ждать ответа другой реплики (round-robin LB)
|
||||
@@ -56,7 +69,7 @@ def big_body() -> bytes:
|
||||
def test_upload_png(api: Api, alice: Actor, chat: dict[str, Any]) -> None:
|
||||
data = images.sample_png()
|
||||
attachment = api.upload(alice, chat["id"], data, filename="sample.png")
|
||||
assert attachment["status"] == "ready"
|
||||
assert attachment["status"] == "queued"
|
||||
assert attachment["variants"] == []
|
||||
assert attachment["error_code"] is None
|
||||
assert attachment["content_type"] == "image/png"
|
||||
@@ -167,7 +180,7 @@ def test_exactly_max_pixels(
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.png(8000, 5000, color=0, depth=1)
|
||||
api.upload(alice, chat["id"], data)
|
||||
api.upload_ready(alice, chat["id"], data)
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Данные длиннее размеров")
|
||||
@@ -247,7 +260,7 @@ def test_unsuitable_content_type(
|
||||
data,
|
||||
content_type="IMAGE/PNG; charset=binary",
|
||||
)
|
||||
assert assert_ok(resp, 201, "Attachment")["content_type"] == "image/png"
|
||||
assert assert_accepted(resp)["content_type"] == "image/png"
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Обрезанный файл")
|
||||
@@ -329,7 +342,7 @@ def test_tail_after_end(
|
||||
("image/png", images.with_tail(images.sample_png())),
|
||||
("image/jpeg", images.with_tail(images.jpeg())),
|
||||
):
|
||||
attachment = api.upload(
|
||||
attachment = api.upload_ready(
|
||||
alice,
|
||||
chat["id"],
|
||||
data,
|
||||
@@ -385,7 +398,7 @@ def test_filename_not_utf8(
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
"""Процент-коды `filename` идут в строке запроса как есть: httpx их
|
||||
не перекодирует. Без строгого разбора `a%FFb.png` давал 201 с U+FFFD
|
||||
не перекодирует. Без строгого разбора `a%FFb.png` давал успех с U+FFFD
|
||||
в имени вместо байта."""
|
||||
data = images.sample_png()
|
||||
path = f"{API}/chats/{chat['id']}/attachments"
|
||||
@@ -408,11 +421,7 @@ def test_filename_not_utf8(
|
||||
400,
|
||||
)
|
||||
# верный UTF-8 в процент-кодах — то же имя, что прислано
|
||||
attachment = assert_ok(
|
||||
upload("filename=%C3%A9t%C3%A9.png"),
|
||||
201,
|
||||
"Attachment",
|
||||
)
|
||||
attachment = assert_accepted(upload("filename=%C3%A9t%C3%A9.png"))
|
||||
assert attachment["filename"] == "été.png"
|
||||
|
||||
|
||||
@@ -511,7 +520,7 @@ def test_other_member_reads(
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
attachment = api.upload(alice, chat["id"], data)
|
||||
attachment = api.upload_ready(alice, chat["id"], data)
|
||||
assert_ok(api.attachment_meta(bob, attachment["id"]), 200, "Attachment")
|
||||
assert_content(
|
||||
api.attachment_content(bob, attachment["id"]),
|
||||
@@ -582,7 +591,13 @@ def test_meta_equals_upload(
|
||||
200,
|
||||
"Attachment",
|
||||
)
|
||||
assert meta == attachment
|
||||
for field in ORIGINAL_FIELDS:
|
||||
assert meta[field] == attachment[field], field
|
||||
ready = api.wait_attachment(bob, attachment["id"])
|
||||
for field in ORIGINAL_FIELDS:
|
||||
assert ready[field] == attachment[field], field
|
||||
assert ready["error_code"] is None
|
||||
assert ready["variants"], "ready attachment has no variants"
|
||||
|
||||
|
||||
@pytest.mark.spec("attachments", "Побайтный оригинал")
|
||||
@@ -596,7 +611,7 @@ def test_original_bytes(
|
||||
("image/png", images.sample_png()),
|
||||
("image/jpeg", images.jpeg(size=(320, 200))),
|
||||
):
|
||||
attachment = api.upload(
|
||||
attachment = api.upload_ready(
|
||||
alice,
|
||||
chat["id"],
|
||||
data,
|
||||
@@ -615,7 +630,7 @@ def test_variant_original(
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
attachment = api.upload(alice, chat["id"], data)
|
||||
attachment = api.upload_ready(alice, chat["id"], data)
|
||||
assert_content(
|
||||
api.attachment_content(alice, attachment["id"], variant="original"),
|
||||
data,
|
||||
@@ -628,7 +643,7 @@ def test_variant_original(
|
||||
attachment["id"],
|
||||
variant=variant,
|
||||
)
|
||||
for variant in ("thumbnail", "")
|
||||
for variant in ("big", "")
|
||||
},
|
||||
400,
|
||||
)
|
||||
@@ -643,12 +658,19 @@ def test_no_storage_traces(
|
||||
data = images.sample_png()
|
||||
upload = api.post_attachment(alice, chat["id"], data)
|
||||
# assert_ok сверяет тело со схемой контракта: лишних полей нет
|
||||
attachment = assert_ok(upload, 201, "Attachment")
|
||||
attachment = assert_accepted(upload)
|
||||
ready = api.wait_attachment(alice, attachment["id"])
|
||||
meta = api.attachment_meta(alice, attachment["id"])
|
||||
assert_ok(meta, 200, "Attachment")
|
||||
content = api.attachment_content(alice, attachment["id"])
|
||||
assert_content(content, data, "image/png")
|
||||
for resp in (upload, meta, content):
|
||||
thumbnail = api.attachment_content(
|
||||
alice,
|
||||
attachment["id"],
|
||||
variant="thumbnail",
|
||||
)
|
||||
assert_variant_content(thumbnail, ready["variants"][0])
|
||||
for resp in (upload, meta, content, thumbnail):
|
||||
assert_no_storage_traces(resp)
|
||||
|
||||
|
||||
@@ -660,8 +682,8 @@ def test_repeated_upload(
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
first = api.upload(alice, chat["id"], data)
|
||||
second = api.upload(alice, chat["id"], data)
|
||||
first = api.upload_ready(alice, chat["id"], data)
|
||||
second = api.upload_ready(alice, chat["id"], data)
|
||||
assert first["id"] != second["id"]
|
||||
assert first["sha256"] == second["sha256"]
|
||||
for attachment in (first, second):
|
||||
@@ -711,6 +733,7 @@ def test_concurrent_uploads(api: Api, base_url: str) -> None:
|
||||
overlapping = sum(started < spans[0][1] for started, _ in spans)
|
||||
assert overlapping >= 2, f"uploads did not overlap: {spans}"
|
||||
for number, attachment in enumerate(attachments):
|
||||
api.wait_attachment(actors[0], attachment["id"])
|
||||
assert_content(
|
||||
api.attachment_content(actors[0], attachment["id"]),
|
||||
bodies[number],
|
||||
@@ -728,8 +751,9 @@ def test_download_through_other_replica(
|
||||
) -> None:
|
||||
data = images.sample_png()
|
||||
upload = api.post_attachment(alice, chat["id"], data)
|
||||
attachment = assert_ok(upload, 201, "Attachment")
|
||||
attachment = assert_accepted(upload)
|
||||
uploaded_via = assert_instance_id(upload)
|
||||
api.wait_attachment(alice, attachment["id"])
|
||||
seen = {uploaded_via}
|
||||
for _ in range(REPLICA_ATTEMPTS):
|
||||
resp = api.attachment_content(bob, attachment["id"])
|
||||
|
||||
+1683
-111
File diff suppressed because it is too large
Load Diff
@@ -36,7 +36,8 @@ def test_member_sends(
|
||||
|
||||
|
||||
def upload(api: Api, actor: Actor, chat_id: str) -> str:
|
||||
"""Готовое вложение чата; id."""
|
||||
"""Принятое вложение чата; id. Сообщение можно отправить и с вложением в
|
||||
обработке: `ready` не ждём."""
|
||||
return api.upload(actor, chat_id, images.sample_png())["id"]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user