forked from mtusi2026/mtusi2026lab5
ЛР 5: реализация мессенджера и сценарии проверки
This commit is contained in:
+2
-14
@@ -1,20 +1,8 @@
|
|||||||
.git
|
.git
|
||||||
.github
|
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
|
||||||
secrets
|
secrets
|
||||||
certs
|
certs
|
||||||
volumes
|
|
||||||
data
|
|
||||||
backups
|
|
||||||
*.key
|
|
||||||
*.pem
|
|
||||||
*.p12
|
|
||||||
*.pfx
|
|
||||||
*.jks
|
|
||||||
.venv
|
|
||||||
__pycache__
|
|
||||||
node_modules
|
|
||||||
evidence
|
evidence
|
||||||
.DS_Store
|
**/__pycache__
|
||||||
|
.venv
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM python:3.12.12-slim-bookworm
|
||||||
|
WORKDIR /app
|
||||||
|
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=/app/src
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY src ./src
|
||||||
|
USER 10001:10001
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["python", "-m", "app"]
|
||||||
@@ -1,37 +1,40 @@
|
|||||||
# Отчёт — лабораторная 5
|
# Отчёт — лабораторная 5
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор и группа — Шемрук Марк, БВТ2304.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка — 5. Трек 2. Идемпотентность pipeline.
|
||||||
- Commit/PR: TODO после публикации
|
- Ветка решения — `solution/bvt2304-shemruk`. Ссылка на PR появится после отправки.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Источники — контракт курса, собственная ЛР1, официальные руководства используемых компонентов. Codex помог с реализацией, проверками и отчётом. Присланные чужие реализации использовались для сверки тем и сценариев курса.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
На Windows команды выполняются в PowerShell из корня репозитория. Нужны Python 3.11+, Docker Desktop с Linux Engine и Compose. Образ API использует Python 3.12.12. Подготовьте свободные локальные порты. Рабочие файлы .env и secrets создаёт bootstrap. Точные версии зависимостей находятся в `requirements.txt` и `compose.yaml`.
|
||||||
|
|
||||||
## Архитектура и решения
|
```powershell
|
||||||
|
python -X utf8 scripts/check_contract.py
|
||||||
|
python -X utf8 scripts/bootstrap.py
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d --build --wait
|
||||||
|
```
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
На Linux вместо `python -X utf8` можно использовать `python3 -X utf8`. Безопасная остановка — `docker compose down`. Она сохраняет named volumes. Преднамеренный сброс отдельного учебного окружения — `docker compose down -v`.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Архитектура и границы гарантий
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
POST сохраняет проверенный оригинал в приватный `staging/<UUID>` и одним COMMIT записывает метаданные и задание outbox. Только после этого клиент получает `202 queued`. Relay публикует ID и версию в отдельный Redis Streams. Брокер пишет AOF, а relay повторяет публикацию старых незавершённых заданий. Worker отбирает одно задание, выделяет аренду на 45 с, запускает Pillow в дочернем процессе с лимитом 15 с и сохраняет оригинал и варианты под ключами, зависящими от версии.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
Готовое состояние публикуется транзакцией после записи всех объектов. XACK следует после DB-эффекта. Если worker остановился до ACK, следующий получатель видит состояние и проверяет версию/попытку. Просроченная попытка не меняет активную версию. Повторы ограничены пятью попытками с задержкой и jitter. Постоянная ошибка попадает в failed. Объекты staging пока сохраняются для повторной обработки и требуют операторской очистки. Варианты включают JPEG thumbnail до 256×256, центральный crop 128×128 и WebP до 1280×1280. EXIF orientation применяется, прозрачность компонуется с белым фоном, метаданные вариантов очищаются.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Проверки и результаты
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
```powershell
|
||||||
|
python -X utf8 tests/smoke.py
|
||||||
|
python -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd
|
||||||
|
python -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.cmd
|
||||||
|
docker compose start api
|
||||||
|
```
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
Статическая проверка контракта, синтаксис и конфигурация Compose прошли. Публичный HTTP smoke прошёл на локальном PostgreSQL 18.0 с тестовой заменой Redis. S3 является тестовой заменой Moto. Этот прогон проверяет API. Фактические отказы контейнеров и Compose-эксперименты требуют отдельного запуска.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
`python -X utf8 student-tests/worker_pause.py` останавливает worker, загружает PNG, привязывает queued-вложение к сообщению, перезапускает API и Redis broker, проверяет queued и запускает worker. Готовый thumbnail должен быть 256×160. SHA-256 и побайтовое сравнение проверяют оригинал.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Трек идемпотентности описан в `student-tests/pipeline_faults.py`. На пустом учебном стенде остановить relay и worker, загрузить один файл, взять attachment ID из ответа. Передать скрипт на stdin команды `docker compose run --rm --no-deps -T --entrypoint python worker - <ATTACHMENT_ID>`. Он вводит истечение lease до эффекта, прерывание после записи S3, повтор после COMMIT и старую доставку после появления новой версии. `python -m replay <id>` внутри worker с операционным доступом повторяет только failed. Параметр `--new-version` создаёт другую версию для ready. Аудит хранится в image_replays.
|
||||||
|
|||||||
+163
@@ -0,0 +1,163 @@
|
|||||||
|
x-app: &app
|
||||||
|
build: .
|
||||||
|
image: shemruk-messenger-lab5:local
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 320m
|
||||||
|
init: true
|
||||||
|
environment:
|
||||||
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
|
CACHE_URL_FILE: /run/secrets/cache_url
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
S3_ACCESS_KEY_FILE: /run/secrets/s3_access
|
||||||
|
S3_SECRET_KEY_FILE: /run/secrets/s3_secret
|
||||||
|
secrets: [database_url, cache_url, cursor_key, s3_access, s3_secret]
|
||||||
|
|
||||||
|
x-job-env: &job-env
|
||||||
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
|
S3_ACCESS_KEY_FILE: /run/secrets/s3_access
|
||||||
|
S3_SECRET_KEY_FILE: /run/secrets/s3_secret
|
||||||
|
BROKER_URL_FILE: /run/secrets/broker_url
|
||||||
|
JOB_MAX_ATTEMPTS: 5
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:17.6-bookworm
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 512m
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||||
|
secrets: [db_password]
|
||||||
|
volumes: [postgres_data:/var/lib/postgresql/data]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, pg_isready -U messenger -d messenger -h 127.0.0.1]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 20
|
||||||
|
cache:
|
||||||
|
image: redis:7.4.6-bookworm
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 128m
|
||||||
|
command: [redis-server, /run/secrets/redis_config]
|
||||||
|
secrets: [redis_config, cache_password]
|
||||||
|
volumes: [redis_data:/data]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, 'REDISCLI_AUTH=$$(cat /run/secrets/cache_password) redis-cli ping | grep -qx PONG']
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 20
|
||||||
|
migrate:
|
||||||
|
<<: *app
|
||||||
|
command: [python, -m, db]
|
||||||
|
depends_on:
|
||||||
|
db: {condition: service_healthy}
|
||||||
|
broker:
|
||||||
|
image: redis:7.4.6-bookworm
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 160m
|
||||||
|
command: [redis-server, /run/secrets/broker_config]
|
||||||
|
secrets: [broker_config, broker_password]
|
||||||
|
volumes: [broker_data:/data]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, 'REDISCLI_AUTH=$$(cat /run/secrets/broker_password) redis-cli ping | grep -qx PONG']
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 20
|
||||||
|
relay:
|
||||||
|
<<: *app
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 120m
|
||||||
|
command: [python, -m, pipeline, relay]
|
||||||
|
environment: *job-env
|
||||||
|
secrets: [database_url, broker_url]
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
broker: {condition: service_healthy}
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
worker:
|
||||||
|
<<: *app
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 704m
|
||||||
|
command: [python, -m, pipeline, worker]
|
||||||
|
environment: *job-env
|
||||||
|
secrets: [database_url, broker_url, s3_access, s3_secret]
|
||||||
|
stop_grace_period: 25s
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
relay: {condition: service_started}
|
||||||
|
s3-init: {condition: service_completed_successfully}
|
||||||
|
s3-perms:
|
||||||
|
image: busybox:1.37.0
|
||||||
|
command: ["chown", "10001:10001", "/data"]
|
||||||
|
volumes: [object_data:/data]
|
||||||
|
s3:
|
||||||
|
image: rustfs/rustfs:1.0.7
|
||||||
|
cpus: 0.75
|
||||||
|
mem_limit: 512m
|
||||||
|
env_file: ./secrets/s3_root.env
|
||||||
|
environment:
|
||||||
|
RUSTFS_VOLUMES: /data
|
||||||
|
RUSTFS_ADDRESS: :9000
|
||||||
|
RUSTFS_CONSOLE_ENABLE: "false"
|
||||||
|
volumes: [object_data:/data]
|
||||||
|
depends_on:
|
||||||
|
s3-perms: {condition: service_completed_successfully}
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, curl, -fsS, "http://127.0.0.1:9000/health/ready"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 30
|
||||||
|
s3-init:
|
||||||
|
image: rustfs/rc:v0.1.38
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 96m
|
||||||
|
env_file: ./secrets/s3_root.env
|
||||||
|
entrypoint: ["/bin/sh", "/bootstrap/s3-init.sh"]
|
||||||
|
volumes: ["./infra/s3:/bootstrap:ro"]
|
||||||
|
secrets: [s3_access, s3_secret]
|
||||||
|
depends_on:
|
||||||
|
s3: {condition: service_healthy}
|
||||||
|
api:
|
||||||
|
<<: *app
|
||||||
|
scale: ${API_REPLICAS:-2}
|
||||||
|
cpus: ${API_CPUS:-0.75}
|
||||||
|
mem_limit: ${API_MEMORY:-448m}
|
||||||
|
stop_grace_period: 12s
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
cache: {condition: service_healthy}
|
||||||
|
s3-init: {condition: service_completed_successfully}
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3)"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 4s
|
||||||
|
retries: 20
|
||||||
|
lb:
|
||||||
|
image: haproxy:3.2.28-trixie
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 96m
|
||||||
|
ports: ["127.0.0.1:${HTTP_PORT:-8080}:8080"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
depends_on: [api]
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
|
object_data:
|
||||||
|
broker_data:
|
||||||
|
|
||||||
|
secrets:
|
||||||
|
database_url: {file: ./secrets/database_url}
|
||||||
|
db_password: {file: ./secrets/db_password}
|
||||||
|
cache_url: {file: ./secrets/cache_url}
|
||||||
|
cache_password: {file: ./secrets/cache_password}
|
||||||
|
cursor_key: {file: ./secrets/cursor_key}
|
||||||
|
redis_config: {file: ./secrets/redis.conf}
|
||||||
|
s3_access: {file: ./secrets/s3_access}
|
||||||
|
s3_secret: {file: ./secrets/s3_secret}
|
||||||
|
broker_config: {file: ./secrets/broker.conf}
|
||||||
|
broker_password: {file: ./secrets/broker_password}
|
||||||
|
broker_url: {file: ./secrets/broker_url}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
PASS: public lab5 API smoke on native PostgreSQL 18.0, fake Redis Streams and Moto S3, while separate threads ran relay and worker.
|
||||||
|
The check included queued metadata, original bytes, thumbnail checksum and 256x160 dimensions.
|
||||||
|
Docker Compose with real Redis/S3, worker interruption and outbox test remain pending.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
global
|
||||||
|
maxconn 128
|
||||||
|
log stdout format raw local0
|
||||||
|
|
||||||
|
defaults
|
||||||
|
mode http
|
||||||
|
log global
|
||||||
|
timeout connect 1s
|
||||||
|
timeout client 15s
|
||||||
|
timeout server 15s
|
||||||
|
timeout http-request 8s
|
||||||
|
timeout queue 2s
|
||||||
|
timeout check 1s
|
||||||
|
retries 0
|
||||||
|
|
||||||
|
resolvers docker
|
||||||
|
nameserver internal 127.0.0.11:53
|
||||||
|
resolve_retries 2
|
||||||
|
timeout resolve 500ms
|
||||||
|
timeout retry 500ms
|
||||||
|
hold valid 2s
|
||||||
|
|
||||||
|
frontend public
|
||||||
|
bind :8080
|
||||||
|
default_backend messenger
|
||||||
|
|
||||||
|
backend messenger
|
||||||
|
balance roundrobin
|
||||||
|
option httpchk GET /health/ready
|
||||||
|
http-check expect status 200
|
||||||
|
server-template api 8 api:8080 check inter 500ms fall 2 rise 1 resolvers docker resolve-prefer ipv4 init-addr none
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [
|
||||||
|
{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::attachments"]},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
|
||||||
|
"Resource": ["arn:aws:s3:::attachments/original/*", "arn:aws:s3:::attachments/staging/*",
|
||||||
|
"arn:aws:s3:::attachments/results/*"]}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
export HOME=/tmp
|
||||||
|
rc alias set lab http://s3:9000 "$RUSTFS_ACCESS_KEY" "$RUSTFS_SECRET_KEY"
|
||||||
|
rc mb --ignore-existing lab/attachments
|
||||||
|
access=$(cat /run/secrets/s3_access)
|
||||||
|
secret=$(cat /run/secrets/s3_secret)
|
||||||
|
rc admin user add lab/ "$access" "$secret"
|
||||||
|
rc admin policy create lab/ messenger-objects /bootstrap/api-policy.json
|
||||||
|
rc admin policy attach lab/ messenger-objects --user "$access"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
psycopg[binary]==3.2.13
|
||||||
|
psycopg-pool==3.2.8
|
||||||
|
redis==6.4.0
|
||||||
|
boto3==1.40.67
|
||||||
|
Pillow==12.2.0
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Create local credentials once. Run from the repository on Windows or Linux."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from secrets import token_hex
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
LOCAL = ROOT / "secrets"
|
||||||
|
|
||||||
|
|
||||||
|
def keep(path, value):
|
||||||
|
try:
|
||||||
|
with path.open("x", encoding="utf-8", newline="\n") as stream:
|
||||||
|
stream.write(value + "\n")
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
return path.read_text(encoding="utf-8").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
LOCAL.mkdir(mode=0o700, exist_ok=True)
|
||||||
|
db = keep(LOCAL / "db_password", token_hex(24))
|
||||||
|
cache = keep(LOCAL / "cache_password", token_hex(24))
|
||||||
|
broker = keep(LOCAL / "broker_password", token_hex(24))
|
||||||
|
keep(LOCAL / "database_url", f"postgresql://messenger:{db}@db:5432/messenger")
|
||||||
|
keep(LOCAL / "cache_url", f"redis://:{cache}@cache:6379/0")
|
||||||
|
keep(LOCAL / "broker_url", f"redis://:{broker}@broker:6379/0")
|
||||||
|
keep(LOCAL / "cursor_key", token_hex(32))
|
||||||
|
keep(LOCAL / "s3_root.env",
|
||||||
|
f"RUSTFS_ACCESS_KEY=labroot{token_hex(8)}\nRUSTFS_SECRET_KEY={token_hex(24)}")
|
||||||
|
keep(LOCAL / "s3_access", "messenger" + token_hex(6))
|
||||||
|
keep(LOCAL / "s3_secret", token_hex(24))
|
||||||
|
config = "\n".join((
|
||||||
|
"bind 0.0.0.0", "protected-mode yes", "dir /data",
|
||||||
|
"appendonly yes", "appendfsync always", "maxmemory 64mb",
|
||||||
|
"maxmemory-policy noeviction",
|
||||||
|
))
|
||||||
|
keep(LOCAL / "redis.conf", f"{config}\nrequirepass {cache}")
|
||||||
|
keep(LOCAL / "broker.conf", f"{config}\nrequirepass {broker}")
|
||||||
|
keep(ROOT / ".env", "HTTP_PORT=8080\nSESSION_TTL_SECONDS=3600")
|
||||||
|
print("Локальная конфигурация готова.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Map a live process alias to a Compose container, then control that container."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
PROBE = """
|
||||||
|
import urllib.request
|
||||||
|
response = urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=3)
|
||||||
|
print(response.headers["X-Instance-Id"])
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args, capture=True):
|
||||||
|
return subprocess.run(
|
||||||
|
("docker", *args), cwd=ROOT, capture_output=capture, text=True,
|
||||||
|
check=True, timeout=60,
|
||||||
|
).stdout
|
||||||
|
|
||||||
|
|
||||||
|
def replicas():
|
||||||
|
result = {}
|
||||||
|
for container in docker("compose", "ps", "-q", "api").split():
|
||||||
|
try:
|
||||||
|
alias = docker("exec", container, "python", "-c", PROBE).strip()
|
||||||
|
except subprocess.CalledProcessError:
|
||||||
|
continue
|
||||||
|
if alias and alias not in result:
|
||||||
|
result[alias] = container
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("operation", choices=("list", "stop"))
|
||||||
|
args = parser.parse_args()
|
||||||
|
mapping = replicas()
|
||||||
|
if args.operation == "list":
|
||||||
|
print(json.dumps(mapping, indent=2))
|
||||||
|
return
|
||||||
|
alias = os.environ.get("TARGET_INSTANCE_ID")
|
||||||
|
if not alias or alias not in mapping:
|
||||||
|
raise SystemExit("TARGET_INSTANCE_ID must match a running API process")
|
||||||
|
docker("stop", "--timeout", "10", mapping[alias], capture=False)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
docker compose ps lb api db cache s3 broker worker relay || exit /b 1
|
||||||
|
docker compose restart db cache s3 broker || exit /b 1
|
||||||
|
docker compose restart api lb relay worker || exit /b 1
|
||||||
|
docker compose ps lb api db cache s3 broker worker relay
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
docker compose ps lb api db cache s3 broker worker relay
|
||||||
|
docker compose restart db cache s3 broker
|
||||||
|
docker compose restart api lb relay worker
|
||||||
|
docker compose ps lb api db cache s3 broker worker relay
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
python scripts/replicas.py stop
|
||||||
Executable
+4
@@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
exec python3 scripts/replicas.py stop
|
||||||
+520
@@ -0,0 +1,520 @@
|
|||||||
|
"""HTTP entry point for the persistent messenger (based on lab 1)."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import datetime as dt
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import unicodedata
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg_pool import PoolTimeout
|
||||||
|
from redis.exceptions import RedisError
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
|
||||||
|
from attachments import BadImage, MAX_UPLOAD, Objects, PixelLimit, spool, verify_image
|
||||||
|
from auth import Sessions, USERNAME, parse_basic, parse_bearer, password_hash, valid_password, verify_password
|
||||||
|
from db import KeyConflict, MissingAttachment, Store, UnusableAttachment, setting
|
||||||
|
|
||||||
|
|
||||||
|
MAX_BODY = 64 * 1024
|
||||||
|
QUERY_LIMIT = re.compile(r"[0-9]{1,6}")
|
||||||
|
LENGTH = re.compile(r"[0-9]{1,12}")
|
||||||
|
IDEMPOTENCY_KEY = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||||
|
FIRST = (dt.datetime.min.replace(tzinfo=dt.timezone.utc), UUID(int=0))
|
||||||
|
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
def __init__(self, status, code, message, headers=None):
|
||||||
|
super().__init__(message)
|
||||||
|
self.status, self.code, self.message = status, code, message
|
||||||
|
self.headers = headers or {}
|
||||||
|
|
||||||
|
|
||||||
|
def bad(message="Некорректный запрос"):
|
||||||
|
return ApiError(400, "invalid_request", message)
|
||||||
|
|
||||||
|
|
||||||
|
def not_found():
|
||||||
|
return ApiError(404, "not_found", "Объект не найден")
|
||||||
|
|
||||||
|
|
||||||
|
def unauthorized(scheme):
|
||||||
|
challenge = f'{scheme} realm="messenger"'
|
||||||
|
if scheme == "Basic":
|
||||||
|
challenge += ', charset="UTF-8"'
|
||||||
|
return ApiError(401, "unauthorized", "Нужна аутентификация", {"WWW-Authenticate": challenge})
|
||||||
|
|
||||||
|
|
||||||
|
def clean_text(value, min_len, max_len, field):
|
||||||
|
if not isinstance(value, str) or not min_len <= len(value) <= max_len or not value.strip():
|
||||||
|
raise bad(f"Поле {field} имеет недопустимую длину или тип")
|
||||||
|
try:
|
||||||
|
value.encode("utf-8")
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
raise bad(f"Поле {field} содержит недопустимые символы")
|
||||||
|
if "\x00" in value:
|
||||||
|
raise bad(f"Поле {field} содержит NUL")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def parse_uuid(value):
|
||||||
|
if not isinstance(value, str):
|
||||||
|
raise bad("Некорректный UUID")
|
||||||
|
try:
|
||||||
|
return UUID(value)
|
||||||
|
except ValueError:
|
||||||
|
raise bad("Некорректный UUID")
|
||||||
|
|
||||||
|
|
||||||
|
def only_fields(body, required, optional=()):
|
||||||
|
if not isinstance(body, dict) or set(required) - body.keys() or body.keys() - set(required + optional):
|
||||||
|
raise bad("Неверный набор полей")
|
||||||
|
|
||||||
|
|
||||||
|
def json_value(value):
|
||||||
|
if isinstance(value, dt.datetime):
|
||||||
|
return value.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
if isinstance(value, UUID):
|
||||||
|
return str(value)
|
||||||
|
raise TypeError("Unsupported JSON value")
|
||||||
|
|
||||||
|
|
||||||
|
def encode_cursor(scope, row, key):
|
||||||
|
raw = json.dumps([scope, row["created_at"], row["id"]], default=json_value).encode()
|
||||||
|
signature = hmac.digest(key, raw, "sha256")
|
||||||
|
return base64.urlsafe_b64encode(raw + signature).decode().rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def decode_cursor(cursor, scope, key):
|
||||||
|
try:
|
||||||
|
if len(cursor) > 512 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
|
||||||
|
raise ValueError
|
||||||
|
envelope = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
||||||
|
raw, signature = envelope[:-32], envelope[-32:]
|
||||||
|
if not hmac.compare_digest(hmac.digest(key, raw, "sha256"), signature):
|
||||||
|
raise ValueError
|
||||||
|
actual_scope, timestamp, item_id = json.loads(raw)
|
||||||
|
if actual_scope != scope:
|
||||||
|
raise ValueError
|
||||||
|
return dt.datetime.fromisoformat(timestamp.replace("Z", "+00:00")), UUID(item_id)
|
||||||
|
except (ValueError, TypeError, AttributeError):
|
||||||
|
raise bad("Некорректный cursor")
|
||||||
|
|
||||||
|
|
||||||
|
def page(ctx, scope, read):
|
||||||
|
limit = ctx.param("limit", "50")
|
||||||
|
cursor = ctx.param("cursor")
|
||||||
|
if not QUERY_LIMIT.fullmatch(limit) or not 1 <= int(limit) <= 100:
|
||||||
|
raise bad("limit должен быть целым числом от 1 до 100")
|
||||||
|
count = int(limit)
|
||||||
|
key = ctx.server.cursor_key
|
||||||
|
rows = read(decode_cursor(cursor, scope, key) if cursor is not None else FIRST, count + 1)
|
||||||
|
return {"items": rows[:count],
|
||||||
|
"next_cursor": encode_cursor(scope, rows[count - 1], key) if len(rows) > count else None}
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(ctx):
|
||||||
|
body = ctx.json_body()
|
||||||
|
only_fields(body, ("username", "display_name", "password"))
|
||||||
|
username = body["username"]
|
||||||
|
if not isinstance(username, str) or not USERNAME.fullmatch(username):
|
||||||
|
raise bad("Некорректный username")
|
||||||
|
name = clean_text(body["display_name"], 1, 100, "display_name")
|
||||||
|
if not valid_password(body["password"]):
|
||||||
|
raise bad("Некорректный password")
|
||||||
|
try:
|
||||||
|
return 201, ctx.store.register(username, name, password_hash(body["password"]))
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
raise ApiError(409, "conflict", "Username уже занят")
|
||||||
|
|
||||||
|
|
||||||
|
def login(ctx):
|
||||||
|
if ctx.content_length():
|
||||||
|
raise bad("Вход принимает только Basic Authorization")
|
||||||
|
credentials = parse_basic(ctx.header("Authorization"))
|
||||||
|
if not credentials:
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
username, password = credentials
|
||||||
|
user, stored = ctx.store.credential(username)
|
||||||
|
if not verify_password(password, stored):
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
token, expires = ctx.server.sessions.issue(user["id"])
|
||||||
|
return 201, {"token": token, "token_type": "Bearer", "expires_at": expires, "user": user}
|
||||||
|
|
||||||
|
|
||||||
|
def logout(ctx):
|
||||||
|
if not ctx.server.sessions.revoke(ctx.token):
|
||||||
|
raise unauthorized("Bearer")
|
||||||
|
return 204, None
|
||||||
|
|
||||||
|
|
||||||
|
def get_me(ctx):
|
||||||
|
return 200, ctx.user
|
||||||
|
|
||||||
|
|
||||||
|
def create_chat(ctx):
|
||||||
|
body = ctx.json_body()
|
||||||
|
only_fields(body, ("title", "member_ids"))
|
||||||
|
title = clean_text(body["title"], 1, 100, "title")
|
||||||
|
ids = body["member_ids"]
|
||||||
|
if not isinstance(ids, list) or not 1 <= len(ids) <= 100:
|
||||||
|
raise bad("member_ids: от 1 до 100 элементов")
|
||||||
|
members = [parse_uuid(value) for value in ids]
|
||||||
|
if len(set(members)) != len(members) or ctx.user["id"] not in members:
|
||||||
|
raise bad("member_ids: дубликаты или нет вызывающего")
|
||||||
|
try:
|
||||||
|
return 201, ctx.store.create_chat(title, members)
|
||||||
|
except psycopg.errors.ForeignKeyViolation:
|
||||||
|
raise bad("member_ids: неизвестный пользователь")
|
||||||
|
|
||||||
|
|
||||||
|
def list_chats(ctx):
|
||||||
|
user_id = ctx.user["id"]
|
||||||
|
return 200, page(ctx, f"chats:{user_id}", lambda cursor, n: ctx.store.chats(user_id, cursor, n))
|
||||||
|
|
||||||
|
|
||||||
|
def visible_chat(ctx, chat_id):
|
||||||
|
chat = ctx.store.chat(ctx.user["id"], parse_uuid(chat_id))
|
||||||
|
if chat is None:
|
||||||
|
raise not_found()
|
||||||
|
return chat
|
||||||
|
|
||||||
|
|
||||||
|
def get_chat(ctx, chat_id):
|
||||||
|
return 200, visible_chat(ctx, chat_id)
|
||||||
|
|
||||||
|
|
||||||
|
def create_message(ctx, chat_id):
|
||||||
|
chat = visible_chat(ctx, chat_id)
|
||||||
|
body = ctx.json_body()
|
||||||
|
only_fields(body, ("text",), ("attachment_ids",))
|
||||||
|
items = body.get("attachment_ids", [])
|
||||||
|
if not isinstance(items, list) or len(items) > 10:
|
||||||
|
raise bad("attachment_ids: от 0 до 10 элементов")
|
||||||
|
attachment_ids = [parse_uuid(value) for value in items]
|
||||||
|
if len(set(attachment_ids)) != len(attachment_ids):
|
||||||
|
raise bad("attachment_ids: дубликаты")
|
||||||
|
raw_text = body["text"]
|
||||||
|
if raw_text == "" and attachment_ids:
|
||||||
|
text = ""
|
||||||
|
else:
|
||||||
|
text = clean_text(raw_text, 1, 4000, "text")
|
||||||
|
key = ctx.header("Idempotency-Key")
|
||||||
|
if not IDEMPOTENCY_KEY.fullmatch(key):
|
||||||
|
raise bad("Некорректный или отсутствующий Idempotency-Key")
|
||||||
|
try:
|
||||||
|
return 201, ctx.store.message(ctx.user["id"], chat["id"], text, key, attachment_ids)
|
||||||
|
except KeyConflict:
|
||||||
|
raise ApiError(409, "conflict", "Ключ уже использован для другого сообщения")
|
||||||
|
except MissingAttachment:
|
||||||
|
raise not_found()
|
||||||
|
except UnusableAttachment:
|
||||||
|
raise ApiError(409, "conflict", "Вложение недоступно")
|
||||||
|
|
||||||
|
|
||||||
|
def list_messages(ctx, chat_id):
|
||||||
|
cid = visible_chat(ctx, chat_id)["id"]
|
||||||
|
return 200, page(ctx, f"messages:{cid}", lambda cursor, n: ctx.store.messages(cid, cursor, n))
|
||||||
|
|
||||||
|
|
||||||
|
def upload_attachment(ctx, chat_id):
|
||||||
|
chat = visible_chat(ctx, chat_id)
|
||||||
|
filename = clean_text(ctx.param("filename"), 1, 255, "filename")
|
||||||
|
if any(char in "/\\" or unicodedata.category(char) == "Cc" for char in filename):
|
||||||
|
raise bad("Некорректное имя файла")
|
||||||
|
mime = ctx.header("Content-Type").split(";")[0].strip().lower()
|
||||||
|
if mime not in ("image/jpeg", "image/png"):
|
||||||
|
raise ApiError(415, "unsupported_media_type", "Поддерживаются PNG и JPEG")
|
||||||
|
with ctx.server.image_slot, spool() as file:
|
||||||
|
length = ctx.stream_body(file)
|
||||||
|
try:
|
||||||
|
verify_image(file, mime)
|
||||||
|
except BadImage:
|
||||||
|
raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение")
|
||||||
|
except PixelLimit:
|
||||||
|
raise ApiError(413, "payload_too_large", "Изображение превышает лимит пикселей")
|
||||||
|
objects = ctx.server.objects
|
||||||
|
row = ctx.store.save_attachment(
|
||||||
|
chat["id"], ctx.user["id"], filename, mime, length,
|
||||||
|
lambda item: objects.put(objects.key(item, "staging"), file, mime, length),
|
||||||
|
)
|
||||||
|
return 202, public_attachment(row)
|
||||||
|
|
||||||
|
|
||||||
|
def public_attachment(row):
|
||||||
|
return {key: value for key, value in row.items() if key != "pipeline_version"}
|
||||||
|
|
||||||
|
|
||||||
|
def get_metadata(ctx, attachment_id):
|
||||||
|
row = ctx.store.attachment(ctx.user["id"], parse_uuid(attachment_id))
|
||||||
|
if row is None:
|
||||||
|
raise not_found()
|
||||||
|
return 200, public_attachment(row)
|
||||||
|
|
||||||
|
|
||||||
|
def download_attachment(ctx, attachment_id):
|
||||||
|
row = ctx.store.attachment(ctx.user["id"], parse_uuid(attachment_id))
|
||||||
|
if row is None:
|
||||||
|
raise not_found()
|
||||||
|
if row["status"] != "ready":
|
||||||
|
raise ApiError(409, "conflict", "Вложение ещё недоступно")
|
||||||
|
variant = ctx.param("variant", "original")
|
||||||
|
variants = {item["name"]: item["content_type"] for item in row["variants"]}
|
||||||
|
if variant != "original" and variant not in variants:
|
||||||
|
raise not_found()
|
||||||
|
objects = ctx.server.objects
|
||||||
|
ctx.content_type = row["content_type"] if variant == "original" else variants[variant]
|
||||||
|
key = objects.result_key(row["id"], row["pipeline_version"], variant)
|
||||||
|
return 200, objects.get(key)
|
||||||
|
|
||||||
|
|
||||||
|
def live(ctx):
|
||||||
|
return 200, {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
def ready(ctx):
|
||||||
|
if ctx.server.stopping.is_set():
|
||||||
|
raise ApiError(503, "unavailable", "Сервер завершает работу")
|
||||||
|
ctx.store.ready()
|
||||||
|
ctx.server.sessions.redis.ping()
|
||||||
|
ctx.server.objects.ready()
|
||||||
|
return live(ctx)
|
||||||
|
|
||||||
|
|
||||||
|
ROUTES = [(method, re.compile(path), action, authenticated) for method, path, action, authenticated in (
|
||||||
|
("GET", r"/health/live", live, False),
|
||||||
|
("GET", r"/health/ready", ready, False),
|
||||||
|
("POST", r"/api/v1/users", create_user, False),
|
||||||
|
("POST", r"/api/v1/auth/sessions", login, False),
|
||||||
|
("DELETE", r"/api/v1/auth/sessions/current", logout, True),
|
||||||
|
("GET", r"/api/v1/users/me", get_me, True),
|
||||||
|
("POST", r"/api/v1/chats", create_chat, True),
|
||||||
|
("GET", r"/api/v1/chats", list_chats, True),
|
||||||
|
("GET", r"/api/v1/chats/([^/]+)", get_chat, True),
|
||||||
|
("POST", r"/api/v1/chats/([^/]+)/messages", create_message, True),
|
||||||
|
("GET", r"/api/v1/chats/([^/]+)/messages", list_messages, True),
|
||||||
|
("POST", r"/api/v1/chats/([^/]+)/attachments", upload_attachment, True),
|
||||||
|
("GET", r"/api/v1/attachments/([^/]+)", get_metadata, True),
|
||||||
|
("GET", r"/api/v1/attachments/([^/]+)/content", download_attachment, True),
|
||||||
|
)]
|
||||||
|
|
||||||
|
|
||||||
|
class Context:
|
||||||
|
def __init__(self, handler):
|
||||||
|
self.handler = handler
|
||||||
|
self.server = handler.server
|
||||||
|
self.store = self.server.store
|
||||||
|
self.user = self.token = None
|
||||||
|
self.body_read = False
|
||||||
|
self.route = "unmatched"
|
||||||
|
self.content_type = None
|
||||||
|
|
||||||
|
def header(self, name):
|
||||||
|
values = self.handler.headers.get_all(name, [])
|
||||||
|
return values[0] if len(values) == 1 else ""
|
||||||
|
|
||||||
|
def param(self, name, default=None):
|
||||||
|
values = self.query.get(name, [])
|
||||||
|
if len(values) > 1:
|
||||||
|
raise bad(f"Повторяющийся параметр {name}")
|
||||||
|
return values[0] if values else default
|
||||||
|
|
||||||
|
def content_length(self):
|
||||||
|
if self.handler.headers.get_all("Transfer-Encoding"):
|
||||||
|
raise bad("Нужен запрос с Content-Length")
|
||||||
|
if not self.handler.headers.get_all("Content-Length"):
|
||||||
|
return 0
|
||||||
|
value = self.header("Content-Length")
|
||||||
|
if not LENGTH.fullmatch(value):
|
||||||
|
raise bad("Некорректный Content-Length")
|
||||||
|
return int(value)
|
||||||
|
|
||||||
|
def read_body(self, limit):
|
||||||
|
length = self.content_length()
|
||||||
|
if length > limit:
|
||||||
|
raise ApiError(413, "payload_too_large", "Слишком большое тело запроса")
|
||||||
|
try:
|
||||||
|
raw = self.handler.rfile.read(length)
|
||||||
|
except TimeoutError:
|
||||||
|
raise bad("Таймаут чтения тела")
|
||||||
|
self.body_read = True
|
||||||
|
if len(raw) != length:
|
||||||
|
raise bad("Тело запроса получено не полностью")
|
||||||
|
return raw
|
||||||
|
|
||||||
|
def json_body(self):
|
||||||
|
raw = self.read_body(MAX_BODY)
|
||||||
|
if self.header("Content-Type").split(";")[0].strip().lower() != "application/json":
|
||||||
|
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
||||||
|
try:
|
||||||
|
return json.loads(raw.decode("utf-8"))
|
||||||
|
except (ValueError, RecursionError):
|
||||||
|
raise bad("Некорректный JSON")
|
||||||
|
|
||||||
|
def stream_body(self, file):
|
||||||
|
length = self.content_length()
|
||||||
|
if length > MAX_UPLOAD:
|
||||||
|
raise ApiError(413, "payload_too_large", "Слишком большой файл")
|
||||||
|
remaining = length
|
||||||
|
deadline = time.monotonic() + 10
|
||||||
|
while remaining:
|
||||||
|
timeout = deadline - time.monotonic()
|
||||||
|
if timeout <= 0:
|
||||||
|
raise bad("Таймаут загрузки")
|
||||||
|
self.handler.connection.settimeout(timeout)
|
||||||
|
try:
|
||||||
|
chunk = self.handler.rfile.read1(min(remaining, 64 * 1024))
|
||||||
|
except TimeoutError:
|
||||||
|
raise bad("Таймаут загрузки")
|
||||||
|
if not chunk:
|
||||||
|
raise bad("Тело запроса получено не полностью")
|
||||||
|
file.write(chunk)
|
||||||
|
remaining -= len(chunk)
|
||||||
|
self.body_read = True
|
||||||
|
file.seek(0)
|
||||||
|
return length
|
||||||
|
|
||||||
|
def authenticate(self):
|
||||||
|
self.token = parse_bearer(self.header("Authorization"))
|
||||||
|
if self.token:
|
||||||
|
user_id = self.server.sessions.get(self.token)
|
||||||
|
if user_id:
|
||||||
|
self.user = self.store.user(user_id)
|
||||||
|
if self.user:
|
||||||
|
return
|
||||||
|
raise unauthorized("Bearer")
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
protocol_version = "HTTP/1.1"
|
||||||
|
server_version = "messenger"
|
||||||
|
sys_version = ""
|
||||||
|
timeout = 8
|
||||||
|
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def dispatch(self, ctx):
|
||||||
|
try:
|
||||||
|
parts = urlsplit(self.path)
|
||||||
|
ctx.query = parse_qs(parts.query, keep_blank_values=True, max_num_fields=32)
|
||||||
|
except ValueError:
|
||||||
|
raise bad("Некорректный URL")
|
||||||
|
for method, pattern, action, authenticated in ROUTES:
|
||||||
|
if method == self.command and (match := pattern.fullmatch(parts.path)):
|
||||||
|
ctx.route = action.__name__
|
||||||
|
if self.server.stopping.is_set() and action != live:
|
||||||
|
raise ApiError(503, "unavailable", "Сервер завершает работу")
|
||||||
|
if authenticated:
|
||||||
|
ctx.authenticate()
|
||||||
|
return action(ctx, *match.groups())
|
||||||
|
raise not_found()
|
||||||
|
|
||||||
|
def handle_any(self):
|
||||||
|
started = time.monotonic()
|
||||||
|
request_id = str(uuid4())
|
||||||
|
ctx = Context(self)
|
||||||
|
headers = {}
|
||||||
|
error = None
|
||||||
|
try:
|
||||||
|
status, payload = self.dispatch(ctx)
|
||||||
|
except ApiError as exc:
|
||||||
|
error = exc
|
||||||
|
except (RedisError, BotoCoreError, ClientError, PoolTimeout, psycopg.OperationalError, psycopg.errors.QueryCanceled,
|
||||||
|
psycopg.errors.LockNotAvailable):
|
||||||
|
error = ApiError(503, "unavailable", "Хранилище временно недоступно")
|
||||||
|
except Exception as exc:
|
||||||
|
print(json.dumps({"request_id": request_id, "exception": type(exc).__name__}), flush=True)
|
||||||
|
error = ApiError(500, "internal_error", "Внутренняя ошибка")
|
||||||
|
if error:
|
||||||
|
status, headers = error.status, error.headers
|
||||||
|
payload = {"error": {"code": error.code, "message": error.message, "request_id": request_id}}
|
||||||
|
self.close_connection = True # Rejected bodies are never parsed as a next request.
|
||||||
|
if isinstance(payload, bytes):
|
||||||
|
data, content_type = payload, ctx.content_type
|
||||||
|
else:
|
||||||
|
content_type = "application/json; charset=utf-8"
|
||||||
|
data = b"" if status == 204 else json.dumps(payload, default=json_value, ensure_ascii=False).encode()
|
||||||
|
try:
|
||||||
|
self.send_response(status)
|
||||||
|
if status != 204:
|
||||||
|
self.send_header("Content-Type", content_type)
|
||||||
|
self.send_header("X-Content-Type-Options", "nosniff")
|
||||||
|
self.send_header("Content-Length", str(len(data)))
|
||||||
|
self.send_header("X-Request-Id", request_id)
|
||||||
|
self.send_header("X-Instance-Id", self.server.instance_id)
|
||||||
|
self.send_header("Connection", "close")
|
||||||
|
for name, value in headers.items():
|
||||||
|
self.send_header(name, value)
|
||||||
|
self.end_headers()
|
||||||
|
if data:
|
||||||
|
self.wfile.write(data)
|
||||||
|
except (OSError, TimeoutError):
|
||||||
|
pass
|
||||||
|
print(json.dumps({"method": self.command, "route": ctx.route, "status": status,
|
||||||
|
"duration_ms": round((time.monotonic() - started) * 1000, 2),
|
||||||
|
"request_id": request_id}), flush=True)
|
||||||
|
|
||||||
|
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
|
||||||
|
|
||||||
|
|
||||||
|
class Server(ThreadingHTTPServer):
|
||||||
|
request_queue_size = 64
|
||||||
|
daemon_threads = False
|
||||||
|
|
||||||
|
def __init__(self, address):
|
||||||
|
super().__init__(address, Handler)
|
||||||
|
self.stopping = threading.Event()
|
||||||
|
self.instance_id = uuid4().hex
|
||||||
|
self.workers = threading.BoundedSemaphore(16)
|
||||||
|
self.cursor_key = setting("CURSOR_KEY").encode()
|
||||||
|
self.store = Store()
|
||||||
|
self.sessions = Sessions()
|
||||||
|
self.objects = Objects()
|
||||||
|
self.image_slot = threading.BoundedSemaphore(1)
|
||||||
|
|
||||||
|
def process_request(self, request, address):
|
||||||
|
if not self.workers.acquire(blocking=False):
|
||||||
|
self.shutdown_request(request)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
super().process_request(request, address)
|
||||||
|
except BaseException:
|
||||||
|
self.workers.release()
|
||||||
|
raise
|
||||||
|
|
||||||
|
def process_request_thread(self, request, address):
|
||||||
|
try:
|
||||||
|
super().process_request_thread(request, address)
|
||||||
|
finally:
|
||||||
|
self.workers.release()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
address = os.environ.get("APP_HOST", "0.0.0.0"), int(os.environ.get("APP_PORT", "8080"))
|
||||||
|
with Server(address) as server:
|
||||||
|
def stop(signum, frame):
|
||||||
|
if not server.stopping.is_set():
|
||||||
|
server.stopping.set()
|
||||||
|
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, stop)
|
||||||
|
signal.signal(signal.SIGINT, stop)
|
||||||
|
try:
|
||||||
|
server.serve_forever()
|
||||||
|
finally:
|
||||||
|
server.server_close()
|
||||||
|
server.store.pool.close()
|
||||||
|
server.sessions.redis.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Validate binary uploads and keep original data in a private S3 bucket."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import warnings
|
||||||
|
from contextlib import closing
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from db import setting
|
||||||
|
|
||||||
|
MAX_UPLOAD = 10 * 1024 * 1024
|
||||||
|
MAX_PIXELS = 40_000_000
|
||||||
|
MEDIA_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||||
|
|
||||||
|
|
||||||
|
class BadImage(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class PixelLimit(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def verify_image(file, mime):
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||||
|
with Image.open(file) as image:
|
||||||
|
if image.width * image.height > MAX_PIXELS:
|
||||||
|
raise PixelLimit()
|
||||||
|
if MEDIA_TYPES.get(image.format) != mime:
|
||||||
|
raise BadImage()
|
||||||
|
if getattr(image, "n_frames", 1) != 1:
|
||||||
|
raise BadImage()
|
||||||
|
image.verify()
|
||||||
|
file.seek(0)
|
||||||
|
with Image.open(file) as image:
|
||||||
|
image.load()
|
||||||
|
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||||
|
raise PixelLimit() from None
|
||||||
|
except (OSError, SyntaxError, ValueError):
|
||||||
|
raise BadImage() from None
|
||||||
|
finally:
|
||||||
|
file.seek(0)
|
||||||
|
|
||||||
|
|
||||||
|
class Objects:
|
||||||
|
def __init__(self):
|
||||||
|
self.bucket = os.environ.get("S3_BUCKET", "attachments")
|
||||||
|
self.client = boto3.client(
|
||||||
|
"s3", endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
|
||||||
|
aws_access_key_id=setting("S3_ACCESS_KEY"),
|
||||||
|
aws_secret_access_key=setting("S3_SECRET_KEY"),
|
||||||
|
region_name="us-east-1", verify=os.environ.get("S3_CA_FILE") or True,
|
||||||
|
config=Config(connect_timeout=2, read_timeout=4, retries={"total_max_attempts": 1},
|
||||||
|
max_pool_connections=16, s3={"addressing_style": "path"},
|
||||||
|
request_checksum_calculation="when_required",
|
||||||
|
response_checksum_validation="when_required"),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def key(attachment_id, variant="original"):
|
||||||
|
return f"{variant}/{attachment_id}"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def result_key(attachment_id, version, variant):
|
||||||
|
if version == 0:
|
||||||
|
return Objects.key(attachment_id, variant)
|
||||||
|
return f"results/v{version}/{variant}/{attachment_id}"
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
self.client.head_bucket(Bucket=self.bucket)
|
||||||
|
|
||||||
|
def put(self, key, file, mime, length):
|
||||||
|
digest = hashlib.file_digest(file, "sha256").hexdigest()
|
||||||
|
file.seek(0)
|
||||||
|
self.client.put_object(Bucket=self.bucket, Key=key, Body=file,
|
||||||
|
ContentType=mime, ContentLength=length)
|
||||||
|
return digest
|
||||||
|
|
||||||
|
def get(self, key):
|
||||||
|
result = self.client.get_object(Bucket=self.bucket, Key=key)
|
||||||
|
with closing(result["Body"]) as body:
|
||||||
|
data = body.read(MAX_UPLOAD + 1)
|
||||||
|
if len(data) > MAX_UPLOAD:
|
||||||
|
raise ValueError("object exceeds configured limit")
|
||||||
|
return data
|
||||||
|
|
||||||
|
def has(self, key):
|
||||||
|
try:
|
||||||
|
self.client.head_object(Bucket=self.bucket, Key=key)
|
||||||
|
except ClientError as error:
|
||||||
|
if str(error.response["Error"]["Code"]) in ("404", "NotFound", "NoSuchKey"):
|
||||||
|
return False
|
||||||
|
raise
|
||||||
|
return True
|
||||||
|
|
||||||
|
def delete(self, key):
|
||||||
|
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||||
|
|
||||||
|
|
||||||
|
def spool():
|
||||||
|
return tempfile.SpooledTemporaryFile(max_size=512 * 1024, mode="w+b")
|
||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
"""Password verification and revocable Redis-backed sessions."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from redis import Redis
|
||||||
|
|
||||||
|
from db import setting
|
||||||
|
|
||||||
|
|
||||||
|
USERNAME = re.compile(r"[a-z0-9_]{3,32}")
|
||||||
|
TOKEN = re.compile(r"[A-Za-z0-9_-]{43}")
|
||||||
|
|
||||||
|
|
||||||
|
def valid_password(password):
|
||||||
|
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
password.encode("utf-8")
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def password_hash(password, salt=None):
|
||||||
|
if salt is None:
|
||||||
|
salt = secrets.token_bytes(16)
|
||||||
|
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=3)
|
||||||
|
return f"scrypt:{salt.hex()}:{digest.hex()}"
|
||||||
|
|
||||||
|
|
||||||
|
DUMMY_HASH = password_hash("dummy unknown account")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password, stored):
|
||||||
|
_, salt, _ = (stored or DUMMY_HASH).split(":")
|
||||||
|
actual = password_hash(password, bytes.fromhex(salt))
|
||||||
|
return hmac.compare_digest(actual, stored or DUMMY_HASH) and stored is not None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_basic(value):
|
||||||
|
scheme, _, data = value.partition(" ")
|
||||||
|
if scheme.lower() != "basic" or not 1 <= len(data) <= 1024:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
username, sep, password = base64.b64decode(data, validate=True).decode("utf-8").partition(":")
|
||||||
|
except (ValueError, UnicodeError):
|
||||||
|
return None
|
||||||
|
if sep and USERNAME.fullmatch(username) and valid_password(password):
|
||||||
|
return username, password
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_bearer(value):
|
||||||
|
scheme, _, token = value.partition(" ")
|
||||||
|
if scheme.lower() == "bearer" and TOKEN.fullmatch(token):
|
||||||
|
return token
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class Sessions:
|
||||||
|
def __init__(self):
|
||||||
|
self.redis = Redis.from_url(
|
||||||
|
setting("CACHE_URL"), socket_timeout=2, socket_connect_timeout=2,
|
||||||
|
max_connections=24, decode_responses=True,
|
||||||
|
)
|
||||||
|
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
if self.ttl < 1:
|
||||||
|
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def key(token):
|
||||||
|
return "messenger:session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||||
|
|
||||||
|
def issue(self, user_id):
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
seconds, micros = self.redis.time()
|
||||||
|
expires_ms = seconds * 1000 + micros // 1000 + self.ttl * 1000
|
||||||
|
self.redis.set(self.key(token), str(user_id), pxat=expires_ms)
|
||||||
|
return token, datetime.fromtimestamp(expires_ms / 1000, timezone.utc)
|
||||||
|
|
||||||
|
def get(self, token):
|
||||||
|
return self.redis.get(self.key(token))
|
||||||
|
|
||||||
|
def revoke(self, token):
|
||||||
|
return bool(self.redis.delete(self.key(token)))
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
"""PostgreSQL migrations, transactional writes and keyset reads."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.conninfo import make_conninfo
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
|
||||||
|
def setting(name):
|
||||||
|
path = os.environ.get(name + "_FILE")
|
||||||
|
return Path(path).read_text(encoding="utf-8").strip() if path else os.environ[name]
|
||||||
|
|
||||||
|
|
||||||
|
def connection_string():
|
||||||
|
return make_conninfo(
|
||||||
|
setting("DATABASE_URL"),
|
||||||
|
connect_timeout=3,
|
||||||
|
options="-c statement_timeout=4000 -c lock_timeout=2500",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate():
|
||||||
|
with psycopg.connect(connection_string(), autocommit=True) as connection:
|
||||||
|
migrations = Path(__file__).with_name("migrations")
|
||||||
|
with connection.transaction():
|
||||||
|
connection.execute("SELECT pg_advisory_xact_lock(17002026)")
|
||||||
|
connection.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
for file in sorted(migrations.glob("*.sql")):
|
||||||
|
with connection.transaction():
|
||||||
|
connection.execute("SELECT pg_advisory_xact_lock(17002026)")
|
||||||
|
if connection.execute(
|
||||||
|
"SELECT 1 FROM schema_migrations WHERE name = %s", (file.name,)
|
||||||
|
).fetchone():
|
||||||
|
continue
|
||||||
|
connection.execute(file.read_text(encoding="utf-8"))
|
||||||
|
connection.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (file.name,))
|
||||||
|
|
||||||
|
|
||||||
|
class KeyConflict(Exception):
|
||||||
|
"""The same active idempotency key has a different canonical request."""
|
||||||
|
|
||||||
|
|
||||||
|
class MissingAttachment(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UnusableAttachment(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def lock_attachment(connection, attachment_id):
|
||||||
|
connection.execute(
|
||||||
|
"SELECT pg_advisory_xact_lock(hashtextextended(%s, 4412))", (str(attachment_id),)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self):
|
||||||
|
self.pool = ConnectionPool(
|
||||||
|
connection_string(), min_size=1, max_size=8, timeout=2, open=False,
|
||||||
|
kwargs={"row_factory": dict_row},
|
||||||
|
)
|
||||||
|
self.pool.open()
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
connection.execute("SELECT 1")
|
||||||
|
|
||||||
|
def register(self, username, display_name, password_hash):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
return connection.execute("""
|
||||||
|
INSERT INTO users(id, username, display_name, password_hash)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id, username, display_name, created_at
|
||||||
|
""", (uuid4(), username, display_name, password_hash)).fetchone()
|
||||||
|
|
||||||
|
def credential(self, username):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
user = connection.execute("""
|
||||||
|
SELECT id, username, display_name, created_at, password_hash
|
||||||
|
FROM users WHERE username = %s
|
||||||
|
""", (username,)).fetchone()
|
||||||
|
if user:
|
||||||
|
return user, user.pop("password_hash")
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
def user(self, user_id):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
return connection.execute("""
|
||||||
|
SELECT id, username, display_name, created_at FROM users WHERE id = %s
|
||||||
|
""", (user_id,)).fetchone()
|
||||||
|
|
||||||
|
def create_chat(self, title, members):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
chat = connection.execute("""
|
||||||
|
INSERT INTO chats(id, title) VALUES (%s, %s) RETURNING *
|
||||||
|
""", (uuid4(), title)).fetchone()
|
||||||
|
connection.execute("""
|
||||||
|
INSERT INTO chat_members(chat_id, user_id, position)
|
||||||
|
SELECT %s, member, ord FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(member, ord)
|
||||||
|
""", (chat["id"], members))
|
||||||
|
return {**chat, "member_ids": members}
|
||||||
|
|
||||||
|
def chat(self, user_id, chat_id):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
return connection.execute("""
|
||||||
|
SELECT c.*, ARRAY(SELECT user_id FROM chat_members m
|
||||||
|
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
|
||||||
|
FROM chats c JOIN chat_members membership ON membership.chat_id = c.id
|
||||||
|
WHERE membership.user_id = %s AND c.id = %s
|
||||||
|
""", (user_id, chat_id)).fetchone()
|
||||||
|
|
||||||
|
def chats(self, user_id, cursor, count):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
return connection.execute("""
|
||||||
|
SELECT c.*, ARRAY(SELECT m.user_id FROM chat_members m
|
||||||
|
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
|
||||||
|
FROM chats c JOIN chat_members membership ON membership.chat_id = c.id
|
||||||
|
WHERE membership.user_id = %s
|
||||||
|
AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)
|
||||||
|
ORDER BY c.created_at, c.id LIMIT %s
|
||||||
|
""", (user_id, *cursor, count)).fetchall()
|
||||||
|
|
||||||
|
def message(self, user_id, chat_id, text, key, attachment_ids):
|
||||||
|
scope = (user_id, chat_id, key)
|
||||||
|
# Existing text-only requests still compare the same after migration.
|
||||||
|
body = {"text": text}
|
||||||
|
if attachment_ids:
|
||||||
|
body["attachment_ids"] = [str(value) for value in attachment_ids]
|
||||||
|
fingerprint = hashlib.sha256(json.dumps(body, separators=(",", ":")).encode()).digest()
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
accepted = connection.execute("""
|
||||||
|
INSERT INTO message_requests(user_id, chat_id, request_key, fingerprint)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
ON CONFLICT (user_id, chat_id, request_key) DO UPDATE
|
||||||
|
SET fingerprint = EXCLUDED.fingerprint, message_id = NULL,
|
||||||
|
expires_at = clock_timestamp() + interval '24 hours'
|
||||||
|
WHERE message_requests.expires_at <= clock_timestamp()
|
||||||
|
RETURNING request_key
|
||||||
|
""", (*scope, fingerprint)).fetchone()
|
||||||
|
if accepted:
|
||||||
|
self.check_attachments(connection, chat_id, attachment_ids)
|
||||||
|
message = self.insert_message(connection, user_id, chat_id, text, attachment_ids)
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE message_requests SET message_id = %s
|
||||||
|
WHERE user_id = %s AND chat_id = %s AND request_key = %s
|
||||||
|
""", (message["id"], *scope))
|
||||||
|
return message
|
||||||
|
existing = connection.execute("""
|
||||||
|
SELECT m.*, r.fingerprint
|
||||||
|
FROM message_requests r JOIN messages m ON m.id = r.message_id
|
||||||
|
WHERE r.user_id = %s AND r.chat_id = %s AND r.request_key = %s
|
||||||
|
""", scope).fetchone()
|
||||||
|
if existing.pop("fingerprint") != fingerprint:
|
||||||
|
raise KeyConflict()
|
||||||
|
return existing
|
||||||
|
|
||||||
|
def check_attachments(self, connection, chat_id, attachment_ids):
|
||||||
|
if not attachment_ids:
|
||||||
|
return
|
||||||
|
rows = connection.execute("""
|
||||||
|
SELECT id, status FROM attachments
|
||||||
|
WHERE chat_id = %s AND id = ANY(%s::uuid[])
|
||||||
|
ORDER BY id FOR SHARE
|
||||||
|
""", (chat_id, attachment_ids)).fetchall()
|
||||||
|
if len(rows) != len(attachment_ids):
|
||||||
|
raise MissingAttachment()
|
||||||
|
if any(row["status"] == "failed" for row in rows):
|
||||||
|
raise UnusableAttachment()
|
||||||
|
|
||||||
|
def insert_message(self, connection, user_id, chat_id, text, attachment_ids):
|
||||||
|
return connection.execute("""
|
||||||
|
INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids)
|
||||||
|
VALUES (%s, %s, %s, %s, %s::uuid[])
|
||||||
|
RETURNING *
|
||||||
|
""", (uuid4(), chat_id, user_id, text, attachment_ids)).fetchone()
|
||||||
|
|
||||||
|
def save_attachment(self, chat_id, user_id, filename, mime, length, store_original):
|
||||||
|
attachment_id = uuid4()
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
lock_attachment(connection, attachment_id)
|
||||||
|
digest = store_original(attachment_id)
|
||||||
|
attachment = connection.execute("""
|
||||||
|
INSERT INTO attachments(id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||||
|
sha256, status, pipeline_version)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued', 1) RETURNING *
|
||||||
|
""", (attachment_id, chat_id, user_id, filename, mime, length, digest)).fetchone()
|
||||||
|
connection.execute("""
|
||||||
|
INSERT INTO image_jobs(id, attachment_id, pipeline_version)
|
||||||
|
VALUES (%s, %s, 1)
|
||||||
|
""", (uuid4(), attachment_id))
|
||||||
|
return attachment
|
||||||
|
|
||||||
|
def attachment(self, user_id, attachment_id):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
return connection.execute("""
|
||||||
|
SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id
|
||||||
|
WHERE a.id = %s AND m.user_id = %s
|
||||||
|
""", (attachment_id, user_id)).fetchone()
|
||||||
|
|
||||||
|
def messages(self, chat_id, cursor, count):
|
||||||
|
with self.pool.connection() as connection:
|
||||||
|
return connection.execute("""
|
||||||
|
SELECT * FROM messages
|
||||||
|
WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid)
|
||||||
|
ORDER BY created_at, id LIMIT %s
|
||||||
|
""", (chat_id, *cursor, count)).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
migrate()
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
display_name text NOT NULL,
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE INDEX chats_page ON chats (created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE chat_members (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
position integer NOT NULL CHECK (position > 0),
|
||||||
|
PRIMARY KEY (chat_id, user_id),
|
||||||
|
UNIQUE (chat_id, position)
|
||||||
|
);
|
||||||
|
CREATE INDEX chat_members_by_user ON chat_members (user_id, chat_id);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL,
|
||||||
|
sender_id uuid NOT NULL,
|
||||||
|
text text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX messages_page ON messages (chat_id, created_at, id);
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
CREATE TABLE message_requests (
|
||||||
|
user_id uuid NOT NULL,
|
||||||
|
chat_id uuid NOT NULL,
|
||||||
|
request_key text NOT NULL,
|
||||||
|
fingerprint bytea NOT NULL,
|
||||||
|
expires_at timestamptz NOT NULL DEFAULT (clock_timestamp() + interval '24 hours'),
|
||||||
|
message_id uuid REFERENCES messages(id),
|
||||||
|
PRIMARY KEY (user_id, chat_id, request_key),
|
||||||
|
FOREIGN KEY (chat_id, user_id) REFERENCES chat_members(chat_id, user_id)
|
||||||
|
);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE attachments (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
owner_id uuid NOT NULL,
|
||||||
|
filename text NOT NULL,
|
||||||
|
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||||
|
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||||
|
sha256 text NOT NULL,
|
||||||
|
status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready', 'failed')),
|
||||||
|
variants jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
error_code text,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members(chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX attachments_recent ON attachments(created_at, id);
|
||||||
|
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT ARRAY[]::uuid[];
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||||
|
ALTER TABLE attachments ADD CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
|
||||||
|
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
CREATE TABLE image_jobs (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||||
|
pipeline_version integer NOT NULL CHECK (pipeline_version > 0),
|
||||||
|
attempt integer NOT NULL DEFAULT 0,
|
||||||
|
state text NOT NULL DEFAULT 'waiting' CHECK (state IN ('waiting', 'leased', 'done', 'failed')),
|
||||||
|
next_run timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
leased_until timestamptz,
|
||||||
|
published_at timestamptz,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
trace_context jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
UNIQUE (attachment_id, pipeline_version)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX image_jobs_pending ON image_jobs(next_run, id) WHERE state IN ('waiting', 'leased');
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
CREATE TABLE image_replays (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
job_id uuid NOT NULL REFERENCES image_jobs(id),
|
||||||
|
event text NOT NULL CHECK (event IN ('retry_failed', 'new_version')),
|
||||||
|
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
+255
@@ -0,0 +1,255 @@
|
|||||||
|
"""Durable PostgreSQL outbox, Redis Streams relay and leased image processing."""
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from psycopg_pool import PoolTimeout
|
||||||
|
from redis import Redis
|
||||||
|
from redis.exceptions import RedisError, ResponseError
|
||||||
|
|
||||||
|
from attachments import Objects
|
||||||
|
from db import Store, setting
|
||||||
|
|
||||||
|
STREAM = "messenger:images"
|
||||||
|
GROUP = "image-workers"
|
||||||
|
MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))
|
||||||
|
LEASE_SECONDS = 45
|
||||||
|
CHILD_TIMEOUT = 15
|
||||||
|
JOB_TYPE = "attachment.process.v1"
|
||||||
|
|
||||||
|
|
||||||
|
class PermanentImageError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def connect_broker():
|
||||||
|
return Redis.from_url(setting("BROKER_URL"), socket_timeout=3, socket_connect_timeout=2,
|
||||||
|
decode_responses=True)
|
||||||
|
|
||||||
|
|
||||||
|
def record(event, **fields):
|
||||||
|
print(json.dumps({"event": event, **fields}), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def settle(connection, job, outcome, code=None):
|
||||||
|
waiting = outcome == "waiting"
|
||||||
|
delay = min(20, 2 ** job["attempt"]) * random.uniform(0.8, 1.2) if waiting else 0
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE image_jobs SET state = %s, leased_until = NULL, published_at = NULL,
|
||||||
|
next_run = clock_timestamp() + %s * interval '1 second'
|
||||||
|
WHERE id = %s
|
||||||
|
""", (outcome, delay, job["id"]))
|
||||||
|
if outcome != "done":
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE attachments SET status = %s, error_code = %s, updated_at = clock_timestamp()
|
||||||
|
WHERE id = %s AND pipeline_version = %s
|
||||||
|
""", ("queued" if waiting else "failed", None if waiting else code,
|
||||||
|
job["attachment_id"], job["pipeline_version"]))
|
||||||
|
|
||||||
|
|
||||||
|
def relay_once(store, broker):
|
||||||
|
with store.pool.connection() as connection:
|
||||||
|
row = connection.execute("""
|
||||||
|
SELECT * FROM image_jobs
|
||||||
|
WHERE ((state = 'waiting' AND next_run <= clock_timestamp())
|
||||||
|
OR (state = 'leased' AND leased_until <= clock_timestamp()))
|
||||||
|
AND (published_at IS NULL OR published_at <= clock_timestamp() - interval '50 seconds')
|
||||||
|
ORDER BY next_run, id FOR UPDATE SKIP LOCKED LIMIT 1
|
||||||
|
""").fetchone()
|
||||||
|
if row is None:
|
||||||
|
return False
|
||||||
|
message = {
|
||||||
|
"schema_version": 1, "job_id": str(row["id"]), "type": JOB_TYPE,
|
||||||
|
"attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"],
|
||||||
|
"attempt": row["attempt"] + 1,
|
||||||
|
"created_at": row["created_at"].astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||||
|
**row["trace_context"],
|
||||||
|
}
|
||||||
|
broker.xadd(STREAM, {"job": json.dumps(message, separators=(",", ":"))})
|
||||||
|
connection.execute("UPDATE image_jobs SET published_at = clock_timestamp() WHERE id = %s",
|
||||||
|
(row["id"],))
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def claim(store, message):
|
||||||
|
with store.pool.connection() as connection:
|
||||||
|
job = connection.execute("""
|
||||||
|
SELECT j.*, a.content_type, a.sha256, a.size_bytes,
|
||||||
|
a.pipeline_version AS active_version,
|
||||||
|
j.leased_until > clock_timestamp() AS lease_active,
|
||||||
|
j.next_run > clock_timestamp() AS too_early
|
||||||
|
FROM image_jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||||
|
WHERE j.id = %s FOR UPDATE OF j, a
|
||||||
|
""", (UUID(message["job_id"]),)).fetchone()
|
||||||
|
if not job or job["state"] in ("done", "failed"):
|
||||||
|
return None
|
||||||
|
if job["pipeline_version"] != job["active_version"]:
|
||||||
|
settle(connection, job, "done")
|
||||||
|
return None
|
||||||
|
if job["lease_active"] or job["too_early"]:
|
||||||
|
return None
|
||||||
|
if job["attempt"] >= MAX_ATTEMPTS:
|
||||||
|
settle(connection, job, "failed", "retry_exhausted")
|
||||||
|
return None
|
||||||
|
job["attempt"] += 1
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE image_jobs SET state = 'leased', attempt = %s,
|
||||||
|
leased_until = clock_timestamp() + %s * interval '1 second'
|
||||||
|
WHERE id = %s
|
||||||
|
""", (job["attempt"], LEASE_SECONDS, job["id"]))
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE attachments SET status='processing', updated_at = clock_timestamp() WHERE id=%s
|
||||||
|
""", (job["attachment_id"],))
|
||||||
|
return job
|
||||||
|
|
||||||
|
|
||||||
|
def encode_images(original):
|
||||||
|
with tempfile.TemporaryDirectory(prefix="messenger-image-") as name:
|
||||||
|
root = Path(name)
|
||||||
|
(root / "source").write_bytes(original)
|
||||||
|
result = subprocess.run(
|
||||||
|
[sys.executable, "-m", "variants", str(root)], check=False,
|
||||||
|
timeout=CHILD_TIMEOUT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
if result.returncode == 2:
|
||||||
|
raise PermanentImageError()
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise OSError("image subprocess failed")
|
||||||
|
descriptors = json.loads((root / "variants.json").read_text(encoding="utf-8"))
|
||||||
|
return [(descriptor, (root / descriptor["name"]).read_bytes()) for descriptor in descriptors]
|
||||||
|
|
||||||
|
|
||||||
|
def try_publish(store, objects, job):
|
||||||
|
attachment_id, version = job["attachment_id"], job["pipeline_version"]
|
||||||
|
original = objects.get(objects.key(attachment_id, "staging"))
|
||||||
|
processed = encode_images(original)
|
||||||
|
with store.pool.connection() as connection:
|
||||||
|
current = connection.execute("""
|
||||||
|
SELECT j.attempt, j.state, a.pipeline_version,
|
||||||
|
j.leased_until > clock_timestamp() AS lease_active
|
||||||
|
FROM image_jobs j JOIN attachments a ON a.id = j.attachment_id
|
||||||
|
WHERE j.id = %s FOR UPDATE OF j,a
|
||||||
|
""", (job["id"],)).fetchone()
|
||||||
|
if not current or current["state"] != "leased" or current["attempt"] != job["attempt"]:
|
||||||
|
return "stale"
|
||||||
|
if current["pipeline_version"] != version or not current["lease_active"]:
|
||||||
|
return "stale"
|
||||||
|
digest = objects.put(objects.result_key(attachment_id, version, "original"),
|
||||||
|
io.BytesIO(original), job["content_type"], len(original))
|
||||||
|
if digest != job["sha256"] or len(original) != job["size_bytes"]:
|
||||||
|
raise PermanentImageError()
|
||||||
|
variants = []
|
||||||
|
for descriptor, data in processed:
|
||||||
|
name, mime = descriptor["name"], descriptor["content_type"]
|
||||||
|
digest = objects.put(objects.result_key(attachment_id, version, name),
|
||||||
|
io.BytesIO(data), mime, len(data))
|
||||||
|
variants.append({**descriptor, "size_bytes": len(data), "sha256": digest})
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE attachments SET status = 'ready', error_code = NULL, variants = %s,
|
||||||
|
updated_at = clock_timestamp()
|
||||||
|
WHERE id = %s AND pipeline_version = %s
|
||||||
|
""", (Jsonb(variants), attachment_id, version))
|
||||||
|
settle(connection, job, "done")
|
||||||
|
return "ready"
|
||||||
|
|
||||||
|
|
||||||
|
def fail(store, job, permanent):
|
||||||
|
with store.pool.connection() as connection:
|
||||||
|
current = connection.execute("""
|
||||||
|
SELECT state, attempt FROM image_jobs WHERE id = %s FOR UPDATE
|
||||||
|
""", (job["id"],)).fetchone()
|
||||||
|
if current != {"state": "leased", "attempt": job["attempt"]}:
|
||||||
|
return "stale"
|
||||||
|
if permanent or job["attempt"] >= MAX_ATTEMPTS:
|
||||||
|
settle(connection, job, "failed", "invalid_image" if permanent else "retry_exhausted")
|
||||||
|
return "failed"
|
||||||
|
settle(connection, job, "waiting")
|
||||||
|
return "retry"
|
||||||
|
|
||||||
|
|
||||||
|
def process(store, objects, message):
|
||||||
|
job = claim(store, message)
|
||||||
|
if job is None:
|
||||||
|
return "ignored"
|
||||||
|
try:
|
||||||
|
return try_publish(store, objects, job)
|
||||||
|
except PermanentImageError:
|
||||||
|
return fail(store, job, permanent=True)
|
||||||
|
except (OSError, subprocess.TimeoutExpired, BotoCoreError, ClientError):
|
||||||
|
return fail(store, job, permanent=False)
|
||||||
|
|
||||||
|
|
||||||
|
def operate_worker(store, broker, stop):
|
||||||
|
try:
|
||||||
|
broker.xgroup_create(STREAM, GROUP, id="0-0", mkstream=True)
|
||||||
|
except ResponseError as exc:
|
||||||
|
if not str(exc).startswith("BUSYGROUP"):
|
||||||
|
raise
|
||||||
|
consumer = uuid4().hex
|
||||||
|
objects = Objects()
|
||||||
|
reclaim_cursor = "0-0"
|
||||||
|
while not stop.is_set():
|
||||||
|
reclaim_cursor, entries, _ = broker.xautoclaim(
|
||||||
|
STREAM, GROUP, consumer, LEASE_SECONDS * 1000, reclaim_cursor, count=1
|
||||||
|
)
|
||||||
|
if not entries:
|
||||||
|
streams = broker.xreadgroup(GROUP, consumer, {STREAM: ">"}, block=500, count=1)
|
||||||
|
entries = streams[0][1] if streams else []
|
||||||
|
for entry_id, fields in entries:
|
||||||
|
started = time.monotonic()
|
||||||
|
try:
|
||||||
|
message = json.loads(fields["job"])
|
||||||
|
if message.get("schema_version") != 1 or message.get("type") != JOB_TYPE:
|
||||||
|
raise ValueError
|
||||||
|
UUID(message["job_id"])
|
||||||
|
except (ValueError, KeyError, TypeError, AttributeError):
|
||||||
|
record("job_invalid")
|
||||||
|
else:
|
||||||
|
outcome = process(store, objects, message)
|
||||||
|
record("job_processed", outcome=outcome, duration_s=round(time.monotonic() - started, 4))
|
||||||
|
# XACK plus XDEL atomically. There is one consumer group on this stream.
|
||||||
|
with broker.pipeline(transaction=True) as pipe:
|
||||||
|
pipe.xack(STREAM, GROUP, entry_id).xdel(STREAM, entry_id).execute()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
role = sys.argv[1]
|
||||||
|
stop = threading.Event()
|
||||||
|
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||||
|
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||||
|
store, broker = Store(), connect_broker()
|
||||||
|
try:
|
||||||
|
while not stop.is_set():
|
||||||
|
try:
|
||||||
|
if role == "worker":
|
||||||
|
operate_worker(store, broker, stop)
|
||||||
|
elif role == "relay":
|
||||||
|
if not relay_once(store, broker):
|
||||||
|
stop.wait(0.25)
|
||||||
|
else:
|
||||||
|
raise ValueError("Expected worker or relay")
|
||||||
|
except (RedisError, psycopg.OperationalError, psycopg.errors.LockNotAvailable,
|
||||||
|
psycopg.errors.QueryCanceled, PoolTimeout) as exc:
|
||||||
|
record("worker_dependency_unavailable", error_type=type(exc).__name__)
|
||||||
|
stop.wait(1)
|
||||||
|
finally:
|
||||||
|
broker.close()
|
||||||
|
store.pool.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""Explicitly replay failed work or request a new version of an image pipeline."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
from db import Store
|
||||||
|
|
||||||
|
|
||||||
|
def replay(store, attachment_id, new_version):
|
||||||
|
with store.pool.connection() as connection:
|
||||||
|
attachment = connection.execute("""
|
||||||
|
SELECT status, pipeline_version FROM attachments WHERE id=%s FOR UPDATE
|
||||||
|
""", (attachment_id,)).fetchone()
|
||||||
|
if not attachment or attachment["pipeline_version"] == 0:
|
||||||
|
raise ValueError("No durable staging source for this attachment")
|
||||||
|
version = attachment["pipeline_version"]
|
||||||
|
if new_version:
|
||||||
|
if attachment["status"] != "ready":
|
||||||
|
raise ValueError("Request a new version only for a ready attachment")
|
||||||
|
version += 1
|
||||||
|
job_id = uuid4()
|
||||||
|
connection.execute("""
|
||||||
|
INSERT INTO image_jobs(id, attachment_id, pipeline_version) VALUES(%s,%s,%s)
|
||||||
|
""", (job_id, attachment_id, version))
|
||||||
|
event = "new_version"
|
||||||
|
else:
|
||||||
|
if attachment["status"] != "failed":
|
||||||
|
raise ValueError("Only failed attachments can be replayed in place")
|
||||||
|
row = connection.execute("""
|
||||||
|
UPDATE image_jobs SET state='waiting', attempt=0, next_run=clock_timestamp(),
|
||||||
|
leased_until=NULL, published_at=NULL
|
||||||
|
WHERE attachment_id=%s AND pipeline_version=%s AND state='failed' RETURNING id
|
||||||
|
""", (attachment_id, version)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise ValueError("No failed job for the active version")
|
||||||
|
job_id = row["id"]
|
||||||
|
event = "retry_failed"
|
||||||
|
connection.execute("""
|
||||||
|
UPDATE attachments SET status='queued', error_code=NULL, variants='[]'::jsonb,
|
||||||
|
pipeline_version=%s, updated_at=clock_timestamp()
|
||||||
|
WHERE id=%s
|
||||||
|
""", (version, attachment_id))
|
||||||
|
connection.execute("INSERT INTO image_replays(id,job_id,event) VALUES(%s,%s,%s)",
|
||||||
|
(uuid4(), job_id, event))
|
||||||
|
return job_id
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("attachment_id", type=UUID)
|
||||||
|
parser.add_argument("--new-version", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
store = Store()
|
||||||
|
try:
|
||||||
|
print(replay(store, args.attachment_id, args.new_version))
|
||||||
|
finally:
|
||||||
|
store.pool.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Bounded child process for the CPU-intensive image conversion."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
from attachments import MAX_PIXELS
|
||||||
|
|
||||||
|
|
||||||
|
def fit(image, limit):
|
||||||
|
longest = max(image.size)
|
||||||
|
if longest <= limit:
|
||||||
|
return image
|
||||||
|
size = tuple(max(1, side * limit // longest) for side in image.size)
|
||||||
|
return image.resize(size, Image.Resampling.LANCZOS)
|
||||||
|
|
||||||
|
|
||||||
|
def convert(root):
|
||||||
|
try:
|
||||||
|
with Image.open(root / "source") as source:
|
||||||
|
if source.width * source.height > MAX_PIXELS or source.format not in ("PNG", "JPEG"):
|
||||||
|
return 2
|
||||||
|
with ImageOps.exif_transpose(source).convert("RGBA") as image:
|
||||||
|
rgb = Image.new("RGB", image.size, "white")
|
||||||
|
rgb.paste(image, mask=image.getchannel("A"))
|
||||||
|
except (UnidentifiedImageError, Image.DecompressionBombError, SyntaxError, OSError):
|
||||||
|
return 2
|
||||||
|
outputs = [
|
||||||
|
("thumbnail", fit(rgb, 256), "JPEG", "image/jpeg", 85),
|
||||||
|
("crop", ImageOps.fit(rgb, (128, 128), Image.Resampling.LANCZOS), "JPEG", "image/jpeg", 85),
|
||||||
|
("optimized", fit(rgb, 1280), "WEBP", "image/webp", 82),
|
||||||
|
]
|
||||||
|
descriptors = []
|
||||||
|
for name, image, format_name, mime, quality in outputs:
|
||||||
|
image.info.clear()
|
||||||
|
image.save(root / name, format=format_name, quality=quality)
|
||||||
|
descriptors.append({"name": name, "content_type": mime, "width": image.width, "height": image.height})
|
||||||
|
(root / "variants.json").write_text(json.dumps(descriptors), encoding="utf-8")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(convert(Path(sys.argv[1])))
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Inject worker termination around effects and verify a stale version is a no-op."""
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import json
|
||||||
|
from unittest.mock import patch
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from attachments import Objects
|
||||||
|
from db import Store
|
||||||
|
from pipeline import GROUP, STREAM, claim, connect_broker, process, relay_once, try_publish
|
||||||
|
from replay import replay
|
||||||
|
|
||||||
|
|
||||||
|
class InjectedCrash(BaseException):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def expire_lease(store, message):
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
db.execute("""
|
||||||
|
UPDATE image_jobs SET leased_until=clock_timestamp()-interval '1 second'
|
||||||
|
WHERE id=%s
|
||||||
|
""", (UUID(message["job_id"]),))
|
||||||
|
|
||||||
|
|
||||||
|
def state(store, row):
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
return db.execute("SELECT * FROM attachments WHERE id=%s", (row,)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def event(broker, job_id):
|
||||||
|
for _, fields in reversed(broker.xrange(STREAM)):
|
||||||
|
message = json.loads(fields["job"])
|
||||||
|
if message["job_id"] == str(job_id):
|
||||||
|
return message
|
||||||
|
raise AssertionError("durable job was not relayed")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("attachment", type=UUID, help="One newly queued image in the isolated test stack")
|
||||||
|
args = parser.parse_args()
|
||||||
|
store, broker, objects = Store(), connect_broker(), Objects()
|
||||||
|
attachment = args.attachment
|
||||||
|
try:
|
||||||
|
assert state(store, attachment)["status"] == "queued"
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
original = db.execute("SELECT id FROM image_jobs WHERE attachment_id=%s", (attachment,)).fetchone()["id"]
|
||||||
|
assert relay_once(store, broker)
|
||||||
|
message = event(broker, original)
|
||||||
|
job = claim(store, message)
|
||||||
|
assert job
|
||||||
|
|
||||||
|
# The first worker dies after taking a lease, before any object is written.
|
||||||
|
expire_lease(store, message)
|
||||||
|
job = claim(store, message)
|
||||||
|
calls = collections.Counter()
|
||||||
|
put = objects.put
|
||||||
|
|
||||||
|
def crash_after_object(key, *pos, **named):
|
||||||
|
result = put(key, *pos, **named)
|
||||||
|
calls[key] += 1
|
||||||
|
raise InjectedCrash()
|
||||||
|
|
||||||
|
try:
|
||||||
|
with patch.object(objects, "put", side_effect=crash_after_object):
|
||||||
|
try_publish(store, objects, job)
|
||||||
|
except InjectedCrash:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("fault did not fire after an object was written")
|
||||||
|
|
||||||
|
assert state(store, attachment)["status"] == "processing"
|
||||||
|
expire_lease(store, message)
|
||||||
|
assert process(store, objects, message) == "ready"
|
||||||
|
first = state(store, attachment)
|
||||||
|
assert process(store, objects, message) == "ignored"
|
||||||
|
assert state(store, attachment) == first
|
||||||
|
|
||||||
|
second_id = replay(store, attachment, new_version=True)
|
||||||
|
assert relay_once(store, broker)
|
||||||
|
second_message = event(broker, second_id)
|
||||||
|
assert process(store, objects, second_message) == "ready"
|
||||||
|
second = state(store, attachment)
|
||||||
|
assert second["pipeline_version"] == first["pipeline_version"] + 1
|
||||||
|
assert process(store, objects, message) == "ignored"
|
||||||
|
assert state(store, attachment) == second
|
||||||
|
assert len(calls) == 1 and len(second["variants"]) == 3
|
||||||
|
print(json.dumps({"before_effect": True, "after_effect_before_commit": True,
|
||||||
|
"duplicate_after_commit": True, "old_delivery_after_v2": True,
|
||||||
|
"ready_variants": len(second["variants"])}, indent=2))
|
||||||
|
finally:
|
||||||
|
broker.close()
|
||||||
|
store.pool.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Reproduce the worker-offline trajectory on a running test stack."""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
from client import Client, Failure, check
|
||||||
|
from image_probe import jpeg_size
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):
|
||||||
|
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, timeout=90)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_api(client):
|
||||||
|
end = time.monotonic() + 45
|
||||||
|
while time.monotonic() < end:
|
||||||
|
try:
|
||||||
|
client.call("GET", "/health/ready", schema="Health")
|
||||||
|
return
|
||||||
|
except Failure:
|
||||||
|
time.sleep(0.5)
|
||||||
|
raise Failure("API did not recover")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||||
|
parser.add_argument("--pause", type=int, default=0, help="Extra seconds with worker stopped")
|
||||||
|
parser.add_argument("--no-restart", action="store_true", help="Keep API up during telemetry demo")
|
||||||
|
args = parser.parse_args()
|
||||||
|
client = Client(args.base_url)
|
||||||
|
actor, peer, _, chat = client.bootstrap()
|
||||||
|
compose("stop", "worker")
|
||||||
|
try:
|
||||||
|
upload, original = client.attachment(actor, chat)
|
||||||
|
message = client.message(actor, chat, "", attachments=[upload["id"]])["json"]
|
||||||
|
check(message["attachment_ids"] == [upload["id"]], "message lost queued attachment")
|
||||||
|
meta = "/api/v1/attachments/" + upload["id"]
|
||||||
|
client.call("GET", meta + "/content", 409, actor=peer)
|
||||||
|
print("202 queued, привязка к сообщению 201, скачивание 409.", flush=True)
|
||||||
|
if args.pause:
|
||||||
|
time.sleep(args.pause)
|
||||||
|
if not args.no_restart:
|
||||||
|
compose("restart", "broker", "api")
|
||||||
|
wait_api(client)
|
||||||
|
queued = client.call("GET", meta, actor=peer, schema="Attachment")["json"]
|
||||||
|
check(queued["status"] == "queued", "restart lost the pending job")
|
||||||
|
print("После рестарта без worker задача осталась queued.", flush=True)
|
||||||
|
finally:
|
||||||
|
compose("start", "worker")
|
||||||
|
ready = client.wait_ready(peer, upload)
|
||||||
|
variants = {item["name"]: item for item in ready["variants"]}
|
||||||
|
check({"thumbnail", "crop", "optimized"} <= variants.keys(), "missing generated variants")
|
||||||
|
downloaded = client.call("GET", meta + "/content", actor=peer)["bytes"]
|
||||||
|
thumb = client.call("GET", meta + "/content?variant=thumbnail", actor=peer)["bytes"]
|
||||||
|
check(downloaded == original, "original changed")
|
||||||
|
check(jpeg_size(thumb) == (256, 160), "thumbnail dimensions changed")
|
||||||
|
check(variants["thumbnail"]["sha256"] == hashlib.sha256(thumb).hexdigest(), "thumbnail hash changed")
|
||||||
|
print(json.dumps({"status": ready["status"], "thumbnail": "256x160",
|
||||||
|
"variants": sorted(variants), "original_matches": True}, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user