feat(attachments): add durable Kafka image processing

This commit is contained in:
2026-11-26 18:55:59 +03:00
parent 276dbdad8a
commit f0fc096948
105 changed files with 15987 additions and 7 deletions
+1
View File
@@ -16,5 +16,6 @@ backups
.venv
__pycache__
node_modules
.pnpm-store
evidence
.DS_Store
+8 -3
View File
@@ -18,8 +18,13 @@ S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2
# Kafka partition count is applied when creating a new topic.
ATTACHMENT_TOPIC_PARTITIONS=1
ATTACHMENT_QUEUE_CAPACITY=64
WORKER_CONCURRENCY=1
WORKER_PREFETCH_BYTES=1048576
JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400
WORKER_MEMORY_LIMIT=768m
ORPHAN_GRACE_SECONDS=600
RECONCILE_INTERVAL_SECONDS=60
+3
View File
@@ -0,0 +1,3 @@
infra/*.sh text eol=lf
scripts/*.sh text eol=lf
scripts/*.cmd text eol=crlf
+1
View File
@@ -18,6 +18,7 @@ backups/
__pycache__/
*.py[cod]
node_modules/
.pnpm-store/
dist/
build/
target/
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": ["src/generated/**"],
"rules": {
"typescript/no-explicit-any": "off",
"typescript/no-floating-promises": "error"
},
"env": {
"node": true
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
+64
View File
@@ -0,0 +1,64 @@
FROM node:24.20.0-bookworm-slim AS base
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends openssl \
&& rm -rf /var/lib/apt/lists/*
RUN npm install --global pnpm@10.14.0
FROM base AS dependencies
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
FROM dependencies AS migrate
COPY prisma ./prisma
COPY prisma.config.ts ./
CMD ["pnpm", "db:deploy"]
FROM migrate AS build
COPY nest-cli.json tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN pnpm build
FROM base AS production-dependencies
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --prod --frozen-lockfile
FROM production-dependencies AS storage-init
COPY infra/rustfs ./infra/rustfs
CMD ["node", "infra/rustfs/bootstrap.mjs"]
FROM node:24.20.0-bookworm-slim AS runtime
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
ENV NODE_ENV=production \
APP_HOST=0.0.0.0 \
APP_PORT=8080
WORKDIR /app
RUN groupadd --system --gid 10001 app \
&& useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app
RUN mkdir -p /app/data && chown 10001:10001 /app/data
COPY --from=production-dependencies --chown=10001:10001 /app/node_modules ./node_modules
COPY --from=build --chown=10001:10001 /app/dist ./dist
COPY --from=build --chown=10001:10001 /app/package.json ./package.json
COPY --chown=10001:10001 contracts ./contracts
USER 10001:10001
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \
CMD curl --fail --silent --show-error --max-time 2 --output /dev/null "http://127.0.0.1:${APP_PORT:-8080}/health/ready"
CMD ["node", "dist/main.js"]
+270
View File
@@ -0,0 +1,270 @@
services:
api:
build:
context: .
target: runtime
restart: unless-stopped
init: true
deploy:
replicas: 2
command: ['sh', '-c', 'INSTANCE_ID=$$(hostname) exec node dist/main.js']
environment:
NODE_ENV: production
UPLOAD_MEMORY_PROFILE: ${UPLOAD_MEMORY_PROFILE:-0}
APP_ENV: ${APP_ENV:-lab}
APP_HOST: 0.0.0.0
APP_PORT: 8080
DATABASE_URL: postgresql://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-local_dev_password}@postgres:5432/${POSTGRES_DB:-chat}
DB_POOL_MAX: ${DB_POOL_MAX:-15}
CACHE_URL: redis://redis:6379/0
CACHE_PREFIX: ${CACHE_PREFIX:-messenger:cache:v1}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:${S3_PUBLIC_PORT:-9000}}
DIRECT_UPLOAD_TTL_SECONDS: ${DIRECT_UPLOAD_TTL_SECONDS:-60}
S3_ACCESS_KEY_ID: ${S3_API_ACCESS_KEY_ID:-LABAPI}
S3_SECRET_ACCESS_KEY: ${S3_API_SECRET_ACCESS_KEY:-local_api_storage_password}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
UPLOAD_BODY_TIMEOUT_MS: ${UPLOAD_BODY_TIMEOUT_MS:-15000}
KAFKA_BROKERS: kafka:9092
ATTACHMENT_QUEUE_CAPACITY: ${ATTACHMENT_QUEUE_CAPACITY:-64}
depends_on:
migrate:
condition: service_completed_successfully
postgres:
condition: service_healthy
redis:
condition: service_healthy
s3-init:
condition: service_completed_successfully
kafka-init:
condition: service_completed_successfully
healthcheck:
test:
- CMD
- curl
- --fail
- --silent
- --show-error
- --max-time
- '2'
- --output
- /dev/null
- http://127.0.0.1:8080/health/ready
interval: 10s
timeout: 3s
start_period: 20s
retries: 5
stop_grace_period: 30s
worker:
build:
context: .
target: runtime
command: ['node', 'dist/attachment-worker.main.js']
restart: unless-stopped
init: true
mem_limit: ${WORKER_MEMORY_LIMIT:-768m}
memswap_limit: ${WORKER_MEMORY_LIMIT:-768m}
tmpfs:
- /tmp:size=32m,mode=1777
environment:
NODE_ENV: production
DATABASE_URL: postgresql://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-local_dev_password}@postgres:5432/${POSTGRES_DB:-chat}
DB_POOL_MAX: 2
KAFKA_BROKERS: kafka:9092
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1}
WORKER_PREFETCH_BYTES: ${WORKER_PREFETCH_BYTES:-1048576}
ATTACHMENT_QUEUE_CAPACITY: ${ATTACHMENT_QUEUE_CAPACITY:-64}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID: ${S3_API_ACCESS_KEY_ID:-LABAPI}
S3_SECRET_ACCESS_KEY: ${S3_API_SECRET_ACCESS_KEY:-local_api_storage_password}
depends_on:
migrate:
condition: service_completed_successfully
kafka-init:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
healthcheck:
disable: true
stop_grace_period: 120s
kafka:
image: apache/kafka:3.9.2
restart: unless-stopped
environment:
CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
KAFKA_NODE_ID: 1
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@127.0.0.1:9093
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS: 1
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'false'
KAFKA_LOG_DIRS: /var/lib/kafka/data
KAFKA_HEAP_OPTS: '-Xms128m -Xmx512m'
volumes:
- kafka_data:/var/lib/kafka/data
healthcheck:
test: ['CMD', 'bash', '-c', 'true </dev/tcp/127.0.0.1/9092']
interval: 10s
timeout: 5s
start_period: 90s
retries: 12
stop_grace_period: 30s
kafka-init:
image: apache/kafka:3.9.2
depends_on:
kafka:
condition: service_healthy
entrypoint: ['/opt/kafka/bin/kafka-topics.sh']
command: ['--bootstrap-server', 'kafka:9092', '--create', '--if-not-exists', '--topic', 'attachments.process.v1', '--partitions', '${ATTACHMENT_TOPIC_PARTITIONS:-1}', '--replication-factor', '1', '--config', 'retention.ms=-1', '--config', 'flush.messages=1']
reconciler:
build:
context: .
target: runtime
command: ['node', 'dist/Attachment/reconcile.cli.js', '--watch', '--apply']
restart: unless-stopped
init: true
environment:
NODE_ENV: production
DATABASE_URL: postgresql://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-local_dev_password}@postgres:5432/${POSTGRES_DB:-chat}
DB_POOL_MAX: 2
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID: ${S3_RECONCILER_ACCESS_KEY_ID:-LABRECONCILER}
S3_SECRET_ACCESS_KEY: ${S3_RECONCILER_SECRET_ACCESS_KEY:-local_reconciler_storage_password}
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-600}
RECONCILE_INTERVAL_SECONDS: ${RECONCILE_INTERVAL_SECONDS:-60}
depends_on:
api:
condition: service_healthy
healthcheck:
test: ['CMD', 'node', 'dist/Attachment/reconcile-health.js']
interval: 10s
timeout: 5s
start_period: 30s
retries: 5
stop_grace_period: 30s
nginx:
image: nginx:1.30.6-alpine
restart: unless-stopped
ports:
- '127.0.0.1:${APP_PORT:-8080}:80'
- '127.0.0.1:${S3_PUBLIC_PORT:-9000}:9000'
volumes:
- ./infra/nginx.conf:/etc/nginx/nginx.conf:ro
- ./infra/start-nginx.sh:/etc/nginx/start-nginx.sh:ro
entrypoint: ['/bin/sh', '/etc/nginx/start-nginx.sh']
depends_on:
api:
condition: service_healthy
healthcheck:
test: ['CMD', 'wget', '-q', '-T', '2', '-t', '1', '-O', '/dev/null', 'http://127.0.0.1/health/ready']
interval: 5s
timeout: 3s
start_period: 10s
retries: 5
migrate:
build:
context: .
target: migrate
environment:
DATABASE_URL: postgresql://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-local_dev_password}@postgres:5432/${POSTGRES_DB:-chat}
depends_on:
postgres:
condition: service_healthy
postgres:
image: postgres:17.6-bookworm
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:-chat}
POSTGRES_USER: ${POSTGRES_USER:-app}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-local_dev_password}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"']
interval: 5s
timeout: 3s
start_period: 10s
retries: 10
stop_grace_period: 30s
redis:
image: redis:7.4.5-alpine
restart: unless-stopped
command:
['redis-server', '--appendonly', 'yes', '--appendfsync', 'everysec']
volumes:
- redis_data:/data
healthcheck:
test: ['CMD', 'redis-cli', 'ping']
interval: 5s
timeout: 3s
retries: 10
stop_grace_period: 30s
s3:
image: rustfs/rustfs:1.0.4
restart: unless-stopped
environment:
RUSTFS_ACCESS_KEY: ${S3_ROOT_ACCESS_KEY_ID:-${S3_ACCESS_KEY_ID:-LABSTORAGE}}
RUSTFS_SECRET_KEY: ${S3_ROOT_SECRET_ACCESS_KEY:-${S3_SECRET_ACCESS_KEY:-local_app_storage_password}}
RUSTFS_VOLUMES: /data
RUSTFS_ADDRESS: 0.0.0.0:9000
RUSTFS_CONSOLE_ENABLE: 'false'
volumes:
- s3_data:/data
healthcheck:
test: ['CMD', 'curl', '--fail', '--silent', 'http://127.0.0.1:9000/health']
interval: 5s
timeout: 3s
retries: 10
start_period: 30s
s3-init:
build:
context: .
target: storage-init
environment:
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID: ${S3_ROOT_ACCESS_KEY_ID:-${S3_ACCESS_KEY_ID:-LABSTORAGE}}
S3_SECRET_ACCESS_KEY: ${S3_ROOT_SECRET_ACCESS_KEY:-${S3_SECRET_ACCESS_KEY:-local_app_storage_password}}
S3_API_ACCESS_KEY_ID: ${S3_API_ACCESS_KEY_ID:-LABAPI}
S3_API_SECRET_ACCESS_KEY: ${S3_API_SECRET_ACCESS_KEY:-local_api_storage_password}
S3_RECONCILER_ACCESS_KEY_ID: ${S3_RECONCILER_ACCESS_KEY_ID:-LABRECONCILER}
S3_RECONCILER_SECRET_ACCESS_KEY: ${S3_RECONCILER_SECRET_ACCESS_KEY:-local_reconciler_storage_password}
depends_on:
s3:
condition: service_healthy
volumes:
postgres_data:
redis_data:
s3_data:
kafka_data:
+6
View File
@@ -54,8 +54,14 @@ Basic — это кодирование, не шифрование. HTTP lab1–
## Фоновая обработка (с lab5)
При заполнении общей очереди обычная загрузка и завершение прямой загрузки возвращают `429 rate_limited` с `Retry-After`. Лимит `ATTACHMENT_QUEUE_CAPACITY` учитывает вложения в `queued` и `processing`, включая ожидающие автоматического повтора.
До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно.
Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла.
В этой реализации worker записывает оригинал и все три варианта перед переходом в `ready`. Crop кодируется в JPEG с качеством 85 и белым фоном для прозрачных пикселей. Optimized кодируется в WebP с качеством 80 и effort 4, с сохранением прозрачности. Варианты учитывают EXIF-ориентацию и выходят без EXIF. Для вложений, обработанных до миграции вариантов, доступны ранее записанные объекты.
Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое.
В стенде lab5 PostgreSQL сохраняет вложение и задание в `attachment_outbox` одной транзакцией. После её фиксации обычный upload и факультативный direct-upload complete подтверждаются с 202. Задание отправляется в Kafka асинхронно. Повтор direct-upload complete возвращает исходный снимок приёма того же ID. Вложения, сохранённые до миграции lab5, доступны как `ready` с исходным набором вариантов.
+13 -1
View File
@@ -18,4 +18,16 @@
Staging не удаляется до безопасной публикации результатов. Неуспешные/непривязанные исходники имеют документированный retention и cleanup; он не удаляет текущую работу. Broker принимает только ID/служебные данные, не произвольный URL для скачивания и не путь из клиентского filename. Worker берёт доверенные storage metadata из БД.
Ack подтверждает устойчивую обработку, publisher confirm — приём брокером; это разные границы. См. [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability). At-least-once + идемпотентный эффект не означает exactly-once доставку.
## Реализация на Kafka
При создании вложения в `queued` или при ручном replay триггер PostgreSQL записывает задание в `attachment_outbox` в той же транзакции. После перезапуска API publisher снова подбирает сохранённые задания. Реплики делят работу через `FOR UPDATE SKIP LOCKED`.
В `attachments.process.v1` ключ записи равен `attachment_id`, а её значение — JSON по схеме. Для pipeline 1 идентификатор работы совпадает с идентификатором вложения. Publisher отправляет запись с `acks=-1`. После ответа брокера он удаляет соответствующую пару `attachment_id` и `generation` из outbox и фиксирует время публикации для текущего поколения. При потере подтверждения Kafka или сбое транзакции publisher повторно отправит задание с тем же ID и поколением.
Группа `attachment-worker-v1` фиксирует offset после `ready` или `failed`. Тот же offset удерживается при автоматических повторах. Поле `attempt` в записи Kafka равно 1, текущая попытка равна `failures + 1` в PostgreSQL. После временной ошибки worker сохраняет в PostgreSQL `next_attempt_at`. Пауза равномерно выбирается от нуля до растущего предела (1, 2, 4, 8 и далее до 30 секунд). При ожидании worker отправляет heartbeat. После потери worker незавершённый захват истекает через 120 секунд.
Реестр отказов использует строки `attachments` со статусом `failed`. Staging защищён от очистки 24 часа после отказа. Операторский replay под той же блокировкой, что и очистка, проверяет наличие staging и одной транзакцией меняет `failed` на `queued`, увеличивает `generation`, сбрасывает счётчик и возвращает вложение в outbox. Таблица `attachment_replays` хранит аудит и результат принятого запроса по паре `attachment_id` и `request_id`.
Повторная доставка завершённого задания и сообщений прежнего поколения подтверждается без обработки. Отсутствующий `generation` у ранее опубликованных сообщений читается как 0. У оригинала и всех вариантов стабильные ключи S3, а `job_id` и `pipeline_version` сохраняются при replay. Worker публикует `ready` и метаданные всех вариантов одной записью в PostgreSQL после сохранения оригинала, thumbnail, crop и optimized.
Общий дедлайн попытки охватывает чтение staging, преобразования и запись объектов. После дедлайна worker записывает `processing_timeout` и завершает процесс до подтверждения offset. Если процесс потерян до записи результата, по истечении аренды следующая доставка засчитывает прерванную попытку как `worker_interrupted`. Для обеих ошибок применяется общий бюджет автоматических повторов.
+11 -2
View File
@@ -35,14 +35,23 @@
"Redis Streams",
"Valkey Streams",
"NATS JetStream",
"Apache Kafka",
"documented durable equivalent"
],
"persistent_volume": true,
"delivery": "at-least-once"
"delivery": "at-least-once",
"implementation": {
"service": "kafka",
"mode": "KRaft",
"topic": "attachments.process.v1",
"volume": "kafka_data"
}
},
{
"role": "worker",
"separate_process": true
"separate_process": true,
"service": "worker",
"consumer_group": "attachment-worker-v1"
}
],
"optional_components": [
+9
View File
@@ -2,6 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:mtusi:messenger:attachment-job:v1",
"title": "Durable attachment processing job v1",
"description": "Kafka topic attachments.process.v1, key attachment_id. Each publication starts with attempt=1 and job_id=attachment_id. Managed retry state is stored in PostgreSQL while the consumer keeps the offset uncommitted. An explicit replay increments generation; absent generation means 0.",
"type": "object",
"additionalProperties": false,
"required": [
@@ -36,6 +37,13 @@
"type": "integer",
"minimum": 1
},
"generation": {
"type": "integer",
"minimum": 0,
"maximum": 2147483647,
"default": 0,
"description": "Replay generation. Automatic retries and broker redelivery retain the same generation."
},
"created_at": {
"type": "string",
"format": "date-time"
@@ -56,6 +64,7 @@
"type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222",
"pipeline_version": 1,
"generation": 0,
"attempt": 1,
"created_at": "2026-09-01T12:00:00Z"
}
+3 -1
View File
@@ -2150,9 +2150,10 @@
"post": {
"operationId": "uploadAttachment",
"summary": "Принять один PNG/JPEG, до 10 MiB",
"description": "До 202 файл полностью сохраняется в S3 staging, а задание фиксируется в PostgreSQL. Задание публикуется в Kafka асинхронно. Готовность проверяется по GET метаданных.",
"responses": {
"202": {
"description": "Успех",
"description": "Загрузка принята. Снимок Attachment содержит status=queued, variants=[] и error_code=null.",
"headers": {
"X-Request-Id": {
"description": "Непустой идентификатор запроса; обязателен во всех ответах.",
@@ -2684,6 +2685,7 @@
"get": {
"operationId": "downloadAttachment",
"summary": "Скачать байты через авторизованный API",
"description": "После обработки доступны побайтный original, JPEG thumbnail до 256×256, центральный JPEG crop 128×128 и WebP optimized до 1280×1280. Для queued, processing и failed возвращается 409. Для отсутствующего варианта готового вложения возвращается 404.",
"responses": {
"200": {
"description": "Успех",
+56
View File
@@ -0,0 +1,56 @@
events {}
http {
# Capabilities are query strings; never write signed URLs to access logs.
server {
listen 9000;
access_log off;
error_log /dev/null;
client_max_body_size 10m;
client_body_timeout 15s;
location ~ "^/messenger-attachments/staging/[0-9a-f-]{36}/[0-9a-f-]{36}$" {
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Methods 'PUT, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Content-Type, Content-Length, If-None-Match, x-amz-checksum-sha256' always;
add_header Access-Control-Expose-Headers 'ETag, x-amz-checksum-sha256' always;
if ($request_method = OPTIONS) { return 204; }
if ($request_method != PUT) { return 405; }
proxy_pass http://s3:9000;
proxy_request_buffering off;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header Connection '';
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Headers;
proxy_hide_header Access-Control-Allow-Methods;
proxy_connect_timeout 2s;
proxy_read_timeout 30s;
}
location / { return 403; }
}
upstream api {
least_conn;
zone api 64k;
include /etc/nginx/ready-upstreams.conf;
}
server {
listen 80;
client_max_body_size 11m;
location / {
proxy_pass http://api;
proxy_request_buffering off;
proxy_http_version 1.1;
# Preserve early 4xx responses while the client is still sending a body.
# The default Connection: close can make Node close before Nginx reads 413.
proxy_set_header Connection '';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 2s;
proxy_read_timeout 30s;
}
}
}
+98
View File
@@ -0,0 +1,98 @@
import { createHash, createHmac } from 'node:crypto';
const hash = (value) => createHash('sha256').update(value).digest('hex');
const hmac = (key, value) => createHmac('sha256', key).update(value).digest();
const encode = (value) =>
encodeURIComponent(value).replace(
/[!'()*]/g,
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
);
/** Sign RustFS native JSON admin requests; credentials and response bodies are never logged. */
export function signAdminRequest({
endpoint,
credentials,
region = 'us-east-1',
method,
operation,
query = {},
body,
now = new Date(),
}) {
const url = new URL(`/rustfs/admin/v3/${operation}`, endpoint);
const canonicalQuery = Object.entries(query)
.map(([key, value]) => [encode(key), encode(String(value))])
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, value]) => `${key}=${value}`)
.join('&');
url.search = canonicalQuery;
const payload = body === undefined ? '' : JSON.stringify(body);
const date = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
const headers = {
'content-type': 'application/json',
host: url.host,
'x-amz-content-sha256': hash(payload),
'x-amz-date': date,
};
const names = Object.keys(headers).sort();
const canonicalHeaders = names
.map((name) => `${name}:${headers[name]}\n`)
.join('');
const canonical = [
method,
url.pathname,
canonicalQuery,
canonicalHeaders,
names.join(';'),
hash(payload),
].join('\n');
const scope = `${date.slice(0, 8)}/${region}/s3/aws4_request`;
const stringToSign = ['AWS4-HMAC-SHA256', date, scope, hash(canonical)].join(
'\n',
);
const signingKey = hmac(
hmac(
hmac(
hmac(`AWS4${credentials.secretAccessKey}`, date.slice(0, 8)),
region,
),
's3',
),
'aws4_request',
);
const signature = createHmac('sha256', signingKey)
.update(stringToSign)
.digest('hex');
headers.authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`;
return {
url,
method,
headers,
body: body === undefined ? undefined : payload,
};
}
export async function adminRequest(config, method, operation, query, body) {
const request = signAdminRequest({
...config,
method,
operation,
query,
body,
});
const response = await fetch(request.url, {
...request,
signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) {
const code =
text.match(/<Code>([A-Za-z0-9_]+)<\/Code>/)?.[1] ?? 'AdminRequestFailed';
const error = new Error(
`RustFS admin ${operation}: HTTP ${response.status} ${code}`,
);
error.status = response.status;
throw error;
}
return text ? JSON.parse(text) : null;
}
+62
View File
@@ -0,0 +1,62 @@
import {
S3Client,
CreateBucketCommand,
HeadBucketCommand,
} from '@aws-sdk/client-s3';
import { adminRequest } from './admin.mjs';
import { bootstrapSettings, storagePolicies } from './policies.mjs';
const settings = bootstrapSettings();
const client = new S3Client({
endpoint: settings.endpoint,
region: settings.region,
forcePathStyle: true,
maxAttempts: 1,
credentials: settings.credentials,
});
const Bucket = settings.bucket;
try {
try {
await client.send(new HeadBucketCommand({ Bucket }), {
abortSignal: AbortSignal.timeout(30000),
});
} catch (error) {
if (error.$metadata?.httpStatusCode !== 404) throw error;
try {
await client.send(new CreateBucketCommand({ Bucket }), {
abortSignal: AbortSignal.timeout(30000),
});
} catch (error) {
if (error.name !== 'BucketAlreadyOwnedByYou') throw error;
}
}
const policies = storagePolicies(Bucket);
for (const role of ['api', 'reconciler']) {
const identity = settings[role];
const policyName = `${Bucket}-${role}`;
await adminRequest(
settings,
'PUT',
'add-canned-policy',
{ name: policyName },
policies[role],
);
await adminRequest(
settings,
'PUT',
'add-user',
{ accessKey: identity.accessKeyId },
{ secretKey: identity.secretAccessKey, status: 'enabled' },
);
// Replace the direct binding instead of accumulating old policies across bootstraps.
await adminRequest(settings, 'PUT', 'set-user-or-group-policy', {
policyName,
userOrGroup: identity.accessKeyId,
isGroup: false,
});
console.log(`Restricted S3 identity provisioned: ${role}`);
}
console.log('Private attachments bucket and restricted identities are ready');
} finally {
client.destroy();
}
+87
View File
@@ -0,0 +1,87 @@
export function storagePolicies(bucket) {
const bucketArn = `arn:aws:s3:::${bucket}`;
const objectsArn = `${bucketArn}/originals/*`;
const base = [
{
Effect: 'Allow',
Action: ['s3:GetBucketLocation'],
Resource: [bucketArn],
},
];
return {
api: {
Version: '2012-10-17',
Statement: [
...base,
{
Effect: 'Allow',
Action: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject'],
Resource: [objectsArn, `${bucketArn}/staging/*`, `${bucketArn}/variants/*`],
},
],
},
reconciler: {
Version: '2012-10-17',
Statement: [
...base,
{
Effect: 'Allow',
Action: ['s3:ListBucket'],
Resource: [bucketArn],
Condition: {
StringLike: { 's3:prefix': ['originals/*', 'staging/*'] },
},
},
{
Effect: 'Allow',
Action: ['s3:GetObject', 's3:DeleteObject'],
Resource: [objectsArn, `${bucketArn}/staging/*`],
},
],
},
};
}
export function bootstrapSettings(env = process.env) {
const settings = {
endpoint: env.S3_ENDPOINT ?? 'http://s3:9000',
region: env.S3_REGION ?? 'us-east-1',
bucket: env.S3_BUCKET ?? 'messenger-attachments',
credentials: {
accessKeyId: env.S3_ACCESS_KEY_ID,
secretAccessKey: env.S3_SECRET_ACCESS_KEY,
},
api: {
accessKeyId: env.S3_API_ACCESS_KEY_ID ?? 'LABAPI',
secretAccessKey:
env.S3_API_SECRET_ACCESS_KEY ?? 'local_api_storage_password',
},
reconciler: {
accessKeyId: env.S3_RECONCILER_ACCESS_KEY_ID ?? 'LABRECONCILER',
secretAccessKey:
env.S3_RECONCILER_SECRET_ACCESS_KEY ??
'local_reconciler_storage_password',
},
};
const identities = [settings.credentials, settings.api, settings.reconciler];
for (const identity of identities) {
if (
!identity.accessKeyId ||
!identity.secretAccessKey ||
identity.secretAccessKey.length < 8
) {
throw new Error(
'All S3 identities require an access key and a secret of at least 8 characters',
);
}
}
if (
new Set(identities.map((identity) => identity.accessKeyId)).size !== 3 ||
new Set(identities.map((identity) => identity.secretAccessKey)).size !== 3
) {
throw new Error(
'Root, API and reconciler identities must have distinct access and secret keys',
);
}
return settings;
}
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
set -eu
upstreams=/etc/nginx/ready-upstreams.conf
printf 'server 127.0.0.1:9 down;\n' > "$upstreams"
check_ready() {
state=/tmp/nginx-readiness.state
probes=/tmp/nginx-readiness-probes
mkdir -p "$probes"
: > "$state"
sleep 2
while :; do
next="${upstreams}.next"
previous="${upstreams}.previous"
: > "${state}.next"
printf 'server 127.0.0.1:9 down;\n' > "$next"
addresses=$(getent ahostsv4 api | awk '{print $1}' | sort -u)
for address in $addresses; do
(
if wget -q -T 1 -t 1 -O /dev/null "http://${address}:8080/health/ready"; then
printf '1\n'
else
printf '0\n'
fi > "$probes/$address"
) &
done
wait
for address in $addresses; do
record=$(awk -v address="$address" '$1 == address {print $2, $3, $4}' "$state")
set -- ${record:-0 0 0}
ready=$1
successes=$2
failures=$3
if [ "$(cat "$probes/$address")" = 1 ]; then
failures=0
if [ "$successes" -lt 2 ]; then successes=$((successes + 1)); fi
if [ "$successes" -ge 2 ]; then ready=1; fi
else
successes=0
if [ "$failures" -lt 2 ]; then failures=$((failures + 1)); fi
if [ "$failures" -ge 2 ]; then ready=0; fi
fi
printf '%s %s %s %s\n' "$address" "$ready" "$successes" "$failures" >> "${state}.next"
if [ "$ready" -eq 1 ]; then
printf 'server %s:8080 max_fails=2 fail_timeout=2s;\n' "$address" >> "$next"
fi
done
mv "${state}.next" "$state"
if cmp -s "$next" "$upstreams"; then
rm -f "$next"
else
cp "$upstreams" "$previous"
mv "$next" "$upstreams"
if nginx -t -q && nginx -s reload; then
rm -f "$previous"
else
mv "$previous" "$upstreams"
printf 'Could not reload Nginx readiness upstreams\n' >&2
fi
fi
sleep 2
done
}
check_ready &
exec nginx -g 'daemon off;'
+31
View File
@@ -0,0 +1,31 @@
import type { Config } from 'jest';
import { pathsToModuleNameMapper } from 'ts-jest';
import ts from 'typescript';
const { config: tsconfig } = ts.readConfigFile(
'./tsconfig.json',
ts.sys.readFile,
);
const paths = tsconfig?.compilerOptions?.paths ?? {};
const config: Config = {
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: '.',
testRegex: '.*\\.spec\\.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
moduleNameMapper: {
...pathsToModuleNameMapper(paths, { prefix: '<rootDir>/' }),
'^(\\.{1,2}/.*)\\.js$': '$1',
},
collectCoverageFrom: [
'src/**/*.(t|j)s',
'libs/**/*.(t|j)s',
'apps/**/*.(t|j)s',
],
coverageDirectory: './coverage',
testEnvironment: 'node',
};
export default config;
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
+74
View File
@@ -0,0 +1,74 @@
{
"name": "mtusi2026lab4",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"db:generate": "prisma generate",
"db:validate": "prisma validate",
"db:migrate": "prisma migrate dev",
"db:deploy": "prisma migrate deploy",
"prebuild": "pnpm db:generate",
"prestart:dev": "pnpm db:generate",
"prestart": "pnpm db:generate",
"pretest": "pnpm db:generate",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "oxlint --type-aware src/",
"test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js",
"test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --watch",
"test:cov": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --coverage",
"test:debug": "node --inspect-brk --experimental-vm-modules -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1164.0",
"@aws-sdk/s3-request-presigner": "^3.1165.0",
"@fastify/static": "^10.1.4",
"@nestjs/common": "^12.0.1",
"@nestjs/core": "^12.0.1",
"@nestjs/platform-fastify": "12.0.1",
"@nestjs/swagger": "^12.0.1",
"@prisma/adapter-pg": "^7.10.0",
"@prisma/client": "^7.10.0",
"@scalar/nestjs-api-reference": "^1.2.19",
"dotenv": "^18.0.7",
"fastify": "5.12.1",
"ioredis": "^6.0.0",
"kafkajs": "2.2.4",
"nestjs-pino": "^5.2.0",
"pg": "^8.23.1",
"pino-http": "^11.0.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sharp": "^0.35.5"
},
"devDependencies": {
"@nestjs/cli": "^12.0.0",
"@nestjs/mau": "^0.2.6",
"@nestjs/schematics": "^12.0.0",
"@nestjs/testing": "^12.0.1",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.0",
"@types/pg": "^8.23.1",
"@types/supertest": "^7.0.0",
"jest": "^30.0.0",
"oxlint": "^1.58.0",
"oxlint-tsgolint": "^7.0.2001",
"pino-pretty": "^13.1.3",
"prettier": "^3.4.2",
"prisma": "7.10.0",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.4.0",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^6.0.2"
}
}
+8376
View File
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
import 'dotenv/config';
import { defineConfig } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
datasource: { url: process.env.DATABASE_URL },
});
@@ -0,0 +1,56 @@
CREATE SCHEMA IF NOT EXISTS "public";
CREATE TABLE "users" (
"id" UUID NOT NULL,
"username" VARCHAR(32) NOT NULL,
"display_name" VARCHAR(100) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "chats" (
"id" UUID NOT NULL,
"title" VARCHAR(100) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "chats_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "chat_members" (
"chat_id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"position" INTEGER NOT NULL,
CONSTRAINT "chat_members_pkey" PRIMARY KEY ("chat_id","user_id")
);
CREATE TABLE "messages" (
"id" UUID NOT NULL,
"chat_id" UUID NOT NULL,
"sender_id" UUID NOT NULL,
"text" VARCHAR(4000) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "messages_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");
CREATE INDEX "chats_created_at_id_idx" ON "chats"("created_at", "id");
CREATE INDEX "chat_members_user_id_chat_id_idx" ON "chat_members"("user_id", "chat_id");
CREATE UNIQUE INDEX "chat_members_chat_id_position_key" ON "chat_members"("chat_id", "position");
CREATE INDEX "messages_chat_id_created_at_id_idx" ON "messages"("chat_id", "created_at", "id");
CREATE INDEX "messages_sender_id_idx" ON "messages"("sender_id");
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "messages" ADD CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY ("sender_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,20 @@
ALTER TABLE "users" ADD COLUMN "password_hash" TEXT;
CREATE TABLE "sessions" (
"id" UUID NOT NULL,
"user_id" UUID NOT NULL,
"token_hash" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMPTZ(3) NOT NULL,
"revoked_at" TIMESTAMPTZ(3),
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "sessions_token_hash_key" ON "sessions"("token_hash");
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
CREATE INDEX "sessions_expires_at_idx" ON "sessions"("expires_at");
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
ALTER TABLE "users" ADD COLUMN "chats_epoch" BIGINT NOT NULL DEFAULT 0;
ALTER TABLE "chats" ADD COLUMN "messages_epoch" BIGINT NOT NULL DEFAULT 0;
@@ -0,0 +1,13 @@
CREATE TABLE "chat_message_epochs" (
"chat_id" UUID NOT NULL,
"bucket" SMALLINT NOT NULL,
"epoch" BIGINT NOT NULL DEFAULT 0,
CONSTRAINT "chat_message_epochs_pkey" PRIMARY KEY ("chat_id", "bucket"),
CONSTRAINT "chat_message_epochs_bucket_check" CHECK ("bucket" BETWEEN 0 AND 15),
CONSTRAINT "chat_message_epochs_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "chat_message_epochs" ("chat_id", "bucket", "epoch")
SELECT "id", 0, "messages_epoch" FROM "chats";
ALTER TABLE "chats" DROP COLUMN "messages_epoch";
@@ -0,0 +1,15 @@
CREATE TABLE "message_idempotency" (
"user_id" UUID NOT NULL,
"chat_id" UUID NOT NULL,
"key" VARCHAR(128) NOT NULL,
"message_id" UUID,
"expires_at" TIMESTAMPTZ(3) NOT NULL,
CONSTRAINT "message_idempotency_pkey" PRIMARY KEY ("user_id", "chat_id", "key"),
CONSTRAINT "message_idempotency_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "message_idempotency_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "message_idempotency_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX "message_idempotency_expires_at_idx" ON "message_idempotency"("expires_at");
CREATE INDEX "message_idempotency_chat_id_idx" ON "message_idempotency"("chat_id");
CREATE INDEX "message_idempotency_message_id_idx" ON "message_idempotency"("message_id");
@@ -0,0 +1,20 @@
ALTER TABLE "messages" ADD COLUMN "attachment_ids" UUID[] NOT NULL DEFAULT ARRAY[]::UUID[];
CREATE TABLE "attachments" (
"id" UUID NOT NULL,
"chat_id" UUID NOT NULL,
"owner_id" UUID NOT NULL,
"object_key" TEXT NOT NULL,
"filename" VARCHAR(255) NOT NULL,
"content_type" VARCHAR(32) NOT NULL,
"size_bytes" INTEGER NOT NULL CHECK ("size_bytes" BETWEEN 1 AND 10485760),
"sha256" CHAR(64) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "attachments_pkey" PRIMARY KEY ("id"),
CONSTRAINT "attachments_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "attachments_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE UNIQUE INDEX "attachments_object_key_key" ON "attachments"("object_key");
CREATE INDEX "attachments_chat_id_idx" ON "attachments"("chat_id");
CREATE INDEX "attachments_owner_id_idx" ON "attachments"("owner_id");
@@ -0,0 +1,20 @@
CREATE TYPE "direct_upload_status" AS ENUM ('pending', 'completed', 'rejected', 'expired');
CREATE TABLE "direct_uploads" (
"id" UUID NOT NULL,
"chat_id" UUID NOT NULL,
"owner_id" UUID NOT NULL,
"filename" VARCHAR(255) NOT NULL,
"content_type" VARCHAR(32) NOT NULL,
"size_bytes" INTEGER NOT NULL,
"sha256" CHAR(64) NOT NULL,
"status" "direct_upload_status" NOT NULL DEFAULT 'pending',
"expires_at" TIMESTAMPTZ(3) NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "direct_uploads_pkey" PRIMARY KEY ("id"),
CONSTRAINT "direct_uploads_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "direct_uploads_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "direct_uploads_size_check" CHECK ("size_bytes" BETWEEN 1 AND 10485760)
);
CREATE INDEX "direct_uploads_status_expires_at_idx" ON "direct_uploads"("status", "expires_at");
CREATE INDEX "direct_uploads_chat_id_idx" ON "direct_uploads"("chat_id");
CREATE INDEX "direct_uploads_owner_id_idx" ON "direct_uploads"("owner_id");
@@ -0,0 +1,15 @@
CREATE TYPE "attachment_status" AS ENUM ('queued', 'processing', 'ready', 'failed');
ALTER TABLE "attachments"
ADD COLUMN "status" "attachment_status" NOT NULL DEFAULT 'ready',
ADD COLUMN "error_code" TEXT,
ADD COLUMN "thumbnail_size" INTEGER,
ADD COLUMN "thumbnail_width" INTEGER,
ADD COLUMN "thumbnail_height" INTEGER,
ADD COLUMN "thumbnail_sha256" CHAR(64),
ADD COLUMN "published_at" TIMESTAMPTZ(3),
ADD COLUMN "lease_until" TIMESTAMPTZ(3),
ADD COLUMN "failures" INTEGER NOT NULL DEFAULT 0;
CREATE INDEX "attachments_pending_publish_idx" ON "attachments" ("created_at", "id")
WHERE "published_at" IS NULL AND "status" = 'queued';
@@ -0,0 +1,23 @@
ALTER TABLE "attachments"
ADD COLUMN "next_attempt_at" TIMESTAMPTZ(3),
ADD COLUMN "failed_at" TIMESTAMPTZ(3),
ADD COLUMN "replay_until" TIMESTAMPTZ(3),
ADD COLUMN "generation" INTEGER NOT NULL DEFAULT 0;
UPDATE "attachments"
SET "failed_at" = "updated_at",
"replay_until" = "updated_at" + INTERVAL '24 hours'
WHERE "status" = 'failed';
CREATE INDEX "attachments_status_failed_at_id_idx" ON "attachments" ("status", "failed_at", "id");
CREATE TABLE "attachment_replays" (
"attachment_id" UUID NOT NULL REFERENCES "attachments" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
"request_id" UUID NOT NULL,
"operator" VARCHAR(128) NOT NULL,
"generation" INTEGER NOT NULL,
"error_code" TEXT,
"failures" INTEGER NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ("attachment_id", "request_id")
);
@@ -0,0 +1,7 @@
ALTER TABLE "attachments"
ADD COLUMN "crop_size" INTEGER,
ADD COLUMN "crop_sha256" CHAR(64),
ADD COLUMN "optimized_size" INTEGER,
ADD COLUMN "optimized_width" INTEGER,
ADD COLUMN "optimized_height" INTEGER,
ADD COLUMN "optimized_sha256" CHAR(64);
@@ -0,0 +1,35 @@
BEGIN;
CREATE TABLE "attachment_outbox" (
"attachment_id" UUID NOT NULL REFERENCES "attachments" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
"generation" INTEGER NOT NULL,
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ("attachment_id", "generation")
);
CREATE INDEX "attachment_outbox_created_at_attachment_id_generation_idx"
ON "attachment_outbox" ("created_at", "attachment_id", "generation");
-- Insertion and explicit replay both enqueue work in the surrounding transaction.
CREATE FUNCTION enqueue_attachment_outbox() RETURNS TRIGGER
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.status = 'queued' AND (TG_OP = 'INSERT' OR NEW.generation IS DISTINCT FROM OLD.generation) THEN
INSERT INTO attachment_outbox (attachment_id, generation)
VALUES (NEW.id, NEW.generation);
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER attachment_outbox_enqueue
AFTER INSERT OR UPDATE OF generation ON "attachments"
FOR EACH ROW EXECUTE FUNCTION enqueue_attachment_outbox();
INSERT INTO "attachment_outbox" ("attachment_id", "generation", "created_at")
SELECT "id", "generation", "created_at" FROM "attachments"
WHERE "status" = 'queued' AND "published_at" IS NULL;
DROP INDEX "attachments_pending_publish_idx";
COMMIT;
+1
View File
@@ -0,0 +1 @@
provider = "postgresql"
+215
View File
@@ -0,0 +1,215 @@
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
moduleFormat = "cjs"
}
datasource db {
provider = "postgresql"
}
model User {
id String @id @default(uuid()) @db.Uuid
username String @unique @db.VarChar(32)
displayName String @map("display_name") @db.VarChar(100)
passwordHash String? @map("password_hash")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
chatsEpoch BigInt @default(0) @map("chats_epoch")
memberships ChatMember[]
messages Message[]
sessions Session[]
idempotencyRecords MessageIdempotency[]
attachments Attachment[]
directUploads DirectUpload[]
@@map("users")
}
model Session {
id String @id @default(uuid()) @db.Uuid
userId String @map("user_id") @db.Uuid
tokenHash String @unique @map("token_hash") @db.Char(64)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
revokedAt DateTime? @map("revoked_at") @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([expiresAt])
@@map("sessions")
}
model Chat {
id String @id @default(uuid()) @db.Uuid
title String @db.VarChar(100)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
messageEpochs ChatMessageEpoch[]
members ChatMember[]
messages Message[]
idempotencyRecords MessageIdempotency[]
attachments Attachment[]
directUploads DirectUpload[]
@@index([createdAt, id])
@@map("chats")
}
model ChatMember {
chatId String @map("chat_id") @db.Uuid
userId String @map("user_id") @db.Uuid
position Int
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
@@id([chatId, userId])
@@unique([chatId, position])
@@index([userId, chatId])
@@map("chat_members")
}
model ChatMessageEpoch {
chatId String @map("chat_id") @db.Uuid
bucket Int @db.SmallInt
epoch BigInt @default(0)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
@@id([chatId, bucket])
@@map("chat_message_epochs")
}
model Message {
id String @id @default(uuid()) @db.Uuid
chatId String @map("chat_id") @db.Uuid
senderId String @map("sender_id") @db.Uuid
text String @db.VarChar(4000)
attachmentIds String[] @default([]) @map("attachment_ids") @db.Uuid
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
sender User @relation(fields: [senderId], references: [id], onDelete: Restrict)
idempotencyRecords MessageIdempotency[]
@@index([chatId, createdAt, id])
@@index([senderId])
@@map("messages")
}
enum AttachmentStatus {
queued
processing
ready
failed
@@map("attachment_status")
}
model Attachment {
id String @id @default(uuid()) @db.Uuid
chatId String @map("chat_id") @db.Uuid
ownerId String @map("owner_id") @db.Uuid
objectKey String @unique @map("object_key")
filename String @db.VarChar(255)
contentType String @map("content_type") @db.VarChar(32)
sizeBytes Int @map("size_bytes")
sha256 String @db.Char(64)
status AttachmentStatus @default(ready)
errorCode String? @map("error_code")
thumbnailSize Int? @map("thumbnail_size")
thumbnailWidth Int? @map("thumbnail_width")
thumbnailHeight Int? @map("thumbnail_height")
thumbnailSha256 String? @map("thumbnail_sha256") @db.Char(64)
cropSize Int? @map("crop_size")
cropSha256 String? @map("crop_sha256") @db.Char(64)
optimizedSize Int? @map("optimized_size")
optimizedWidth Int? @map("optimized_width")
optimizedHeight Int? @map("optimized_height")
optimizedSha256 String? @map("optimized_sha256") @db.Char(64)
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
leaseUntil DateTime? @map("lease_until") @db.Timestamptz(3)
nextAttemptAt DateTime? @map("next_attempt_at") @db.Timestamptz(3)
failedAt DateTime? @map("failed_at") @db.Timestamptz(3)
replayUntil DateTime? @map("replay_until") @db.Timestamptz(3)
generation Int @default(0)
failures Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Restrict)
owner User @relation(fields: [ownerId], references: [id], onDelete: Restrict)
replays AttachmentReplay[]
outbox AttachmentOutbox[]
@@index([chatId])
@@index([ownerId])
@@index([status, failedAt, id])
@@map("attachments")
}
model AttachmentOutbox {
attachmentId String @map("attachment_id") @db.Uuid
generation Int
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
attachment Attachment @relation(fields: [attachmentId], references: [id], onDelete: Restrict)
@@id([attachmentId, generation])
@@index([createdAt, attachmentId, generation])
@@map("attachment_outbox")
}
model AttachmentReplay {
attachmentId String @map("attachment_id") @db.Uuid
requestId String @map("request_id") @db.Uuid
operator String @db.VarChar(128)
generation Int
errorCode String? @map("error_code")
failures Int
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
attachment Attachment @relation(fields: [attachmentId], references: [id], onDelete: Restrict)
@@id([attachmentId, requestId])
@@map("attachment_replays")
}
enum DirectUploadStatus {
pending
completed
rejected
expired
@@map("direct_upload_status")
}
model DirectUpload {
id String @id @default(uuid()) @db.Uuid
chatId String @map("chat_id") @db.Uuid
ownerId String @map("owner_id") @db.Uuid
filename String @db.VarChar(255)
contentType String @map("content_type") @db.VarChar(32)
sizeBytes Int @map("size_bytes")
sha256 String @db.Char(64)
status DirectUploadStatus @default(pending)
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Restrict)
owner User @relation(fields: [ownerId], references: [id], onDelete: Restrict)
@@index([status, expiresAt])
@@index([chatId])
@@index([ownerId])
@@map("direct_uploads")
}
model MessageIdempotency {
userId String @map("user_id") @db.Uuid
chatId String @map("chat_id") @db.Uuid
key String @db.VarChar(128)
messageId String? @map("message_id") @db.Uuid
expiresAt DateTime @map("expires_at") @db.Timestamptz(3)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade)
message Message? @relation(fields: [messageId], references: [id], onDelete: Cascade)
@@id([userId, chatId, key])
@@index([chatId])
@@index([messageId])
@@index([expiresAt])
@@map("message_idempotency")
}
+10
View File
@@ -0,0 +1,10 @@
@echo off
setlocal
if defined GIT_BASH goto run
set "GIT_BASH=%ProgramFiles%\Git\bin\bash.exe"
if exist "%GIT_BASH%" goto run
echo Git Bash was not found. Set GIT_BASH to the full path to bash.exe. 1>&2
exit /b 2
:run
"%GIT_BASH%" "%~dp0restart.sh"
exit /b %ERRORLEVEL%
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
project_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_dir"
for service in api nginx reconciler worker postgres redis s3 kafka; do
if [ -z "$(docker compose ps --all --quiet "$service")" ]; then
printf '%s\n' "Missing container for $service; start the Compose stack first." >&2
exit 1
fi
done
replicas=$(docker compose ps --all --quiet api | wc -l | tr -d ' ')
if [ "$replicas" -lt 1 ]; then
printf 'No API replicas found.\n' >&2
exit 1
fi
docker compose stop nginx reconciler api worker postgres redis s3 kafka
docker compose up --detach --no-recreate --no-build --no-deps --wait --wait-timeout 60 postgres redis s3 kafka
docker compose up --detach --no-recreate --no-build --no-deps --scale "api=$replicas" --wait --wait-timeout 45 api
docker compose up --detach --no-recreate --no-build --no-deps --wait --wait-timeout 30 nginx reconciler worker
+33
View File
@@ -0,0 +1,33 @@
@echo off
setlocal EnableDelayedExpansion
cd /d "%~dp0.."
if not defined TARGET_INSTANCE_ID (
echo TARGET_INSTANCE_ID is required 1>&2
exit /b 2
)
set "containers="
for /f "delims=" %%C in ('docker compose ps --all --quiet api') do (
set "containers=!containers! %%C"
set "candidate=%%C"
rem This Compose uses Docker's default hostname: the first 12 container-ID characters.
if "!candidate:~0,12!"=="%TARGET_INSTANCE_ID%" (
docker stop --time 0 %%C >nul
if errorlevel 1 exit /b 1
exit /b 0
)
)
if not defined containers (
echo No API containers found 1>&2
exit /b 2
)
rem Fallback for explicitly configured hostnames, still scoped to this project's API containers.
for /f "tokens=1,2 delims=:" %%H in ('docker inspect --format "{{.Config.Hostname}}:{{.Id}}" !containers!') do (
if "%%H"=="%TARGET_INSTANCE_ID%" (
rem Failure injection: stop immediately, leaving time for recovery within the 10-second test budget.
docker stop --time 0 %%I >nul
if errorlevel 1 exit /b 1
exit /b 0
)
)
echo No API container matches X-Instance-Id 1>&2
exit /b 2
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
set -eu
project_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_dir"
target=${TARGET_INSTANCE_ID:?test provides target API instance ID}
containers=$(docker compose ps --all --quiet api)
if [ -z "$containers" ]; then
printf 'No API containers found\n' >&2
exit 2
fi
for entry in $(docker inspect --format '{{.Config.Hostname}}:{{.Id}}' $containers); do
instance=${entry%%:*}
container=${entry#*:}
if [ "$instance" = "$target" ]; then
docker stop --time 8 "$container" >/dev/null
exit 0
fi
done
printf 'No API container matches X-Instance-Id\n' >&2
exit 2
+1
View File
@@ -0,0 +1 @@
/generated/
+20
View File
@@ -0,0 +1,20 @@
import type { Prisma } from '../generated/prisma/client';
import { ApiException } from '../common/exceptions/api.exception';
const capacity = Number(process.env.ATTACHMENT_QUEUE_CAPACITY ?? 64);
if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 10000)
throw new Error('ATTACHMENT_QUEUE_CAPACITY must be between 1 and 10000');
export async function hasAttachmentCapacity(tx: Prisma.TransactionClient) {
// All producers share the lock. The subsequent statement sees the last admission's commit.
await tx.$queryRaw`SELECT 1 FROM pg_advisory_xact_lock(hashtextextended('attachment-admission', 0))`;
const active = await tx.attachment.count({
where: { status: { in: ['queued', 'processing'] } },
});
return active < capacity;
}
export async function assertAttachmentCapacity(tx: Prisma.TransactionClient) {
if (!(await hasAttachmentCapacity(tx)))
throw new ApiException(429, 'rate_limited', 'Очередь вложений заполнена');
}
+58
View File
@@ -0,0 +1,58 @@
import { Kafka } from 'kafkajs';
import { uuidPattern } from '../common/validation';
export const ATTACHMENT_TOPIC = 'attachments.process.v1';
export const ATTACHMENT_GROUP = 'attachment-worker-v1';
export function attachmentKafka(clientId: string) {
return new Kafka({
clientId,
brokers: (process.env.KAFKA_BROKERS ?? 'kafka:9092')
.split(',')
.map((broker) => broker.trim()),
connectionTimeout: 3000,
requestTimeout: 5000,
retry: { retries: 1 },
});
}
export function firstJob(id: string, createdAt: Date, generation: number) {
return {
schema_version: 1,
job_id: id,
type: 'attachment.process.v1',
attachment_id: id,
pipeline_version: 1,
generation,
attempt: 1,
created_at: createdAt.toISOString(),
} as const;
}
export function parseAttachmentJob(value: Buffer | null, key: Buffer | null) {
if (!value || !key) return null;
try {
const job = JSON.parse(value.toString()) as Partial<
ReturnType<typeof firstJob>
> | null;
const generation = job?.generation === undefined ? 0 : job.generation;
if (
job?.schema_version === 1 &&
job.type === 'attachment.process.v1' &&
job.pipeline_version === 1 &&
job.attempt === 1 &&
Number.isSafeInteger(generation) &&
generation >= 0 &&
generation <= 2147483647 &&
typeof job.attachment_id === 'string' &&
uuidPattern.test(job.attachment_id) &&
job.job_id === job.attachment_id &&
key.toString() === job.attachment_id
) {
return { id: job.attachment_id, generation };
}
} catch {
return null;
}
return null;
}
+27
View File
@@ -0,0 +1,27 @@
type AttachmentIdentity = { chatId: string; id: string };
export const CROP_SIZE = 128;
export const variantFormats = {
thumbnail: { extension: 'jpg', contentType: 'image/jpeg' },
crop: { extension: 'jpg', contentType: 'image/jpeg' },
optimized: { extension: 'webp', contentType: 'image/webp' },
} as const;
export type AttachmentVariantName = keyof typeof variantFormats;
export function isAttachmentVariant(
value: unknown,
): value is AttachmentVariantName {
return typeof value === 'string' && Object.hasOwn(variantFormats, value);
}
export function stagingKeyFor({ chatId, id }: AttachmentIdentity) {
return `staging/${chatId}/${id}`;
}
export function variantKeyFor(
{ chatId, id }: AttachmentIdentity,
name: AttachmentVariantName,
) {
return `variants/${chatId}/${id}/v1/${name}.${variantFormats[name].extension}`;
}
@@ -0,0 +1,77 @@
import { randomUUID } from 'node:crypto';
import type { PrismaService } from '../prisma/prisma.service';
import { ATTACHMENT_TOPIC, firstJob } from './attachment-kafka';
import { publishAttachmentOutboxBatch } from './attachment-publisher';
function fixture() {
const attachmentId = randomUUID();
const createdAt = new Date('2026-11-24T10:00:00Z');
const generation = 2;
const tx = {
$queryRaw: jest
.fn()
.mockResolvedValue([{ attachmentId, createdAt, generation }]),
$executeRaw: jest.fn(),
};
const db = {
$transaction: jest.fn(
async (callback: (value: typeof tx) => Promise<boolean>) => callback(tx),
),
};
const producer = { send: jest.fn().mockResolvedValue([]) };
return {
attachmentId,
createdAt,
generation,
tx,
producer,
publish: () =>
publishAttachmentOutboxBatch(db as unknown as PrismaService, producer),
};
}
describe('attachment outbox publisher', () => {
it('acknowledges the selected generation only after Kafka confirms', async () => {
const f = fixture();
let acknowledge!: (value: []) => void;
const confirmation = new Promise<[]>((resolve) => {
acknowledge = resolve;
});
f.producer.send.mockReturnValueOnce(confirmation);
const publishing = f.publish();
await Promise.resolve();
expect(f.producer.send).toHaveBeenCalledWith({
topic: ATTACHMENT_TOPIC,
acks: -1,
timeout: 5000,
messages: [
{
key: f.attachmentId,
value: JSON.stringify(
firstJob(f.attachmentId, f.createdAt, f.generation),
),
},
],
});
expect(f.tx.$executeRaw).not.toHaveBeenCalled();
acknowledge([]);
await expect(publishing).resolves.toBe(true);
expect(f.tx.$executeRaw).toHaveBeenCalledWith(
expect.objectContaining({
values: [f.attachmentId, f.generation],
}),
);
});
it('leaves the job pending after broker failure and republishes the same record', async () => {
const f = fixture();
f.producer.send.mockRejectedValueOnce(new Error('broker unavailable'));
await expect(f.publish()).rejects.toThrow('broker unavailable');
expect(f.tx.$executeRaw).not.toHaveBeenCalled();
await expect(f.publish()).resolves.toBe(true);
expect(f.producer.send.mock.calls[1]).toEqual(
f.producer.send.mock.calls[0],
);
expect(f.tx.$executeRaw).toHaveBeenCalledTimes(1);
});
});
+107
View File
@@ -0,0 +1,107 @@
import {
Injectable,
Logger,
type OnApplicationBootstrap,
type OnModuleDestroy,
} from '@nestjs/common';
import { setTimeout as delay } from 'node:timers/promises';
import type { Producer } from 'kafkajs';
import { Prisma } from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import {
ATTACHMENT_TOPIC,
attachmentKafka,
firstJob,
} from './attachment-kafka';
export function publishAttachmentOutboxBatch(
db: PrismaService,
producer: Pick<Producer, 'send'>,
) {
return db.$transaction(
async (tx) => {
const jobs = await tx.$queryRaw<
{ attachmentId: string; createdAt: Date; generation: number }[]
>`
SELECT attachment_id AS "attachmentId", generation, created_at AS "createdAt"
FROM attachment_outbox
ORDER BY created_at, attachment_id, generation
LIMIT 20 FOR UPDATE SKIP LOCKED
`;
if (!jobs.length) return false;
await producer.send({
topic: ATTACHMENT_TOPIC,
acks: -1,
timeout: 5000,
messages: jobs.map(({ attachmentId, createdAt, generation }) => ({
key: attachmentId,
value: JSON.stringify(firstJob(attachmentId, createdAt, generation)),
})),
});
const keys = jobs.map(
({ attachmentId, generation }) =>
Prisma.sql`(${attachmentId}::uuid, ${generation}::integer)`,
);
await tx.$executeRaw(Prisma.sql`
WITH published AS (
DELETE FROM attachment_outbox
WHERE (attachment_id, generation) IN (${Prisma.join(keys)})
RETURNING attachment_id, generation
)
UPDATE attachments AS a SET published_at = now()
FROM published AS p
WHERE a.id = p.attachment_id AND a.generation = p.generation
`);
return true;
},
{ timeout: 20000 },
);
}
@Injectable()
export class AttachmentPublisher
implements OnApplicationBootstrap, OnModuleDestroy
{
private readonly logger = new Logger(AttachmentPublisher.name);
private readonly producer = attachmentKafka('attachment-api').producer({
allowAutoTopicCreation: false,
});
private readonly stop = new AbortController();
private loop?: Promise<void>;
private connected = false;
constructor(private readonly db: PrismaService) {}
onApplicationBootstrap() {
this.loop = this.publishPending();
}
async onModuleDestroy() {
this.stop.abort();
await this.loop;
await this.producer.disconnect();
}
private async publishPending() {
while (!this.stop.signal.aborted) {
try {
if (!this.connected) {
await this.producer.connect();
this.connected = true;
}
if (await publishAttachmentOutboxBatch(this.db, this.producer))
continue;
} catch {
if (!this.stop.signal.aborted)
this.logger.warn(
'Kafka publication deferred; attachment jobs remain in PostgreSQL',
);
}
await delay(1000, undefined, { signal: this.stop.signal }).catch(
() => {},
);
}
}
}
+56
View File
@@ -0,0 +1,56 @@
import 'reflect-metadata';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../Storage/storage.service';
import { uuidPattern } from '../common/validation';
import { listFailedAttachments, replayAttachment } from './attachment-replay';
async function main(args: string[]) {
const [command, id, requestId, operator] = args;
const list = command === 'list' && args.length === 1;
const replay =
command === 'replay' &&
args.length === 4 &&
uuidPattern.test(id) &&
uuidPattern.test(requestId) &&
operator.trim().length > 0 &&
Array.from(operator).length <= 128;
if (!list && !replay) {
console.error(
'Usage: attachment-replay.cli.js list | replay <attachment-id> <request-id> <operator>',
);
process.exitCode = 2;
return;
}
const db = new PrismaService();
const storage = replay ? new StorageService() : undefined;
try {
await db.$connect();
if (storage) {
const result = await replayAttachment(
db,
storage,
id.toLowerCase(),
requestId.toLowerCase(),
operator.trim(),
);
console.log(JSON.stringify(result));
if (result.status !== 'queued' && result.status !== 'ready')
process.exitCode = 2;
} else {
console.log(JSON.stringify(await listFailedAttachments(db)));
}
} finally {
storage?.onModuleDestroy();
await db.$disconnect();
}
}
void main(process.argv.slice(2)).catch((error: unknown) => {
console.error(
JSON.stringify({
event: 'attachment_operator_command_failed',
errorType: error instanceof Error ? error.name : 'UnknownError',
}),
);
process.exitCode = 1;
});
+115
View File
@@ -0,0 +1,115 @@
import { randomUUID } from 'node:crypto';
import type { Attachment } from '../generated/prisma/client';
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import { firstJob, parseAttachmentJob } from './attachment-kafka';
import { replayAttachment } from './attachment-replay';
function fixture() {
const id = randomUUID();
const requestId = randomUUID();
const attachment = {
id,
chatId: randomUUID(),
status: 'failed',
failures: 5,
generation: 0,
errorCode: 'retry_exhausted',
replayUntil: new Date(Date.now() + 60000),
} satisfies Partial<Attachment>;
const tx = {
$executeRaw: jest.fn(),
$queryRaw: jest.fn().mockResolvedValue([{ locked: true }]),
attachment: {
count: jest.fn().mockResolvedValue(0),
findUnique: jest.fn(async () => ({ ...attachment })),
update: jest.fn(({ data }: { data: Partial<Attachment> }) =>
Object.assign(attachment, data),
),
},
attachmentReplay: {
findUnique: jest.fn(),
create: jest.fn(({ data }: { data: object }) => {
tx.attachmentReplay.findUnique.mockResolvedValue(data);
}),
},
};
const db = {
attachment: tx.attachment,
$transaction: jest.fn(async (fn: (value: typeof tx) => Promise<unknown>) =>
fn(tx),
),
};
const storage = { stat: jest.fn().mockResolvedValue({ key: 'staged' }) };
const replay = (operator = 'operator') =>
replayAttachment(
db as unknown as PrismaService,
storage as unknown as StorageService,
id,
requestId,
operator,
);
return { id, requestId, attachment, tx, storage, replay };
}
describe('attachment replay', () => {
it('requeues once and returns the audited result even after another failure', async () => {
const f = fixture();
const result = { status: 'queued', generation: 1 };
await expect(f.replay()).resolves.toEqual(result);
expect(f.attachment).toMatchObject({
...result,
failures: 0,
publishedAt: null,
nextAttemptAt: null,
});
expect(f.tx.attachmentReplay.create).toHaveBeenCalledWith({
data: {
attachmentId: f.id,
requestId: f.requestId,
generation: 1,
operator: 'operator',
errorCode: 'retry_exhausted',
failures: 5,
},
});
Object.assign(f.attachment, { status: 'failed', failures: 5 });
await expect(f.replay()).resolves.toEqual(result);
await expect(f.replay('other')).resolves.toEqual({
status: 'request_conflict',
});
expect(f.tx.attachment.update).toHaveBeenCalledTimes(1);
expect(f.storage.stat).toHaveBeenCalledTimes(1);
});
it('leaves the attachment unchanged if replay expired, staging is absent or it is already ready', async () => {
const f = fixture();
f.attachment.replayUntil = new Date(0);
await expect(f.replay()).resolves.toEqual({ status: 'replay_expired' });
expect(f.storage.stat).not.toHaveBeenCalled();
f.attachment.replayUntil = new Date(Date.now() + 60000);
f.storage.stat.mockResolvedValue(null);
await expect(f.replay()).resolves.toEqual({ status: 'source_missing' });
Object.assign(f.attachment, { status: 'ready' });
await expect(f.replay()).resolves.toEqual({
status: 'ready',
generation: 0,
});
expect(f.tx.attachment.update).not.toHaveBeenCalled();
});
it('reads generation zero for pre-migration Kafka messages', () => {
const id = randomUUID();
const { generation, ...legacy } = firstJob(id, new Date(), 2);
const key = Buffer.from(id);
expect(
parseAttachmentJob(Buffer.from(JSON.stringify(legacy)), key),
).toEqual({ id, generation: 0 });
expect(
parseAttachmentJob(
Buffer.from(JSON.stringify({ ...legacy, generation })),
key,
),
).toEqual({ id, generation: 2 });
});
});
+92
View File
@@ -0,0 +1,92 @@
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import { stagingKeyFor } from './attachment-keys';
import { hasAttachmentCapacity } from './attachment-capacity';
import { OBJECT_TRANSACTION, tryAttachmentObjectLock } from './object-lock';
export const FAILED_STAGING_RETENTION_MS = 24 * 60 * 60 * 1000;
export function listFailedAttachments(db: PrismaService) {
return db.attachment.findMany({
where: { status: 'failed' },
orderBy: [{ failedAt: 'desc' }, { id: 'desc' }],
take: 100,
select: {
id: true,
generation: true,
failures: true,
errorCode: true,
failedAt: true,
replayUntil: true,
},
});
}
export async function replayAttachment(
db: PrismaService,
storage: StorageService,
id: string,
requestId: string,
operator: string,
) {
const identity = await db.attachment.findUnique({
where: { id },
select: { id: true, chatId: true },
});
if (!identity) return { status: 'not_found' } as const;
const stagingKey = stagingKeyFor(identity);
return db.$transaction(async (tx) => {
// The reconciler takes this same lock before deleting the source.
if (!(await tryAttachmentObjectLock(tx, stagingKey)))
return { status: 'busy' } as const;
const previous = await tx.attachmentReplay.findUnique({
where: { attachmentId_requestId: { attachmentId: id, requestId } },
});
if (previous) {
if (previous.operator !== operator)
return { status: 'request_conflict' } as const;
return { status: 'queued', generation: previous.generation } as const;
}
const attachment = await tx.attachment.findUnique({ where: { id } });
if (!attachment) return { status: 'not_found' } as const;
if (attachment.status === 'ready')
return { status: 'ready', generation: attachment.generation } as const;
if (attachment.status !== 'failed')
return { status: 'not_failed' } as const;
if (!attachment.replayUntil || attachment.replayUntil <= new Date())
return { status: 'replay_expired' } as const;
if (!(await storage.stat(stagingKey)))
return { status: 'source_missing' } as const;
if (!(await hasAttachmentCapacity(tx)))
return { status: 'busy' } as const;
const generation = attachment.generation + 1;
await tx.attachment.update({
where: { id, status: 'failed', generation: attachment.generation },
data: {
generation,
status: 'queued',
failures: 0,
errorCode: null,
failedAt: null,
replayUntil: null,
nextAttemptAt: null,
leaseUntil: null,
publishedAt: null,
},
});
await tx.attachmentReplay.create({
data: {
attachmentId: id,
requestId,
operator,
generation,
errorCode: attachment.errorCode,
failures: attachment.failures,
},
});
return { status: 'queued', generation } as const;
}, OBJECT_TRANSACTION);
}
+292
View File
@@ -0,0 +1,292 @@
import { createHash, randomUUID } from 'node:crypto';
import { statSync } from 'node:fs';
import { copyFile, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import sharp from 'sharp';
import type { Attachment } from '../generated/prisma/client';
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import { ApiException } from '../common/exceptions/api.exception';
import {
AttachmentAttemptTimeout,
AttachmentWorker,
} from './attachment-worker';
const sample = join(__dirname, '../../tests/fixtures/sample.png');
function fixture(input?: Buffer, timeoutMs?: number) {
const id = randomUUID();
const chatId = randomUUID();
const attachment: Partial<Attachment> = {
id,
chatId,
status: 'queued',
generation: 0,
failures: 0,
sizeBytes: input?.length ?? statSync(sample).size,
objectKey: `originals/${chatId}/${id}`,
};
const db = {
attachment: {
findUnique: jest.fn().mockResolvedValue(attachment),
updateMany: jest.fn(async ({ data }: { data: Partial<Attachment> }) => {
Object.assign(attachment, data);
return { count: 1 };
}),
},
};
const storage = {
inspectToFile: jest.fn(
async (
_key: string,
target: string,
_expected?: unknown,
_signal?: AbortSignal,
) => {
if (input) await writeFile(target, input);
else await copyFile(sample, target);
return '"etag"';
},
),
publishCopy: jest.fn(),
put: jest.fn<void, [string, Buffer, string]>(),
};
const worker = new AttachmentWorker(
db as unknown as PrismaService,
storage as unknown as StorageService,
timeoutMs,
);
const process = (generation = 0, signal = new AbortController().signal) =>
worker.process({ id, generation }, async () => {}, signal);
return { attachment, storage, process, id, chatId };
}
describe('attachment worker', () => {
it('publishes all variants and their metadata and ignores redelivery', async () => {
const f = fixture();
await expect(f.process()).resolves.toBe(true);
const [
[key, jpeg, type],
[cropKey, crop, cropType],
[optimizedKey, webp, optimizedType],
] = f.storage.put.mock.calls;
expect(key).toBe(`variants/${f.chatId}/${f.id}/v1/thumbnail.jpg`);
expect(type).toBe('image/jpeg');
expect(await sharp(jpeg).metadata()).toMatchObject({
format: 'jpeg',
width: 256,
height: 160,
});
expect(cropKey).toBe(`variants/${f.chatId}/${f.id}/v1/crop.jpg`);
expect(cropType).toBe('image/jpeg');
expect(await sharp(crop).metadata()).toMatchObject({
format: 'jpeg',
width: 128,
height: 128,
});
expect(optimizedKey).toBe(`variants/${f.chatId}/${f.id}/v1/optimized.webp`);
expect(optimizedType).toBe('image/webp');
expect(await sharp(webp).metadata()).toMatchObject({
format: 'webp',
width: 320,
height: 200,
});
expect(f.storage.publishCopy).toHaveBeenCalledWith(
`staging/${f.chatId}/${f.id}`,
f.attachment.objectKey,
'"etag"',
expect.any(AbortSignal),
);
expect(f.attachment).toMatchObject({
status: 'ready',
thumbnailWidth: 256,
thumbnailHeight: 160,
thumbnailSize: jpeg.length,
thumbnailSha256: createHash('sha256').update(jpeg).digest('hex'),
cropSize: crop.length,
cropSha256: createHash('sha256').update(crop).digest('hex'),
optimizedSize: webp.length,
optimizedWidth: 320,
optimizedHeight: 200,
optimizedSha256: createHash('sha256').update(webp).digest('hex'),
});
expect(jpeg).not.toEqual(await readFile(sample));
await expect(f.process()).resolves.toBe(true);
expect(f.storage.put).toHaveBeenCalledTimes(3);
});
it('centers the crop and applies EXIF orientation to the bounded WebP', async () => {
const input = await sharp({
create: { width: 1600, height: 800, channels: 3, background: '#0000ff' },
})
.composite([
{
input: {
create: {
width: 800,
height: 800,
channels: 3,
background: '#00ff00',
},
},
left: 400,
top: 0,
},
])
.withMetadata({ orientation: 6 })
.jpeg()
.toBuffer();
expect((await sharp(input).metadata()).orientation).toBe(6);
const f = fixture(input);
await expect(f.process()).resolves.toBe(true);
const crop = f.storage.put.mock.calls[1][1];
const webp = f.storage.put.mock.calls[2][1];
const { channels } = await sharp(crop).stats();
expect(channels[1].mean).toBeGreaterThan(240);
expect(channels[2].mean).toBeLessThan(15);
const metadata = await sharp(webp).metadata();
expect(metadata).toMatchObject({
format: 'webp',
width: 640,
height: 1280,
});
expect(metadata.exif).toBeUndefined();
});
it('keeps the attachment queued if the final variant write fails', async () => {
const f = fixture();
const stop = new AbortController();
f.storage.put.mockImplementation((key) => {
if (key.endsWith('/optimized.webp')) {
stop.abort();
throw new Error('temporary storage error');
}
});
await expect(f.process(0, stop.signal)).resolves.toBe(false);
expect(f.attachment).toMatchObject({ status: 'queued', failures: 1 });
expect(f.attachment.optimizedSha256).toBeUndefined();
expect(f.storage.publishCopy).not.toHaveBeenCalled();
});
it('commits failed metadata for invalid staged data without publishing effects', async () => {
const f = fixture();
f.storage.inspectToFile.mockRejectedValue(
new ApiException(400, 'invalid_request', 'Checksum mismatch'),
);
await expect(f.process()).resolves.toBe(true);
expect(f.attachment).toMatchObject({
status: 'failed',
errorCode: 'invalid_image',
nextAttemptAt: null,
failedAt: expect.any(Date),
replayUntil: expect.any(Date),
});
expect(f.storage.publishCopy).not.toHaveBeenCalled();
});
it('persists a jittered retry deadline and respects it on redelivery', async () => {
const f = fixture();
f.attachment.failures = 2;
const stop = new AbortController();
f.storage.inspectToFile.mockImplementationOnce(async () => {
stop.abort();
throw new Error('temporary storage error');
});
const random = jest.spyOn(Math, 'random').mockReturnValue(0.5);
const before = Date.now();
try {
await expect(f.process(0, stop.signal)).resolves.toBe(false);
} finally {
random.mockRestore();
}
expect(f.attachment).toMatchObject({
status: 'queued',
failures: 3,
errorCode: 'processing_error',
failedAt: null,
});
const deadline = f.attachment.nextAttemptAt!.getTime();
expect(deadline).toBeGreaterThanOrEqual(before + 2000);
expect(deadline).toBeLessThanOrEqual(Date.now() + 2000);
f.attachment.nextAttemptAt = new Date(Date.now() + 30000);
const redelivery = new AbortController();
const pending = f.process(0, redelivery.signal);
redelivery.abort();
await expect(pending).resolves.toBe(false);
expect(f.storage.inspectToFile).toHaveBeenCalledTimes(1);
});
it('ignores Kafka jobs from an earlier replay generation', async () => {
const f = fixture();
f.attachment.generation = 1;
await expect(f.process()).resolves.toBe(true);
expect(f.storage.inspectToFile).not.toHaveBeenCalled();
await expect(f.process(1)).resolves.toBe(true);
expect(f.storage.inspectToFile).toHaveBeenCalledTimes(1);
});
it('rejects oversized staged metadata before downloading from S3', async () => {
const f = fixture();
f.attachment.sizeBytes = 10485761;
await expect(f.process()).resolves.toBe(true);
expect(f.attachment).toMatchObject({
status: 'failed',
errorCode: 'invalid_image',
});
expect(f.storage.inspectToFile).not.toHaveBeenCalled();
});
it('aborts a stalled operation and records the timeout before requesting worker restart', async () => {
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
try {
const f = fixture(undefined, 50);
let onRead!: (signal: AbortSignal) => void;
const reading = new Promise<AbortSignal>((resolve) => {
onRead = resolve;
});
f.storage.inspectToFile.mockImplementation(
async (_key, _target, _expected, signal) => {
onRead(signal!);
return new Promise<string>((resolve) => {
signal!.addEventListener('abort', () => resolve('"late-etag"'), {
once: true,
});
});
},
);
const finished = expect(f.process()).rejects.toBeInstanceOf(
AttachmentAttemptTimeout,
);
const signal = await reading;
await jest.advanceTimersByTimeAsync(50);
await finished;
expect(signal.aborted).toBe(true);
expect(f.attachment).toMatchObject({
status: 'queued',
failures: 1,
errorCode: 'processing_timeout',
});
expect(f.attachment.nextAttemptAt).toBeInstanceOf(Date);
expect(f.storage.put).not.toHaveBeenCalled();
expect(f.storage.publishCopy).not.toHaveBeenCalled();
} finally {
jest.useRealTimers();
}
});
it('counts a lost worker lease against the attempt budget', async () => {
const f = fixture();
Object.assign(f.attachment, {
status: 'processing',
leaseUntil: new Date(0),
failures: 19,
});
await expect(f.process()).resolves.toBe(true);
expect(f.attachment).toMatchObject({
status: 'failed',
failures: 20,
errorCode: 'worker_interrupted',
});
expect(f.storage.inspectToFile).not.toHaveBeenCalled();
});
});
+356
View File
@@ -0,0 +1,356 @@
import { createHash } from 'node:crypto';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import sharp from 'sharp';
import type { Attachment } from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../Storage/storage.service';
import { ApiException } from '../common/exceptions/api.exception';
import {
CROP_SIZE,
stagingKeyFor,
variantFormats,
variantKeyFor,
type AttachmentVariantName,
} from './attachment-keys';
import { MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES } from './attachment.service';
import { FAILED_STAGING_RETENTION_MS } from './attachment-replay';
const HEARTBEAT_POLL_MS = 1000;
const RETRY_BASE_MS = 1000;
const RETRY_CAP_MS = 30000;
const LEASE_MS = 120000;
const MAX_JOB_TIMEOUT_MS = 100000;
export class AttachmentAttemptTimeout extends Error {}
function fitWithin(
{ width, height }: { width: number; height: number },
bound: number,
) {
const longSide = Math.max(width, height);
if (longSide <= bound) return { width, height };
return {
width: Math.max(1, Math.floor((width * bound) / longSide)),
height: Math.max(1, Math.floor((height * bound) / longSide)),
};
}
export class AttachmentWorker {
private readonly maxAttempts = Number(process.env.JOB_MAX_ATTEMPTS ?? 5);
constructor(
private readonly db: PrismaService,
private readonly storage: StorageService,
private readonly timeoutMs = Number(process.env.JOB_TIMEOUT_SECONDS ?? 60) *
1000,
) {
if (
!Number.isSafeInteger(this.maxAttempts) ||
this.maxAttempts < 1 ||
this.maxAttempts > 20
)
throw new Error('JOB_MAX_ATTEMPTS must be between 1 and 20');
if (
!Number.isSafeInteger(this.timeoutMs) ||
this.timeoutMs < 1 ||
this.timeoutMs > MAX_JOB_TIMEOUT_MS
)
throw new Error(
'JOB_TIMEOUT_SECONDS must be greater than 0 and at most 100',
);
}
async process(
{ id, generation }: { id: string; generation: number },
heartbeat: () => Promise<void>,
signal: AbortSignal,
) {
while (!signal.aborted) {
const attachment = await this.db.attachment.findUnique({ where: { id } });
if (
!attachment ||
attachment.generation !== generation ||
attachment.status === 'ready' ||
attachment.status === 'failed'
)
return true;
const now = new Date();
const dueAt =
attachment.status === 'processing'
? attachment.leaseUntil
: attachment.nextAttemptAt;
const waitMs = dueAt ? dueAt.getTime() - now.getTime() : 0;
if (waitMs > 0) {
await heartbeat();
await delay(Math.min(waitMs, HEARTBEAT_POLL_MS), undefined, {
signal,
}).catch(() => {});
continue;
}
if (attachment.status === 'processing') {
if (await this.recordFailure(attachment, 'worker_interrupted'))
return true;
await heartbeat();
continue;
}
const leaseUntil = new Date(now.getTime() + LEASE_MS);
const claim = await this.db.attachment.updateMany({
where: {
id,
generation,
status: 'queued',
failures: attachment.failures,
OR: [{ nextAttemptAt: null }, { nextAttemptAt: { lte: now } }],
},
data: { status: 'processing', leaseUntil, nextAttemptAt: null },
});
if (claim.count) {
const completed = await this.runAttempt(
{ ...attachment, leaseUntil },
heartbeat,
);
if (completed) return true;
}
await heartbeat();
if (!claim.count)
await delay(HEARTBEAT_POLL_MS, undefined, { signal }).catch(() => {});
}
return false;
}
private async runAttempt(
attachment: Attachment,
heartbeat: () => Promise<void>,
) {
const deadline = new AbortController();
const expiresAt = performance.now() + this.timeoutMs;
const timeoutError = new AttachmentAttemptTimeout(
'Attachment attempt exceeded its deadline',
);
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(timeoutError);
deadline.abort(timeoutError);
}, this.timeoutMs);
});
let variants: Awaited<ReturnType<AttachmentWorker['publishObjects']>>;
try {
const operation = this.publishObjects(attachment, deadline.signal).then(
async (published) => {
deadline.signal.throwIfAborted();
await heartbeat();
if (performance.now() >= expiresAt) {
deadline.abort(timeoutError);
throw timeoutError;
}
return published;
},
);
variants = await Promise.race([timeout, operation]).finally(() =>
clearTimeout(timer),
);
} catch (cause) {
const invalid =
cause instanceof ApiException &&
[400, 413, 415].includes(cause.getStatus());
const reason = deadline.signal.aborted
? 'processing_timeout'
: invalid
? 'invalid_image'
: 'processing_error';
try {
return await this.recordFailure(attachment, reason);
} finally {
// A native encoder can still be running after the JavaScript deadline.
deadline.signal.throwIfAborted();
}
}
// The lease fences stale attempts; repeat writes under the same keys contain the same bytes.
const result = await this.db.attachment.updateMany({
where: this.claimedAttachment(attachment),
data: {
status: 'ready',
errorCode: null,
leaseUntil: null,
...variants,
},
});
return result.count === 1;
}
private claimedAttachment(attachment: Attachment) {
return {
id: attachment.id,
generation: attachment.generation,
status: 'processing' as const,
leaseUntil: attachment.leaseUntil,
};
}
private async recordFailure(attachment: Attachment, reason: string) {
const failures = attachment.failures + 1;
const terminal = reason === 'invalid_image' || failures >= this.maxAttempts;
const now = new Date();
const delayLimit = Math.min(
RETRY_CAP_MS,
RETRY_BASE_MS * 2 ** (failures - 1),
);
const nextAttemptAt = terminal
? null
: new Date(now.getTime() + Math.floor(Math.random() * (delayLimit + 1)));
const errorCode =
terminal && reason === 'processing_error' ? 'retry_exhausted' : reason;
const result = await this.db.attachment.updateMany({
where: this.claimedAttachment(attachment),
data: {
status: terminal ? 'failed' : 'queued',
failures,
errorCode,
nextAttemptAt,
failedAt: terminal ? now : null,
replayUntil: terminal
? new Date(now.getTime() + FAILED_STAGING_RETENTION_MS)
: null,
leaseUntil: null,
},
});
if (result.count)
console.warn('Attachment processing attempt failed', {
attachmentId: attachment.id,
generation: attachment.generation,
attempt: failures,
errorCode,
nextAttemptAt,
});
return result.count === 1 && terminal;
}
private async publishObjects(attachment: Attachment, signal: AbortSignal) {
if (
!Number.isSafeInteger(attachment.sizeBytes) ||
attachment.sizeBytes <= 0 ||
attachment.sizeBytes > MAX_UPLOAD_BYTES
)
throw new ApiException(
413,
'payload_too_large',
'Размер файла вне допустимого диапазона',
);
const dir = await mkdtemp(join(tmpdir(), 'attachment-worker-'));
const file = join(dir, 'original');
const staging = stagingKeyFor(attachment);
try {
signal.throwIfAborted();
const etag = await this.storage.inspectToFile(
staging,
file,
attachment,
signal,
);
signal.throwIfAborted();
const image = sharp(file, {
limitInputPixels: MAX_IMAGE_PIXELS,
failOn: 'warning',
});
const { autoOrient: oriented } = await image.metadata();
const { width, height } = oriented;
const thumbnailDimensions = fitWithin(oriented, 256);
const optimizedDimensions = fitWithin(oriented, 1280);
const square = Math.min(width, height);
const thumbnail = await this.storeVariant(
attachment,
'thumbnail',
signal,
image
.clone()
.autoOrient()
.resize(thumbnailDimensions.width, thumbnailDimensions.height, {
fit: 'fill',
})
.flatten({ background: '#ffffff' })
.jpeg({ quality: 85 }),
);
// Crop at input resolution so even a very wide image only scales a square.
const crop = await this.storeVariant(
attachment,
'crop',
signal,
image
.clone()
.autoOrient()
.extract({
left: Math.floor((width - square) / 2),
top: Math.floor((height - square) / 2),
width: square,
height: square,
})
.resize(CROP_SIZE, CROP_SIZE)
.flatten({ background: '#ffffff' })
.jpeg({ quality: 85 }),
);
const optimized = await this.storeVariant(
attachment,
'optimized',
signal,
image
.clone()
.autoOrient()
.resize(optimizedDimensions.width, optimizedDimensions.height, {
fit: 'fill',
})
.webp({ quality: 80, effort: 4 }),
);
signal.throwIfAborted();
await this.storage.publishCopy(
staging,
attachment.objectKey,
etag,
signal,
);
signal.throwIfAborted();
return {
thumbnailSize: thumbnail.size,
thumbnailWidth: thumbnailDimensions.width,
thumbnailHeight: thumbnailDimensions.height,
thumbnailSha256: thumbnail.sha256,
cropSize: crop.size,
cropSha256: crop.sha256,
optimizedSize: optimized.size,
optimizedWidth: optimizedDimensions.width,
optimizedHeight: optimizedDimensions.height,
optimizedSha256: optimized.sha256,
};
} finally {
await rm(dir, { recursive: true, force: true }).catch(() => {
console.warn('Attachment worker temporary file cleanup failed');
});
}
}
private async storeVariant(
attachment: Attachment,
name: AttachmentVariantName,
signal: AbortSignal,
image: sharp.Sharp,
) {
signal.throwIfAborted();
const bytes = await image.timeout({ seconds: 15 }).toBuffer();
signal.throwIfAborted();
await this.storage.put(
variantKeyFor(attachment, name),
bytes,
variantFormats[name].contentType,
signal,
);
return {
size: bytes.length,
sha256: createHash('sha256').update(bytes).digest('hex'),
};
}
}
+86
View File
@@ -0,0 +1,86 @@
import {
Body,
Controller,
Get,
Headers,
HttpCode,
Param,
Post,
Query,
Req,
StreamableFile,
UseGuards,
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiBody,
ApiConsumes,
ApiOperation,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from '../User/user.guard';
import { AttachmentService } from './attachment.service';
@ApiTags('attachments')
@ApiBearerAuth('bearerAuth')
@UseGuards(UserGuard)
@Controller('api/v1')
export class AttachmentController {
constructor(private readonly attachments: AttachmentService) {}
@Post('chats/:chat_id/attachments')
@HttpCode(202)
@ApiOperation({ operationId: 'uploadAttachment' })
@ApiConsumes('image/png', 'image/jpeg')
@ApiBody({ schema: { type: 'string', format: 'binary' } })
@ApiQuery({ name: 'filename', required: true, type: String })
upload(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Query('filename') filename: unknown,
@Headers('content-type') contentType: unknown,
@Body() body: unknown,
) {
return this.attachments.upload(
chatId,
request.currentUser.id,
filename,
contentType,
body,
);
}
@Get('attachments/:attachment_id')
@ApiOperation({ operationId: 'getAttachment' })
get(
@Req() request: AuthenticatedRequest,
@Param('attachment_id') id: string,
) {
return this.attachments.get(id, request.currentUser.id);
}
@Get('attachments/:attachment_id/content')
@ApiOperation({ operationId: 'downloadAttachment' })
@ApiQuery({
name: 'variant',
required: false,
enum: ['original', 'thumbnail', 'crop', 'optimized'],
})
async content(
@Req() request: AuthenticatedRequest,
@Param('attachment_id') id: string,
@Query('variant') variant: unknown,
) {
const { attachment, stream } = await this.attachments.content(
id,
request.currentUser.id,
variant,
);
return new StreamableFile(stream, {
type: attachment.contentType,
length: attachment.sizeBytes,
disposition: `attachment; filename*=UTF-8''${encodeURIComponent(attachment.filename).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`,
});
}
}
+15
View File
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { UserModule } from '../User/user.module';
import { StorageModule } from '../Storage/storage.module';
import { AttachmentController } from './attachment.controller';
import { AttachmentService } from './attachment.service';
import { DirectUploadController } from './direct-upload.controller';
import { DirectUploadService } from './direct-upload.service';
import { AttachmentPublisher } from './attachment-publisher';
@Module({
imports: [UserModule, StorageModule],
controllers: [AttachmentController, DirectUploadController],
providers: [AttachmentService, DirectUploadService, AttachmentPublisher],
})
export class AttachmentModule {}
+181
View File
@@ -0,0 +1,181 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import { AttachmentService } from './attachment.service';
const chatId = '11111111-1111-4111-8111-111111111111';
const userId = '22222222-2222-4222-8222-222222222222';
const attachmentId = '33333333-3333-4333-8333-333333333333';
const png = readFileSync(join(__dirname, '../../tests/fixtures/sample.png'));
function fixture() {
const stored = {
id: attachmentId,
chatId,
ownerId: userId,
objectKey: 'stored-key',
filename: 'test.png',
contentType: 'image/png',
sizeBytes: png.length,
sha256: 'checksum',
createdAt: new Date(),
updatedAt: new Date(),
};
const tx = {
$executeRaw: jest.fn().mockResolvedValue(0),
$queryRaw: jest.fn().mockResolvedValue([{ locked: true }]),
attachment: {
count: jest.fn().mockResolvedValue(0),
create: jest.fn().mockResolvedValue(stored),
findUnique: jest.fn().mockResolvedValue(null),
},
};
const prisma = {
chatMember: { findUnique: jest.fn().mockResolvedValue({ chatId }) },
attachment: { findFirst: jest.fn() },
$transaction: jest.fn(
async (callback: (value: typeof tx) => Promise<unknown>) => callback(tx),
),
};
const storage = {
get: jest.fn().mockResolvedValue(Readable.from(png)),
put: jest.fn().mockResolvedValue(undefined),
remove: jest.fn().mockResolvedValue(undefined),
};
const service = new AttachmentService(
prisma as unknown as PrismaService,
storage as unknown as StorageService,
);
return {
stored,
tx,
prisma,
storage,
service,
upload: () => service.upload(chatId, userId, 'test.png', 'image/png', png),
};
}
describe('upload compensation', () => {
it('rejects an upload at queue capacity and removes the unadmitted staging object', async () => {
const f = fixture();
f.tx.attachment.count.mockResolvedValue(10000);
await expect(f.upload()).rejects.toMatchObject({ status: 429 });
expect(f.tx.attachment.create).not.toHaveBeenCalled();
expect(f.storage.remove).toHaveBeenCalledTimes(1);
});
it('compensates a PUT whose acknowledgement was lost before metadata creation', async () => {
const f = fixture();
f.storage.put.mockRejectedValue(new Error('uncertain PUT'));
await expect(f.upload()).rejects.toThrow('uncertain PUT');
expect(f.tx.attachment.create).not.toHaveBeenCalled();
expect(f.storage.remove).toHaveBeenCalledTimes(1);
});
it('removes bytes after a confirmed metadata failure', async () => {
const f = fixture();
f.tx.attachment.create.mockRejectedValue(new Error('metadata failure'));
await expect(f.upload()).rejects.toThrow('metadata failure');
expect(f.storage.remove).toHaveBeenCalledTimes(1);
});
it('preserves a committed attachment if the transaction acknowledgement was lost', async () => {
const f = fixture();
f.prisma.$transaction.mockImplementationOnce(async (callback) => {
await callback(f.tx);
throw new Error('lost commit acknowledgement');
});
f.tx.attachment.findUnique.mockResolvedValue(f.stored);
await expect(f.upload()).resolves.toMatchObject({
id: f.stored.id,
status: 'queued',
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
});
describe('attachment variants', () => {
it('reports and serves the crop and optimized variants of a ready attachment', async () => {
const f = fixture();
f.prisma.attachment.findFirst.mockResolvedValue({
...f.stored,
status: 'ready',
cropSize: 42,
cropSha256: 'crop-hash',
optimizedSize: 128,
optimizedWidth: 320,
optimizedHeight: 200,
optimizedSha256: 'webp-hash',
});
const metadata = await f.service.get(attachmentId, userId);
expect(metadata.variants).toEqual([
{
name: 'crop',
content_type: 'image/jpeg',
size_bytes: 42,
width: 128,
height: 128,
sha256: 'crop-hash',
},
{
name: 'optimized',
content_type: 'image/webp',
size_bytes: 128,
width: 320,
height: 200,
sha256: 'webp-hash',
},
]);
await expect(
f.service.content(attachmentId, userId, 'crop'),
).resolves.toMatchObject({
attachment: {
filename: 'test.png.crop.jpg',
contentType: 'image/jpeg',
sizeBytes: 42,
},
});
await expect(
f.service.content(attachmentId, userId, 'optimized'),
).resolves.toMatchObject({
attachment: {
filename: 'test.png.optimized.webp',
contentType: 'image/webp',
sizeBytes: 128,
},
});
expect(f.storage.get.mock.calls).toEqual([
[`variants/${chatId}/${attachmentId}/v1/crop.jpg`],
[`variants/${chatId}/${attachmentId}/v1/optimized.webp`],
]);
});
it('distinguishes unavailable content from variants missing on older ready attachments', async () => {
const f = fixture();
f.prisma.attachment.findFirst.mockResolvedValueOnce({
...f.stored,
status: 'processing',
});
await expect(
f.service.content(attachmentId, userId, 'optimized'),
).rejects.toMatchObject({ status: 409 });
f.prisma.attachment.findFirst.mockResolvedValue({
...f.stored,
status: 'ready',
cropSize: null,
optimizedSize: null,
});
await expect(
f.service.content(attachmentId, userId, 'optimized'),
).rejects.toMatchObject({ status: 404 });
await expect(
f.service.content(attachmentId, userId, undefined),
).resolves.toMatchObject({
attachment: { contentType: 'image/png' },
});
expect(f.storage.get.mock.calls).toEqual([[f.stored.objectKey]]);
});
});
+314
View File
@@ -0,0 +1,314 @@
import { Injectable, Logger } from '@nestjs/common';
import { createHash, randomUUID } from 'node:crypto';
import sharp from 'sharp';
import type { Attachment } from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../Storage/storage.service';
import { ApiException } from '../common/exceptions/api.exception';
import { invalidRequest, uuid } from '../common/validation';
import { OBJECT_TRANSACTION, tryAttachmentObjectLock } from './object-lock';
import {
CROP_SIZE,
isAttachmentVariant,
stagingKeyFor,
variantFormats,
variantKeyFor,
} from './attachment-keys';
import { profileStage } from '../common/http/upload-memory-profile';
import { assertAttachmentCapacity } from './attachment-capacity';
function limit(name: string, maximum: number): number {
const value = Number(process.env[name] ?? maximum);
if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
throw new Error(`${name} must be between 1 and ${maximum}`);
}
return value;
}
export const MAX_UPLOAD_BYTES = limit('MAX_UPLOAD_BYTES', 10485760);
export const MAX_IMAGE_PIXELS = limit('MAX_IMAGE_PIXELS', 40000000);
@Injectable()
export class AttachmentService {
private readonly logger = new Logger(AttachmentService.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
) {}
async upload(
chatValue: unknown,
userId: string,
filename: unknown,
mime: unknown,
body: unknown,
) {
profileStage('authorize_and_validate_fields');
const chatId = uuid(chatValue, 'chat_id');
await this.authorizeChat(chatId, userId);
const fields = this.validateFields(filename, mime);
if (!Buffer.isBuffer(body) || body.length === 0)
throw new ApiException(
415,
'unsupported_media_type',
'Ожидается PNG или JPEG',
);
if (body.length > MAX_UPLOAD_BYTES)
throw new ApiException(413, 'payload_too_large', 'Превышен лимит файла');
const contentType = fields.contentType;
await this.validateImage(body, contentType);
const id = randomUUID();
const objectKey = `originals/${chatId}/${id}`;
const stagingKey = stagingKeyFor({ id, chatId });
try {
profileStage('db_lock');
const stored = await this.prisma.$transaction(async (tx) => {
if (!(await tryAttachmentObjectLock(tx, stagingKey))) {
throw new ApiException(503, 'unavailable', 'Объект занят');
}
profileStage('s3_put');
await this.storage.put(stagingKey, body, contentType);
profileStage('sha256');
const sha256 = createHash('sha256').update(body).digest('hex');
await assertAttachmentCapacity(tx);
profileStage('db_insert_and_commit');
return tx.attachment.create({
data: {
id,
chatId,
ownerId: userId,
objectKey,
status: 'queued',
filename: fields.filename,
contentType,
sizeBytes: body.length,
sha256,
},
});
}, OBJECT_TRANSACTION);
profileStage('serialize_response');
return this.serialize(stored, true);
} catch (error) {
// A database timeout can occur after commit. Never delete a referenced object.
try {
const committed = await this.prisma.$transaction(async (tx) => {
if (!(await tryAttachmentObjectLock(tx, stagingKey))) return null;
const record = await tx.attachment.findUnique({
where: { objectKey },
});
if (record) return record;
await this.storage.remove(stagingKey);
return null;
}, OBJECT_TRANSACTION);
if (committed) return this.serialize(committed, true);
} catch {
this.logger.error(
{ attachmentId: id },
'Upload requires reconciliation',
);
}
throw error;
}
}
async get(id: unknown, userId: string) {
return this.serialize(await this.authorizeAttachment(id, userId));
}
async content(id: unknown, userId: string, variant: unknown) {
const attachment = await this.authorizeAttachment(id, userId);
const name = variant === undefined ? 'original' : variant;
if (name !== 'original' && !isAttachmentVariant(name)) {
return invalidRequest('Некорректный variant');
}
if (attachment.status !== 'ready') {
throw new ApiException(
409,
'conflict',
'Вложение недоступно для скачивания',
);
}
if (name === 'original') {
return {
attachment,
stream: await this.storage.get(attachment.objectKey),
};
}
const metadata = this.variants(attachment).find(
(item) => item.name === name,
);
if (!metadata) {
throw new ApiException(404, 'not_found', 'Вариант не найден');
}
return {
attachment: {
filename: `${attachment.filename}.${name}.${variantFormats[name].extension}`,
contentType: metadata.content_type,
sizeBytes: metadata.size_bytes,
},
stream: await this.storage.get(variantKeyFor(attachment, name)),
};
}
validateFields(filename: unknown, mime: unknown) {
if (
typeof filename !== 'string' ||
filename.trim().length === 0 ||
Array.from(filename).length > 255 ||
Array.from(filename).some((character) => {
const point = character.codePointAt(0)!;
return (
character === '/' ||
character === '\\' ||
point < 32 ||
(point >= 127 && point <= 159)
);
})
) {
return invalidRequest('Некорректный filename');
}
const contentType =
typeof mime === 'string' ? mime.split(';')[0].trim().toLowerCase() : '';
if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
throw new ApiException(
415,
'unsupported_media_type',
'Ожидается PNG или JPEG',
);
}
return { filename, contentType };
}
async authorizeChat(chatId: string, userId: string) {
const member = await this.prisma.chatMember.findUnique({
where: { chatId_userId: { chatId, userId } },
select: { chatId: true },
});
if (!member) throw new ApiException(404, 'not_found', 'Объект не найден');
}
private async authorizeAttachment(value: unknown, userId: string) {
const id = uuid(value, 'attachment_id');
const attachment = await this.prisma.attachment.findFirst({
where: { id, chat: { members: { some: { userId } } } },
});
if (!attachment)
throw new ApiException(404, 'not_found', 'Объект не найден');
return attachment;
}
async validateImage(body: Buffer | string, contentType: string) {
try {
profileStage('sharp_metadata');
// metadata reads headers without decoding pixels; check dimensions before full validation.
const metadata = await sharp(body, {
limitInputPixels: false,
failOn: 'warning',
}).metadata();
const actualType =
metadata.format === 'png'
? 'image/png'
: metadata.format === 'jpeg'
? 'image/jpeg'
: null;
if (
actualType !== contentType ||
!metadata.width ||
!metadata.height ||
(metadata.pages ?? 1) > 1
) {
throw new ApiException(
415,
'unsupported_media_type',
'Некорректное изображение',
);
}
if (metadata.width * metadata.height > MAX_IMAGE_PIXELS) {
throw new ApiException(
413,
'payload_too_large',
'Превышен лимит пикселей',
);
}
profileStage('sharp_decode_stats');
await sharp(body, {
limitInputPixels: MAX_IMAGE_PIXELS,
failOn: 'warning',
}).stats();
profileStage('image_validated');
} catch (cause) {
if (cause instanceof ApiException) throw cause;
throw new ApiException(
415,
'unsupported_media_type',
'Некорректное изображение',
{ cause },
);
}
}
serialize(value: Attachment, accepted = false) {
return {
id: value.id,
chat_id: value.chatId,
owner_id: value.ownerId,
filename: value.filename,
content_type: value.contentType,
size_bytes: value.sizeBytes,
sha256: value.sha256,
status: accepted ? 'queued' : value.status,
variants:
!accepted && value.status === 'ready' ? this.variants(value) : [],
error_code:
!accepted && value.status === 'failed' ? value.errorCode : null,
created_at: value.createdAt.toISOString(),
updated_at: (accepted ? value.createdAt : value.updatedAt).toISOString(),
};
}
private variants(value: Attachment) {
const candidates = [
{
name: 'thumbnail',
size_bytes: value.thumbnailSize,
width: value.thumbnailWidth,
height: value.thumbnailHeight,
sha256: value.thumbnailSha256,
},
{
name: 'crop',
size_bytes: value.cropSize,
width: CROP_SIZE,
height: CROP_SIZE,
sha256: value.cropSha256,
},
{
name: 'optimized',
size_bytes: value.optimizedSize,
width: value.optimizedWidth,
height: value.optimizedHeight,
sha256: value.optimizedSha256,
},
] as const;
return candidates.flatMap(({ name, size_bytes, width, height, sha256 }) => {
if (
typeof size_bytes !== 'number' ||
typeof width !== 'number' ||
typeof height !== 'number' ||
typeof sha256 !== 'string'
)
return [];
return [
{
name,
content_type: variantFormats[name].contentType,
size_bytes,
width,
height,
sha256,
},
];
});
}
}
+161
View File
@@ -0,0 +1,161 @@
import {
Body,
Controller,
HttpCode,
Header,
Param,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiBody,
ApiOperation,
ApiParam,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from '../User/user.guard';
import { DirectUploadService } from './direct-upload.service';
@ApiTags('direct uploads')
@ApiBearerAuth('bearerAuth')
@UseGuards(UserGuard)
@Controller('api/v1/chats/:chat_id/attachment-uploads')
@ApiParam({ name: 'chat_id', type: 'string', format: 'uuid', required: true })
@ApiResponse({
status: 401,
description: 'Требуется Bearer-сессия',
schema: { $ref: '#/components/schemas/Error' },
})
@ApiResponse({
status: 404,
description: 'Чат/разрешение недоступно пользователю',
schema: { $ref: '#/components/schemas/Error' },
})
@ApiResponse({
status: 503,
description: 'БД или хранилище временно недоступно',
schema: { $ref: '#/components/schemas/Error' },
})
export class DirectUploadController {
constructor(private readonly uploads: DirectUploadService) {}
@Post()
@HttpCode(201)
@Header('Cache-Control', 'no-store')
@ApiOperation({
operationId: 'initiateDirectUpload',
summary: 'Выдать короткоживущее разрешение PUT в staging',
})
@ApiBody({
schema: {
type: 'object',
additionalProperties: false,
required: ['filename', 'content_type', 'size_bytes', 'sha256'],
properties: {
filename: { type: 'string', minLength: 1, maxLength: 255 },
content_type: { type: 'string', enum: ['image/png', 'image/jpeg'] },
size_bytes: { type: 'integer', minimum: 1, maximum: 10485760 },
sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' },
expires_in: {
type: 'integer',
minimum: 1,
maximum: 300,
description:
'Не больше серверного DIRECT_UPLOAD_TTL_SECONDS (60 по умолчанию)',
},
},
},
})
@ApiResponse({
status: 201,
description: 'PUT URL и обязательные заголовки; URL не логировать',
schema: {
type: 'object',
required: [
'upload_id',
'expires_at',
'method',
'url',
'headers',
'complete_url',
],
properties: {
upload_id: { type: 'string', format: 'uuid' },
expires_at: { type: 'string', format: 'date-time' },
method: { type: 'string', enum: ['PUT'] },
url: { type: 'string', format: 'uri' },
headers: { type: 'object', additionalProperties: { type: 'string' } },
complete_url: { type: 'string' },
},
},
})
@ApiResponse({ status: 400, description: 'Некорректные поля разрешения' })
@ApiResponse({ status: 413, description: 'Запрошен размер больше 10 MiB' })
@ApiResponse({ status: 415, description: 'Разрешены только PNG и JPEG' })
initiate(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Body() body: unknown,
) {
return this.uploads.initiate(chatId, request.currentUser.id, body);
}
@Post(':upload_id/complete')
@HttpCode(202)
@ApiParam({
name: 'upload_id',
type: 'string',
format: 'uuid',
required: true,
})
@ApiBody({
required: false,
schema: { type: 'object', additionalProperties: false, properties: {} },
})
@ApiOperation({
operationId: 'completeDirectUpload',
summary:
'Проверить байты и поставить вложение в очередь; идемпотентно для владельца',
})
@ApiResponse({
status: 202,
description: 'Подтверждение приёма Attachment; повтор возвращает то же вложение',
schema: { $ref: '#/components/schemas/Attachment' },
})
@ApiResponse({
status: 400,
description: 'Размер/checksum не совпадает или некорректные параметры',
})
@ApiResponse({ status: 404, description: 'Чужая или неизвестная загрузка' })
@ApiResponse({
status: 409,
description:
'Истёкшее/отклонённое разрешение, нет файла или complete выполняется другой репликой',
})
@ApiResponse({ status: 413, description: 'Превышен лимит bytes/pixels' })
@ApiResponse({
status: 415,
description: 'Повреждённое изображение или неверный MIME',
})
@ApiResponse({
status: 429,
description: 'Очередь вложений заполнена',
headers: { 'Retry-After': { schema: { type: 'integer', minimum: 1 } } },
})
complete(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Param('upload_id') uploadId: string,
@Body() body: unknown,
) {
return this.uploads.complete(
chatId,
uploadId,
request.currentUser.id,
body,
);
}
}
@@ -0,0 +1,151 @@
import { randomUUID } from 'node:crypto';
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import type { AttachmentService } from './attachment.service';
import { DirectUploadService } from './direct-upload.service';
import { ApiException } from '../common/exceptions/api.exception';
function fixture() {
const upload = {
id: randomUUID(),
chatId: randomUUID(),
ownerId: randomUUID(),
filename: 'photo.png',
contentType: 'image/png',
sizeBytes: 200,
sha256: 'a'.repeat(64),
expiresAt: new Date(Date.now() + 60000),
status: 'pending',
};
let saved: unknown = null;
const db = {
directUpload: {
create: jest.fn().mockResolvedValue(upload),
findFirst: jest.fn().mockResolvedValue(upload),
update: jest.fn(async ({ data }: { data: { status: string } }) =>
Object.assign(upload, data),
),
},
attachment: {
count: jest.fn().mockResolvedValue(0),
findUnique: jest.fn(async () => saved),
create: jest.fn(async ({ data }: { data: Record<string, unknown> }) => {
saved = { ...data, createdAt: new Date(), updatedAt: new Date() };
return saved;
}),
},
$executeRaw: jest.fn().mockResolvedValue(0),
$queryRaw: jest.fn().mockResolvedValue([{ locked: true }]),
$transaction: jest.fn(),
};
db.$transaction.mockImplementation((fn: (tx: unknown) => unknown) => fn(db));
const storage = {
presignPut: jest
.fn()
.mockResolvedValue({ url: 'http://example.test/upload', headers: {} }),
inspectToFile: jest.fn().mockResolvedValue('"etag"'),
publishCopy: jest.fn().mockResolvedValue(undefined),
remove: jest.fn().mockResolvedValue(undefined),
};
const attachments = {
authorizeChat: jest.fn().mockResolvedValue(undefined),
validateFields: jest
.fn()
.mockReturnValue({
filename: upload.filename,
contentType: upload.contentType,
}),
validateImage: jest.fn().mockResolvedValue(undefined),
serialize: jest.fn((value: unknown) => value),
};
const service = new DirectUploadService(
db as unknown as PrismaService,
storage as unknown as StorageService,
attachments as unknown as AttachmentService,
);
const complete = () =>
service.complete(upload.chatId, upload.id, upload.ownerId, undefined);
return { upload, db, storage, attachments, service, complete };
}
describe('direct upload publication', () => {
it('uses immutable expected fields and a short server-bounded grant', async () => {
const f = fixture();
await expect(
f.service.initiate(f.upload.chatId, f.upload.ownerId, {
filename: 'photo.png',
content_type: 'image/png',
size_bytes: 200,
sha256: 'a'.repeat(64),
expires_in: 1,
}),
).resolves.toMatchObject({ upload_id: f.upload.id, method: 'PUT' });
expect(f.storage.presignPut).toHaveBeenCalledWith(
`staging/${f.upload.chatId}/${f.upload.id}`,
200,
'image/png',
'a'.repeat(64),
1,
expect.any(Date),
);
await expect(
f.service.initiate(f.upload.chatId, f.upload.ownerId, {
filename: 'photo.png',
content_type: 'image/png',
size_bytes: 10485761,
sha256: 'a'.repeat(64),
}),
).rejects.toMatchObject({ status: 413 });
});
it('queues the staged object once and reuses the same attachment on replay', async () => {
const f = fixture();
const first = await f.complete();
expect(await f.complete()).toEqual(first);
expect(f.storage.inspectToFile).toHaveBeenCalledTimes(1);
expect(first).toMatchObject({ id: f.upload.id, status: 'queued' });
expect(f.storage.publishCopy).not.toHaveBeenCalled();
expect(f.storage.remove).not.toHaveBeenCalled();
expect(f.db.attachment.create).toHaveBeenCalledTimes(1);
expect(f.upload.status).toBe('completed');
});
it('commits a rejected reservation when image validation fails, publishing no metadata', async () => {
const f = fixture();
f.attachments.validateImage.mockRejectedValue(
new ApiException(415, 'unsupported_media_type', 'invalid image'),
);
await expect(f.complete()).rejects.toMatchObject({ status: 415 });
expect(f.upload.status).toBe('rejected');
expect(f.db.attachment.create).not.toHaveBeenCalled();
expect(f.storage.publishCopy).not.toHaveBeenCalled();
await expect(f.complete()).rejects.toMatchObject({ status: 409 });
});
it('expires pending reservations without downloading their objects', async () => {
const f = fixture();
f.upload.expiresAt = new Date(Date.now() - 1000);
await expect(f.complete()).rejects.toMatchObject({ status: 409 });
expect(f.upload.status).toBe('expired');
expect(f.storage.inspectToFile).not.toHaveBeenCalled();
});
it('does not reject an intent for an infrastructure failure or a missing upload', async () => {
const f = fixture();
f.storage.inspectToFile.mockRejectedValue(
new ApiException(503, 'unavailable', 'storage unavailable'),
);
await expect(f.complete()).rejects.toMatchObject({ status: 503 });
expect(f.upload.status).toBe('pending');
expect(f.db.attachment.create).not.toHaveBeenCalled();
});
it('does not fetch an object for a foreign reservation or simultaneous completion', async () => {
const f = fixture();
f.db.directUpload.findFirst.mockResolvedValueOnce(null);
await expect(f.complete()).rejects.toMatchObject({ status: 404 });
f.db.$queryRaw.mockResolvedValueOnce([{ locked: false }]);
await expect(f.complete()).rejects.toMatchObject({ status: 409 });
expect(f.storage.inspectToFile).not.toHaveBeenCalled();
});
});
+220
View File
@@ -0,0 +1,220 @@
import { Injectable } from '@nestjs/common';
import { mkdtemp, rm, rmdir } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import type { Attachment } from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../Storage/storage.service';
import { ApiException } from '../common/exceptions/api.exception';
import { invalidRequest, objectBody, uuid } from '../common/validation';
import { AttachmentService, MAX_UPLOAD_BYTES } from './attachment.service';
import { OBJECT_TRANSACTION, tryAttachmentObjectLock } from './object-lock';
import { profileStage } from '../common/http/upload-memory-profile';
import { stagingKeyFor } from './attachment-keys';
import { assertAttachmentCapacity } from './attachment-capacity';
type Outcome = { attachment: Attachment } | { error: ApiException };
@Injectable()
export class DirectUploadService {
private readonly maxTtl = Number(process.env.DIRECT_UPLOAD_TTL_SECONDS ?? 60);
constructor(
private readonly db: PrismaService,
private readonly storage: StorageService,
private readonly attachments: AttachmentService,
) {
if (
!Number.isSafeInteger(this.maxTtl) ||
this.maxTtl < 1 ||
this.maxTtl > 300
) {
throw new Error('DIRECT_UPLOAD_TTL_SECONDS must be between 1 and 300');
}
}
async initiate(chatValue: unknown, userId: string, value: unknown) {
const chatId = uuid(chatValue, 'chat_id');
await this.attachments.authorizeChat(chatId, userId);
const body = objectBody(value, [
'filename',
'content_type',
'size_bytes',
'sha256',
'expires_in',
]);
const fields = this.attachments.validateFields(
body.filename,
body.content_type,
);
if (
typeof body.size_bytes !== 'number' ||
!Number.isSafeInteger(body.size_bytes) ||
body.size_bytes < 1
)
invalidRequest('Некорректный size_bytes');
if (body.size_bytes > MAX_UPLOAD_BYTES)
throw new ApiException(413, 'payload_too_large', 'Превышен лимит файла');
if (typeof body.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(body.sha256))
invalidRequest('Ожидается lowercase SHA-256');
const ttl = body.expires_in === undefined ? this.maxTtl : body.expires_in;
if (
typeof ttl !== 'number' ||
!Number.isSafeInteger(ttl) ||
ttl < 1 ||
ttl > this.maxTtl
)
invalidRequest('Некорректный expires_in');
// SigV4 timestamps have second precision; report the same expiry to the client.
const now = new Date(Math.floor(Date.now() / 1000) * 1000);
const upload = await this.db.directUpload.create({
data: {
chatId,
ownerId: userId,
filename: fields.filename,
contentType: fields.contentType,
sizeBytes: body.size_bytes,
sha256: body.sha256,
expiresAt: new Date(now.getTime() + ttl * 1000),
},
});
const signed = await this.storage.presignPut(
stagingKeyFor(upload),
upload.sizeBytes,
upload.contentType,
upload.sha256,
ttl,
now,
);
return {
upload_id: upload.id,
expires_at: upload.expiresAt.toISOString(),
method: 'PUT' as const,
...signed,
complete_url: `/api/v1/chats/${chatId}/attachment-uploads/${upload.id}/complete`,
};
}
async complete(
chatValue: unknown,
uploadValue: unknown,
userId: string,
body: unknown,
) {
profileStage('authorize_and_lookup');
const chatId = uuid(chatValue, 'chat_id');
const id = uuid(uploadValue, 'upload_id');
if (body !== undefined) objectBody(body, []);
await this.attachments.authorizeChat(chatId, userId);
const where = { id, chatId, ownerId: userId };
if (!(await this.db.directUpload.findFirst({ where })))
throw new ApiException(404, 'not_found', 'Объект не найден');
const stagingKey = stagingKeyFor({ chatId, id });
const originalKey = `originals/${chatId}/${id}`;
const directory = await mkdtemp(join(tmpdir(), 'pe-direct-'));
const file = join(directory, 'image');
let outcome: Outcome;
try {
outcome = await this.db.$transaction(async (tx): Promise<Outcome> => {
if (
!(await tryAttachmentObjectLock(tx, stagingKey)) ||
!(await tryAttachmentObjectLock(tx, originalKey))
) {
throw new ApiException(
409,
'conflict',
'Загрузка уже завершается; повторите complete',
);
}
const upload = await tx.directUpload.findFirst({ where });
if (!upload)
throw new ApiException(404, 'not_found', 'Объект не найден');
const existing = await tx.attachment.findUnique({ where: { id } });
if (upload.status === 'completed') {
if (!existing)
throw new ApiException(
503,
'unavailable',
'Метаданные завершённой загрузки недоступны',
);
return { attachment: existing };
}
if (upload.status !== 'pending')
return {
error: new ApiException(
409,
'conflict',
'Разрешение загрузки больше не действует',
),
};
if (upload.expiresAt <= new Date()) {
await tx.directUpload.update({
where: { id },
data: { status: 'expired' },
});
return {
error: new ApiException(
409,
'conflict',
'Разрешение загрузки истекло',
),
};
}
if (existing)
throw new ApiException(
503,
'unavailable',
'Конфликт идентификатора вложения',
);
try {
profileStage('s3_get_headers');
await this.storage.inspectToFile(stagingKey, file, upload);
await this.attachments.validateImage(file, upload.contentType);
} catch (error) {
if (
!(error instanceof ApiException) ||
![400, 413, 415].includes(error.getStatus())
)
throw error;
// Commit rejection before reporting a permanent validation error. No attachment is published.
await tx.directUpload.update({
where: { id },
data: { status: 'rejected' },
});
return { error };
}
// The signed PUT is create-only; the worker verifies the stored checksum again.
profileStage('db_insert_and_commit');
await assertAttachmentCapacity(tx);
const attachment = await tx.attachment.create({
data: {
id,
chatId,
ownerId: userId,
objectKey: originalKey,
status: 'queued',
filename: upload.filename,
contentType: upload.contentType,
sizeBytes: upload.sizeBytes,
sha256: upload.sha256,
},
});
await tx.directUpload.update({
where: { id },
data: { status: 'completed' },
});
return { attachment };
}, OBJECT_TRANSACTION);
} finally {
profileStage('temp_file_cleanup');
await rm(file, { force: true });
await rmdir(directory);
}
if ('error' in outcome) throw outcome.error;
profileStage('serialize_response');
return this.attachments.serialize(
outcome.attachment,
outcome.attachment.publishedAt !== null || outcome.attachment.status !== 'ready' || outcome.attachment.thumbnailSize !== null,
);
}
}
+16
View File
@@ -0,0 +1,16 @@
import { Prisma } from '../generated/prisma/client';
export const OBJECT_TRANSACTION = { maxWait: 5000, timeout: 20000 };
/** All writers and cleaners use the same transaction-scoped lock for an immutable key. */
export async function tryAttachmentObjectLock(
tx: Prisma.TransactionClient,
objectKey: string,
): Promise<boolean> {
// A suspended/crashed writer must not keep an idle transaction open indefinitely.
await tx.$executeRaw`SET LOCAL idle_in_transaction_session_timeout = '15s'`;
const [result] = await tx.$queryRaw<{ locked: boolean }[]>(Prisma.sql`
SELECT pg_try_advisory_xact_lock(hashtextextended(${`attachment:${objectKey}`}, 0)) AS locked
`);
return result.locked;
}
+30
View File
@@ -0,0 +1,30 @@
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const file = join(tmpdir(), 'mtusi2026lab4-reconciler-success');
export function clearReconcileHealth(): void {
rmSync(file, { force: true });
}
export function markReconcileHealth(): void {
writeFileSync(file, String(Date.now()), { mode: 0o600 });
}
if (require.main === module) {
try {
const age = Date.now() - Number(readFileSync(file, 'utf8'));
const interval = Number(process.env.RECONCILE_INTERVAL_SECONDS ?? 60);
process.exitCode =
Number.isFinite(age) &&
age >= 0 &&
Number.isFinite(interval) &&
interval > 0 &&
age <= (interval + 120) * 1000
? 0
: 1;
} catch {
process.exitCode = 1;
}
}
+83
View File
@@ -0,0 +1,83 @@
import { uuidPattern } from '../common/validation';
export interface ReconcileOptions {
apply: boolean;
graceSeconds: number;
prefix: string;
signal?: AbortSignal;
}
export function positiveSeconds(value: string, name: string): number {
if (!/^[1-9]\d*$/.test(value))
throw new Error(`${name} must be a positive integer`);
const seconds = Number(value);
if (!Number.isSafeInteger(seconds) || seconds > 2147483) {
throw new Error(`${name} is too large`);
}
return seconds;
}
export function managedObjectKey(key: string): boolean {
const parts = key.split('/');
return (
parts.length === 3 &&
parts[0] === 'originals' &&
uuidPattern.test(parts[1]) &&
uuidPattern.test(parts[2])
);
}
export function reconcileOptions(args: string[], env = process.env) {
let apply = false;
let dryRun = false;
let watch = false;
let prefix = 'originals/';
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--apply':
apply = true;
break;
case '--dry-run':
dryRun = true;
break;
case '--watch':
watch = true;
break;
case '--prefix': {
prefix = args[++i] ?? '';
const parts = prefix.split('/');
if (
prefix !== 'originals/' &&
!(
parts.length === 3 &&
parts[0] === 'originals' &&
uuidPattern.test(parts[1]) &&
parts[2] === ''
)
) {
throw new Error(
'Prefix must be originals/ or originals/<chat UUID>/',
);
}
break;
}
default:
throw new Error(`Unknown argument: ${args[i]}`);
}
}
if (apply && dryRun)
throw new Error('--apply and --dry-run are mutually exclusive');
return {
apply,
watch,
prefix,
graceSeconds: positiveSeconds(
env.ORPHAN_GRACE_SECONDS ?? '600',
'ORPHAN_GRACE_SECONDS',
),
intervalSeconds: positiveSeconds(
env.RECONCILE_INTERVAL_SECONDS ?? '60',
'RECONCILE_INTERVAL_SECONDS',
),
};
}
+67
View File
@@ -0,0 +1,67 @@
import 'reflect-metadata';
import { setTimeout as delay } from 'node:timers/promises';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../Storage/storage.service';
import { reconcileOptions } from './reconcile-options';
import { ReconcileService } from './reconcile.service';
import { clearReconcileHealth, markReconcileHealth } from './reconcile-health';
async function main() {
const options = reconcileOptions(process.argv.slice(2));
if (options.watch) clearReconcileHealth();
const controller = new AbortController();
const stop = () => controller.abort();
process.once('SIGTERM', stop);
process.once('SIGINT', stop);
const prisma = new PrismaService();
let storage: StorageService | undefined;
const output = (event: object) => console.log(JSON.stringify(event));
try {
storage = new StorageService();
await prisma.onModuleInit();
const service = new ReconcileService(prisma, storage, output);
do {
try {
const report = await service.run({
...options,
signal: controller.signal,
});
if (options.watch) markReconcileHealth();
output({ event: 'reconcile_summary', ...report });
if (!options.watch && report.missingObjects > 0) process.exitCode = 2;
} catch (error) {
if (controller.signal.aborted) break;
if (options.watch) clearReconcileHealth();
output({
event: 'reconcile_failed',
errorType: error instanceof Error ? error.name : 'UnknownError',
});
if (!options.watch) {
process.exitCode = 1;
break;
}
}
if (!options.watch || controller.signal.aborted) break;
await delay(options.intervalSeconds * 1000, undefined, {
signal: controller.signal,
}).catch((error: unknown) => {
if (!controller.signal.aborted) throw error;
});
} while (!controller.signal.aborted);
} finally {
storage?.onModuleDestroy();
await prisma.onModuleDestroy();
process.removeListener('SIGTERM', stop);
process.removeListener('SIGINT', stop);
}
}
void main().catch((error: unknown) => {
console.error(
JSON.stringify({
event: 'reconcile_failed',
errorType: error instanceof Error ? error.name : 'UnknownError',
}),
);
process.exitCode = 1;
});
+200
View File
@@ -0,0 +1,200 @@
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService, StoredObject } from '../Storage/storage.service';
import { ReconcileService } from './reconcile.service';
import { reconcileOptions } from './reconcile-options';
const key =
'originals/11111111-1111-4111-8111-111111111111/22222222-2222-4222-8222-222222222222';
const now = new Date('2026-11-09T12:00:00Z');
const old = new Date(now.getTime() - 601000);
const fresh = new Date(now.getTime() - 599000);
function fixture(objects: StoredObject[] = [{ key, lastModified: old }]) {
const tx = {
$executeRaw: jest.fn().mockResolvedValue(0),
$queryRaw: jest.fn().mockResolvedValue([{ locked: true }]),
attachment: { findUnique: jest.fn().mockResolvedValue(null) },
directUpload: { findUnique: jest.fn().mockResolvedValue(null) },
};
const prisma = {
$queryRaw: jest.fn().mockResolvedValue([{ '?column?': 1 }]),
$transaction: jest.fn(
async (callback: (value: typeof tx) => Promise<unknown>) => callback(tx),
),
attachment: { findMany: jest.fn().mockResolvedValue([]) },
directUpload: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) },
};
const storage = {
ready: jest.fn().mockResolvedValue(undefined),
objects: jest.fn(async function* (prefix: string) {
if (prefix === 'staging/') return;
yield* objects;
}),
stat: jest.fn().mockResolvedValue({ key, lastModified: old }),
remove: jest.fn().mockResolvedValue(undefined),
};
const emit = jest.fn();
const service = new ReconcileService(
prisma as unknown as PrismaService,
storage as unknown as StorageService,
emit,
);
const run = (apply = true) =>
service.run({ apply, graceSeconds: 600, prefix: 'originals/' }, now);
return { tx, prisma, storage, emit, run };
}
describe('attachment reconciliation', () => {
it('reports old orphans in dry-run without removing bytes', async () => {
const f = fixture();
expect(await f.run(false)).toMatchObject({
orphanCandidates: 1,
deletedObjects: 0,
});
expect(f.storage.remove).not.toHaveBeenCalled();
expect(f.emit).toHaveBeenCalledWith({
event: 'orphan_candidate',
objectKey: key,
});
});
it('deletes an old orphan and safely handles another pass after it is gone', async () => {
const f = fixture();
expect(await f.run()).toMatchObject({ deletedObjects: 1 });
f.storage.stat.mockResolvedValue(null);
expect(await f.run()).toMatchObject({ deletedObjects: 0 });
expect(f.storage.remove).toHaveBeenCalledTimes(1);
});
it('keeps fresh objects, unknown keys and objects with no trusted timestamp', async () => {
const f = fixture([
{ key, lastModified: fresh },
{ key: 'originals/manual.txt', lastModified: old },
{ key },
]);
expect(await f.run()).toMatchObject({
freshObjects: 2,
unknownObjects: 1,
deletedObjects: 0,
});
expect(f.prisma.$transaction).not.toHaveBeenCalled();
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('does not delete objects referenced by metadata', async () => {
const f = fixture();
f.tx.attachment.findUnique.mockResolvedValue({ id: 'published' });
expect(await f.run()).toMatchObject({
referencedObjects: 1,
deletedObjects: 0,
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('skips an object locked by an active uploader or another cleaner', async () => {
const f = fixture();
f.tx.$queryRaw.mockResolvedValue([{ locked: false }]);
expect(await f.run()).toMatchObject({
lockedObjects: 1,
deletedObjects: 0,
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('rechecks current S3 age instead of trusting an old LIST result', async () => {
const f = fixture();
f.storage.stat.mockResolvedValue({ key, lastModified: fresh });
expect(await f.run()).toMatchObject({ freshObjects: 1, deletedObjects: 0 });
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('rechecks metadata immediately before deletion', async () => {
const f = fixture();
f.tx.attachment.findUnique
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: 'published' });
expect(await f.run()).toMatchObject({
referencedObjects: 1,
deletedObjects: 0,
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('aborts before contacting S3 if the DB is unavailable', async () => {
const f = fixture();
f.prisma.$queryRaw.mockRejectedValue(new Error('DB unavailable'));
await expect(f.run()).rejects.toThrow('DB unavailable');
expect(f.storage.ready).not.toHaveBeenCalled();
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('does not delete when the DB fails after the S3 age check', async () => {
const f = fixture();
f.tx.attachment.findUnique
.mockResolvedValueOnce(null)
.mockRejectedValueOnce(new Error('DB unavailable'));
await expect(f.run()).rejects.toThrow('DB unavailable');
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('does not treat S3 failure as a missing object or successful cleanup', async () => {
const f = fixture();
f.storage.stat.mockRejectedValue(new Error('S3 unavailable'));
await expect(f.run()).rejects.toThrow('S3 unavailable');
expect(f.storage.remove).not.toHaveBeenCalled();
expect(f.emit).not.toHaveBeenCalled();
});
it('reports missing bytes without deleting metadata', async () => {
const f = fixture([]);
f.prisma.attachment.findMany.mockResolvedValue([
{ id: 'published', objectKey: key },
]);
f.storage.stat.mockResolvedValue(null);
expect(await f.run()).toMatchObject({
missingObjects: 1,
deletedObjects: 0,
});
expect(f.emit).toHaveBeenCalledWith({
event: 'missing_object',
objectKey: key,
attachmentId: 'published',
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
});
describe('reconciliation CLI options', () => {
it('defaults to dry-run with a ten-minute grace and one-minute interval', () => {
expect(reconcileOptions([], {})).toMatchObject({
apply: false,
watch: false,
graceSeconds: 600,
intervalSeconds: 60,
});
});
it('accepts explicit apply and a scope limited to one chat', () => {
expect(
reconcileOptions(
['--apply', '--prefix', key.slice(0, key.lastIndexOf('/') + 1)],
{ ORPHAN_GRACE_SECONDS: '1200' },
),
).toMatchObject({ apply: true, graceSeconds: 1200 });
});
it.each(['0', '-1', '1.5', 'NaN', '999999999999'])(
'rejects invalid grace %s',
(value) => {
expect(() =>
reconcileOptions([], { ORPHAN_GRACE_SECONDS: value }),
).toThrow();
},
);
it('rejects unsafe prefixes and conflicting modes', () => {
expect(() => reconcileOptions(['--prefix', 'other/'], {})).toThrow();
expect(() => reconcileOptions(['--apply', '--dry-run'], {})).toThrow();
expect(() => reconcileOptions(['--unknown'], {})).toThrow();
});
});
+133
View File
@@ -0,0 +1,133 @@
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../Storage/storage.service';
import { OBJECT_TRANSACTION, tryAttachmentObjectLock } from './object-lock';
import { managedObjectKey, type ReconcileOptions } from './reconcile-options';
import { cleanStaging } from './staging-cleanup';
export interface ReconcileEvent {
event: string;
objectKey?: string;
attachmentId?: string;
}
export class ReconcileService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly emit: (event: ReconcileEvent) => void = () => {},
) {}
async run(options: ReconcileOptions, now = new Date()) {
const cutoff = now.getTime() - options.graceSeconds * 1000;
const report = {
mode: options.apply ? 'apply' : 'dry-run',
graceSeconds: options.graceSeconds,
prefix: options.prefix,
objectsScanned: 0,
freshObjects: 0,
referencedObjects: 0,
lockedObjects: 0,
unknownObjects: 0,
orphanCandidates: 0,
deletedObjects: 0,
missingObjects: 0,
};
const oldEnough = (date?: Date) =>
date !== undefined &&
Number.isFinite(date.getTime()) &&
date.getTime() <= cutoff;
// Check the DB before contacting S3. Any subsequent DB/S3 error aborts this pass.
await this.prisma.$queryRaw`SELECT 1`;
await this.storage.ready();
for await (const object of this.storage.objects(options.prefix)) {
options.signal?.throwIfAborted();
report.objectsScanned++;
if (!managedObjectKey(object.key)) {
report.unknownObjects++;
continue;
}
if (!oldEnough(object.lastModified)) {
report.freshObjects++;
continue;
}
const outcome = await this.prisma.$transaction(async (tx) => {
if (!(await tryAttachmentObjectLock(tx, object.key))) return 'locked';
if (
await tx.attachment.findUnique({
where: { objectKey: object.key },
select: { id: true },
})
) {
return 'referenced';
}
// LIST timestamps may be stale. HEAD checks the current object under the writer lock.
const current = await this.storage.stat(object.key);
if (!current) return 'gone';
if (!oldEnough(current.lastModified)) return 'fresh';
// Recheck immediately before DELETE, also detecting DB failure after HEAD.
if (
await tx.attachment.findUnique({
where: { objectKey: object.key },
select: { id: true },
})
) {
return 'referenced';
}
options.signal?.throwIfAborted();
if (options.apply) await this.storage.remove(object.key);
return options.apply ? 'deleted' : 'candidate';
}, OBJECT_TRANSACTION);
if (outcome === 'locked') report.lockedObjects++;
if (outcome === 'referenced') report.referencedObjects++;
if (outcome === 'fresh') report.freshObjects++;
if (outcome === 'candidate' || outcome === 'deleted') {
report.orphanCandidates++;
if (outcome === 'deleted') report.deletedObjects++;
this.emit({
event: outcome === 'deleted' ? 'orphan_deleted' : 'orphan_candidate',
objectKey: object.key,
});
}
}
// Reverse check: missing bytes are an integrity incident, never a reason to delete metadata.
let after: string | undefined;
while (true) {
options.signal?.throwIfAborted();
const rows = await this.prisma.attachment.findMany({
where: {
status: 'ready',
objectKey: { startsWith: options.prefix },
...(after ? { id: { gt: after } } : {}),
},
select: { id: true, objectKey: true },
orderBy: { id: 'asc' },
take: 200,
});
for (const row of rows) {
options.signal?.throwIfAborted();
if (!(await this.storage.stat(row.objectKey))) {
report.missingObjects++;
this.emit({
event: 'missing_object',
objectKey: row.objectKey,
attachmentId: row.id,
});
}
}
if (rows.length < 200) break;
after = rows[rows.length - 1].id;
}
// Chat-scoped original-only diagnostics must not scan another chat's staging.
if (options.prefix === 'originals/') {
const staging = await cleanStaging(
this.prisma,
this.storage,
options,
now,
);
return { ...report, ...staging };
}
return report;
}
}
+110
View File
@@ -0,0 +1,110 @@
import { randomUUID } from 'node:crypto';
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import { cleanStaging } from './staging-cleanup';
function fixture() {
const chat = randomUUID();
const id = randomUUID();
const key = `staging/${chat}/${id}`;
const now = new Date();
const old = new Date(now.getTime() - 1200000);
const upload = { chatId: chat, expiresAt: old };
const tx = {
$queryRaw: jest.fn().mockResolvedValue([{ locked: true }]),
$executeRaw: jest.fn().mockResolvedValue(0),
directUpload: { findUnique: jest.fn().mockResolvedValue(upload) },
attachment: { findFirst: jest.fn().mockResolvedValue(null) },
};
const db = {
$queryRaw: jest.fn().mockResolvedValue([]),
$transaction: jest.fn(async (fn: (value: unknown) => unknown) => fn(tx)),
directUpload: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) },
};
const storage = {
objects: jest.fn(async function* () {
yield { key, lastModified: old };
}),
stat: jest.fn().mockResolvedValue({ key, lastModified: old }),
remove: jest.fn().mockResolvedValue(undefined),
};
const options = {
apply: true,
graceSeconds: 600,
prefix: `originals/${chat}/`,
};
const run = (apply = true) =>
cleanStaging(
db as unknown as PrismaService,
storage as unknown as StorageService,
{ ...options, apply },
now,
);
return { key, chat, now, upload, tx, db, storage, run };
}
describe('staging cleanup', () => {
it('keeps aged staging while an accepted job is queued or processing', async () => {
const f = fixture();
f.tx.attachment.findFirst.mockResolvedValue({ id: 'active' });
expect(await f.run()).toMatchObject({ stagingProtected: 1 });
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('checks the replay retention deadline before deleting failed staging', async () => {
const f = fixture();
f.tx.attachment.findFirst.mockResolvedValue({ id: 'retained' });
expect(await f.run()).toMatchObject({ stagingProtected: 1 });
expect(f.tx.attachment.findFirst).toHaveBeenCalledWith({
where: expect.objectContaining({
OR: expect.arrayContaining([
{ status: 'failed', replayUntil: { gt: f.now } },
]),
}),
select: { id: true },
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('deletes only aged objects after reservation expiry plus grace', async () => {
const f = fixture();
expect(await f.run()).toMatchObject({ stagingDeleted: 1 });
expect(f.storage.objects).toHaveBeenCalledWith(`staging/${f.chat}/`);
expect(f.storage.remove).toHaveBeenCalledWith(f.key);
expect(f.db.directUpload.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ chatId: f.chat }),
}),
);
});
it('protects an unexpired URL even if the object already looks old', async () => {
const f = fixture();
f.upload.expiresAt = new Date(f.now.getTime() + 60000);
expect(await f.run()).toMatchObject({
stagingDeleted: 0,
stagingProtected: 1,
});
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('protects an active complete and a freshly recreated staging object', async () => {
const f = fixture();
f.tx.$queryRaw.mockResolvedValueOnce([{ locked: false }]);
expect(await f.run()).toMatchObject({ stagingProtected: 1 });
f.storage.stat.mockResolvedValueOnce({ key: f.key, lastModified: f.now });
expect(await f.run()).toMatchObject({ stagingProtected: 1 });
expect(f.storage.remove).not.toHaveBeenCalled();
});
it('performs a dry run without deleting files or changing reservations', async () => {
const f = fixture();
expect(await f.run(false)).toMatchObject({
stagingCandidates: 1,
stagingDeleted: 0,
});
expect(f.storage.remove).not.toHaveBeenCalled();
expect(f.db.directUpload.updateMany).not.toHaveBeenCalled();
});
it('fails closed when PostgreSQL is unavailable', async () => {
const f = fixture();
f.db.$queryRaw.mockRejectedValueOnce(new Error('database unavailable'));
await expect(f.run()).rejects.toThrow('database unavailable');
expect(f.storage.objects).not.toHaveBeenCalled();
});
});
+89
View File
@@ -0,0 +1,89 @@
import type { PrismaService } from '../prisma/prisma.service';
import type { StorageService } from '../Storage/storage.service';
import { uuidPattern } from '../common/validation';
import type { ReconcileOptions } from './reconcile-options';
import { OBJECT_TRANSACTION, tryAttachmentObjectLock } from './object-lock';
export async function cleanStaging(
db: PrismaService,
storage: StorageService,
options: ReconcileOptions,
now: Date,
) {
const cutoff = new Date(now.getTime() - options.graceSeconds * 1000);
const scope =
options.prefix === 'originals/' ? undefined : options.prefix.split('/')[1];
if (
options.prefix !== 'originals/' &&
(!scope ||
options.prefix !== `originals/${scope}/` ||
!uuidPattern.test(scope))
)
throw new Error('Unsafe staging cleanup scope');
const prefix = scope ? `staging/${scope}/` : 'staging/';
const report = {
stagingScanned: 0,
stagingProtected: 0,
stagingCandidates: 0,
stagingDeleted: 0,
};
// Fail closed before looking for objects. Never infer "no intent" from a DB outage.
await db.$queryRaw`SELECT 1`;
for await (const object of storage.objects(prefix)) {
options.signal?.throwIfAborted();
report.stagingScanned++;
const parts = object.key.split('/');
if (
parts.length !== 3 ||
parts[0] !== 'staging' ||
!uuidPattern.test(parts[1]) ||
!uuidPattern.test(parts[2]) ||
!object.lastModified ||
object.lastModified > cutoff
) {
report.stagingProtected++;
continue;
}
const outcome = await db.$transaction(async (tx) => {
if (!(await tryAttachmentObjectLock(tx, object.key))) return false;
const protectedAttachment = await tx.attachment.findFirst({
where: {
id: parts[2],
chatId: parts[1],
OR: [
{ status: { in: ['queued', 'processing'] } },
{ status: 'failed', replayUntil: { gt: now } },
],
},
select: { id: true },
});
if (protectedAttachment) return false;
const upload = await tx.directUpload.findUnique({
where: { id: parts[2] },
});
// Wait for BOTH signature expiry and grace. A late replay must not outlive its reservation.
if (upload && (upload.chatId !== parts[1] || upload.expiresAt > cutoff))
return false;
const current = await storage.stat(object.key);
if (!current || !current.lastModified || current.lastModified > cutoff)
return false;
options.signal?.throwIfAborted();
if (options.apply) await storage.remove(object.key);
return true;
}, OBJECT_TRANSACTION);
if (outcome) {
report.stagingCandidates++;
if (options.apply) report.stagingDeleted++;
} else report.stagingProtected++;
}
if (options.apply)
await db.directUpload.updateMany({
where: {
status: 'pending',
expiresAt: { lte: cutoff },
...(scope ? { chatId: scope } : {}),
},
data: { status: 'expired' },
});
return report;
}
+69
View File
@@ -0,0 +1,69 @@
import {
Body,
Controller,
Delete,
HttpCode,
HttpStatus,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBasicAuth,
ApiBearerAuth,
ApiCreatedResponse,
ApiNoContentResponse,
ApiOperation,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from '../User/user.guard';
import { AuthService } from './auth.service';
import { Session } from './auth.schema';
@ApiTags('auth')
@Controller('api/v1/auth/sessions')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiBasicAuth('basicAuth')
@ApiOperation({
operationId: 'createSession',
summary: 'Вход',
})
@ApiCreatedResponse({ type: Session })
@ApiUnauthorizedResponse({
headers: {
'WWW-Authenticate': {
schema: { type: 'string' },
example: 'Basic realm="messenger", charset="UTF-8"',
},
},
})
create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {
return this.auth.login(request.headers.authorization, body);
}
@Delete('current')
@HttpCode(HttpStatus.NO_CONTENT)
@UseGuards(UserGuard)
@ApiBearerAuth('bearerAuth')
@ApiOperation({
operationId: 'revokeSession',
summary: 'Отзыв текущей сессии',
})
@ApiNoContentResponse()
@ApiUnauthorizedResponse({
headers: {
'WWW-Authenticate': {
schema: { type: 'string' },
example: 'Bearer realm="messenger"',
},
},
})
logout(@Req() request: AuthenticatedRequest) {
return this.auth.logout(request.currentSessionId);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { HttpStatus } from '@nestjs/common';
import { ApiException } from '../common/exceptions/api.exception';
export class AuthException extends ApiException {
readonly challenge: string;
constructor(scheme: 'Basic' | 'Bearer') {
super(
HttpStatus.UNAUTHORIZED,
'unauthorized',
'Требуется действительная аутентификация',
);
this.challenge =
scheme === 'Basic'
? 'Basic realm="messenger", charset="UTF-8"'
: 'Bearer realm="messenger"';
}
}
+15
View File
@@ -0,0 +1,15 @@
import { ApiProperty } from '@nestjs/swagger';
import { User } from '../User/user.schema';
export class Session {
token!: string;
@ApiProperty({ enum: ['Bearer'] })
token_type!: 'Bearer';
@ApiProperty({ format: 'date-time' })
expires_at!: string;
@ApiProperty({ type: User })
user!: User;
}
+182
View File
@@ -0,0 +1,182 @@
import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'node:crypto';
import { TextDecoder } from 'node:util';
import { PrismaService } from '../prisma/prisma.service';
import { Prisma } from '../generated/prisma/client';
import { UserService } from '../User/user.service';
import type { User } from '../User/user.schema';
import { invalidRequest, uuid, uuidPattern } from '../common/validation';
import { ApiException } from '../common/exceptions/api.exception';
import { AuthException } from './auth.exception';
import { PasswordService, validPassword } from './password.service';
import type { Session } from './auth.schema';
export interface ChatAccess {
chatId: string;
userId: string;
messagesEpoch: string;
}
@Injectable()
export class AuthService {
private readonly ttlSeconds: number;
constructor(
private readonly prisma: PrismaService,
private readonly users: UserService,
private readonly passwords: PasswordService,
) {
this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);
if (
!Number.isSafeInteger(this.ttlSeconds) ||
this.ttlSeconds <= 0 ||
Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())
) {
throw new Error(
'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',
);
}
}
async login(authorization: unknown, body: unknown): Promise<Session> {
const { username, password } = this.basicCredentials(authorization);
const user = await this.prisma.user.findUnique({ where: { username } });
const verified = await this.passwords.verify(
password,
user?.passwordHash ?? null,
);
if (!user || !verified) throw new AuthException('Basic');
if (body !== undefined)
return invalidRequest('Вход через Basic не принимает тело запроса');
const token = randomBytes(32).toString('base64url');
const session = await this.prisma.session.create({
data: {
userId: user.id,
tokenHash: this.tokenHash(token),
expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),
},
});
return {
token,
token_type: 'Bearer',
expires_at: session.expiresAt.toISOString(),
user: this.users.serialize(user),
};
}
async authenticate(
authorization: unknown,
chatId?: unknown,
): Promise<{
user: User;
sessionId: string;
chatsEpoch: string;
chatAccess?: ChatAccess;
}> {
const match =
typeof authorization === 'string' &&
/^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);
if (!match) throw new AuthException('Bearer');
const requestedChat =
typeof chatId === 'string' && uuidPattern.test(chatId)
? chatId.toLowerCase()
: null;
const [session] = await this.prisma.$queryRaw<
{
id: string;
userId: string;
username: string;
displayName: string;
createdAt: Date;
chatsEpoch: bigint;
chatId: string | null;
messagesEpoch: bigint | null;
}[]
>(Prisma.sql`
SELECT s.id, s.user_id AS "userId", u.chats_epoch AS "chatsEpoch",
u.username, u.display_name AS "displayName", u.created_at AS "createdAt",
${
chatId === undefined
? Prisma.sql`NULL::uuid AS "chatId", NULL::bigint AS "messagesEpoch"`
: Prisma.sql`c.id AS "chatId", COALESCE((SELECT SUM(e.epoch) FROM "public"."chat_message_epochs" AS e WHERE e.chat_id = c.id), 0)::bigint AS "messagesEpoch"`
}
FROM sessions AS s
JOIN users AS u ON u.id = s.user_id
${
chatId === undefined
? Prisma.empty
: Prisma.sql`
LEFT JOIN chat_members AS cm
ON cm.user_id = s.user_id AND cm.chat_id = ${requestedChat}::uuid
LEFT JOIN chats AS c ON c.id = cm.chat_id
`
}
WHERE s.token_hash = ${this.tokenHash(match[1])}
AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}
LIMIT 1
`);
if (!session) throw new AuthException('Bearer');
if (chatId !== undefined) {
uuid(chatId, 'chat_id');
if (session.chatId === null || session.messagesEpoch === null)
throw new ApiException(404, 'not_found', 'Объект не найден');
}
return {
user: this.users.serialize({ ...session, id: session.userId }),
sessionId: session.id,
chatsEpoch: session.chatsEpoch.toString(),
chatAccess:
session.chatId !== null && session.messagesEpoch !== null
? {
chatId: session.chatId,
userId: session.userId,
messagesEpoch: session.messagesEpoch.toString(),
}
: undefined,
};
}
async logout(sessionId: string): Promise<void> {
const now = new Date();
const result = await this.prisma.session.updateMany({
where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },
data: { revokedAt: now },
});
if (result.count !== 1) throw new AuthException('Bearer');
}
private tokenHash(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
private basicCredentials(authorization: unknown): {
username: string;
password: string;
} {
const match =
typeof authorization === 'string' &&
/^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);
if (!match) throw new AuthException('Basic');
try {
const bytes = Buffer.from(match[1], 'base64');
if (
bytes.toString('base64').replace(/=+$/, '') !==
match[1].replace(/=+$/, '')
)
throw new AuthException('Basic');
const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
const colon = value.indexOf(':');
const username = value.slice(0, colon);
const password = value.slice(colon + 1);
if (
colon < 0 ||
!/^[a-z0-9_]{3,32}$/.test(username) ||
!validPassword(password)
)
throw new AuthException('Basic');
return { username, password };
} catch {
throw new AuthException('Basic');
}
}
}
+72
View File
@@ -0,0 +1,72 @@
import { Injectable } from '@nestjs/common';
import { argon2, randomBytes, timingSafeEqual } from 'node:crypto';
import { invalidRequest } from '../common/validation';
const argonParameters = {
memory: 19456,
passes: 2,
parallelism: 1,
tagLength: 32,
};
const argonPrefix = '$argon2id$v=19$m=19456,t=2,p=1';
function decodeBase64(value: string, length: number) {
const decoded = Buffer.from(value, 'base64');
return decoded.length === length &&
decoded.toString('base64').replace(/=+$/, '') === value
? decoded
: undefined;
}
function argonHash(value: string | null) {
const parts = value?.split('$');
if (parts?.length !== 6 || parts.slice(0, 4).join('$') !== argonPrefix)
return undefined;
const salt = decodeBase64(parts[4], 16);
const key = decodeBase64(parts[5], 32);
return salt && key ? { salt, key } : undefined;
}
export function validPassword(value: unknown): value is string {
if (typeof value !== 'string' || value.trim().length === 0) return false;
const length = Array.from(value).length;
return length >= 12 && length <= 128;
}
export function registrationPassword(value: unknown): string {
if (!validPassword(value))
return invalidRequest('Пароль должен содержать 12–128 Unicode-символов');
return value;
}
@Injectable()
export class PasswordService {
async hash(password: string): Promise<string> {
const salt = randomBytes(16);
const key = await this.deriveArgon(password, salt);
return `${argonPrefix}$${salt.toString('base64').replace(/=+$/, '')}$${key.toString('base64').replace(/=+$/, '')}`;
}
async verify(password: string, storedHash: string | null): Promise<boolean> {
const stored = argonHash(storedHash);
const key = await this.deriveArgon(
password,
stored?.salt ?? Buffer.alloc(16),
);
const matches = timingSafeEqual(key, stored?.key ?? Buffer.alloc(32));
return Boolean(stored && matches);
}
private deriveArgon(password: string, salt: Buffer): Promise<Buffer> {
return new Promise((resolve, reject) => {
argon2(
'argon2id',
{ ...argonParameters, message: password, nonce: salt },
(error, key) => {
if (error) reject(error);
else resolve(key);
},
);
});
}
}
+132
View File
@@ -0,0 +1,132 @@
import {
Body,
Controller,
Get,
Headers,
HttpCode,
HttpStatus,
Param,
Post,
Query,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBody,
ApiBearerAuth,
ApiCreatedResponse,
ApiHeader,
ApiOkResponse,
ApiOperation,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from '../User/user.guard';
import {
CreateChatDto,
CreateMessageDto,
Chat,
Message,
ChatPage,
MessagePage,
} from './chat.schema';
import { ChatService } from './chat.service';
@ApiTags('chats')
@ApiBearerAuth('bearerAuth')
@UseGuards(UserGuard)
@Controller('api/v1/chats')
export class ChatController {
constructor(private readonly chats: ChatService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiBody({ type: CreateChatDto })
@ApiOperation({ operationId: 'createChat' })
@ApiCreatedResponse({ type: Chat })
create(@Req() request: AuthenticatedRequest, @Body() body: unknown) {
return this.chats.create(body, request.currentUser.id);
}
@Get()
@ApiOperation({ operationId: 'listChats' })
@ApiOkResponse({ type: ChatPage })
@ApiQuery({
name: 'limit',
required: false,
schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },
})
@ApiQuery({ name: 'cursor', required: false, type: String })
list(
@Req() request: AuthenticatedRequest,
@Query('limit') limit: unknown,
@Query('cursor') cursor: unknown,
) {
return this.chats.list(
request.currentUser.id,
limit,
cursor,
request.currentChatsEpoch,
);
}
@Get(':chat_id')
@ApiOperation({ operationId: 'getChat' })
@ApiOkResponse({ type: Chat })
get(@Req() request: AuthenticatedRequest, @Param('chat_id') chatId: string) {
return this.chats.get(chatId, request.currentUser.id);
}
@Post(':chat_id/messages')
@HttpCode(HttpStatus.CREATED)
@ApiBody({ type: CreateMessageDto })
@ApiHeader({
name: 'Idempotency-Key',
required: true,
schema: {
type: 'string',
minLength: 1,
maxLength: 128,
pattern: '^[A-Za-z0-9._:-]+$',
},
})
@ApiOperation({ operationId: 'createMessage' })
@ApiCreatedResponse({ type: Message })
createMessage(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Headers('idempotency-key') idempotencyKey: unknown,
@Body() body: unknown,
) {
return this.chats.createMessage(
chatId,
body,
request.currentUser.id,
idempotencyKey,
);
}
@Get(':chat_id/messages')
@ApiOperation({ operationId: 'listMessages' })
@ApiOkResponse({ type: MessagePage })
@ApiQuery({
name: 'limit',
required: false,
schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 },
})
@ApiQuery({ name: 'cursor', required: false, type: String })
listMessages(
@Req() request: AuthenticatedRequest,
@Param('chat_id') chatId: string,
@Query('limit') limit: unknown,
@Query('cursor') cursor: unknown,
) {
return this.chats.listMessages(
chatId,
request.currentUser.id,
limit,
cursor,
request.currentChatAccess,
);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { UserModule } from '../User/user.module';
import { ChatController } from './chat.controller';
import { ChatService } from './chat.service';
@Module({
imports: [UserModule],
controllers: [ChatController],
providers: [ChatService],
})
export class ChatModule {}
+68
View File
@@ -0,0 +1,68 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateChatDto {
@ApiProperty({ example: 'Проект по ВНП', maxLength: 100 })
title!: string;
@ApiProperty({ type: [String], format: 'uuid' })
member_ids!: string[];
}
export class CreateMessageDto {
@ApiProperty({ example: 'Привет, Боб!', maxLength: 4000 })
text!: string;
@ApiPropertyOptional({
type: [String],
format: 'uuid',
maxItems: 10,
uniqueItems: true,
default: [],
})
attachment_ids?: string[];
}
export class Chat {
@ApiProperty({ format: 'uuid' })
id!: string;
@ApiProperty({ maxLength: 100 })
title!: string;
@ApiProperty({ type: [String], format: 'uuid' })
member_ids!: string[];
@ApiProperty({ format: 'date-time' })
created_at!: string;
}
export class Message {
@ApiProperty({ format: 'uuid' })
id!: string;
@ApiProperty({ format: 'uuid' })
chat_id!: string;
@ApiProperty({ format: 'uuid' })
sender_id!: string;
@ApiProperty({ maxLength: 4000 })
text!: string;
@ApiProperty({ type: [String], format: 'uuid', maxItems: 10 })
attachment_ids!: string[];
@ApiProperty({ format: 'date-time' })
created_at!: string;
}
export class ChatPage {
@ApiProperty({ type: [Chat] })
items!: Chat[];
@ApiProperty({ type: String, nullable: true })
next_cursor!: string | null;
}
export class MessagePage {
@ApiProperty({ type: [Message] })
items!: Message[];
@ApiProperty({ type: String, nullable: true })
next_cursor!: string | null;
}
export interface Page<T> {
items: T[];
next_cursor: string | null;
}
+432
View File
@@ -0,0 +1,432 @@
import { HttpStatus, Injectable } from '@nestjs/common';
import { randomUUID } from 'node:crypto';
import type { ChatAccess } from '../Auth/auth.service';
import {
Prisma,
type Message as StoredMessage,
} from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { ApiException } from '../common/exceptions/api.exception';
import {
invalidRequest,
objectBody,
pageLimit,
requiredText,
uuid,
} from '../common/validation';
import type { Chat, Message, Page } from './chat.schema';
import { CacheService, CACHE_TTL } from '../cache/cache.service';
interface Cursor {
scope: string;
created_at: string;
id: string;
}
const chatInclude = {
members: { orderBy: { position: 'asc' as const } },
} satisfies Prisma.ChatInclude;
type StoredChat = Prisma.ChatGetPayload<{ include: typeof chatInclude }>;
@Injectable()
export class ChatService {
private readonly idempotencyTtlSeconds: number;
constructor(
private readonly prisma: PrismaService,
private readonly cache: CacheService,
) {
this.idempotencyTtlSeconds = Number(
process.env.IDEMPOTENCY_TTL_SECONDS ?? 86400,
);
if (
!Number.isSafeInteger(this.idempotencyTtlSeconds) ||
this.idempotencyTtlSeconds < 86400 ||
Number.isNaN(
new Date(Date.now() + this.idempotencyTtlSeconds * 1000).getTime(),
)
) {
throw new Error('IDEMPOTENCY_TTL_SECONDS must be at least 86400');
}
}
async create(value: unknown, userId: string): Promise<Chat> {
const body = objectBody(value, ['title', 'member_ids']);
const title = requiredText(body.title, 'title', 100);
if (
!Array.isArray(body.member_ids) ||
body.member_ids.length < 1 ||
body.member_ids.length > 100
) {
return invalidRequest('Некорректный member_ids');
}
const memberIds = body.member_ids.map((id: unknown) =>
uuid(id, 'member_ids'),
);
if (
new Set(memberIds).size !== memberIds.length ||
!memberIds.includes(userId)
) {
return invalidRequest(
'Список участников содержит дубликат или не содержит вызывающего',
);
}
try {
const chat = await this.prisma.$transaction(async (tx) => {
const count = await tx.user.count({ where: { id: { in: memberIds } } });
if (count !== memberIds.length)
return invalidRequest('Неизвестный участник чата');
const created = await tx.chat.create({
data: {
title,
members: {
create: memberIds.map((userId, position) => ({
userId,
position,
})),
},
},
include: chatInclude,
});
await tx.$executeRaw(Prisma.sql`
WITH locked AS MATERIALIZED (
SELECT id FROM users
WHERE id IN (${Prisma.join(memberIds.map((id) => Prisma.sql`${id}::uuid`))})
ORDER BY id FOR UPDATE
)
UPDATE users AS u SET chats_epoch = u.chats_epoch + 1
FROM locked WHERE u.id = locked.id
`);
return created;
});
return this.serializeChat(chat);
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2003'
) {
return invalidRequest('Неизвестный участник чата');
}
throw error;
}
}
async list(
userId: string,
limitValue: unknown,
cursorValue: unknown,
epoch: string,
): Promise<Page<Chat>> {
const limit = pageLimit(limitValue);
const scope = `chats:${userId}`;
const cursor = this.decodeCursor(cursorValue, scope);
return this.cache.remember(
scope,
{ limit, cursor },
CACHE_TTL.page,
async () => {
const chats = await this.prisma.chat.findMany({
where: { members: { some: { userId } }, ...this.after(cursor) },
include: chatInclude,
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
take: limit + 1,
});
return this.page(
chats.map((chat) => this.serializeChat(chat)),
limit,
scope,
);
},
epoch,
);
}
async get(value: unknown, userId: string): Promise<Chat> {
const { id } = await this.authorizeChat(value, userId);
return this.getMetadata(id);
}
private async authorizeChat(value: unknown, userId: string) {
const id = uuid(value, 'chat_id');
const [membership] = await this.prisma.$queryRaw<
{ id: string; messagesEpoch: bigint }[]
>(Prisma.sql`
SELECT c.id, COALESCE((SELECT SUM(e.epoch) FROM "public"."chat_message_epochs" AS e WHERE e.chat_id = c.id), 0)::bigint AS "messagesEpoch"
FROM chat_members AS cm JOIN chats AS c ON c.id = cm.chat_id
WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid
`);
if (!membership) {
throw new ApiException(
HttpStatus.NOT_FOUND,
'not_found',
'Объект не найден',
);
}
return membership;
}
private getMetadata(id: string): Promise<Chat> {
return this.cache.remember(
`chat:${id}`,
'metadata',
CACHE_TTL.entity,
async () => {
const chat = await this.prisma.chat.findUnique({
where: { id },
include: chatInclude,
});
if (!chat)
throw new ApiException(
HttpStatus.NOT_FOUND,
'not_found',
'Объект не найден',
);
return this.serializeChat(chat);
},
);
}
async createMessage(
chatId: unknown,
value: unknown,
userId: string,
keyValue: unknown,
): Promise<Message> {
const id = uuid(chatId, 'chat_id');
if (
typeof keyValue !== 'string' ||
!/^[A-Za-z0-9._:-]{1,128}$/.test(keyValue)
) {
return invalidRequest('Некорректный Idempotency-Key');
}
const body = objectBody(value, ['text', 'attachment_ids']);
const ids = body.attachment_ids === undefined ? [] : body.attachment_ids;
if (!Array.isArray(ids) || ids.length > 10)
return invalidRequest('Некорректный attachment_ids');
const attachmentIds = ids.map((value: unknown) =>
uuid(value, 'attachment_ids'),
);
if (new Set(attachmentIds).size !== attachmentIds.length)
return invalidRequest('Дубликат attachment_ids');
if (
typeof body.text !== 'string' ||
Array.from(body.text).length > 4000 ||
(body.text.trim().length === 0 && attachmentIds.length === 0)
) {
return invalidRequest('Некорректный text');
}
const text = body.text;
await this.authorizeChat(id, userId);
const sqlAttachmentIds = `{${attachmentIds.join(',')}}`;
return this.prisma.$transaction(async (tx) => {
await tx.$executeRaw(Prisma.sql`
DELETE FROM message_idempotency
WHERE user_id = ${userId}::uuid AND chat_id = ${id}::uuid
AND "key" = ${keyValue} AND expires_at <= NOW()
`);
const claimed = await tx.$queryRaw<{ key: string }[]>(Prisma.sql`
INSERT INTO message_idempotency (user_id, chat_id, "key", expires_at)
VALUES (
${userId}::uuid, ${id}::uuid, ${keyValue},
NOW() + (${this.idempotencyTtlSeconds} * INTERVAL '1 second')
)
ON CONFLICT (user_id, chat_id, "key") DO NOTHING
RETURNING "key"
`);
if (claimed.length === 0) {
const [existing] = await tx.$queryRaw<StoredMessage[]>(Prisma.sql`
SELECT m.id, m.chat_id AS "chatId", m.sender_id AS "senderId",
m.text, m.attachment_ids AS "attachmentIds", m.created_at AS "createdAt"
FROM message_idempotency AS i
JOIN messages AS m ON m.id = i.message_id
WHERE i.user_id = ${userId}::uuid AND i.chat_id = ${id}::uuid
AND i."key" = ${keyValue}
`);
if (!existing) throw new Error('Idempotency record has no message');
if (
existing.text !== text ||
JSON.stringify(existing.attachmentIds) !==
JSON.stringify(attachmentIds)
) {
throw new ApiException(
HttpStatus.CONFLICT,
'conflict',
'Idempotency-Key уже использован с другим сообщением',
);
}
return this.serializeMessage(existing);
}
if (attachmentIds.length) {
const statuses = await tx.$queryRaw<{ status: string }[]>(Prisma.sql`
SELECT status::text FROM attachments
WHERE chat_id = ${id}::uuid AND id = ANY(${sqlAttachmentIds}::uuid[])
ORDER BY id FOR SHARE
`);
if (statuses.length !== attachmentIds.length)
throw new ApiException(404, 'not_found', 'Вложение не найдено');
if (statuses.some(({ status }) => status === 'failed'))
throw new ApiException(409, 'conflict', 'Обработка вложения завершилась ошибкой');
}
const messageId = randomUUID();
const bucket = parseInt(messageId.slice(0, 2), 16) % 16;
const [message] = await tx.$queryRaw<StoredMessage[]>(Prisma.sql`
WITH updated AS (
INSERT INTO "public"."chat_message_epochs" AS e (chat_id, bucket, epoch)
SELECT cm.chat_id, ${bucket}::smallint, 1 FROM chat_members AS cm
WHERE cm.chat_id = ${id}::uuid AND cm.user_id = ${userId}::uuid
ON CONFLICT (chat_id, bucket) DO UPDATE SET epoch = e.epoch + 1
RETURNING chat_id
)
INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids)
SELECT ${messageId}::uuid, updated.chat_id, ${userId}::uuid, ${text}, ${sqlAttachmentIds}::uuid[] FROM updated
RETURNING id, chat_id AS "chatId", sender_id AS "senderId", text, attachment_ids AS "attachmentIds", created_at AS "createdAt"
`);
if (!message)
throw new ApiException(
HttpStatus.NOT_FOUND,
'not_found',
'Объект не найден',
);
await tx.$executeRaw(Prisma.sql`
UPDATE message_idempotency SET message_id = ${message.id}::uuid
WHERE user_id = ${userId}::uuid AND chat_id = ${id}::uuid
AND "key" = ${keyValue}
`);
return this.serializeMessage(message);
});
}
async listMessages(
chatId: unknown,
userId: string,
limitValue: unknown,
cursorValue: unknown,
access?: ChatAccess,
): Promise<Page<Message>> {
const id = uuid(chatId, 'chat_id');
const chat =
access?.chatId === id && access.userId === userId
? { id, messagesEpoch: access.messagesEpoch }
: await this.authorizeChat(id, userId);
const limit = pageLimit(limitValue);
const scope = `messages:${chat.id}`;
const cursor = this.decodeCursor(cursorValue, scope);
return this.cache.remember(
scope,
{ limit, cursor },
CACHE_TTL.page,
async () => {
const messages = cursor
? await this.prisma.$queryRaw<StoredMessage[]>(Prisma.sql`
SELECT id, chat_id AS "chatId", sender_id AS "senderId",
text, attachment_ids AS "attachmentIds", created_at AS "createdAt"
FROM "public"."messages"
WHERE chat_id = ${chat.id}::uuid
AND (created_at, id) >
(${new Date(cursor.created_at)}::timestamptz, ${cursor.id}::uuid)
ORDER BY created_at ASC, id ASC
LIMIT ${limit + 1}
`)
: await this.prisma.message.findMany({
where: { chatId: chat.id },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
take: limit + 1,
});
return this.page(
messages.map((message) => this.serializeMessage(message)),
limit,
scope,
);
},
chat.messagesEpoch.toString(),
);
}
private after(cursor: Cursor | null) {
if (!cursor) return {};
const createdAt = new Date(cursor.created_at);
return {
OR: [
{ createdAt: { gt: createdAt } },
{ createdAt, id: { gt: cursor.id } },
],
};
}
private serializeChat(chat: StoredChat): Chat {
return {
id: chat.id,
title: chat.title,
member_ids: chat.members.map((member) => member.userId),
created_at: chat.createdAt.toISOString(),
};
}
private serializeMessage(message: StoredMessage): Message {
return {
id: message.id,
chat_id: message.chatId,
sender_id: message.senderId,
text: message.text,
attachment_ids: message.attachmentIds,
created_at: message.createdAt.toISOString(),
};
}
private page<T extends { id: string; created_at: string }>(
items: T[],
limit: number,
scope: string,
): Page<T> {
const result = items.slice(0, limit);
const last = result.at(-1);
return {
items: result,
next_cursor:
items.length > limit && last
? Buffer.from(
JSON.stringify({
scope,
created_at: last.created_at,
id: last.id,
}),
).toString('base64url')
: null,
};
}
private decodeCursor(value: unknown, scope: string): Cursor | null {
if (value === undefined) return null;
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))
return invalidRequest('Некорректный cursor');
try {
const cursor: unknown = JSON.parse(
Buffer.from(value, 'base64url').toString('utf8'),
);
if (
typeof cursor !== 'object' ||
cursor === null ||
Array.isArray(cursor)
)
return invalidRequest('Некорректный cursor');
const data = cursor as Record<string, unknown>;
if (
data.scope !== scope ||
typeof data.created_at !== 'string' ||
Number.isNaN(Date.parse(data.created_at)) ||
typeof data.id !== 'string'
) {
return invalidRequest('Некорректный cursor');
}
return {
scope,
created_at: data.created_at,
id: uuid(data.id, 'cursor'),
};
} catch {
return invalidRequest('Некорректный cursor');
}
}
}
+5
View File
@@ -0,0 +1,5 @@
import { Module } from '@nestjs/common';
import { StorageService } from './storage.service';
@Module({ providers: [StorageService], exports: [StorageService] })
export class StorageModule {}
+136
View File
@@ -0,0 +1,136 @@
import { S3Client } from '@aws-sdk/client-s3';
import { createHash } from 'node:crypto';
import { mkdtemp, readFile, rm, rmdir } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { StorageService } from './storage.service';
describe('direct upload storage constraints', () => {
let storage: StorageService;
let directory: string;
let saved: Record<string, string | undefined>;
const names = [
'S3_ACCESS_KEY_ID',
'S3_SECRET_ACCESS_KEY',
'S3_ACCESS_KEY_ID_FILE',
'S3_SECRET_ACCESS_KEY_FILE',
'S3_PUBLIC_ENDPOINT',
];
const data = Buffer.from('streamed fixture');
const sha256 = createHash('sha256').update(data).digest('hex');
beforeEach(async () => {
saved = Object.fromEntries(names.map((name) => [name, process.env[name]]));
for (const name of names) delete process.env[name];
process.env.S3_ACCESS_KEY_ID = 'UNITONLY';
process.env.S3_SECRET_ACCESS_KEY = 'unit-only-synthetic-secret';
process.env.S3_PUBLIC_ENDPOINT = 'http://127.0.0.1:9000';
storage = new StorageService();
directory = await mkdtemp(join(tmpdir(), 'storage-unit-'));
});
afterEach(async () => {
jest.restoreAllMocks();
storage.onModuleDestroy();
await rm(join(directory, 'image'), { force: true });
await rmdir(directory);
for (const name of names) {
if (saved[name] === undefined) delete process.env[name];
else process.env[name] = saved[name];
}
});
it('binds size, MIME, checksum and create-only semantics into the signature', async () => {
const grant = await storage.presignPut(
'staging/test/object',
data.length,
'image/png',
sha256,
60,
new Date(),
);
const url = new URL(grant.url);
const signed = url.searchParams.get('X-Amz-SignedHeaders')?.split(';');
expect(signed).toEqual(
expect.arrayContaining([
'content-length',
'content-type',
'if-none-match',
'x-amz-checksum-sha256',
]),
);
expect(grant.headers['If-None-Match']).toBe('*');
expect(url.origin).toBe('http://127.0.0.1:9000');
expect(url.searchParams.get('X-Amz-Expires')).toBe('60');
});
it('hashes a bounded stream to disk, returning its source ETag', async () => {
jest.spyOn(S3Client.prototype, 'send').mockResolvedValue({
Body: Readable.from([data]),
ContentLength: data.length,
ContentType: 'image/png',
ETag: '"etag"',
} as never);
await expect(
storage.inspectToFile('staging/test/object', join(directory, 'image'), {
sizeBytes: data.length,
sha256,
contentType: 'image/png',
}),
).resolves.toBe('"etag"');
expect(await readFile(join(directory, 'image'))).toEqual(data);
});
it('propagates an attempt deadline to the S3 request and response stream', async () => {
const deadline = new AbortController();
const body = new Readable({ read: () => deadline.abort() });
const send = jest.spyOn(S3Client.prototype, 'send').mockResolvedValue({
Body: body,
ContentLength: data.length,
ContentType: 'image/png',
ETag: '"etag"',
} as never);
await expect(
storage.inspectToFile(
'staging/test/object',
join(directory, 'image'),
{
sizeBytes: data.length,
sha256,
contentType: 'image/png',
},
deadline.signal,
),
).rejects.toMatchObject({ status: 503 });
expect(send).toHaveBeenCalledWith(expect.anything(), {
abortSignal: expect.objectContaining({ aborted: true }),
});
expect(body.destroyed).toBe(true);
});
it('rejects a real checksum mismatch and a stream larger than its declared length', async () => {
const send = jest.spyOn(S3Client.prototype, 'send');
send.mockResolvedValueOnce({
Body: Readable.from([data]),
ContentLength: data.length,
ContentType: 'image/png',
ETag: '"etag"',
} as never);
await expect(
storage.inspectToFile('staging/test/object', join(directory, 'image'), {
sizeBytes: data.length,
sha256: '0'.repeat(64),
contentType: 'image/png',
}),
).rejects.toMatchObject({ status: 400 });
await rm(join(directory, 'image'));
send.mockResolvedValueOnce({
Body: Readable.from([data, data]),
ContentLength: data.length,
ContentType: 'image/png',
ETag: '"etag"',
} as never);
await expect(
storage.inspectToFile('staging/test/object', join(directory, 'image'), {
sizeBytes: data.length,
sha256,
contentType: 'image/png',
}),
).rejects.toMatchObject({ status: 413 });
});
});
+355
View File
@@ -0,0 +1,355 @@
import { Injectable, type OnModuleDestroy } from '@nestjs/common';
import { createWriteStream, readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import {
S3Client,
GetBucketLocationCommand,
PutObjectCommand,
GetObjectCommand,
DeleteObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
CopyObjectCommand,
} from '@aws-sdk/client-s3';
import { ApiException } from '../common/exceptions/api.exception';
import { profileStage } from '../common/http/upload-memory-profile';
export interface StoredObject {
key: string;
lastModified?: Date;
}
function credential(name: string): string {
const file = process.env[`${name}_FILE`];
const value = file ? readFileSync(file, 'utf8').trim() : process.env[name];
if (!value) throw new Error(`${name} or ${name}_FILE is required`);
return value;
}
@Injectable()
export class StorageService implements OnModuleDestroy {
private readonly bucket = process.env.S3_BUCKET ?? 'messenger-attachments';
private readonly client: S3Client;
private readonly signer: S3Client;
constructor() {
this.client = new S3Client({
endpoint: process.env.S3_ENDPOINT ?? 'http://s3:9000',
region: process.env.S3_REGION ?? 'us-east-1',
forcePathStyle: true,
maxAttempts: 1,
credentials: {
accessKeyId: credential('S3_ACCESS_KEY_ID'),
secretAccessKey: credential('S3_SECRET_ACCESS_KEY'),
},
requestHandler: { connectionTimeout: 2000, socketTimeout: 5000 },
});
const endpoint = new URL(
process.env.S3_PUBLIC_ENDPOINT ?? 'http://127.0.0.1:9000',
);
if (
!['http:', 'https:'].includes(endpoint.protocol) ||
endpoint.username ||
endpoint.password ||
endpoint.search ||
endpoint.hash ||
endpoint.pathname !== '/'
) {
throw new Error(
'S3_PUBLIC_ENDPOINT must be an HTTP(S) origin without credentials or a path',
);
}
this.signer = new S3Client({
endpoint: endpoint.origin,
region: process.env.S3_REGION ?? 'us-east-1',
forcePathStyle: true,
requestChecksumCalculation: 'WHEN_REQUIRED',
credentials: {
accessKeyId: credential('S3_ACCESS_KEY_ID'),
secretAccessKey: credential('S3_SECRET_ACCESS_KEY'),
},
});
}
async presignPut(
key: string,
size: number,
contentType: string,
sha256: string,
seconds: number,
now: Date,
) {
const checksum = Buffer.from(sha256, 'hex').toString('base64');
const url = await getSignedUrl(
this.signer,
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
ContentLength: size,
ContentType: contentType,
ChecksumSHA256: checksum,
IfNoneMatch: '*',
}),
{
expiresIn: seconds,
signingDate: now,
signableHeaders: new Set([
'content-length',
'content-type',
'if-none-match',
]),
unhoistableHeaders: new Set(['x-amz-checksum-sha256']),
},
);
const signed =
new URL(url).searchParams.get('X-Amz-SignedHeaders')?.split(';') ?? [];
if (
![
'content-length',
'content-type',
'if-none-match',
'x-amz-checksum-sha256',
].every((name) => signed.includes(name))
) {
throw new Error('Presigner omitted a required upload constraint');
}
return {
url,
headers: {
'Content-Type': contentType,
'Content-Length': String(size),
'If-None-Match': '*',
'x-amz-checksum-sha256': checksum,
},
};
}
async inspectToFile(
key: string,
filename: string,
expected: { sizeBytes: number; contentType: string; sha256: string },
signal?: AbortSignal,
) {
return this.run(async () => {
let object;
try {
object = await this.client.send(
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: this.operationSignal(15000, signal) },
);
} catch (error) {
if (
typeof error === 'object' &&
error !== null &&
'$metadata' in error &&
(error.$metadata as { httpStatusCode?: number } | undefined)
?.httpStatusCode === 404
) {
throw new ApiException(409, 'conflict', 'Файл ещё не загружен');
}
throw error;
}
if (!(object.Body instanceof Readable))
throw new Error('Missing S3 body');
const body = object.Body;
try {
if (object.ContentLength !== expected.sizeBytes)
throw new ApiException(
(object.ContentLength ?? 0) > 10485760 ? 413 : 400,
(object.ContentLength ?? 0) > 10485760
? 'payload_too_large'
: 'invalid_request',
'Размер файла не совпадает с разрешением',
);
if (object.ContentType !== expected.contentType)
throw new ApiException(
415,
'unsupported_media_type',
'Content-Type не совпадает с разрешением',
);
if (!object.ETag) throw new Error('S3 did not provide an ETag');
const hash = createHash('sha256');
let received = 0;
const bounded = new Transform({
transform(chunk: Buffer, _encoding, done) {
received += chunk.length;
if (received > expected.sizeBytes) {
done(
new ApiException(
413,
'payload_too_large',
'Превышен разрешённый размер',
),
);
return;
}
hash.update(chunk);
done(null, chunk);
},
});
profileStage('s3_stream_sha256_to_file');
await pipeline(
body,
bounded,
createWriteStream(filename, { flags: 'wx', mode: 0o600 }),
{ signal: this.operationSignal(15000, signal) },
);
profileStage('sha256_finalize');
if (
received !== expected.sizeBytes ||
hash.digest('hex') !== expected.sha256
)
throw new ApiException(
400,
'invalid_request',
'Checksum или размер файла не совпадает',
);
return object.ETag;
} finally {
body.destroy();
}
});
}
async publishCopy(
source: string,
destination: string,
etag: string,
signal?: AbortSignal,
): Promise<void> {
await this.run(() =>
this.client.send(
new CopyObjectCommand({
Bucket: this.bucket,
Key: destination,
CopySource: `${this.bucket}/${source.split('/').map(encodeURIComponent).join('/')}`,
CopySourceIfMatch: etag,
MetadataDirective: 'COPY',
}),
{ abortSignal: this.operationSignal(5000, signal) },
),
);
}
async ready(): Promise<void> {
await this.run(() =>
this.client.send(new GetBucketLocationCommand({ Bucket: this.bucket }), {
abortSignal: AbortSignal.timeout(5000),
}),
);
}
async put(
key: string,
bytes: Buffer,
contentType: string,
signal?: AbortSignal,
): Promise<void> {
await this.run(() =>
this.client.send(
new PutObjectCommand({
Bucket: this.bucket,
Key: key,
Body: bytes,
ContentLength: bytes.length,
ContentType: contentType,
}),
{ abortSignal: this.operationSignal(5000, signal) },
),
);
}
async get(key: string): Promise<Readable> {
return this.run(async () => {
const result = await this.client.send(
new GetObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: AbortSignal.timeout(5000) },
);
if (!(result.Body instanceof Readable))
throw new Error('Missing S3 body');
return result.Body;
});
}
async remove(key: string): Promise<void> {
await this.run(() =>
this.client.send(
new DeleteObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: AbortSignal.timeout(5000) },
),
);
}
async *objects(prefix: string): AsyncGenerator<StoredObject> {
let token: string | undefined;
do {
const page = await this.run(() =>
this.client.send(
new ListObjectsV2Command({
Bucket: this.bucket,
Prefix: prefix,
MaxKeys: 200,
ContinuationToken: token,
}),
{ abortSignal: AbortSignal.timeout(5000) },
),
);
for (const object of page.Contents ?? []) {
if (object.Key)
yield { key: object.Key, lastModified: object.LastModified };
}
if (!page.IsTruncated) break;
if (!page.NextContinuationToken || page.NextContinuationToken === token) {
throw new ApiException(503, 'unavailable', 'Некорректная страница S3');
}
token = page.NextContinuationToken;
} while (token);
}
async stat(key: string): Promise<StoredObject | null> {
return this.run(async () => {
try {
const object = await this.client.send(
new HeadObjectCommand({ Bucket: this.bucket, Key: key }),
{ abortSignal: AbortSignal.timeout(5000) },
);
return { key, lastModified: object.LastModified };
} catch (error) {
if (
typeof error === 'object' &&
error !== null &&
'$metadata' in error
) {
const metadata = error.$metadata as
{ httpStatusCode?: number } | undefined;
if (metadata?.httpStatusCode === 404) return null;
}
throw error;
}
});
}
onModuleDestroy(): void {
this.client.destroy();
this.signer.destroy();
}
private operationSignal(timeoutMs: number, signal?: AbortSignal) {
const timeout = AbortSignal.timeout(timeoutMs);
return signal ? AbortSignal.any([timeout, signal]) : timeout;
}
private async run<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (cause) {
if (cause instanceof ApiException) throw cause;
throw new ApiException(503, 'unavailable', 'Хранилище недоступно', {
cause,
});
}
}
}
+45
View File
@@ -0,0 +1,45 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import {
ApiBody,
ApiBearerAuth,
ApiCreatedResponse,
ApiOkResponse,
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { UserGuard, type AuthenticatedRequest } from './user.guard';
import { CreateUserDto, User } from './user.schema';
import { UserService } from './user.service';
@ApiTags('users')
@Controller('api/v1/users')
export class UserController {
constructor(private readonly users: UserService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiBody({ type: CreateUserDto })
@ApiOperation({ operationId: 'registerUser' })
@ApiCreatedResponse({ type: User })
create(@Body() body: unknown) {
return this.users.create(body);
}
@Get('me')
@UseGuards(UserGuard)
@ApiBearerAuth('bearerAuth')
@ApiOperation({ operationId: 'currentUser' })
@ApiOkResponse({ type: User })
me(@Req() request: AuthenticatedRequest) {
return request.currentUser;
}
}
+34
View File
@@ -0,0 +1,34 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import type { FastifyRequest } from 'fastify';
import { AuthService, type ChatAccess } from '../Auth/auth.service';
import type { User } from './user.schema';
export type AuthenticatedRequest = FastifyRequest & {
currentUser: User;
currentSessionId: string;
currentChatsEpoch: string;
currentChatAccess?: ChatAccess;
};
@Injectable()
export class UserGuard implements CanActivate {
constructor(private readonly auth: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
const chatId =
request.method === 'GET' &&
request.routeOptions.url === '/api/v1/chats/:chat_id/messages'
? (request.params as { chat_id: string }).chat_id
: undefined;
const session = await this.auth.authenticate(
request.headers.authorization,
chatId,
);
request.currentUser = session.user;
request.currentSessionId = session.sessionId;
request.currentChatsEpoch = session.chatsEpoch;
request.currentChatAccess = session.chatAccess;
return true;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserGuard } from './user.guard';
import { UserService } from './user.service';
import { AuthController } from '../Auth/auth.controller';
import { AuthService } from '../Auth/auth.service';
import { PasswordService } from '../Auth/password.service';
@Module({
controllers: [UserController, AuthController],
providers: [UserService, UserGuard, AuthService, PasswordService],
exports: [UserService, UserGuard, AuthService],
})
export class UserModule {}
+28
View File
@@ -0,0 +1,28 @@
import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ example: 'alice', pattern: '^[a-z0-9_]{3,32}$' })
username!: string;
@ApiProperty({ example: 'Алиса', maxLength: 100 })
display_name!: string;
@ApiProperty({
writeOnly: true,
minLength: 12,
maxLength: 128,
example: 'Example-only-not-a-real-secret-123',
})
password!: string;
}
export class User {
@ApiProperty({ format: 'uuid' })
id!: string;
@ApiProperty({ pattern: '^[a-z0-9_]{3,32}$' })
username!: string;
@ApiProperty({ minLength: 1, maxLength: 100 })
display_name!: string;
@ApiProperty({ format: 'date-time' })
created_at!: string;
}
+77
View File
@@ -0,0 +1,77 @@
import { HttpStatus, Injectable } from '@nestjs/common';
import { Prisma, type User as StoredUser } from '../generated/prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { ApiException } from '../common/exceptions/api.exception';
import { objectBody, requiredText } from '../common/validation';
import {
PasswordService,
registrationPassword,
} from '../Auth/password.service';
import type { User } from './user.schema';
import { CacheService, CACHE_TTL } from '../cache/cache.service';
@Injectable()
export class UserService {
constructor(
private readonly prisma: PrismaService,
private readonly passwords: PasswordService,
private readonly cache: CacheService,
) {}
async create(value: unknown): Promise<User> {
const body = objectBody(value, ['username', 'display_name', 'password']);
const username = body.username;
if (typeof username !== 'string' || !/^[a-z0-9_]{3,32}$/.test(username)) {
throw new ApiException(
HttpStatus.BAD_REQUEST,
'invalid_request',
'Некорректный username',
);
}
const displayName = requiredText(body.display_name, 'display_name', 100);
const password = registrationPassword(body.password);
const passwordHash = await this.passwords.hash(password);
try {
return this.serialize(
await this.prisma.user.create({
data: { username, displayName, passwordHash },
}),
);
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === 'P2002'
) {
throw new ApiException(
HttpStatus.CONFLICT,
'conflict',
'Username уже занят',
);
}
throw error;
}
}
async get(id: string): Promise<User | undefined> {
return this.cache.remember(
`user:${id}`,
'profile',
CACHE_TTL.entity,
async () => {
const user = await this.prisma.user.findUnique({ where: { id } });
return user ? this.serialize(user) : undefined;
},
);
}
serialize(
user: Pick<StoredUser, 'id' | 'username' | 'displayName' | 'createdAt'>,
): User {
return {
id: user.id,
username: user.username,
display_name: user.displayName,
created_at: user.createdAt.toISOString(),
};
}
}
+43
View File
@@ -0,0 +1,43 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaService } from './prisma/prisma.service';
import { StorageService } from './Storage/storage.service';
describe('AppController', () => {
let appController: AppController;
const queryRaw = jest.fn();
beforeEach(async () => {
queryRaw.mockReset();
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [
AppService,
{ provide: PrismaService, useValue: { $queryRaw: queryRaw } },
{
provide: StorageService,
useValue: { ready: jest.fn().mockResolvedValue(undefined) },
},
],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
it('reports ready when PostgreSQL is reachable', async () => {
queryRaw.mockResolvedValue([{ '?column?': 1 }]);
await expect(appController.ready()).resolves.toEqual({ status: 'ok' });
});
it('returns 503 when PostgreSQL is unavailable', async () => {
queryRaw.mockRejectedValue(new Error('connection refused'));
await expect(appController.ready()).rejects.toMatchObject({ status: 503 });
});
});
+55
View File
@@ -0,0 +1,55 @@
import { Controller, Get, HttpStatus } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { AppService } from './app.service';
import { PrismaService } from './prisma/prisma.service';
import { ApiException } from './common/exceptions/api.exception';
import { DrainingFastifyAdapter } from './common/http/fastify-adapter';
import { StorageService } from './Storage/storage.service';
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly prisma: PrismaService,
private readonly adapterHost: HttpAdapterHost,
private readonly storage: StorageService,
) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('health/live')
live() {
return { status: 'ok' };
}
@Get('health/ready')
async ready() {
this.assertNotDraining();
try {
await this.prisma.$queryRaw`SELECT 1`;
} catch {
throw new ApiException(
HttpStatus.SERVICE_UNAVAILABLE,
'unavailable',
'База данных недоступна',
);
}
await this.storage.ready();
this.assertNotDraining();
return { status: 'ok' };
}
private assertNotDraining(): void {
const adapter = this.adapterHost.httpAdapter;
if (adapter instanceof DrainingFastifyAdapter && adapter.isDraining) {
throw new ApiException(
HttpStatus.SERVICE_UNAVAILABLE,
'unavailable',
'API завершает работу',
);
}
}
}
+62
View File
@@ -0,0 +1,62 @@
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { LoggerModule } from 'nestjs-pino';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { UserModule } from './User/user.module';
import { ChatModule } from './Chat/chat.module';
import { PrismaModule } from './prisma/prisma.module';
import { CacheModule } from './cache/cache.module';
import { AttachmentModule } from './Attachment/attachment.module';
import { StorageModule } from './Storage/storage.module';
@Module({
imports: [
PrismaModule,
CacheModule,
UserModule,
ChatModule,
AttachmentModule,
StorageModule,
LoggerModule.forRoot({
pinoHttp: {
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
transport:
process.env.NODE_ENV !== 'production'
? {
target: 'pino-pretty',
options: {
colorize: true,
singleLine: true,
translateTime: 'SYS:standard',
},
}
: undefined,
redact: {
paths: [
'req.headers.authorization',
'req.headers.cookie',
'res.headers.set-cookie',
],
censor: '[REDACTED]',
},
autoLogging: {
ignore: (request) => request.url === '/health',
},
},
}),
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+108
View File
@@ -0,0 +1,108 @@
import {
ATTACHMENT_GROUP,
ATTACHMENT_TOPIC,
attachmentKafka,
parseAttachmentJob,
} from './Attachment/attachment-kafka';
import sharp from 'sharp';
import {
AttachmentAttemptTimeout,
AttachmentWorker,
} from './Attachment/attachment-worker';
import { PrismaService } from './prisma/prisma.service';
import { StorageService } from './Storage/storage.service';
function setting(name: string, defaultValue: number, min: number, max: number) {
const value = Number(process.env[name] ?? defaultValue);
if (!Number.isSafeInteger(value) || value < min || value > max)
throw new Error(`${name} must be between ${min} and ${max}`);
return value;
}
async function main() {
sharp.cache(false);
sharp.concurrency(1);
const concurrency = setting('WORKER_CONCURRENCY', 1, 1, 4);
const maxBytesPerPartition = setting(
'WORKER_PREFETCH_BYTES',
1048576,
1024,
1048576,
);
const stop = new AbortController();
const db = new PrismaService();
const worker = new AttachmentWorker(db, new StorageService());
const consumer = attachmentKafka('attachment-worker').consumer({
groupId: ATTACHMENT_GROUP,
allowAutoTopicCreation: false,
maxBytesPerPartition,
sessionTimeout: 150000,
retry: { retries: 8, maxRetryTime: 5000 },
});
consumer.on(consumer.events.CRASH, ({ payload }) => {
if (!stop.signal.aborted && !payload.restart) {
console.error('Attachment consumer stopped');
process.exit(1);
}
});
await db.$connect();
await consumer.connect();
await consumer.subscribe({ topic: ATTACHMENT_TOPIC, fromBeginning: true });
const shutdown = async () => {
if (stop.signal.aborted) return;
stop.abort();
try {
await consumer.disconnect();
await db.$disconnect();
} catch {
console.error('Attachment worker shutdown failed');
process.exit(1);
}
};
process.on('SIGTERM', () => {
void shutdown();
});
process.on('SIGINT', () => {
void shutdown();
});
await consumer.run({
autoCommit: false,
partitionsConsumedConcurrently: concurrency,
eachMessage: async (payload) => {
const { topic, partition, message } = payload;
const job = parseAttachmentJob(message.value, message.key);
if (!job)
console.warn('Ignoring an invalid Kafka attachment job', {
partition,
offset: message.offset,
});
if (
!job ||
(await worker
.process(job, () => payload.heartbeat(), stop.signal)
.catch((error: unknown) => {
if (error instanceof AttachmentAttemptTimeout) {
console.error(
'Attachment processing deadline reached. Restarting worker.',
);
process.exit(1);
}
throw error;
}))
) {
await consumer.commitOffsets([
{
topic,
partition,
offset: (BigInt(message.offset) + 1n).toString(),
},
]);
}
},
});
}
void main().catch(() => {
console.error('Attachment worker startup failed');
process.exit(1);
});
+6
View File
@@ -0,0 +1,6 @@
import { Global, Module } from '@nestjs/common';
import { CacheService } from './cache.service';
@Global()
@Module({ providers: [CacheService], exports: [CacheService] })
export class CacheModule {}
+149
View File
@@ -0,0 +1,149 @@
import {
Injectable,
Logger,
type OnModuleDestroy,
type OnModuleInit,
} from '@nestjs/common';
import { createHash, randomUUID } from 'node:crypto';
import Redis from 'ioredis';
export const CACHE_TTL = { entity: 300, page: 30 } as const;
const generationTtl = 600;
const storeIfCurrent = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[3])
end
return false`;
@Injectable()
export class CacheService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(CacheService.name);
private readonly redis?: Redis;
private readonly prefix = process.env.CACHE_PREFIX ?? 'messenger:cache:v1';
private warned = false;
constructor() {
if (process.env.CACHE_URL) {
this.redis = new Redis(process.env.CACHE_URL, {
lazyConnect: true,
connectTimeout: 1000,
commandTimeout: 300,
maxRetriesPerRequest: 0,
enableOfflineQueue: false,
autoResendUnfulfilledCommands: false,
retryStrategy: () => 1000,
});
this.redis.on('error', () => this.unavailable());
this.redis.on('ready', () => {
this.warned = false;
});
}
}
async onModuleInit(): Promise<void> {
try {
await this.redis?.connect();
} catch {
this.unavailable();
}
}
onModuleDestroy(): void {
this.redis?.disconnect();
}
async remember<T>(
namespace: string,
parameters: unknown,
ttl: number,
load: () => Promise<T>,
epoch?: string,
): Promise<T> {
if (!this.redis || this.redis.status !== 'ready') return load();
if (epoch !== undefined) {
const digest = createHash('sha256')
.update(JSON.stringify(parameters))
.digest('hex');
const key = `${this.prefix}:${namespace}:epoch:${epoch}:${digest}`;
try {
const value = await this.redis.get(key);
if (value !== null) return JSON.parse(value) as T;
} catch {
this.unavailable();
}
const result = await load();
const serialized = JSON.stringify(result);
if (serialized !== undefined && this.redis.status === 'ready') {
try {
await this.redis.set(key, serialized, 'EX', ttl);
} catch {
this.unavailable();
}
}
return result;
}
const versionKey = `${this.prefix}:${namespace}:generation`;
let version: string | null = null;
let dataKey = '';
try {
await this.redis.set(versionKey, randomUUID(), 'EX', generationTtl, 'NX');
version = await this.redis.get(versionKey);
if (version) {
const digest = createHash('sha256')
.update(JSON.stringify(parameters))
.digest('hex');
dataKey = `${this.prefix}:${namespace}:${version}:${digest}`;
const value = await this.redis.get(dataKey);
if (value !== null) return JSON.parse(value) as T;
}
} catch {
this.unavailable();
}
const result = await load();
const serialized = JSON.stringify(result);
if (version && serialized !== undefined && this.redis.status === 'ready') {
try {
await this.redis.eval(
storeIfCurrent,
2,
versionKey,
dataKey,
version,
serialized,
ttl,
);
} catch {
this.unavailable();
}
}
return result;
}
async invalidate(...namespaces: string[]): Promise<void> {
if (!this.redis || this.redis.status !== 'ready' || namespaces.length === 0)
return;
try {
const transaction = this.redis.multi();
for (const namespace of new Set(namespaces)) {
transaction.set(
`${this.prefix}:${namespace}:generation`,
randomUUID(),
'EX',
generationTtl,
);
}
const results = await transaction.exec();
if (results?.some(([error]) => error !== null)) this.unavailable();
} catch {
this.unavailable();
}
}
private unavailable(): void {
if (!this.warned) {
this.logger.warn('Redis cache unavailable');
this.warned = true;
}
}
}
+58
View File
@@ -0,0 +1,58 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { OpenAPIObject } from '@nestjs/swagger';
import { completeApiDocument } from './api-document';
const contract = JSON.parse(
readFileSync(join(__dirname, '../../contracts/openapi.json'), 'utf8'),
) as OpenAPIObject;
describe('published OpenAPI document', () => {
const generated: OpenAPIObject = {
openapi: '3.0.0',
info: { title: 'Messenger API', version: '1.4.0' },
paths: {
'/': { get: { responses: { 200: { description: 'Root endpoint' } } } },
},
components: { schemas: {} },
};
for (const [path, item] of Object.entries(contract.paths)) {
generated.paths[path] = {};
for (const method of ['get', 'post', 'delete'] as const) {
if (item[method]) generated.paths[path][method] = { responses: {} };
}
}
const document = completeApiDocument(generated, contract);
it('documents every contract operation, including all response headers and binary schemas', () => {
expect(document.openapi).toBe(contract.openapi);
for (const [path, item] of Object.entries(contract.paths)) {
for (const method of ['get', 'post', 'delete'] as const) {
if (!item[method]) continue;
expect(document.paths[path][method]).toEqual({
...item[method],
security: item[method].security ?? contract.security ?? [],
});
}
}
expect(document.components?.schemas).toMatchObject(
contract.components!.schemas!,
);
});
it('preserves extra endpoints and leaves the generated document unchanged', () => {
expect(document.paths['/']).toEqual(generated.paths['/']);
expect(generated.openapi).toBe('3.0.0');
expect(
generated.paths['/api/v1/attachments/{attachment_id}'].get?.responses,
).toEqual({});
});
it('does not advertise contract endpoints missing from the application', () => {
const missing = structuredClone(generated);
delete missing.paths['/api/v1/attachments/{attachment_id}'];
expect(() => completeApiDocument(missing, contract)).toThrow(
'Contract endpoint is not implemented',
);
});
});
+55
View File
@@ -0,0 +1,55 @@
import type { OpenAPIObject } from '@nestjs/swagger';
/** Keep the published API documentation aligned with the lab's normative contract. */
export function completeApiDocument(
generated: OpenAPIObject,
contract: OpenAPIObject,
): OpenAPIObject {
const paths = { ...generated.paths };
const methods = [
'get',
'put',
'post',
'delete',
'options',
'head',
'patch',
'trace',
] as const;
for (const [path, item] of Object.entries(contract.paths)) {
paths[path] = { ...item };
for (const method of methods) {
const operation = item[method];
if (operation) {
if (!generated.paths[path]?.[method]) {
throw new Error(
`Contract endpoint is not implemented: ${method.toUpperCase()} ${path}`,
);
}
paths[path][method] = {
...generated.paths[path]?.[method],
...operation,
security: operation.security ?? contract.security ?? [],
};
}
}
}
return {
...generated,
openapi: contract.openapi,
info: { ...generated.info, version: contract.info.version },
paths,
components: {
...generated.components,
...contract.components,
schemas: {
...generated.components?.schemas,
...contract.components?.schemas,
},
securitySchemes: {
...generated.components?.securitySchemes,
...contract.components?.securitySchemes,
},
},
};
}
+16
View File
@@ -0,0 +1,16 @@
import {
HttpException,
HttpExceptionOptions,
HttpStatus,
} from '@nestjs/common';
export class ApiException extends HttpException {
constructor(
status: HttpStatus,
code: string,
message: string,
options?: HttpExceptionOptions,
) {
super({ code, message }, status, options);
}
}
+184
View File
@@ -0,0 +1,184 @@
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '@nestjs/common';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { Prisma } from '../../generated/prisma/client';
import { ApiException } from '../exceptions/api.exception';
import { AuthException } from '../../Auth/auth.exception';
interface ExceptionPayload {
code?: unknown;
}
const defaultCodes: Partial<Record<HttpStatus, string>> = {
[HttpStatus.BAD_REQUEST]: 'invalid_request',
[HttpStatus.UNAUTHORIZED]: 'unauthorized',
[HttpStatus.FORBIDDEN]: 'forbidden',
[HttpStatus.NOT_FOUND]: 'not_found',
[HttpStatus.CONFLICT]: 'conflict',
[HttpStatus.PAYLOAD_TOO_LARGE]: 'payload_too_large',
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'unsupported_media_type',
[HttpStatus.TOO_MANY_REQUESTS]: 'rate_limited',
[HttpStatus.SERVICE_UNAVAILABLE]: 'unavailable',
};
const defaultMessages: Partial<Record<HttpStatus, string>> = {
[HttpStatus.BAD_REQUEST]: 'Некорректный запрос',
[HttpStatus.UNAUTHORIZED]: 'Требуется авторизация',
[HttpStatus.FORBIDDEN]: 'Доступ запрещён',
[HttpStatus.NOT_FOUND]: 'Ресурс не найден',
[HttpStatus.METHOD_NOT_ALLOWED]: 'Метод не поддерживается',
[HttpStatus.CONFLICT]: 'Конфликт данных',
[HttpStatus.PAYLOAD_TOO_LARGE]: 'Тело запроса слишком большое',
[HttpStatus.UNSUPPORTED_MEDIA_TYPE]: 'Неподдерживаемый формат данных',
[HttpStatus.TOO_MANY_REQUESTS]: 'Слишком много запросов',
[HttpStatus.INTERNAL_SERVER_ERROR]: 'Внутренняя ошибка сервера',
[HttpStatus.SERVICE_UNAVAILABLE]: 'Сервис временно недоступен',
};
const databaseUnavailableCodes = new Set([
'P1000',
'P1001',
'P1002',
'P1008',
'P1017',
'P2024',
'P2037',
'ECONNREFUSED',
'ECONNRESET',
'ETIMEDOUT',
'EPIPE',
'ENOTFOUND',
'EAI_AGAIN',
'EACCES',
'08000',
'08001',
'08003',
'08004',
'08006',
'53300',
'57P01',
'57P02',
'57P03',
'57014',
]);
const driverTimeoutMessages = [
'Query read timeout',
'timeout exceeded when trying to connect',
'Connection terminated unexpectedly',
'Connection terminated due to connection timeout',
];
function databaseUnavailable(exception: unknown): boolean {
if (exception instanceof Prisma.PrismaClientInitializationError) return true;
if (exception instanceof HttpException || !(exception instanceof Error))
return false;
const error = exception as Error & { code?: unknown };
if (
typeof error.code === 'string' &&
databaseUnavailableCodes.has(error.code)
)
return true;
if (exception instanceof Prisma.PrismaClientKnownRequestError) {
const originalCode = exception.meta?.code;
if (
typeof originalCode === 'string' &&
databaseUnavailableCodes.has(originalCode)
)
return true;
const adapter = exception.meta?.driverAdapterError;
if (adapter !== null && typeof adapter === 'object' && 'cause' in adapter) {
const cause = adapter.cause;
if (cause !== null && typeof cause === 'object') {
if ('kind' in cause && cause.kind === 'ConnectionClosed') return true;
if (
'originalCode' in cause &&
typeof cause.originalCode === 'string' &&
databaseUnavailableCodes.has(cause.originalCode)
)
return true;
}
}
}
return driverTimeoutMessages.some((message) =>
exception.message.includes(message),
);
}
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost): void {
if (databaseUnavailable(exception)) {
exception = new ApiException(
HttpStatus.SERVICE_UNAVAILABLE,
'unavailable',
'База данных недоступна',
);
}
const context = host.switchToHttp();
const request = context.getRequest<FastifyRequest>();
const response = context.getResponse<FastifyReply>();
if (exception instanceof AuthException) {
void response.header('WWW-Authenticate', exception.challenge);
}
const status =
exception instanceof HttpException
? exception.getStatus()
: exception instanceof Error &&
'statusCode' in exception &&
typeof exception.statusCode === 'number' &&
[400, 413, 415].includes(exception.statusCode)
? exception.statusCode
: HttpStatus.INTERNAL_SERVER_ERROR;
const payload =
exception instanceof HttpException ? exception.getResponse() : undefined;
if (status === HttpStatus.TOO_MANY_REQUESTS)
void response.header('Retry-After', '1');
const { code, message } = this.extractError(status, payload);
const requestId = request.id;
if (status >= HttpStatus.INTERNAL_SERVER_ERROR) {
request.log.error(
{ err: exception, status, requestId },
'Request failed',
);
}
void response.status(status).send({
error: { code, message, request_id: requestId },
});
}
private extractError(
status: HttpStatus,
payload: string | object | undefined,
): { code: string; message: string } {
if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
return {
code: 'internal_error',
message: defaultMessages[status] ?? 'Ошибка сервера',
};
}
const body = (
payload !== null && typeof payload === 'object' ? payload : {}
) as ExceptionPayload;
return {
code:
typeof body.code === 'string'
? body.code
: (defaultCodes[status] ?? 'http_error'),
message:
defaultMessages[status] ??
(status >= HttpStatus.INTERNAL_SERVER_ERROR
? 'Ошибка сервера'
: 'Ошибка запроса'),
};
}
}
@@ -0,0 +1,56 @@
import type { IncomingMessage } from 'node:http';
import { PassThrough } from 'node:stream';
import { setImmediate as tick } from 'node:timers/promises';
import { drainRejectedBody } from './drain-rejected-body';
describe('bounded discard of rejected upload bodies', () => {
it('waits for the complete body before releasing the error response', async () => {
const body = new PassThrough();
const done = jest.fn();
const result = new Promise<boolean>((resolve) =>
drainRejectedBody(
body as unknown as IncomingMessage,
100,
1000,
(consumed) => {
done(consumed);
resolve(consumed);
},
),
);
body.write('first');
await tick();
expect(done).not.toHaveBeenCalled();
body.end('last');
expect(await result).toBe(true);
expect(body.readableEnded).toBe(true);
expect(done).toHaveBeenCalledTimes(1);
});
it('stops draining beyond its byte budget', async () => {
const body = new PassThrough();
try {
const result = new Promise<boolean>((resolve) =>
drainRejectedBody(body as unknown as IncomingMessage, 4, 1000, resolve),
);
body.write('12345');
expect(await result).toBe(false);
expect(body.isPaused()).toBe(true);
} finally {
body.destroy();
}
});
it('releases a stalled rejected request when its remaining deadline expires', async () => {
const body = new PassThrough();
try {
const result = new Promise<boolean>((resolve) =>
drainRejectedBody(body as unknown as IncomingMessage, 100, 25, resolve),
);
expect(await result).toBe(false);
expect(body.isPaused()).toBe(true);
} finally {
body.destroy();
}
});
});
+44
View File
@@ -0,0 +1,44 @@
import type { IncomingMessage } from 'node:http';
/** Discard a bounded remainder before sending an early 413 through a streaming proxy. */
export function drainRejectedBody(
raw: IncomingMessage,
maxBytes: number,
timeoutMs: number,
done: (consumed: boolean) => void,
) {
let received = 0;
let finished = false;
const finish = (consumed: boolean) => {
if (finished) return;
finished = true;
clearTimeout(timer);
raw.removeListener('data', onData);
raw.removeListener('end', onEnd);
raw.removeListener('aborted', onAborted);
raw.removeListener('error', onAborted);
raw.removeListener('close', onClose);
done(consumed);
};
const onData = (chunk: Buffer) => {
received += chunk.length;
if (received > maxBytes) {
raw.pause();
finish(false);
}
};
const onEnd = () => finish(true);
const onAborted = () => finish(false);
const onClose = () => finish(raw.readableEnded);
const timer = setTimeout(() => {
raw.pause();
finish(false);
}, timeoutMs);
timer.unref();
raw.on('data', onData);
raw.once('end', onEnd);
raw.once('aborted', onAborted);
raw.once('error', onAborted);
raw.once('close', onClose);
raw.resume();
}
+92
View File
@@ -0,0 +1,92 @@
import { request } from 'node:http';
import type { AddressInfo } from 'node:net';
import { setTimeout as delay } from 'node:timers/promises';
import { DrainingFastifyAdapter } from './fastify-adapter';
describe('upload body deadline over real HTTP', () => {
it('returns 408 for a client that keeps sending and never invokes the handler', async () => {
const adapter = new DrainingFastifyAdapter(0, 1000);
const server = adapter.getInstance();
let calls = 0;
server.post('/api/v1/chats/:chat_id/attachments', () => {
calls++;
return {};
});
await server.listen({ host: '127.0.0.1', port: 0 });
let timer: ReturnType<typeof setInterval> | undefined;
let watchdog: ReturnType<typeof setTimeout> | undefined;
try {
const port = (server.server.address() as AddressInfo).port;
const result = await new Promise<{
status?: number;
body: string;
id?: string;
}>((resolve, reject) => {
const client = request(
{
host: '127.0.0.1',
port,
method: 'POST',
path: '/api/v1/chats/test/attachments',
headers: { 'content-type': 'image/png', 'content-length': '10000' },
},
(response) => {
clearInterval(timer);
clearTimeout(watchdog);
let body = '';
response.on('data', (part: Buffer) => {
body += part.toString();
});
response.on('end', () => {
client.destroy();
resolve({
status: response.statusCode,
body,
id: response.headers['x-request-id'] as string,
});
});
response.on('error', reject);
},
);
client.on('error', reject);
watchdog = setTimeout(
() => client.destroy(new Error('deadline did not fire')),
7000,
);
client.write('partial');
timer = setInterval(() => client.write('x'), 100);
});
expect(result.status).toBe(408);
expect(result.id).toBeTruthy();
expect(JSON.parse(result.body)).toMatchObject({
error: { code: 'invalid_request', request_id: result.id },
});
expect(calls).toBe(0);
} finally {
clearInterval(timer);
clearTimeout(watchdog);
await server.close();
}
}, 15000);
it('clears the reception deadline before a completed body is processed', async () => {
const adapter = new DrainingFastifyAdapter(0, 1000);
const server = adapter.getInstance();
server.post('/api/v1/chats/:chat_id/attachments', async () => {
await delay(1200);
return { stored: true };
});
try {
const response = await server.inject({
method: 'POST',
url: '/api/v1/chats/test/attachments',
headers: { 'content-type': 'image/png' },
payload: Buffer.from('complete'),
});
expect(response.statusCode).toBe(200);
expect(response.json()).toEqual({ stored: true });
} finally {
await server.close();
}
});
});
+175
View File
@@ -0,0 +1,175 @@
import { randomUUID } from 'node:crypto';
import { MAX_UPLOAD_BYTES } from '../../Attachment/attachment.service';
import { profileUpload } from './upload-memory-profile';
import { drainRejectedBody } from './drain-rejected-body';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
const requestIdHeader = 'x-request-id';
const instanceIdHeader = 'x-instance-id';
const instanceId = process.env.INSTANCE_ID?.trim() || randomUUID();
// Two parallel readiness rounds: 2 * (1s request timeout + 2s interval),
// plus one second for the upstream reload. Keep below the public hook's 10s limit.
export const DRAIN_DELAY_MS = 7000;
export class DrainingFastifyAdapter extends FastifyAdapter {
private draining = false;
private closing?: Promise<void>;
private httpClosing?: Promise<undefined>;
private readonly uploadDeadlines = new WeakMap<object, number>();
constructor(
private readonly drainDelayMs: number,
uploadBodyTimeoutMs = Number(process.env.UPLOAD_BODY_TIMEOUT_MS ?? 15000),
) {
super({ requestIdHeader, genReqId: () => randomUUID() });
this.getInstance().addHook('onRequest', (request, reply, done) => {
const path = request.routeOptions.url;
const mode =
request.method !== 'POST'
? undefined
: path === '/api/v1/chats/:chat_id/attachments'
? 'proxy'
: path ===
'/api/v1/chats/:chat_id/attachment-uploads/:upload_id/complete'
? 'direct'
: path === '/api/v1/chats/:chat_id/attachment-uploads'
? 'grant'
: undefined;
if (mode) profileUpload(mode, request.id, reply.raw, done);
else done();
});
if (
!Number.isSafeInteger(uploadBodyTimeoutMs) ||
uploadBodyTimeoutMs < 1000 ||
uploadBodyTimeoutMs > 120000
) {
throw new Error('UPLOAD_BODY_TIMEOUT_MS must be between 1000 and 120000');
}
this.getInstance().addHook('onRequest', (request, reply, done) => {
if (
request.method !== 'POST' ||
request.routeOptions.url !== '/api/v1/chats/:chat_id/attachments'
) {
done();
return;
}
// A total deadline, independent of whether the client keeps sending tiny chunks.
// Clear it when reception finishes; decoding and persistence have separate budgets.
const raw = request.raw;
this.uploadDeadlines.set(raw, Date.now() + uploadBodyTimeoutMs);
const cleanup = () => {
this.uploadDeadlines.delete(raw);
clearTimeout(timer);
raw.removeListener('end', cleanup);
raw.removeListener('close', cleanup);
reply.raw.removeListener('finish', cleanup);
};
const timer = setTimeout(() => {
cleanup();
if (
raw.complete ||
reply.sent ||
raw.destroyed ||
reply.statusCode === 413
)
return;
// Let HTTP close after flushing the response. Destroying the request here can
// reset the TCP connection before a still-writing client receives the 408.
void reply
.code(408)
.header('connection', 'close')
.header(requestIdHeader, request.id)
.header(instanceIdHeader, instanceId)
.send({
error: {
code: 'invalid_request',
message: 'Истёк срок приёма изображения',
request_id: request.id,
},
});
}, uploadBodyTimeoutMs);
timer.unref();
raw.once('end', cleanup);
raw.once('close', cleanup);
reply.raw.once('finish', cleanup);
done();
});
this.getInstance().addContentTypeParser(
['image/png', 'image/jpeg', 'application/octet-stream'],
{ parseAs: 'buffer', bodyLimit: MAX_UPLOAD_BYTES },
(_request, body, done) => done(null, body),
);
this.getInstance().addHook('onSend', (request, reply, payload, done) => {
// An already active request may finish after Fastify starts closing.
// Finish its response, then close its keep-alive socket as well.
if (this.httpClosing) void reply.header('connection', 'close');
if (
reply.statusCode === 413 &&
request.routeOptions.url === '/api/v1/chats/:chat_id/attachments' &&
!request.raw.readableEnded &&
!request.raw.destroyed
) {
const deadline =
this.uploadDeadlines.get(request.raw) ??
Date.now() + uploadBodyTimeoutMs;
drainRejectedBody(
request.raw,
MAX_UPLOAD_BYTES + 1048576,
Math.max(1, deadline - Date.now()),
(consumed) => {
if (!consumed) void reply.header('connection', 'close');
done(null, payload);
},
);
return;
}
done(null, payload);
});
}
get isDraining(): boolean {
return this.draining;
}
override beforeClose(): Promise<void> {
return (this.closing ??= this.drainAndClose());
}
override close(): Promise<undefined> {
return (this.httpClosing ??= super.close());
}
private async drainAndClose(): Promise<void> {
this.draining = true;
if (this.drainDelayMs > 0) {
await new Promise<void>((resolve) =>
setTimeout(resolve, this.drainDelayMs),
);
}
// Nest awaits beforeClose before destroying Prisma/Redis providers.
// Fastify first stops new connections and finishes active HTTP requests.
await this.close();
}
}
export function createFastifyAdapter(
drainDelayMs = 0,
uploadBodyTimeoutMs?: number,
): DrainingFastifyAdapter {
return new DrainingFastifyAdapter(drainDelayMs, uploadBodyTimeoutMs);
}
export function exposeRequestIdHeader(app: NestFastifyApplication): void {
app
.getHttpAdapter()
.getInstance()
.addHook('onRequest', (request, reply, done) => {
void reply.header(requestIdHeader, request.id);
void reply.header(instanceIdHeader, instanceId);
done();
});
}
+116
View File
@@ -0,0 +1,116 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { hostname } from 'node:os';
import { performance } from 'node:perf_hooks';
import type { ServerResponse } from 'node:http';
import sharp from 'sharp';
type Memory = ReturnType<typeof process.memoryUsage>;
type Stage = {
name: string;
startedMs: number;
durationMs: number;
before: Memory;
after: Memory;
peak: Memory;
samples: number;
maxSampleGapMs: number;
sharpBefore: ReturnType<typeof sharp.cache>;
sharpAfter: ReturnType<typeof sharp.cache>;
};
type Context = {
started: number;
stages: Stage[];
current: Stage;
lastSample: number;
closed: boolean;
};
const contexts = new AsyncLocalStorage<Context>();
function sample(context: Context) {
const now = performance.now();
const memory = process.memoryUsage();
const stage = context.current;
for (const key of Object.keys(memory) as (keyof Memory)[])
stage.peak[key] = Math.max(stage.peak[key], memory[key]);
stage.after = memory;
stage.samples++;
stage.maxSampleGapMs = Math.max(
stage.maxSampleGapMs,
now - context.lastSample,
);
context.lastSample = now;
stage.durationMs = now - context.started - stage.startedMs;
return memory;
}
function stage(name: string, startedMs: number): Stage {
const memory = process.memoryUsage();
const cache = sharp.cache();
return {
name,
startedMs,
durationMs: 0,
before: memory,
after: memory,
peak: { ...memory },
samples: 0,
maxSampleGapMs: 0,
sharpBefore: cache,
sharpAfter: cache,
};
}
/** Profiling is opt-in. Contains numeric metrics and a request ID, never URLs or payloads. */
export function profileUpload(
mode: 'proxy' | 'direct' | 'grant',
requestId: string,
response: ServerResponse,
done: () => void,
) {
if (process.env.UPLOAD_MEMORY_PROFILE !== '1') return done();
const now = performance.now();
const context: Context = {
started: now,
stages: [],
current: stage('receive_and_authenticate', 0),
lastSample: now,
closed: false,
};
const timer = setInterval(() => sample(context), 20);
timer.unref();
const finish = () => {
if (context.closed) return;
context.closed = true;
clearInterval(timer);
sample(context);
context.current.sharpAfter = sharp.cache();
context.stages.push(context.current);
console.log(
'UPLOAD_MEMORY_PROFILE ' +
JSON.stringify({
mode,
requestId,
instance: hostname(),
pid: process.pid,
status: response.statusCode,
finished: response.writableFinished,
intervalMs: 20,
durationMs: performance.now() - context.started,
stages: context.stages,
}),
);
};
response.once('finish', finish);
response.once('close', finish);
contexts.run(context, done);
}
export function profileStage(name: string) {
const context = contexts.getStore();
if (!context || context.closed || context.stages.length >= 64) return;
sample(context);
context.current.sharpAfter = sharp.cache();
context.stages.push(context.current);
context.current = stage(name, performance.now() - context.started);
context.lastSample = performance.now();
}
+54
View File
@@ -0,0 +1,54 @@
import { ApiException } from './exceptions/api.exception';
import { HttpStatus } from '@nestjs/common';
export const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function invalidRequest(message: string): never {
throw new ApiException(HttpStatus.BAD_REQUEST, 'invalid_request', message);
}
export function objectBody(
value: unknown,
keys: string[],
): Record<string, unknown> {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return invalidRequest('Ожидается JSON-объект');
}
const body = value as Record<string, unknown>;
if (Object.keys(body).some((key) => !keys.includes(key))) {
return invalidRequest('Неизвестное поле запроса');
}
return body;
}
export function requiredText(
value: unknown,
field: string,
max: number,
): string {
if (typeof value !== 'string' || value.trim().length === 0) {
return invalidRequest(`Некорректное поле ${field}`);
}
let codePoints = 0;
for (const _character of value) codePoints++;
if (codePoints > max) return invalidRequest(`Некорректное поле ${field}`);
return value;
}
export function uuid(value: unknown, field: string): string {
if (typeof value !== 'string' || !uuidPattern.test(value)) {
return invalidRequest(`Некорректное поле ${field}`);
}
return value.toLowerCase();
}
export function pageLimit(value: unknown): number {
if (value === undefined) return 50;
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
return invalidRequest('Некорректный limit');
}
const limit = Number(value);
if (limit > 100) return invalidRequest('Некорректный limit');
return limit;
}

Some files were not shown because too many files have changed in this diff Show More