From 3418252554a9e4378ad8446d3d1dffb2051c060b Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 26 Nov 2026 15:35:57 +0300 Subject: [PATCH] =?UTF-8?q?lab7:=20=D0=B1=D0=B0=D0=B7=D0=BE=D0=B2=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82=20=D0=B8=D0=B7=20?= =?UTF-8?q?lab6=20(bf06167)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Перенесена кодовая база и инфраструктура lab6: NestJS-приложение (API + worker, RabbitMQ, outbox, S3, OpenTelemetry), Dockerfile, compose.yaml, infra/{grafana,haproxy,loki,minio,otel/collector.yaml,prometheus, rabbitmq,tempo}, docs/runbooks, стендовые скрипты, scripts/lab{4,5,6} и contracts/extensions.openapi.json. Задание lab7 оставлено своим: README, REPORT, COURSE, CONTRIBUTING, MAINTAINERS, lab.json, contracts/{openapi,infrastructure,jobs.schema, attachment-states,examples,observability,trust-matrix,README}, security/THREAT_MODEL.md, tests (включая security.py), compose.example.yaml, infra/{openbao,otel}/README.md, .github/pull_request_template.md. Не переносились старые evidence/lab4..lab6 (18 МБ трека lab6) и неотслеживаемый docs/lab6.html. Адаптации при переносе: - docker-проект mtusi-lab6 -> mtusi-lab7, тег образа mtusi-messenger:lab7 и папка Grafana Messenger lab7 (compose.yaml, scripts/stop-one.sh, .env.example, infra/README.md, infra/grafana/provisioning/dashboards), чтобы тома и контейнеры не пересекались с lab6; - Makefile: сохранены BASE_URL=https://localhost:8443 и цель test-security из skeleton lab7, добавлены стендовые и проверочные цели lab6; - .env.example: рабочие переменные приложения и стенда lab6 + блок переменных lab7 (PUBLIC_BASE_URL, TLS_*, BAO_*, ARGON2_*) из skeleton. --- .env.example | 149 +- Dockerfile | 38 + Makefile | 86 +- app/.gitignore | 59 + app/.prettierrc | 6 + app/README.md | 314 + app/nest-cli.json | 15 + app/oxlint.json | 10 + app/package-lock.json | 8705 +++++++++++++++++ app/package.json | 84 + app/scripts/graph-modules.ts | 123 + app/src/app.module.ts | 39 + .../attachments/attachment-sweeper.service.ts | 80 + app/src/attachments/attachment.ts | 109 + app/src/attachments/attachments-sweep.cli.ts | 42 + app/src/attachments/attachments.controller.ts | 109 + app/src/attachments/attachments.module.ts | 42 + app/src/attachments/attachments.repository.ts | 216 + .../attachments/attachments.service.spec.ts | 133 + app/src/attachments/attachments.service.ts | 435 + app/src/attachments/direct-uploads.service.ts | 293 + .../dto/create-direct-upload.dto.ts | 16 + app/src/attachments/filename.ts | 34 + .../attachments/image/image-decoder.spec.ts | 70 + app/src/attachments/image/image-decoder.ts | 119 + .../attachments/image/image-inspector.spec.ts | 109 + app/src/attachments/image/image-inspector.ts | 387 + app/src/attachments/upload-request.ts | 9 + app/src/attachments/upload-slots.spec.ts | 54 + app/src/attachments/upload-slots.ts | 41 + app/src/auth/auth.controller.ts | 79 + app/src/auth/auth.module.ts | 16 + app/src/auth/auth.service.ts | 63 + app/src/auth/session.repository.ts | 35 + app/src/chats/chat.ts | 6 + app/src/chats/chats.controller.ts | 49 + app/src/chats/chats.module.ts | 16 + app/src/chats/chats.repository.ts | 109 + app/src/chats/chats.service.ts | 61 + app/src/chats/dto/create-chat.dto.ts | 26 + app/src/common/auth/current-user.decorator.ts | 10 + app/src/common/auth/current-user.guard.ts | 85 + app/src/common/errors/api-error.ts | 7 + app/src/common/errors/api-exception.filter.ts | 196 + app/src/common/http/cursor.spec.ts | 85 + app/src/common/http/cursor.ts | 54 + app/src/common/http/page.ts | 4 + app/src/common/http/request-id.interceptor.ts | 59 + .../validation/code-point-length.spec.ts | 43 + .../common/validation/code-point-length.ts | 38 + app/src/config/app-config.module.ts | 16 + app/src/config/app-config.schema.ts | 263 + app/src/config/instance-id.ts | 14 + app/src/database/database.client.ts | 325 + app/src/database/database.module.ts | 10 + app/src/database/migration.runner.ts | 63 + app/src/database/migrations/001_initial.sql | 41 + .../migrations/002_timestamp_precision.sql | 5 + .../migrations/003_idempotency_keys.sql | 20 + .../migrations/004_pg_stat_statements.sql | 9 + .../database/migrations/005_attachments.sql | 42 + .../migrations/006_attachment_rejected.sql | 8 + .../migrations/007_attachment_pipeline.sql | 81 + .../database/migrations/008_job_reconcile.sql | 37 + .../009_queue_reconcile_indexes.sql | 10 + app/src/health/health.controller.ts | 17 + app/src/health/health.module.ts | 12 + app/src/health/health.service.spec.ts | 91 + app/src/health/health.service.ts | 60 + app/src/jobs/backoff.spec.ts | 19 + app/src/jobs/backoff.ts | 14 + app/src/jobs/broker.client.ts | 478 + app/src/jobs/broker.topology.ts | 37 + app/src/jobs/errors.spec.ts | 33 + app/src/jobs/errors.ts | 65 + app/src/jobs/fault-injector.ts | 134 + app/src/jobs/fit-inside.spec.ts | 14 + app/src/jobs/fit-inside.ts | 15 + app/src/jobs/job-message.spec.ts | 47 + app/src/jobs/job-message.ts | 53 + app/src/jobs/jobs.cli.ts | 234 + app/src/jobs/jobs.module.ts | 14 + app/src/jobs/jobs.repository.ts | 1057 ++ app/src/jobs/outbox-relay.service.ts | 119 + app/src/main.ts | 110 + .../cache/messages-cache.metrics.spec.ts | 37 + .../messages/cache/messages-cache.module.ts | 11 + .../cache/messages-cache.service.spec.ts | 72 + .../messages/cache/messages-cache.service.ts | 205 + app/src/messages/dto/create-message.dto.ts | 23 + .../idempotency/idempotency-gc.cli.ts | 33 + .../idempotency/idempotency.module.ts | 10 + .../idempotency.repository.spec.ts | 24 + .../idempotency/idempotency.repository.ts | 119 + app/src/messages/idempotency/idempotency.ts | 26 + app/src/messages/message.ts | 8 + app/src/messages/messages.controller.ts | 53 + app/src/messages/messages.module.ts | 28 + app/src/messages/messages.repository.spec.ts | 26 + app/src/messages/messages.repository.ts | 145 + app/src/messages/messages.service.spec.ts | 121 + app/src/messages/messages.service.ts | 206 + app/src/metrics/metrics.controller.ts | 54 + app/src/metrics/metrics.module.ts | 10 + app/src/metrics/metrics.service.spec.ts | 77 + app/src/metrics/metrics.service.ts | 123 + app/src/redis/redis.client.ts | 145 + app/src/redis/redis.module.ts | 10 + app/src/storage/object-storage.ts | 257 + app/src/storage/storage.module.ts | 5 + app/src/telemetry/api-bootstrap.ts | 5 + app/src/telemetry/export-counter.ts | 36 + app/src/telemetry/http.spec.ts | 35 + app/src/telemetry/http.ts | 201 + app/src/telemetry/identity.ts | 35 + app/src/telemetry/instruments.ts | 104 + app/src/telemetry/logger.spec.ts | 99 + app/src/telemetry/logger.ts | 224 + app/src/telemetry/queue-stats.service.ts | 164 + app/src/telemetry/redact.spec.ts | 37 + app/src/telemetry/redact.ts | 29 + app/src/telemetry/runtime-metrics.ts | 55 + app/src/telemetry/sdk.ts | 295 + app/src/telemetry/tracing.spec.ts | 72 + app/src/telemetry/tracing.ts | 130 + app/src/telemetry/worker-bootstrap.ts | 4 + app/src/types.d.ts | 7 + app/src/users/dto/create-user.dto.ts | 22 + app/src/users/user.ts | 6 + app/src/users/users.controller.ts | 22 + app/src/users/users.module.ts | 16 + app/src/users/users.repository.ts | 71 + app/src/users/users.service.ts | 31 + app/src/worker.main.ts | 74 + app/src/worker/job-processor.service.spec.ts | 203 + app/src/worker/job-processor.service.ts | 677 ++ app/src/worker/lease-reaper.service.ts | 100 + app/src/worker/pipelines.spec.ts | 102 + app/src/worker/pipelines.ts | 175 + app/src/worker/staging-cleaner.service.ts | 92 + app/src/worker/worker.module.ts | 26 + app/test/app.e2e-spec.ts | 674 ++ app/test/attachments.e2e-spec.ts | 542 + app/test/dependency-failures.e2e-spec.ts | 1107 +++ app/test/direct-upload.e2e-spec.ts | 348 + app/test/fixtures/sample-progressive.jpg | Bin 0 -> 4891 bytes app/test/fixtures/sample.jpg | Bin 0 -> 4726 bytes app/test/support/e2e.ts | 187 + app/test/support/jpeg.ts | 24 + app/test/support/png.ts | 140 + app/tsconfig.build.json | 8 + app/tsconfig.json | 22 + app/vitest.config.e2e.ts | 14 + app/vitest.config.ts | 13 + compose.yaml | 531 + contracts/extensions.openapi.json | 618 ++ docs/runbooks/MessengerApiHighErrorRate.md | 20 + docs/runbooks/MessengerJobsQueueLagGrowing.md | 20 + infra/README.md | 35 + .../dashboards/messenger-overview.json | 1294 +++ .../dashboards/messenger-telemetry.json | 632 ++ .../provisioning/dashboards/dashboards.yaml | 12 + .../provisioning/datasources/datasources.yaml | 48 + infra/haproxy/haproxy.cfg | 63 + infra/loki/loki.yaml | 48 + infra/minio/bootstrap.sh | 58 + infra/otel/collector.yaml | 109 + infra/prometheus/prometheus.yml | 34 + infra/prometheus/rules/alerts.yml | 21 + infra/prometheus/rules/recording.yml | 18 + infra/prometheus/tests/alerts.test.yml | 100 + infra/rabbitmq/enabled_plugins | 1 + infra/rabbitmq/init-worker.sh | 21 + infra/tempo/tempo.yaml | 24 + scripts/app-e2e.sh | 22 + scripts/init-env.sh | 77 + scripts/lab4/attachments_bench.py | 340 + scripts/lab4/check_s3_security.sh | 54 + scripts/lab4/consistency_check.sh | 35 + scripts/lab4/decode_memory.mjs | 33 + scripts/lab4/pngkit.py | 78 + scripts/lab4/run_matrix.sh | 36 + scripts/lab5/fault_suite.py | 749 ++ scripts/lab5/stand.py | 180 + scripts/lab5/worker_down_demo.py | 126 + scripts/lab6/gen_dashboards.py | 238 + scripts/lab6/incidents.py | 676 ++ scripts/lab6/measurement.py | 337 + scripts/lab6/obs.py | 675 ++ scripts/lab6/reconcile.py | 106 + scripts/lab6/resources.py | 181 + scripts/lab6/test_measurement.py | 199 + scripts/lab6/track1.py | 457 + scripts/lab6/verify.py | 671 ++ scripts/lab6/workload.py | 140 + scripts/restart.sh | 8 + scripts/start-replica.sh | 11 + scripts/stop-one.sh | 35 + 198 files changed, 33745 insertions(+), 16 deletions(-) create mode 100644 Dockerfile create mode 100644 app/.gitignore create mode 100644 app/.prettierrc create mode 100644 app/README.md create mode 100644 app/nest-cli.json create mode 100644 app/oxlint.json create mode 100644 app/package-lock.json create mode 100644 app/package.json create mode 100644 app/scripts/graph-modules.ts create mode 100644 app/src/app.module.ts create mode 100644 app/src/attachments/attachment-sweeper.service.ts create mode 100644 app/src/attachments/attachment.ts create mode 100644 app/src/attachments/attachments-sweep.cli.ts create mode 100644 app/src/attachments/attachments.controller.ts create mode 100644 app/src/attachments/attachments.module.ts create mode 100644 app/src/attachments/attachments.repository.ts create mode 100644 app/src/attachments/attachments.service.spec.ts create mode 100644 app/src/attachments/attachments.service.ts create mode 100644 app/src/attachments/direct-uploads.service.ts create mode 100644 app/src/attachments/dto/create-direct-upload.dto.ts create mode 100644 app/src/attachments/filename.ts create mode 100644 app/src/attachments/image/image-decoder.spec.ts create mode 100644 app/src/attachments/image/image-decoder.ts create mode 100644 app/src/attachments/image/image-inspector.spec.ts create mode 100644 app/src/attachments/image/image-inspector.ts create mode 100644 app/src/attachments/upload-request.ts create mode 100644 app/src/attachments/upload-slots.spec.ts create mode 100644 app/src/attachments/upload-slots.ts create mode 100644 app/src/auth/auth.controller.ts create mode 100644 app/src/auth/auth.module.ts create mode 100644 app/src/auth/auth.service.ts create mode 100644 app/src/auth/session.repository.ts create mode 100644 app/src/chats/chat.ts create mode 100644 app/src/chats/chats.controller.ts create mode 100644 app/src/chats/chats.module.ts create mode 100644 app/src/chats/chats.repository.ts create mode 100644 app/src/chats/chats.service.ts create mode 100644 app/src/chats/dto/create-chat.dto.ts create mode 100644 app/src/common/auth/current-user.decorator.ts create mode 100644 app/src/common/auth/current-user.guard.ts create mode 100644 app/src/common/errors/api-error.ts create mode 100644 app/src/common/errors/api-exception.filter.ts create mode 100644 app/src/common/http/cursor.spec.ts create mode 100644 app/src/common/http/cursor.ts create mode 100644 app/src/common/http/page.ts create mode 100644 app/src/common/http/request-id.interceptor.ts create mode 100644 app/src/common/validation/code-point-length.spec.ts create mode 100644 app/src/common/validation/code-point-length.ts create mode 100644 app/src/config/app-config.module.ts create mode 100644 app/src/config/app-config.schema.ts create mode 100644 app/src/config/instance-id.ts create mode 100644 app/src/database/database.client.ts create mode 100644 app/src/database/database.module.ts create mode 100644 app/src/database/migration.runner.ts create mode 100644 app/src/database/migrations/001_initial.sql create mode 100644 app/src/database/migrations/002_timestamp_precision.sql create mode 100644 app/src/database/migrations/003_idempotency_keys.sql create mode 100644 app/src/database/migrations/004_pg_stat_statements.sql create mode 100644 app/src/database/migrations/005_attachments.sql create mode 100644 app/src/database/migrations/006_attachment_rejected.sql create mode 100644 app/src/database/migrations/007_attachment_pipeline.sql create mode 100644 app/src/database/migrations/008_job_reconcile.sql create mode 100644 app/src/database/migrations/009_queue_reconcile_indexes.sql create mode 100644 app/src/health/health.controller.ts create mode 100644 app/src/health/health.module.ts create mode 100644 app/src/health/health.service.spec.ts create mode 100644 app/src/health/health.service.ts create mode 100644 app/src/jobs/backoff.spec.ts create mode 100644 app/src/jobs/backoff.ts create mode 100644 app/src/jobs/broker.client.ts create mode 100644 app/src/jobs/broker.topology.ts create mode 100644 app/src/jobs/errors.spec.ts create mode 100644 app/src/jobs/errors.ts create mode 100644 app/src/jobs/fault-injector.ts create mode 100644 app/src/jobs/fit-inside.spec.ts create mode 100644 app/src/jobs/fit-inside.ts create mode 100644 app/src/jobs/job-message.spec.ts create mode 100644 app/src/jobs/job-message.ts create mode 100644 app/src/jobs/jobs.cli.ts create mode 100644 app/src/jobs/jobs.module.ts create mode 100644 app/src/jobs/jobs.repository.ts create mode 100644 app/src/jobs/outbox-relay.service.ts create mode 100644 app/src/main.ts create mode 100644 app/src/messages/cache/messages-cache.metrics.spec.ts create mode 100644 app/src/messages/cache/messages-cache.module.ts create mode 100644 app/src/messages/cache/messages-cache.service.spec.ts create mode 100644 app/src/messages/cache/messages-cache.service.ts create mode 100644 app/src/messages/dto/create-message.dto.ts create mode 100644 app/src/messages/idempotency/idempotency-gc.cli.ts create mode 100644 app/src/messages/idempotency/idempotency.module.ts create mode 100644 app/src/messages/idempotency/idempotency.repository.spec.ts create mode 100644 app/src/messages/idempotency/idempotency.repository.ts create mode 100644 app/src/messages/idempotency/idempotency.ts create mode 100644 app/src/messages/message.ts create mode 100644 app/src/messages/messages.controller.ts create mode 100644 app/src/messages/messages.module.ts create mode 100644 app/src/messages/messages.repository.spec.ts create mode 100644 app/src/messages/messages.repository.ts create mode 100644 app/src/messages/messages.service.spec.ts create mode 100644 app/src/messages/messages.service.ts create mode 100644 app/src/metrics/metrics.controller.ts create mode 100644 app/src/metrics/metrics.module.ts create mode 100644 app/src/metrics/metrics.service.spec.ts create mode 100644 app/src/metrics/metrics.service.ts create mode 100644 app/src/redis/redis.client.ts create mode 100644 app/src/redis/redis.module.ts create mode 100644 app/src/storage/object-storage.ts create mode 100644 app/src/storage/storage.module.ts create mode 100644 app/src/telemetry/api-bootstrap.ts create mode 100644 app/src/telemetry/export-counter.ts create mode 100644 app/src/telemetry/http.spec.ts create mode 100644 app/src/telemetry/http.ts create mode 100644 app/src/telemetry/identity.ts create mode 100644 app/src/telemetry/instruments.ts create mode 100644 app/src/telemetry/logger.spec.ts create mode 100644 app/src/telemetry/logger.ts create mode 100644 app/src/telemetry/queue-stats.service.ts create mode 100644 app/src/telemetry/redact.spec.ts create mode 100644 app/src/telemetry/redact.ts create mode 100644 app/src/telemetry/runtime-metrics.ts create mode 100644 app/src/telemetry/sdk.ts create mode 100644 app/src/telemetry/tracing.spec.ts create mode 100644 app/src/telemetry/tracing.ts create mode 100644 app/src/telemetry/worker-bootstrap.ts create mode 100644 app/src/types.d.ts create mode 100644 app/src/users/dto/create-user.dto.ts create mode 100644 app/src/users/user.ts create mode 100644 app/src/users/users.controller.ts create mode 100644 app/src/users/users.module.ts create mode 100644 app/src/users/users.repository.ts create mode 100644 app/src/users/users.service.ts create mode 100644 app/src/worker.main.ts create mode 100644 app/src/worker/job-processor.service.spec.ts create mode 100644 app/src/worker/job-processor.service.ts create mode 100644 app/src/worker/lease-reaper.service.ts create mode 100644 app/src/worker/pipelines.spec.ts create mode 100644 app/src/worker/pipelines.ts create mode 100644 app/src/worker/staging-cleaner.service.ts create mode 100644 app/src/worker/worker.module.ts create mode 100644 app/test/app.e2e-spec.ts create mode 100644 app/test/attachments.e2e-spec.ts create mode 100644 app/test/dependency-failures.e2e-spec.ts create mode 100644 app/test/direct-upload.e2e-spec.ts create mode 100644 app/test/fixtures/sample-progressive.jpg create mode 100644 app/test/fixtures/sample.jpg create mode 100644 app/test/support/e2e.ts create mode 100644 app/test/support/jpeg.ts create mode 100644 app/test/support/png.ts create mode 100644 app/tsconfig.build.json create mode 100644 app/tsconfig.json create mode 100644 app/vitest.config.e2e.ts create mode 100644 app/vitest.config.ts create mode 100644 compose.yaml create mode 100644 contracts/extensions.openapi.json create mode 100644 docs/runbooks/MessengerApiHighErrorRate.md create mode 100644 docs/runbooks/MessengerJobsQueueLagGrowing.md create mode 100644 infra/grafana/dashboards/messenger-overview.json create mode 100644 infra/grafana/dashboards/messenger-telemetry.json create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 infra/loki/loki.yaml create mode 100755 infra/minio/bootstrap.sh create mode 100644 infra/otel/collector.yaml create mode 100644 infra/prometheus/prometheus.yml create mode 100644 infra/prometheus/rules/alerts.yml create mode 100644 infra/prometheus/rules/recording.yml create mode 100644 infra/prometheus/tests/alerts.test.yml create mode 100644 infra/rabbitmq/enabled_plugins create mode 100755 infra/rabbitmq/init-worker.sh create mode 100644 infra/tempo/tempo.yaml create mode 100755 scripts/app-e2e.sh create mode 100755 scripts/init-env.sh create mode 100755 scripts/lab4/attachments_bench.py create mode 100755 scripts/lab4/check_s3_security.sh create mode 100755 scripts/lab4/consistency_check.sh create mode 100644 scripts/lab4/decode_memory.mjs create mode 100644 scripts/lab4/pngkit.py create mode 100755 scripts/lab4/run_matrix.sh create mode 100755 scripts/lab5/fault_suite.py create mode 100644 scripts/lab5/stand.py create mode 100755 scripts/lab5/worker_down_demo.py create mode 100755 scripts/lab6/gen_dashboards.py create mode 100755 scripts/lab6/incidents.py create mode 100644 scripts/lab6/measurement.py create mode 100644 scripts/lab6/obs.py create mode 100644 scripts/lab6/reconcile.py create mode 100644 scripts/lab6/resources.py create mode 100644 scripts/lab6/test_measurement.py create mode 100755 scripts/lab6/track1.py create mode 100755 scripts/lab6/verify.py create mode 100644 scripts/lab6/workload.py create mode 100755 scripts/restart.sh create mode 100755 scripts/start-replica.sh create mode 100755 scripts/stop-one.sh diff --git a/.env.example b/.env.example index 2e9f054..8866fbb 100644 --- a/.env.example +++ b/.env.example @@ -1,34 +1,155 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Полный список переменных, которые читают приложение и стенд; значения-образцы +# не являются секретами. Соответствие «переменная -> фактическая конфигурация» +# описано в REPORT.md. +# +# Приложение (проверяется zod-схемой app/src/config/app-config.schema.ts): APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url -API_REPLICAS=2 +DATABASE_URL=postgresql://messenger:change-me@postgres:5432/messenger +REDIS_URL=redis://redis:6379 +DATABASE_POOL_MAX=10 +DATABASE_CONNECTION_TIMEOUT_MS=5000 +DATABASE_STATEMENT_TIMEOUT_MS=5000 +DATABASE_IDLE_TX_TIMEOUT_MS=30000 +CACHE_TTL_SECONDS=30 +CACHE_MODE=protected +CACHE_LOCK_TTL_MS=1000 +CACHE_MISS_DELAY_MS=0 +# Бюджет проверки зависимостей в /health/ready: LB пробует ту же ручку +# (timeout check 500 ms), поэтому проба обязана уложиться заметно раньше. +HEALTH_TIMEOUT_MS=400 +# Токен доступа к /internal/metrics; сгенерируйте свой. +METRICS_TOKEN=change-me +# Дрейн перед выходом по SIGTERM: реплика перестаёт проходить пробы LB, +# ждёт DRAIN_DELAY_MS (длиннее обнаружения отказа ~1 s) и только потом закрывается. +DRAIN_DELAY_MS=3000 +# Переопределяет X-Instance-Id; по умолчанию это hostname контейнера +# (= короткий ID контейнера, по нему работает scripts/stop-one.sh). +# INSTANCE_ID=api-1 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=https://s3:9000 + +# Стенд (compose.yaml и scripts/): +API_REPLICAS=2 +API_CPUS_PER_REPLICA=1.5 +API_MEMORY_PER_REPLICA=1024m +PG_CPUS=1.5 +PG_MEMORY=512m +REDIS_CPUS=0.25 +REDIS_MEMORY=128m +LB_CPUS=0.25 +LB_MEMORY=128m +# Тег образа API; BUILD_ID отличает сборки при rolling update. +API_IMAGE=mtusi-messenger:lab7 +BUILD_ID=local +APP_PUBLIC_PORT=8080 +LB_STATS_PORT=8404 +# Loopback-порты PostgreSQL/Redis нужны только операторским проверкам с хоста +# (make test-e2e, psql). API-реплики портов не публикуют. +POSTGRES_PUBLISHED_PORT=5432 +REDIS_PUBLISHED_PORT=6379 + +# PostgreSQL (пароль подставьте свой; тот же, что в DATABASE_URL): +POSTGRES_DB=messenger +POSTGRES_USER=messenger +POSTGRES_PASSWORD=change-me + +# Объектное хранилище MinIO. Credentials — файлы ./secrets/* (scripts/init-env.sh), не здесь. +S3_ENDPOINT=http://s3:9000 +S3_PUBLIC_ENDPOINT=http://localhost:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +S3_PUBLIC_BIND=127.0.0.1 +S3_PUBLIC_PORT=9000 +S3_CPUS=1.0 +S3_MEMORY=512m +S3_CONNECT_TIMEOUT_MS=1000 +S3_REQUEST_TIMEOUT_MS=15000 MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 +# Каждая загрузка держит копию файла (≤ MAX_UPLOAD_BYTES) до полного декода; +# худший декод (40 Мп RGBA16 interlaced PNG) ≈ 340 MiB. Граница памяти реплики: +# базовый RSS (~250 MiB) + UPLOAD_MAX_IN_FLIGHT × 10 MiB + IMAGE_DECODE_MAX_CONCURRENT × 340 MiB +# = 250 + 160 + 340 ≈ 750 MiB при API_MEMORY_PER_REPLICA=1024m. +UPLOAD_MAX_IN_FLIGHT=16 +# Не больше стольких одновременных загрузок одного пользователя на реплику. +UPLOAD_MAX_IN_FLIGHT_PER_USER=4 +IMAGE_DECODE_MAX_CONCURRENT=1 +DIRECT_UPLOAD_MAX_PENDING_PER_USER=10 +# UPLOAD_TIMEOUT_MS, DIRECT_UPLOAD_URL_TTL_SECONDS, ATTACHMENT_SWEEP_GRACE_SECONDS, +# ATTACHMENT_SWEEP_INTERVAL_MS задаются в compose.yaml (environment) с умолчаниями +# и переопределяются из shell только для экспериментов. + +# lab5: очередь и асинхронная обработка изображений. URL брокера берётся из +# файла секрета (scripts/init-env.sh), байты и credentials в сообщения не +# попадают: только job_id/attachment_id/pipeline_version/attempt. BROKER_URL_FILE=/run/secrets/broker_url +BROKER_DELIVERY_LIMIT=10 +BROKER_PUBLISH_TIMEOUT_MS=5000 +# Сколько заданий worker обрабатывает параллельно; prefetch равен этому числу. WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 +JOB_LEASE_SECONDS=30 +JOB_RETRY_BASE_MS=1000 +JOB_RETRY_MAX_MS=30000 +PIPELINE_VERSION=1 +OUTBOX_POLL_INTERVAL_MS=500 +LEASE_REAPER_INTERVAL_MS=2000 +# 0 выключает фоновую уборку staging (ручной запуск остаётся). +STAGING_CLEANUP_INTERVAL_MS=60000 +# Сколько staging-объект неуспешной загрузки живёт до удаления. STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 +WORKER_HEALTH_PORT=8081 +QUEUED_RECONCILE_GRACE_SECONDS=15 +OUTBOX_RETENTION_SECONDS=86400 +JOB_EVENTS_RETENTION_SECONDS=2592000 +# 1 включает чтение fault: из Redis; в обычном стенде — 0. +FAULT_INJECTION_ENABLED=0 +WORKER_REPLICAS=1 +WORKER_CPUS=1.5 +# Бюджет worker: база ≈250 MiB + WORKER_CONCURRENCY × (10 MiB исходник + +# ≈340 MiB худший декод 40 Мп) ≈ 950 MiB при concurrency 2; лимит 1280m. +WORKER_MEMORY=1280m +BROKER_CPUS=0.5 +BROKER_MEMORY=512m + +# lab6: наблюдаемость (OpenTelemetry). OTEL_SERVICE_NAME здесь не задаётся: +# compose.yaml выставляет messenger-api / messenger-worker литералами. +OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab -# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. +# Управляющие ключи (значения по умолчанию совпадают с compose.yaml): +OTEL_SDK_DISABLED=false +# Доля head sampling корневых трасс (ParentBased + TraceIdRatioBased), 0..1. +OTEL_TRACES_SAMPLER_ARG=1 +OTEL_METRIC_EXPORT_INTERVAL=10000 +OTEL_EXPORTER_OTLP_TIMEOUT=5000 +OTEL_BSP_MAX_QUEUE_SIZE=2048 +OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512 +OTEL_BSP_SCHEDULE_DELAY=1000 +OTEL_BLRP_MAX_QUEUE_SIZE=2048 +OTEL_BLRP_MAX_EXPORT_BATCH_SIZE=512 +OTEL_BLRP_SCHEDULE_DELAY=1000 +LOG_LEVEL=INFO +# Backend-ы наблюдаемости: loopback-порты UI и лимиты контейнеров. +PROMETHEUS_PORT=9090 +GRAFANA_PORT=3000 +OTELCOL_CPUS=0.5 +OTELCOL_MEMORY=256m +PROMETHEUS_CPUS=0.5 +PROMETHEUS_MEMORY=768m +LOKI_CPUS=0.5 +LOKI_MEMORY=512m +TEMPO_CPUS=0.5 +TEMPO_MEMORY=512m +GRAFANA_CPUS=0.5 +GRAFANA_MEMORY=384m + +# lab7: TLS/mTLS, OpenBao и Argon2id (целевые переменные из skeleton lab7; +# до реализации lab7 используются значения стенда lab6 выше). PUBLIC_BASE_URL=https://localhost:8443 TLS_CA_FILE=/run/secrets/ca.crt TLS_CERT_FILE=/run/secrets/service.crt diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7f8f579 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,38 @@ +FROM node:25.7.0-slim AS build + +WORKDIR /usr/src/app + +RUN apt-get update \ + && apt-get install -y --no-install-recommends python3 make g++ \ + && rm -rf /var/lib/apt/lists/* + +COPY app/package.json app/package-lock.json ./ +RUN npm ci + +COPY app/ ./ +RUN npm run build && npm prune --omit=dev + +FROM node:25.7.0-slim AS runtime + +WORKDIR /usr/src/app + +# BUILD_ID доказывается через GET /internal/metrics и меняется при rolling +# update: он показывает, какая именно сборка отвечает на запрос. +ARG BUILD_ID=unknown +ENV BUILD_ID=$BUILD_ID + +ENV NODE_ENV=production +ENV APP_PORT=8080 +ENV DRAIN_DELAY_MS=5000 +COPY --from=build /usr/src/app/package.json /usr/src/app/package-lock.json ./ +COPY --from=build /usr/src/app/node_modules ./node_modules +COPY --from=build /usr/src/app/dist ./dist + +USER node + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \ + CMD node -e "const port=process.env.APP_PORT||'8080'; fetch('http://127.0.0.1:'+port+'/health/ready').then((response) => { if (!response.ok) process.exit(1); }).catch(() => process.exit(1))" + +CMD ["node", "dist/main.js"] diff --git a/Makefile b/Makefile index 5ad43ad..5cd1da7 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,16 @@ PYTHON ?= python3 BASE_URL ?= https://localhost:8443 CA_FILE ?= ACTION_SCRIPT ?= +PROMETHEUS_URL ?= http://localhost:9090 +GRAFANA_URL ?= http://localhost:3000 TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) +CURL_TLS_ARGS = $(if $(CA_FILE),--cacert "$(CA_FILE)",) +LAB6_ARGS = --base-url "$(BASE_URL)" --prometheus-url "$(PROMETHEUS_URL)" --grafana-url "$(GRAFANA_URL)" $(TLS_ARGS) -.PHONY: help check validate test load test-persistence test-failover test-security +.PHONY: help check validate test load test-persistence test-failover test-security test-dependencies stand-up stand-down stand-status wait-ready init-env test-e2e s3-security consistency bench lab5-demo lab5-faults lab5-track2 jobs lab6-ready lab6-signals lab6-correlate lab6-redaction lab6-history lab6-incident-worker lab6-incident-db lab6-incident-telemetry lab6-track1 help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; test-security: external TLS check; init-env: .env + secrets; test-e2e: app e2e" check: $(PYTHON) scripts/check_contract.py @@ -31,3 +35,81 @@ test-failover: test-security: $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +COMPOSE_ENV_FILE ?= .env +COMPOSE = docker compose --env-file $(COMPOSE_ENV_FILE) + +test-dependencies: + cd app && E2E_COMPOSE_DIR="$(CURDIR)" E2E_COMPOSE_ENV_FILE="$(COMPOSE_ENV_FILE)" npm run test:dependencies + +stand-up: + $(COMPOSE) up -d --build --wait + +stand-down: + $(COMPOSE) down + +stand-status: + $(COMPOSE) ps + +wait-ready: + @for attempt in $$(seq 1 60); do \ + if curl -fsS $(CURL_TLS_ARGS) "$(BASE_URL)/health/ready" >/dev/null 2>&1; then \ + echo "stand is ready ($(BASE_URL))"; exit 0; \ + fi; \ + sleep 1; \ + done; \ + echo "stand did not become ready within 60s" >&2; exit 1 + +init-env: + ./scripts/init-env.sh + +test-e2e: + scripts/app-e2e.sh + +s3-security: + scripts/lab4/check_s3_security.sh + +consistency: + scripts/lab4/consistency_check.sh + +bench: + scripts/lab4/run_matrix.sh + +lab5-demo: + $(PYTHON) scripts/lab5/worker_down_demo.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +lab5-faults: + $(PYTHON) scripts/lab5/fault_suite.py --base-url "$(BASE_URL)" --scenario level4 --output evidence/lab5/faults-level4.json $(TLS_ARGS) + +lab5-track2: + $(PYTHON) scripts/lab5/fault_suite.py --base-url "$(BASE_URL)" --scenario track2 --repeat 3 --output evidence/lab5/track2.json $(TLS_ARGS) + +jobs: + docker compose --env-file $(COMPOSE_ENV_FILE) exec -T api node dist/jobs/jobs.cli.js $(ARGS) + +lab6-ready: + $(PYTHON) scripts/lab6/verify.py ready $(LAB6_ARGS) + +lab6-signals: + $(PYTHON) scripts/lab6/verify.py signals $(LAB6_ARGS) + +lab6-correlate: + $(PYTHON) scripts/lab6/verify.py correlation $(LAB6_ARGS) + +lab6-redaction: + $(PYTHON) scripts/lab6/verify.py redaction $(LAB6_ARGS) + +lab6-history: + $(PYTHON) scripts/lab6/verify.py history $(LAB6_ARGS) + +lab6-incident-worker: + $(PYTHON) scripts/lab6/incidents.py --scenario worker $(LAB6_ARGS) + +lab6-incident-db: + $(PYTHON) scripts/lab6/incidents.py --scenario db $(LAB6_ARGS) + +lab6-incident-telemetry: + $(PYTHON) scripts/lab6/incidents.py --scenario telemetry --repeat 2 $(LAB6_ARGS) + +lab6-track1: + $(PYTHON) scripts/lab6/track1.py $(LAB6_ARGS) diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..b266c54 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,59 @@ +# compiled output +/dist +/node_modules +/build + +# TypeScript build cache +*.tsbuildinfo + +# Logs +logs +*.log +npm-debug.log* +pnpm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# OS +.DS_Store + +# Tests +/coverage +/.nyc_output + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# temp directory +.temp +.tmp + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json diff --git a/app/.prettierrc b/app/.prettierrc new file mode 100644 index 0000000..b652839 --- /dev/null +++ b/app/.prettierrc @@ -0,0 +1,6 @@ +{ + "singleQuote": true, + "trailingComma": "all", + "tabWidth": 4, + "useTabs": true +} diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000..b285bd3 --- /dev/null +++ b/app/README.md @@ -0,0 +1,314 @@ +# app — API мессенджера + +NestJS 12 + Fastify, ESM TypeScript. PostgreSQL — источник истины бизнес-данных, +Redis — серверные Bearer-сессии и производный кэш истории сообщений. + +Общая документация (в корне репозитория): + +| Документ | Что содержит | +|---|---| +| [`../REPORT.md`](../REPORT.md) | архитектура, схема данных, транзакции, политика кэша, команды, результаты проверок и трека 1 | +| [`../evidence/README.md`](../evidence/README.md) | индекс доказательств: что подтверждено и как это воспроизвести | +| [`../contracts/openapi.json`](../contracts/openapi.json) | нормативный контракт API | +| [`../tests/README.md`](../tests/README.md) | публичные проверки репозитория (`make check`, `make test`, persistence) | + +## Что внутри + +```text +src/ + main.ts bootstrap: Fastify, ValidationPipe, shutdown hooks + app.module.ts сборка модулей приложения + config/ Zod-схема env + глобальный ConfigModule + database/ pg.Pool, транзакции, миграции (001..004) + redis/ клиент Redis (AOF-совместимый, без offline queue) + auth/ Basic-вход, Redis-сессии, logout + users/ регистрация (Argon2id), профиль + chats/ создание чата в транзакции, список и чтение + messages/ отправка сообщения, keyset-история + cache/ версионированный кэш истории + lock на страницу + idempotency/ журнал Idempotency-Key (claim/read/store/forget/GC) + metrics/ /internal/metrics и /internal/metrics/reset + health/ liveness/readiness с проверкой зависимостей (readiness — проба LB) + common/ + http/ cursor (формат+календарь), page (конверт {items,next_cursor}), request-id + errors/ exception filter и тип тела ошибки ApiErrorBody + validation/ декоратор CodePointLength (длины в Unicode code points) + auth/ guard и декоратор текущего пользователя +test/ + app.e2e-spec.ts black-box набор против запущенного API (PG + Redis) +scripts/ + graph-modules.ts генератор графа зависимостей (nestjs-spelunker) +``` + +Принципы: raw `pg.Pool` без ORM, параметризованные запросы, никаких in-memory +хранилищ в боевых путях; кэш — производное состояние и всегда допускает +восстановление из PostgreSQL; отказ зависимости даёт ограниченную ошибку +(`503`), а не аварийное завершение процесса; длины строк проверяются в Unicode +code points (свой декоратор `@CodePointLength`), как в JSON Schema, а не в +UTF-16-единицах; состояние, от которого зависит корректность (сессии, журнал +идемпотентности), живёт только в общих PostgreSQL/Redis — локальных сессий и +файлов на диске реплики нет, поэтому `N` взаимозаменяемых реплик за одним LB +дают один и тот же результат. + +## Быстрый старт + +Рекомендуемый путь — весь стенд из корня репозитория (PostgreSQL, Redis, миграции, API): + +```sh +cd .. +cp .env.example .env +password=$(openssl rand -hex 32) +sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$password/" .env +sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:$password@postgres:5432/messenger|" .env +sed -i "s/^METRICS_TOKEN=.*/METRICS_TOKEN=$(openssl rand -hex 16)/" .env +make stand-up # сборка + up -d --wait: migrate -> api x API_REPLICAS -> haproxy +make wait-ready +curl -fsS http://localhost:8080/health/ready +for i in 1 2 3 4; do curl -sD- -o /dev/null localhost:8080/health/live | grep -i x-instance-id; done +``` + +Публичной точкой входа служит HAProxy (`compose.yaml`): реплики API портов не +публикуют. `API_REPLICAS` задаёт их число, `API_TOTAL_CPUS` / `API_TOTAL_MEMORY_MB` +делятся между ними — это бюджет серии трека 1 (`../REPORT.md`). + +Локальный запуск без Docker (нужны доступные PostgreSQL и Redis): + +```sh +cd app +npm ci +npm run build + +export DATABASE_URL=postgresql://messenger:@127.0.0.1:5432/messenger +export REDIS_URL=redis://127.0.0.1:6379 +export APP_PORT=8080 +node dist/database/migration.runner.js # применяет миграции из dist/database/migrations + +npm run start:dev # или npm run start:prod после build +``` + +## Переменные окружения + +Читаются только через конфигурационный слой (`src/config`), типы и диапазоны +проверяет Zod-схема на старте — при некорректном значении приложение падает +с понятной ошибкой. + +| Переменная | По умолчанию | Назначение | +|---|---|---| +| `APP_HOST` / `APP_PORT` | `0.0.0.0` / `8080` | адрес прослушивания | +| `APP_ENV` | `lab` | метка окружения | +| `DATABASE_URL` | — (обязательна) | строка подключения PostgreSQL | +| `REDIS_URL` | — (обязательна) | строка подключения Redis | +| `DATABASE_POOL_MAX` | `10` | размер пула соединений | +| `DATABASE_CONNECTION_TIMEOUT_MS` | `5000` | таймаут установки соединения | +| `DATABASE_STATEMENT_TIMEOUT_MS` | `5000` | таймаут SQL-запроса | +| `SESSION_TTL_SECONDS` | `3600` | TTL сессии (минимум 2) | +| `HEALTH_TIMEOUT_MS` | `400` | бюджет проверки PostgreSQL/Redis внутри `/health/ready`; меньше `timeout check` HAProxy (500 ms) и `DATABASE_STATEMENT_TIMEOUT_MS` | +| `CACHE_TTL_SECONDS` | `30` | TTL страницы истории в Redis | +| `CACHE_MODE` | `protected` | `protected` (lock на страницу) или `naive` (только для эксперимента) | +| `CACHE_LOCK_TTL_MS` | `1000` | TTL lock-а страницы | +| `CACHE_MISS_DELAY_MS` | `0` | искусственная пауза на промахе; влияет только на `naive` | +| `METRICS_TOKEN` | — (необязательна) | токен доступа к `/internal/metrics*`; без него endpoint закрыт | +| `DRAIN_DELAY_MS` | `5000` (в стенде `3000`) | окно дрейна при `SIGTERM`: реплика сразу перестаёт проходить пробу LB, ждёт этот интервал и только затем закрывает сервер и пулы | +| `INSTANCE_ID` | hostname контейнера | значение `X-Instance-Id`; в Docker hostname = короткий ID контейнера, поэтому `scripts/stop-one.sh` находит реплику по нему | +| `IDEMPOTENCY_TTL_SECONDS` | `86400` | срок хранения журнала Idempotency-Key (минимум 60) | + +Поддерживаются также `DATABASE_URL_FILE` / `REDIS_URL_FILE`: если заданы, значение +читается из файла (docker secrets / Swarm). Подробности и компромиссы — +[`../REPORT.md`](../REPORT.md), раздел «Конфигурация и секреты». + +## Эндпоинты + +Публичный контракт — [`../contracts/openapi.json`](../contracts/openapi.json). + +| Метод и путь | Аутентификация | Назначение | +|---|---|---| +| `GET /health/live` | нет | процесс жив; не обращается к зависимостям, поэтому отвечает `200` и при их отказе | +| `GET /health/ready` | нет | готовность реплики: флаг дреина + PostgreSQL и Redis (бюджет `HEALTH_TIMEOUT_MS`), иначе `503`; эту же ручку пробует HAProxy | +| `POST /api/v1/users` | нет | регистрация с паролем (Argon2id) | +| `POST /api/v1/auth/sessions` | `Basic` | вход, выдаёт opaque Bearer-токен | +| `DELETE /api/v1/auth/sessions/current` | `Bearer` | отзыв текущей сессии, `204` | +| `GET /api/v1/users/me` | `Bearer` | текущий пользователь | +| `POST /api/v1/chats` | `Bearer` | создание чата (транзакция) | +| `GET /api/v1/chats` | `Bearer` | список доступных чатов | +| `GET /api/v1/chats/:chatId` | `Bearer` | чат по id (чужой — `404`) | +| `POST /api/v1/chats/:chatId/messages` | `Bearer` + обязательный `Idempotency-Key` | отправка сообщения (см. ниже) | +| `GET /api/v1/chats/:chatId/messages` | `Bearer` | история, keyset-пагинация `(created_at, id)` | +| `GET /internal/metrics` | `Bearer METRICS_TOKEN` | счётчики и агрегаты латентности | +| `POST /internal/metrics/reset` | `Bearer METRICS_TOKEN` | сброс счётчиков (`200`) | + +Правила: `Basic` принимается только на создании сессии, бизнес-запросы — только +`Bearer`; заголовок `X-User-Id` не аутентифицирует и не подменяет владельца +сессии; истёкший, отозванный или неизвестный токен — `401` с соответствующим +`WWW-Authenticate`. + +## npm-скрипты + +| Команда | Что делает | +|---|---| +| `npm run build` | сборка в `dist/` | +| `npm run start:dev` | watch-режим | +| `npm run start:prod` | запуск собранного приложения (`node dist/main`) | +| `npm test` / `npm run test:unit` | unit-тесты (vitest) | +| `npm run test:e2e` | black-box набор против запущенного API (см. ниже) | +| `npm run test:dependencies` | автоматическая проверка отказов Redis/PostgreSQL: останавливает и поднимает контейнеры Compose-стенда | +| `npm run idempotency:gc` | ручной прогон удаления просроченных записей Idempotency-Key | +| `npm run lint` | oxlint по `src/` и `test/` | +| `npm run format` | prettier | +| `npm run graph` | граф модулей и провайдеров через nestjs-spelunker (пишет `../docs/architecture/`) | + +## Тесты + +Unit-тесты не требуют инфраструктуры: + +```sh +npm test +``` + +Интеграционный набор работает по HTTP против запущенного стенда и дополнительно +подключается к PostgreSQL (очистка тестовых данных) и Redis: + +```sh +export API_BASE_URL=http://localhost:8080 +export DATABASE_URL=postgresql://messenger:@:5432/messenger +export REDIS_URL=redis://:6379 +npm run test:e2e +``` + +Название `API_BASE_URL` (а не `BASE_URL`) выбрано потому, что Vitest сам +устанавливает `process.env.BASE_URL` в значение Vite base. Кейс истечения сессии +включается переменной `SESSION_TTL_SECONDS=2` и у запущенного API, и у набора. + +## Отказы зависимостей + +Отдельный набор останавливает и поднимает контейнеры Compose-стенда и проверяет +ограниченные ошибки вместо 500: + +```sh +cd .. # из корня репозитория, стенд поднят через docker compose +make test-dependencies +``` + +Он включён по флагу `E2E_DEPENDENCY_FAULTS=1` (им же управляет цель Makefile), +потому что требует прав на управление Docker Compose-проектом; остальные +переменные — `E2E_COMPOSE_DIR`, `E2E_COMPOSE_ENV_FILE`, `E2E_REDIS_SERVICE`, +`E2E_POSTGRES_SERVICE`, `E2E_API_SERVICE`, `E2E_LB_STATS_URL`, +`E2E_POSTGRES_USER`, `E2E_POSTGRES_DB`, `E2E_PG_HBA_PATH`. + +Проверяются три топологии отказа: + +1. **Отказ Redis** (общая зависимость): `/health/live` реплики остаётся `200`, + `/health/ready` и бизнес-запросы — `503 unavailable` с `request_id` из + `X-Request-Id` и без деталей драйвера, запрос без сессии — по-прежнему `401`. + Неготовыми становятся все реплики, HAProxy исключает их из ротации и + отвечает собственным `503`; после старта Redis сессия и подтверждённое + сообщение живы. +2. **Отказ PostgreSQL** (общая зависимость): то же плюс проверка, что после + возврата зависимости данные на месте и новая запись проходит. +3. **Отказ PostgreSQL у одной реплики** (локальный путь к БД): для адреса + выбранной реплики временно ставится `reject`-строка в `pg_hba.conf` (первое + совпадение) и обрываются её соединения. Выбранная реплика отвечает `503` и её + слот уходит в `DOWN`, здоровая продолжает `200`/`UP` и обслуживает все чтения + через LB; `pg_hba.conf` восстанавливается в `finally`, после чего реплика + возвращается в ротацию и снова получает запросы. + +Реплики API портов не публикуют, поэтому отдельная реплика опрашивается изнутри +своего контейнера (loopback), а состояние слотов — из `stats;csv` HAProxy +(`127.0.0.1:8404`). Каждый запрос к остановленной БД ждёт +`DATABASE_CONNECTION_TIMEOUT_MS`, поэтому набор идёт около минуты. + +## Реплики, балансировка и остановка реплики + +Все реплики запускаются из одного образа и одного `compose.yaml`; API портов не +публикует, трафик идёт только через HAProxy. Состояние, от которого зависит +корректность, лежит в общих PostgreSQL и Redis, поэтому клиент с одним +Bearer-токеном обслуживается любой репликой: + +```sh +make test BASE_URL=http://localhost:8080 # сквозной сценарий через LB +python3 scripts/lab3/lab3.py check spread # распределение X-Instance-Id +make test-failover ACTION_SCRIPT=scripts/stop-one.sh # отказ одной реплики +scripts/start-replica.sh # вернуть остановленную реплику +``` + +- `X-Instance-Id` = `INSTANCE_ID` или hostname процесса, стабилен для процесса; + в Docker hostname контейнера — короткий ID, поэтому `scripts/stop-one.sh` + останавливает ровно ту реплику, которую обслужил запрос теста. Тот же заголовок + добавляется к ответам об ошибках, которые формируются фильтром до интерсептора. +- **Остановка (`SIGTERM`)** идёт в порядке «сначала дрейн, потом разбор ресурсов»: + реплика помечается not-ready (проба LB и `/health/ready` начинают отвечать + `503`), `DRAIN_DELAY_MS` ждёт, пока LB её исключит (обнаружение ≈1 s), и лишь + затем закрываются HTTP-сервер, пул PostgreSQL и соединение Redis. Если + полагаться на стандартный порядок Nest (`onModuleDestroy` вызывает закрытие + пулов раньше `beforeApplicationShutdown`), реплика какое-то время остаётся в + ротации уже без ресурсов — это и было причиной явной последовательности в + `src/main.ts`. +- **Проба LB — тот же `/health/ready`**, что и healthcheck контейнера: реплика, + потерявшая обязательную зависимость (свой путь к PostgreSQL или Redis), + выходит из ротации, и трафик уходит на здоровые реплики. Проба с зависимостями + ограничена общим дедлайном `HEALTH_TIMEOUT_MS=400` на реплику; проверка + PostgreSQL (`SELECT 1`) идёт по отдельному соединению, а не из общего пула + бизнес-запросов, а для `PING` Redis стоит `AbortSignal.timeout`, поэтому проба + укладывается в `timeout check 500ms` HAProxy и не реагирует на перегрузку. + Когда недоступна общая для всех зависимость, + неготовыми становятся все реплики, и клиент получает `503` от самого LB: это + честный ответ «готовых узлов нет» вместо маскировки отказа. +- `/health/live` зависимостей не касается: он отвечает `200`, пока жив процесс, + и по нему проверяют, что реплика не упала (в том числе при отказе PG/Redis). + +## Идемпотентность отправки сообщения + +`POST /api/v1/chats/{chatId}/messages` требует заголовок `Idempotency-Key` +(ASCII `[A-Za-z0-9._:-]{1,128}`). Область уникальности — пользователь + метод + +путь чата + ключ, поэтому одинаковый ключ у разных пользователей или в разных +чатах не конфликтует. Журнал — таблица `idempotency_keys` (миграция 003), то +есть общая для всех реплик. + +| Ситуация | Ответ | +|---|---| +| Заголовок отсутствует, пуст или не подходит под шаблон | `400 invalid_request` (до обращения к БД) | +| Первый запрос с ключом | `201` и сообщение; заявка, вставка сообщения, инкремент версии чата и тело ответа записываются **одним оператором SQL** (атомарность обеспечивает сам оператор) | +| Повтор того же тела с тем же ключом | тот же `201` и тот же JSON (включая `id` и `created_at`), новое сообщение не создаётся | +| Другое тело с тем же ключом | `409 conflict` | +| Повтор после `404` (нет доступа к чату) | `404`, ключ не занят: оператор вставляет заявку только при наличии членства, иначе не создаётся ничего | +| Ключ старше `IDEMPOTENCY_TTL_SECONDS` | запись удаляется, ключ считается свободным | +| Одновременные повторы через разные реплики | ровно одно сообщение: заявка берётся `INSERT ... ON CONFLICT DO NOTHING`, повтор читает сохранённый ответ | + +Путь записи — один round trip: `messages.createIdempotent` проверяет членство, +занимает ключ (`INSERT ... ON CONFLICT DO NOTHING`), вставляет сообщение, поднимает +`chats.message_version` и сохраняет тело ответа, а повтор читает сохранённый ответ +вместе с повторной проверкой доступа (`idempotency.read`). До оптимизации это были +8 обращений к БД в явной транзакции (см. REPORT.md, раздел «A/B улучшения»). + +Отпечаток тела считается по валидированному DTO с фиксированным порядком полей, +поэтому порядок ключей в JSON не влияет на результат. Транзиентные сбои +PostgreSQL (`57014`, `40001`, `40P01`) и обрывы соединения отдаются как +`503 unavailable` и не фиксируются как окончательный результат: клиент может +безопасно повторить запрос с тем же ключом. Просроченные записи удаляются +фоновым проходом (`idempotency.purged` в метриках) под +`pg_try_advisory_xact_lock`, а также вручную: `npm run idempotency:gc`. + +## Харнесс экспериментов + +Уровни 3/4 и трек 1 обслуживает `../scripts/lab3/lab3.py` (только stdlib) и +профили k6 в `../scripts/load/`: `run`, `sweep`, `track1-extras`, `failover`, +`rolling-update`, `ab`, `analyze`, `watch`, `check`, `quiesce`, `track1`. +Сырые результаты прогонов, манифесты условий измерения и графики складываются в +`../evidence/track1/`. Подробности — в `../REPORT.md` и +`../evidence/README.md`. + +## Метрики + +`GET /internal/metrics` возвращает `{counters, latency_ms, instance_id, build_id}`: именованные SQL-метки, +операции Redis, `cache_hit`/`cache_miss`/`cache_lock_wait`, `session_get/set/del`, +`request_count` и процентили латентности (буфер ограничен). Деградации +наблюдаемы отдельными счётчиками: `cache_fallback`, `cache_write_error`, +`cache_unlock_error`, `cache_lock_timeout`, `cache_corrupt_entry`, +`database.pool_error`, `database.rollback_error`, `redis.error`, а также +идемпотентность: `idempotency.claim`, `idempotency.replay`, `idempotency.conflict`, +`idempotency.claim_lost`, `idempotency.released`, `idempotency.purged`, +`idempotency.purge_error`, `messages.write`. + +Счётчики локальны процессу: при нескольких репликах их нельзя суммировать как +распределённый снимок, а рестарт API обнуляет их (данные PostgreSQL и Redis при +этом не затрагиваются). `instance_id` и `build_id` позволяют сопоставить ответ +конкретной реплике и сборке — этим пользуются rolling update и эксперименты. diff --git a/app/nest-cli.json b/app/nest-cli.json new file mode 100644 index 0000000..5a21707 --- /dev/null +++ b/app/nest-cli.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src", + "compilerOptions": { + "deleteOutDir": true, + "assets": [ + { + "include": "database/migrations/*.sql", + "outDir": "dist" + } + ], + "watchAssets": true + } +} diff --git a/app/oxlint.json b/app/oxlint.json new file mode 100644 index 0000000..07ec3bd --- /dev/null +++ b/app/oxlint.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/rules.rs", + "rules": { + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-floating-promises": "warn" + }, + "env": { + "node": true + } +} diff --git a/app/package-lock.json b/app/package-lock.json new file mode 100644 index 0000000..c0894d9 --- /dev/null +++ b/app/package-lock.json @@ -0,0 +1,8705 @@ +{ + "name": "app", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "app", + "version": "0.0.1", + "license": "UNLICENSED", + "dependencies": { + "@aws-sdk/client-s3": "^3.1156.0", + "@aws-sdk/s3-request-presigner": "^3.1156.0", + "@nestjs/common": "^12.0.1", + "@nestjs/config": "^12.0.0", + "@nestjs/core": "^12.0.1", + "@nestjs/platform-express": "^12.0.1", + "@nestjs/platform-fastify": "^12.0.3", + "@opentelemetry/api": "1.9.0", + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-logs-otlp-proto": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-proto": "0.203.0", + "@opentelemetry/exporter-trace-otlp-proto": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "@opentelemetry/sdk-trace-node": "2.0.1", + "@smithy/node-http-handler": "^4.12.1", + "amqplib": "^2.2.1", + "argon2": "^0.45.1", + "class-transformer": "^0.5.1", + "class-validator": "^0.15.1", + "date-fns": "^4.4.0", + "fastify": "5.12.4", + "pg": "^8.23.1", + "redis": "^6.3.0", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "sharp": "^0.35.5", + "zod": "^4.6.5" + }, + "devDependencies": { + "@nestjs/cli": "^12.0.0", + "@nestjs/mau": "^0.2.6", + "@nestjs/schematics": "^12.0.0", + "@nestjs/testing": "^12.0.1", + "@types/express": "^5.0.0", + "@types/node": "^24.0.0", + "@types/pg": "^8.23.1", + "@types/supertest": "^7.0.0", + "@vitest/coverage-v8": "^4.1.2", + "dotenv": "^18.0.5", + "nestjs-spelunker": "^1.3.2", + "oxlint": "^1.58.0", + "prettier": "^3.4.2", + "source-map-support": "^0.5.21", + "supertest": "^7.2.2", + "tsx": "^4.23.15", + "typescript": "^6.0.3", + "vite-tsconfig-paths": "^5.1.4", + "vitest": "^4.1.2" + } + }, + "node_modules/@angular-devkit/core": { + "version": "22.1.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-22.1.8.tgz", + "integrity": "sha512-34lsgg2FwMVBX7nR/ZqzRUcdvdYPvSB8XAEr2GudXAyZwLI9ehzfQlagAWR/gEb8p4uCFZW0r7uU0toxydq4Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "jsonc-parser": "3.3.1", + "picomatch": "4.0.5", + "rxjs": "7.8.2", + "source-map": "0.7.6" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "chokidar": "^5.0.0" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, + "node_modules/@angular-devkit/schematics": { + "version": "22.1.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-22.1.8.tgz", + "integrity": "sha512-Pv3cPa/44kvEwYcqwx4Ns5dhIDmcFNSHhbpheqiEG1Z/u4e2t4zHKDtE3eHZB+8o+IcC7xJj+d+AqGR44RoZDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.1.8", + "jsonc-parser": "3.3.1", + "magic-string": "1.0.0", + "ora": "9.4.1", + "rxjs": "7.8.2" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular-devkit/schematics-cli": { + "version": "22.1.8", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics-cli/-/schematics-cli-22.1.8.tgz", + "integrity": "sha512-SsGG8ompVzprmYE9sHi2L7DYZ+i1sD+YDfun6Rg2vkTCusejtD4SSGVxwuR6++dT22ZpN16OqUTmii/0bhE4xA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.1.8", + "@angular-devkit/schematics": "22.1.8", + "@inquirer/prompts": "8.5.2" + }, + "bin": { + "schematics": "bin/schematics.js" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular-devkit/schematics-cli/node_modules/@inquirer/prompts": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.5.2.tgz", + "integrity": "sha512-IYR/3C/paEVVQYQvdDlFZVjRCJVYHHON0XXMH91KO9GSxs0TdKYWlUdvfQl2EfAHDxUaN3IBffkE/BDTh5nJ6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^5.2.1", + "@inquirer/confirm": "^6.1.1", + "@inquirer/editor": "^5.2.2", + "@inquirer/expand": "^5.1.1", + "@inquirer/input": "^5.1.2", + "@inquirer/number": "^4.1.1", + "@inquirer/password": "^5.1.1", + "@inquirer/rawlist": "^5.3.1", + "@inquirer/search": "^4.2.1", + "@inquirer/select": "^5.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/checksums": { + "version": "3.1001.5", + "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1001.5.tgz", + "integrity": "sha512-6erto9nK2OZO/woEgmFIaPh5gChgdNd7nL6jgAf8TAXz3/QHC8Pan2TFe9GYp3IxOIKCCGWPylSjtOHKfNzQlw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/client-s3": { + "version": "3.1156.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1156.0.tgz", + "integrity": "sha512-Z2PqQqKMDVX56tNZ6ggmjoI5o/8+4+8ArmjLwE5ktYsEzs1BrvklBT1ZzI+s0Vcf3wfPguoEMD7EkMswmEta/A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/checksums": "^3.1001.5", + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/credential-provider-node": "^3.972.88", + "@aws-sdk/middleware-sdk-s3": "^3.972.81", + "@aws-sdk/signature-v4-multi-region": "^3.996.49", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/fetch-http-handler": "^5.8.0", + "@smithy/node-http-handler": "^4.12.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.978.5", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.5.tgz", + "integrity": "sha512-ruI0AWqcrfL20XDS6SwZIJFPOBZ6N0ADa9nLzWlBhxk1aoUjbUX3JkTR9vEmk7o35XpAHi68ahZ4T6RE2U9XyA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.975.0", + "@aws-sdk/xml-builder": "^3.972.41", + "@aws/lambda-invoke-store": "^0.3.0", + "@smithy/core": "^3.36.1", + "@smithy/signature-v4": "^5.7.4", + "@smithy/types": "^4.19.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.972.76", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.76.tgz", + "integrity": "sha512-YxmL1Ar7bV9ZkJvtv+lj+MF6le76NnZnbmgySyZuxpZaCv0/1lZ3KxKy6RIj1h9ui2hWnVjZxbmTMeO0y/NrQA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.972.78", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.78.tgz", + "integrity": "sha512-3VHknDRngoebsaqyT1iR75b5cBT2zfEtODK6yYmYltljkK1HEAQLs2FEd1IpWqAeOYdMGaG9wikngWLTufY7RA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/fetch-http-handler": "^5.8.0", + "@smithy/node-http-handler": "^4.12.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.973.21", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.21.tgz", + "integrity": "sha512-aLx9hbCX6mGAyv4ZZd8UagJ4RASHVJw6BFDSIyuKmLkqNL6H47EjBPK6qaJ4B5TDV6mc+vMa0SJFYyo4mkvVQg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/credential-provider-env": "^3.972.76", + "@aws-sdk/credential-provider-http": "^3.972.78", + "@aws-sdk/credential-provider-login": "^3.972.83", + "@aws-sdk/credential-provider-process": "^3.972.76", + "@aws-sdk/credential-provider-sso": "^3.973.20", + "@aws-sdk/credential-provider-web-identity": "^3.972.82", + "@aws-sdk/nested-clients": "^3.997.50", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/credential-provider-imds": "^4.5.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.972.83", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.83.tgz", + "integrity": "sha512-9bJU6FjRacF4FK/QHf8Dyxhur7B1grRj8C1Yh4IkpoFW2exQflPdCv0VrbemLW9ZctLNle+AE7TETs9KNvuLYg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/nested-clients": "^3.997.50", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.972.88", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.88.tgz", + "integrity": "sha512-AG0KID5qhQPzrFkh5b0Cws1Amytvzo0L0Xj6hMgJXEwD6ZXAqninDhSNAWJiN5zU4YVVZnuidnqwPwYJ04IamA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.76", + "@aws-sdk/credential-provider-http": "^3.972.78", + "@aws-sdk/credential-provider-ini": "^3.973.21", + "@aws-sdk/credential-provider-process": "^3.972.76", + "@aws-sdk/credential-provider-sso": "^3.973.20", + "@aws-sdk/credential-provider-web-identity": "^3.972.82", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/credential-provider-imds": "^4.5.2", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.972.76", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.76.tgz", + "integrity": "sha512-pdhKFTXv1zPYhh92MTlp0jVbLWvUEV9v+rziuEkoskGGQ2iJskxHTO38nA8UAbT/N4IM3n8OZJ9rIY5IBO15/A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.973.20", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.20.tgz", + "integrity": "sha512-DlxrAB3MnjNLx/da7b89W+3DyJQYso/q7Ns15MsST2IV2nkAYQOYTUCaffNSjgrpMP99Dm2mV2jxzcbyF94ZfA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/nested-clients": "^3.997.50", + "@aws-sdk/token-providers": "3.1155.0", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.972.82", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.82.tgz", + "integrity": "sha512-LUo46IqPTJ4xKBsrLuoaxiv/D2GTBCcFDMD1y3jKIqPR/p7Rw14RJFZ0iRWftqZtyLPQX9JMGnSi3mBu4y/pNA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/nested-clients": "^3.997.50", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.972.81", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.81.tgz", + "integrity": "sha512-jfanv1pV0sJFZw6/DPiNjvK7B478god0zOum5yIWo+/+1Gy+CSXWpGBWx+3nBJyDvjcu/2kUMr4ADUp9BHH34Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/signature-v4-multi-region": "^3.996.49", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.997.50", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.50.tgz", + "integrity": "sha512-nKb8qu4QsnpZTq/6JIXc72mzuzfh7BK4sUQkpQznPec2z4W7Ob2xYkcM4i5e1yGTBnbJVeFv/0sf3jcz85hclA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/signature-v4-multi-region": "^3.996.49", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/fetch-http-handler": "^5.8.0", + "@smithy/node-http-handler": "^4.12.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/s3-request-presigner": { + "version": "3.1156.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/s3-request-presigner/-/s3-request-presigner-3.1156.0.tgz", + "integrity": "sha512-M4yj4HmAPydhIMxKK90eTcnHr5FHBl000d2oFMAWpt+XPX86c2kmNJpiYbKrPLIe8jyK9sweRt5CDdWrhq/QTg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/signature-v4-multi-region": "^3.996.49", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.996.49", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.49.tgz", + "integrity": "sha512-nvuAZNRrRRVCiARRKsYlQ0VnXiEQiq7vXPH+UA+LSo+kN3Djl9eo/V2r0udkw85PnsNshmv2Em1clld5M3j67w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.975.0", + "@smithy/signature-v4": "^5.7.4", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.1155.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1155.0.tgz", + "integrity": "sha512-iIcQnYLhWuq9qOLQbIWFrxF3PF0svVeZvHnUS4DUnO4zUFmFHIyGyjqrntXG+e/5PUgfavV0pYfDIKHxTzN2LA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.978.5", + "@aws-sdk/nested-clients": "^3.997.50", + "@aws-sdk/types": "^3.975.0", + "@smithy/core": "^3.36.1", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.975.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.0.tgz", + "integrity": "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.972.41", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz", + "integrity": "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz", + "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz", + "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@borewit/text-codec": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz", + "integrity": "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@colors/colors": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", + "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "license": "MIT" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@fastify/ajv-compiler": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-4.0.6.tgz", + "integrity": "sha512-NtuzM0SfaMJbGlnjr9LWQUN5LzgSrbB8tf/wRZNas+4E1O/Nmzl53e7ruT61HDZyRCJGC6FxIogmNZO1c5ETBA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^4.0.0" + } + }, + "node_modules/@fastify/ajv-compiler/node_modules/fast-uri": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.1.tgz", + "integrity": "sha512-TmHQgewjHtMq1E5QKA0tOE0yeYGQs25KZC/ziJpubRtWI15W92e6vPFydWOeZBVROSHBYw/QhD9d5OefdD6LDg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/@fastify/cors": { + "version": "11.3.0", + "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-11.3.0.tgz", + "integrity": "sha512-ggQGua+xHv1MvePbPr0v//xLYEsCXbWspquXCJS9Ot5YoRXq8J8ZWzHnxDBVnbtXosvistXo6LtNzOJswf64Fw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fastify-plugin": "^6.0.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/@fastify/error": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@fastify/error/-/error-4.2.0.tgz", + "integrity": "sha512-RSo3sVDXfHskiBZKBPRgnQTtIqpi/7zhJOEmAxCiBcM7d0uwdGdxLlsCaLzGs8v8NnxIRlfG0N51p5yFaOentQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/fast-json-stringify-compiler": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-5.1.0.tgz", + "integrity": "sha512-PxcYtKLbQ8Z+yApiqjK8FwxIwvEj38k2OiLc17u8dkJSlmfi2wHHPaSnaoqBPQqtvF8YVsDgDpP2snDCfFrpfw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-json-stringify": "^7.0.0" + } + }, + "node_modules/@fastify/formbody": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@fastify/formbody/-/formbody-9.0.0.tgz", + "integrity": "sha512-T/af26CSrUARBCvsEmv+DJLPfZlrRKESzqironxP1j7qzuLyKcoZtj6MuTGShuKx1THXugoie2oFbUJxXfGFzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fast-querystring": "^1.1.2", + "fastify-plugin": "^6.0.0" + } + }, + "node_modules/@fastify/forwarded": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@fastify/forwarded/-/forwarded-3.0.2.tgz", + "integrity": "sha512-NE8HgKLgYejV9lDpqkEFaDKMLYelJBVfHekhB0UKvX0ghagXRJqg68feg8er1NPXxG4N9i6vPxzt8E+3wHfcmA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/@fastify/merge-json-schemas": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.2.1.tgz", + "integrity": "sha512-OA3KGBCy6KtIvLf8DINC5880o5iBlDX4SxzLQS8HorJAbqluzLRn80UXU0bxZn7UOFhFgpRJDasfwn9nG4FG4A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/@fastify/middie": { + "version": "9.3.4", + "resolved": "https://registry.npmjs.org/@fastify/middie/-/middie-9.3.4.tgz", + "integrity": "sha512-dd8phTnVWzx3iKPBKSvtRUT8+Igvy/MP+P5HcY2tjejEyeVbyjkD4HgzKessUObue5RRM5J6PZdxtAqgbn84yw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastify-plugin": "^6.0.0", + "find-my-way": "^9.5.0", + "path-to-regexp": "^8.1.0", + "reusify": "^1.0.4" + } + }, + "node_modules/@fastify/proxy-addr": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@fastify/proxy-addr/-/proxy-addr-5.1.1.tgz", + "integrity": "sha512-zv07Y9GEuDsJPegZoDFd4SDWaZOW8N2pa0GSrYmKpId/tjt1Hgo3BjZBVjdVpfVrHaA+Qv5jawtS2O50J5xM9g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/forwarded": "^3.0.0", + "ipaddr.js": "^2.1.0" + } + }, + "node_modules/@fastify/proxy-addr/node_modules/ipaddr.js": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz", + "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@inquirer/ansi": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.8.tgz", + "integrity": "sha512-WpQM+Ti6Z40EFwwt+uL2p4UabT+W179zHp6HhLVOzfbwnVn05IPO/eXIZXGNqcT1jbQ15SujNLzQ39k4QPPxBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.5.tgz", + "integrity": "sha512-bRt8J8m+Fot9CXv+zNQGXUq2ET0MggR1fPz7v6edN6MFYmsbfGnMmkmWZJEegMKqrAC8ej/o1sqisHZXZJMAfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.8", + "@inquirer/core": "^12.0.3", + "@inquirer/figures": "^2.0.9", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.3.2.tgz", + "integrity": "sha512-Xvr/0HggjddPtGppuqVmxhTw+Hr8PvsZ/k0HmOEaAqQEt80OITNkFWnsdNmyT0/eM4Ab+iJLx2R8rctlEyfSVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.3.tgz", + "integrity": "sha512-wsSy0sznmXwkty+2PzZwx00Cazc/E0r0B7mAzdGROz2Ct+DFZXaK7WDjGZvgjRldxH5ZhFVfF2lgkYrqgOw2KA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.8", + "@inquirer/figures": "^2.0.9", + "@inquirer/type": "4.1.1", + "cli-width": "^4.1.0", + "fast-wrap-ansi": "^0.2.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/editor": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.3.3.tgz", + "integrity": "sha512-YsKkS2q63IiLtaDK/9nqzdComN97SDQrmKiyNggN+ceP4ty+Z6VwyTz3FpjeUWeW1Efss2xHFKCC9sx7hnrsxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/external-editor": "^3.0.5", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.5.tgz", + "integrity": "sha512-uHuXLmXW+TtIfT/9vSBotypAkqn1n34Ul+CLGPos/xANyO4Ff5xZzkYhbKR4NEcfVK4a9mHQOpwVZzluSHFRGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.5.tgz", + "integrity": "sha512-f3QQJRIX5ZEneBHNUIuPjmbdzHnmRFJA8r2dkcb8q+OM5Uv5KtnuAttQumnrjcBVBM3mcTX1CkmtAkU58VRZxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^2.1.1", + "iconv-lite": "^0.7.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.9.tgz", + "integrity": "sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/input": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.6.tgz", + "integrity": "sha512-HtcJhB2QFVXbLuJ5S3syhNbTUVxYvwqV4VRBDkQceBloC9bmTViUoRFP5PbSaDZb3HzfPmpuU/gG4ybVBz4FHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.2.3.tgz", + "integrity": "sha512-6Yuwh1NGSbu1Lo4N1EWjXs1jKRntLg/ZCwhmeorEHde90v1XxAozdbd4Iu30eOQLW+6h1hp2O9ujNfLSbTPJnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.2.2.tgz", + "integrity": "sha512-W9zYdyzogK+6110mqwaSJWCBu2yA5Q/OfnGSjjZB1bNpHlmUozXxTl0+QOZBNeVd6Qo81/qT75gW05gLAtITxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.8", + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/prompts": { + "version": "8.7.2", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.7.2.tgz", + "integrity": "sha512-QoRB4wFIjgH5iOhSjoIKMkTvSHDuV+O3OITlIqAYO0oK5x364GJILXiMBvlPiE+klg7Xx9tq5XVqQHcGUDYYPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^5.2.5", + "@inquirer/confirm": "^6.3.2", + "@inquirer/editor": "^5.3.3", + "@inquirer/expand": "^5.1.5", + "@inquirer/input": "^5.1.6", + "@inquirer/number": "^4.2.3", + "@inquirer/password": "^5.2.2", + "@inquirer/rawlist": "^5.3.5", + "@inquirer/search": "^4.3.3", + "@inquirer/select": "^5.2.5" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist": { + "version": "5.3.5", + "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.5.tgz", + "integrity": "sha512-1oHky1ONfCOwNrnkQGDE1oaSij/3fI6HFMSf2H/WsGO2lEyDX9My82iggITSy9ddSZ8yk8j9v41OI0fVoSIoaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.3.3.tgz", + "integrity": "sha512-fyuIU1Nbpvwlikjg3gXwJFDI11+EFjqQ7P+iByfmivIKQ1vmaykNrD/vy5unHuUqUpsOsnvJ25//tPF7E/RBRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^12.0.3", + "@inquirer/figures": "^2.0.9", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.5.tgz", + "integrity": "sha512-9kc15hr8r/kI+3DO/xLog5nOzTz1jqsHXa6JBFzmQKhkoJ8Slda1I1L/uD8ZSZ9tF1yp79wwXe7mclvX1rqR2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.8", + "@inquirer/core": "^12.0.3", + "@inquirer/figures": "^2.0.9", + "@inquirer/type": "4.1.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.1.1.tgz", + "integrity": "sha512-yJoHYrMnxIsJZCY+0Vb66Dy3he3kL3e2wOBKhoSwWWAzZAY82emlxwgprCtp6yRixvNRNq9ztfRWQYPNr3Go7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@lukeed/csprng": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@lukeed/csprng/-/csprng-1.1.0.tgz", + "integrity": "sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@nestjs/cli": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-12.0.3.tgz", + "integrity": "sha512-HofsPoiWsx6gZ7/IivaZJrgsq/3CTCb4FkCQzFu/Q3J2V+4xC7GYnit/HNB66EfuY8j3gWJCzasMKmF5VugmOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.1.8", + "@angular-devkit/schematics": "22.1.8", + "@angular-devkit/schematics-cli": "22.1.8", + "@inquirer/prompts": "8.7.2", + "@nestjs/schematics": "^12.0.0", + "ansis": "4.4.0", + "chokidar": "5.0.0", + "cli-table3": "0.6.5", + "commander": "15.0.0", + "minimatch": "10.2.6", + "node-emoji": "2.2.0", + "ora": "9.4.1", + "tsconfig-paths": "4.2.0", + "typescript": "~6.0.2" + }, + "bin": { + "nest": "bin/nest.js" + }, + "engines": { + "node": ">= 20.11" + }, + "peerDependencies": { + "@rspack/core": "^1.7.7 || ^2.1.10", + "@swc/cli": "^0.8.0", + "@swc/core": "^1.15.18", + "fork-ts-checker-webpack-plugin": "^9.1.0", + "ts-loader": "^9.5.4", + "tsconfig-paths-webpack-plugin": "^4.2.0", + "webpack": "^5.105.4", + "webpack-node-externals": "^3.0.0" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "@swc/cli": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "fork-ts-checker-webpack-plugin": { + "optional": true + }, + "ts-loader": { + "optional": true + }, + "tsconfig-paths-webpack-plugin": { + "optional": true + }, + "webpack": { + "optional": true + }, + "webpack-node-externals": { + "optional": true + } + } + }, + "node_modules/@nestjs/common": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-12.0.3.tgz", + "integrity": "sha512-Fosz6lHc9OagZNcF0LTrVHyJS8W7mtuNFBOo9RRccGwyeICBd0hiutjAi9zxnzBcP45RkYXeNB+idA/52jZhBQ==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "1.1.0", + "file-type": "22.1.0", + "iterare": "1.2.1", + "load-esm": "1.0.3", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "class-transformer": ">=0.4.1", + "class-validator": ">=0.13.2", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/config": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@nestjs/config/-/config-12.0.0.tgz", + "integrity": "sha512-pG5+fFfCo3cdgVkLJLvvhUGfxEjwzv9hIAQ1aJVHvHlHVniDWfwX5pR/utgoAkJzSikv2oTR1BmIF03FXdi42Q==", + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "1.1.0", + "dotenv": "17.4.2", + "dotenv-expand": "13.0.0", + "es-toolkit": "1.51.0" + }, + "peerDependencies": { + "@nestjs/common": "^11.0.0 || ^12.0.0", + "rxjs": "^7.1.0" + } + }, + "node_modules/@nestjs/config/node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/@nestjs/core": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-12.0.3.tgz", + "integrity": "sha512-Ouv++gAXOL50S8K8n6AN19QGmw51rnIo6v7y9AqUYoaf0NcZlufTu5XTDeC2RtpMz8oXRr9nykBngRjflcoQKA==", + "license": "MIT", + "dependencies": { + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "8.4.2", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "engines": { + "node": ">= 20" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/microservices": "^12.0.0", + "@nestjs/platform-express": "^12.0.0", + "@nestjs/websockets": "^12.0.0", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + }, + "@nestjs/websockets": { + "optional": true + } + } + }, + "node_modules/@nestjs/mau": { + "version": "0.2.8", + "resolved": "https://registry.npmjs.org/@nestjs/mau/-/mau-0.2.8.tgz", + "integrity": "sha512-nIb0i3c/KhKEbxZfYMEKv9Mcvk5miBdZcexnvkgnAUhoMO2BUjOGT+Khf2cZzu7B51Y7v01NG2JVl/HdQEUQ6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "4.1.2", + "cli-progress": "3.12.0", + "commander": "4.1.1", + "inquirer": "8.2.6", + "node-emoji": "2.1.3", + "ora": "5.4.1", + "undici": "6.20.1" + }, + "bin": { + "mau": "bin/mau.js" + }, + "engines": { + "node": ">= 20.0.0" + } + }, + "node_modules/@nestjs/mau/node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@nestjs/mau/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/@nestjs/mau/node_modules/is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@nestjs/mau/node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@nestjs/mau/node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@nestjs/mau/node_modules/node-emoji": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-2.1.3.tgz", + "integrity": "sha512-E2WEOVsgs7O16zsURJ/eH8BqhF029wGpEOnv7Urwdo2wmQanOACwJQh0devF9D9RhoZru0+9JXIS0dBXIAz+lA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.6.0", + "char-regex": "^1.0.2", + "emojilib": "^2.4.0", + "skin-tone": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@nestjs/mau/node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@nestjs/platform-express": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-12.0.3.tgz", + "integrity": "sha512-q9ImjCMjbYYgqvRHHro6sAypNwhjspIAHad0RTL2ww5wYd9gwUGWMss7Q+ACCw5Sksu7Q8S/3rjSLhB+W6B6bg==", + "license": "MIT", + "dependencies": { + "cors": "2.8.6", + "express": "5.2.1", + "multer": "2.4.0", + "path-to-regexp": "8.4.2", + "tslib": "2.8.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0" + } + }, + "node_modules/@nestjs/platform-fastify": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@nestjs/platform-fastify/-/platform-fastify-12.0.3.tgz", + "integrity": "sha512-Cn8jR8jwPJBk7ftkzunplz0LHDahnq7urAO9VjOV0OWkk1YCwaFMm4CElSk3BwBiDwP177anJjJUbVxTlASk4A==", + "license": "MIT", + "dependencies": { + "@fastify/cors": "11.3.0", + "@fastify/formbody": "9.0.0", + "@fastify/middie": "9.3.4", + "fast-querystring": "1.1.2", + "fastify": "5.12.4", + "find-my-way": "9.9.0", + "light-my-request": "6.6.0", + "path-to-regexp": "8.4.2", + "tslib": "2.8.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@fastify/static": "^10.1.2", + "@fastify/view": "^10.0.0 || ^11.0.0 || ^12.0.0", + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0" + }, + "peerDependenciesMeta": { + "@fastify/static": { + "optional": true + }, + "@fastify/view": { + "optional": true + } + } + }, + "node_modules/@nestjs/schematics": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-12.0.0.tgz", + "integrity": "sha512-ilsxam7i+SWd2psr12faLVSk86FYKnxRUGO6jAGNi1P9+O0kRaYVOScyrKeIj97W9T9UJoJF38fg+7KgjY/nOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.1.5", + "@angular-devkit/schematics": "22.1.5", + "comment-json": "5.0.0", + "jsonc-parser": "3.3.1", + "pluralize": "8.0.0" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "prettier": "^3.0.0", + "typescript": ">=6.0.0" + }, + "peerDependenciesMeta": { + "prettier": { + "optional": true + } + } + }, + "node_modules/@nestjs/schematics/node_modules/@angular-devkit/core": { + "version": "22.1.5", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-22.1.5.tgz", + "integrity": "sha512-HiY6d5dkIdJs5grP9OHvgkf14QOcDIo+hbuT7YKuLItQ++ZxCwUabJMLCCJ5R0KrstE5NqED0dNcyk5WD01t5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "jsonc-parser": "3.3.1", + "picomatch": "4.0.5", + "rxjs": "7.8.2", + "source-map": "0.7.6" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "chokidar": "^5.0.0" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, + "node_modules/@nestjs/schematics/node_modules/@angular-devkit/schematics": { + "version": "22.1.5", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-22.1.5.tgz", + "integrity": "sha512-HTmo9y8wjXKtJGVTYomTjZsjWzhirpu1pPRAzsVob3eiYOuxv1qDRAgWiHXNGp5CpnbHunZweXY/WffNGOFRyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "22.1.5", + "jsonc-parser": "3.3.1", + "magic-string": "1.0.0", + "ora": "9.4.1", + "rxjs": "7.8.2" + }, + "engines": { + "node": "^22.22.3 || ^24.15.0 || >=26.0.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@nestjs/testing": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-12.0.3.tgz", + "integrity": "sha512-TYDvBI8HvYeldNCmsuSaE4XqSs1Mg7IekSPlJf+zbrVt3+s5sqt4ySMUhbTs8JpMTFMyqCwtPTGVHIcFVuTBbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^12.0.0", + "@nestjs/core": "^12.0.0", + "@nestjs/microservices": "^12.0.0", + "@nestjs/platform-express": "^12.0.0" + }, + "peerDependenciesMeta": { + "@nestjs/microservices": { + "optional": true + }, + "@nestjs/platform-express": { + "optional": true + } + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@ogma/common": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ogma/common/-/common-1.2.0.tgz", + "integrity": "sha512-y2GHkT4t3B9CoI7ELfgZXeMHiiOC/X4XvdeqYLbP5A3keop7fANzjd5pQdtyYQvdQ0lPzcHJiMvOGkIINZHZHQ==", + "dev": true + }, + "node_modules/@ogma/styler": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@ogma/styler/-/styler-1.1.0.tgz", + "integrity": "sha512-OtwJ8Ump3sKEAv2DIUi+R2G2Y5v3cEzqRO/sH11MTWikAhac31GZR/xzU+3BoPRT0u8oIob7N5dtOKTdPhqq3w==", + "dev": true, + "dependencies": { + "@ogma/common": "^1.1.1" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/api-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.203.0.tgz", + "integrity": "sha512-9B9RU0H7Ya1Dx/Rkyc4stuBZSGVQF27WigitInx2QQoj6KUpEFYPKoWjdFTunJYxmXmh17HeBvbMa1EhGyPmqQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/context-async-hooks": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.0.1.tgz", + "integrity": "sha512-XuY23lSI3d4PEqKA+7SLtAgwqIfc6E/E9eAQWLN1vlpC53ybO3o6jW4BsXo1xvz9lYyyWItfQDDLzezER01mCw==", + "license": "Apache-2.0", + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.0.1.tgz", + "integrity": "sha512-MaZk9SJIDgo1peKevlbhP6+IwIiNPNmswNL4AF0WaQJLbHXjr9SrZMgS12+iqr9ToV4ZVosCcc0f8Rg67LXjxw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.203.0.tgz", + "integrity": "sha512-nl/7S91MXn5R1aIzoWtMKGvqxgJgepB/sH9qW0rZvZtabnsjbf8OQ1uSx3yogtvLr0GzwD596nQKz2fV7q2RBw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-http": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.203.0.tgz", + "integrity": "sha512-HFSW10y8lY6BTZecGNpV3GpoSy7eaO0Z6GATwZasnT4bEsILp8UJXNG5OmEsz4SdwCSYvyCbTJdNbZP3/8LGCQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.203.0.tgz", + "integrity": "sha512-OZnhyd9npU7QbyuHXFEPVm3LnjZYifuKpT3kTnF84mXeEQ84pJJZgyLBpU4FSkSwUkt/zbMyNAI7y5+jYTWGIg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.203.0", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-metrics": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-proto": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.203.0.tgz", + "integrity": "sha512-1xwNTJ86L0aJmWRwENCJlH4LULMG2sOXWIVw+Szta4fkqKVY50Eo4HoVKKq6U9QEytrWCr8+zjw0q/ZOeXpcAQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-exporter-base": "0.203.0", + "@opentelemetry/otlp-transformer": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-exporter-base": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.203.0.tgz", + "integrity": "sha512-Wbxf7k+87KyvxFr5D7uOiSq/vHXWommvdnNE7vECO3tAhsA2GfOlpWINCMWUEPdHZ7tCXxw6Epp3vgx3jU7llQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/otlp-transformer": "0.203.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-transformer": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.203.0.tgz", + "integrity": "sha512-Y8I6GgoCna0qDQ2W6GCRtaF24SnvqvA8OfeTi7fqigD23u8Jpb4R5KFv/pRvrlGagcCLICMIyh9wiejp4TXu/A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "protobufjs": "^7.3.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.0.1.tgz", + "integrity": "sha512-dZOB3R6zvBwDKnHDTB4X1xtMArB/d324VsbiPkX/Yu0Q8T2xceRthoIVFhJdvgVM2QhGVUyX9tzwiNxGtoBJUw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-logs": { + "version": "0.203.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.203.0.tgz", + "integrity": "sha512-vM2+rPq0Vi3nYA5akQD2f3QwossDnTDLvKbea6u/A2NZ3XDkPxMfo/PNrDoXhDUD/0pPo2CdH5ce/thn9K0kLw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.4.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.0.1.tgz", + "integrity": "sha512-wf8OaJoSnujMAHWR3g+/hGvNcsC16rf9s1So4JlMiFaFHiE4HpIA3oUh+uWZQ7CNuK8gVW/pQSkgoa5HkkOl0g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.9.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.0.1.tgz", + "integrity": "sha512-xYLlvk/xdScGx1aEqvxLwf6sXQLXCjk3/1SQT9X9AoN5rXRhkdvIFShuNNmtTEPRBqcsMbS4p/gJLNI2wXaDuQ==", + "deprecated": "Use @opentelemetry/sdk-trace package", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.0.1", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-node": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.0.1.tgz", + "integrity": "sha512-UhdbPF19pMpBtCWYP5lHbTogLWx9N0EBxtdagvkn5YtsAnCBZzL7SjktG+ZmupRgifsHMjwUaCCaVmqGfSADmA==", + "deprecated": "Use @opentelemetry/sdk-trace package", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "2.0.1", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.45.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.45.0.tgz", + "integrity": "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.150.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.150.0.tgz", + "integrity": "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@oxlint/binding-android-arm-eabi": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.83.0.tgz", + "integrity": "sha512-0yGY24EwsLk5YDe6F+VkmZyRHSwJDALa3nIrPpq7FXmp2lV2d0TzvBCGeZk+wgiULRGr5blhyr4QMp5KCXJUqA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm64": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.83.0.tgz", + "integrity": "sha512-hHfJ0vc17A4iUjH5p9BsTUPYbYRNxGpvD2lbu1aBRk54bzNIx9o5TtYF39QPZcV95DagZd+4DEAw2RH3G2ZsMg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-arm64": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.83.0.tgz", + "integrity": "sha512-hsOjYjszLb/3zym/TkzUMPAoQlTJcuzSyEPOAyA+skXJIX9M0o+4JfOtqopX/Vf4hSLrJ98j0nvFo23gzk8auQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-x64": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.83.0.tgz", + "integrity": "sha512-mjh5oH2EA+wl5yRJYT9K9G61O2zFlpuv+yf2JwZOi0+dq2FnTUtm1h8i+5Ik0fXPWIu/k84I1psZR9aQsLAnyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-freebsd-x64": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.83.0.tgz", + "integrity": "sha512-fNHr64/YaO8YssuoDVC8+F4Uk5enR86q5uxfHkQrjAPs1dbAILOrD2uaud+J7MO8Fx774g44ERLD0IGIvZE48w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-gnueabihf": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.83.0.tgz", + "integrity": "sha512-Qpwy3zzAwMj+8/lyYItHmkSMwbkprFNWTK7jPYDOxSyxEhaSLOWYUTCMkjF334J8/WD0nznCCsoBbIH6hpsuIw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-musleabihf": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.83.0.tgz", + "integrity": "sha512-s+BirYLFq7JL2k9sP0XI3ZXJ9dYvJ8sX3jLCLoag7tt+zrSHpZxP0jqznfL+Gdgwu7ay0dYgGYJXrQvq3iWloA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-gnu": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.83.0.tgz", + "integrity": "sha512-7lihXt3vKr+GIyapNbHrnFHm/biiW30le6Zv/DExbAFPF6YwCQXVFlONPFehxs0CpGO4CBfYPM9rdDT+XMoIlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-musl": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.83.0.tgz", + "integrity": "sha512-q63JalLYVkZiZvls1z3PPUnpmQluOMXp0khqQMznCeAPLGydfNY8JhvuA4WlK57JfrvikU8wB5lPVveqpIXvew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-ppc64-gnu": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.83.0.tgz", + "integrity": "sha512-krQmDF+dRbxvdqVPV88ZuOoPPu8X5BuqDA8Hd+qcS4YMRQCb+nexA57DazgGsc/rGdKBe3QmV0mnv0bdpW/p5g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-gnu": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.83.0.tgz", + "integrity": "sha512-MmOl8Y6txEAXZU1RG8Rr264jQ6D7VPmqFsU/45x/FeWsGe32hklTqGrLE6UxHzp5Rjt0wP+20tY8YXKgSFB3mw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-musl": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.83.0.tgz", + "integrity": "sha512-u1rMymh0W3JZkq370kzQsYPULGWqhE09pZRqnZvUSoYaI9pVO5yVX+iYIslmWuEgwuzH9YAaOsScJiobWCHoOw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-s390x-gnu": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.83.0.tgz", + "integrity": "sha512-y0zK3HNwGysu7rqtE+BQG/d0bx5gh/KwlOtghN8oWeK1KcWzeaLqtZrbm8owqdma1lFyrce/hTO5ismuNu+INQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-gnu": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.83.0.tgz", + "integrity": "sha512-rS5gM0NgD7ngmuJmbIehsidtrOwKkLFwCQbKEeb9KuyQrrWNq5Zkn0uV6AYdXOMJ0grrWEiLwBuvMxt8w5vsNw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-musl": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.83.0.tgz", + "integrity": "sha512-W2IH4EtpcPaWcvNGCA95YoDg4vxqE/ZiPCi3arrxEEpsK7+JQN9WYwrlYFx9pcdP6KPXqRqkv3zdQPHcx7b6YQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-openharmony-arm64": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.83.0.tgz", + "integrity": "sha512-6LyKkUyoajssTPLlZmDbZIbu4IZ5B4bGuRUnBgCGpEvHP3FQMaYITncHA/unPUo7q+Z+pIu2HhdkQ+8d1SG7iA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-arm64-msvc": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.83.0.tgz", + "integrity": "sha512-Uz/fObEtF0jmNJQJ8CGRBKfefYstS0/wjD3s6IGzP8nUwsJykHQJBiN3npHwKiGRGn/vvBEgNr4B3cCzmmatvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-ia32-msvc": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.83.0.tgz", + "integrity": "sha512-u7XcvPW6Bk58tY5iWs2ESb0vJjoE/kuSpHxopbwp/p3ZtWVQXZ6wor5w3ssVTHOqd/v8b+QdhSFWQ4grEUNWpA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-x64-msvc": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.83.0.tgz", + "integrity": "sha512-LZRubd7ph13QmAg4fFecTYVZkiYbROR2Htaxh/ufWRkDhPOm2wrwaEYR89e0YpPFD3dqBrPoxS7myBw5hmYA7Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@paralleldrive/cuid2": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", + "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.1.5" + } + }, + "node_modules/@phc/format": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@phc/format/-/format-1.0.0.tgz", + "integrity": "sha512-m7X9U6BG2+J+R1lSOdCiITLLrxm+cWlNI3HUFA92oLO77ObGNzaKdh8pMLqdZcshtkKuV84olNNXDfMc4FezBQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@redis/bloom": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-6.3.0.tgz", + "integrity": "sha512-NQ5poYpZr0jv6zazN1cy6JY5kIipKFZ3R9GTL4kOUTX3a9YAfY29U8bsE4lWhVQEM+G4V0BXVC57mubIdDijeA==", + "license": "MIT", + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.0" + } + }, + "node_modules/@redis/client": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-6.3.0.tgz", + "integrity": "sha512-fHrjwGCBvAANGi+TuRuwKi83sIOzgHr8eh+Uf48w3fSX7Hhrz174NrWqfJhAC2vnN0d/tfaZpdr6+o6JC3QHwg==", + "license": "MIT", + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@node-rs/xxhash": "^1.1.0", + "@opentelemetry/api": ">=1 <2" + }, + "peerDependenciesMeta": { + "@node-rs/xxhash": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + } + } + }, + "node_modules/@redis/json": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-6.3.0.tgz", + "integrity": "sha512-yt6vRfPBXtW/3qm53cF81TSQpLMjWdW4/2E9WQ2GgbvsKkuCKCFQIcMiKlil1ZMnezK+IQuS795xKU5psbaegw==", + "license": "MIT", + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.0" + } + }, + "node_modules/@redis/search": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-6.3.0.tgz", + "integrity": "sha512-RPXAZmKjZZG7Tm7m1w9keFdXzbL91PiSHQBfQRe9xwW40jNsTRbG0FwhIz4QlHPU4gKDAsCy8IQHj4yZl4H9rw==", + "license": "MIT", + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.0" + } + }, + "node_modules/@redis/time-series": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-6.3.0.tgz", + "integrity": "sha512-+fJOB8mN1z5WRakCJNh5lVdz1KqvHGSOistsKeitD24QsCtPwyRQXWC0iq6T/i/ubLE/YcguZqPm8F598MKk4A==", + "license": "MIT", + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.0" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.9.tgz", + "integrity": "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.9.tgz", + "integrity": "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.9.tgz", + "integrity": "sha512-IwhlH3qK5urrY8hZiEgGkHKEFN901p/p2bjxCxJlr4GyNnF7wYpUvK+Y43uaRYuC4hpfjzbR3SJC3arX1jGvmw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.9.tgz", + "integrity": "sha512-XxpJfVzFh+jilRxIXUqcfYAYcunIc/XEzIizsOL1fcJee5Sf7H3mH8WlLmfHfluz5amqR88QQo9izKtmMlavAw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.9.tgz", + "integrity": "sha512-kSfvhmgeWyfkbT3p/1s5vSgboogoah2zkm9fX2zjg2hHxSV7T4KhMWRUUaRk4OXNqoD3QAUeRqLcs1aZOK4U1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.9.tgz", + "integrity": "sha512-1RVzG17pxqbTfYLC352JlLt6kKLG+6Hr30n8DlIJqsnV5luUDd2Qdx9Ayw1Cabfyb1K9k0jXEZ7evxkRoT+uiw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.9.tgz", + "integrity": "sha512-BXqPvZ2drqVD+/Z8UpKwcs4Mp7grM+eGFku4CAEKrEtcbAsUpzREphK1sogCRZGreVPiMkiiBtw0n3TPteuqvw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.9.tgz", + "integrity": "sha512-11vWvo8YDwLzukt27J3aYDWU+gg2P7J+ZOmiJ0hkF5BXZDW7pVya7r40MXDy6ya0i9KamoENSVKIugvJNgFXIA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.9.tgz", + "integrity": "sha512-a1tijMkdwsIARtc0F39ApURROkf3NwqinI6TOiSSWCTR7dT96dffNvMUtDHnq64wKNTIZOIlzKrFvvFUznJiyw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.9.tgz", + "integrity": "sha512-x6SQNdAvv4c3hWqTMaWuawzMX9myaCs/yEmlGsxJzkdClnHW7FbrjQuSiRDhuSYzEYoEMhsaJy9qHG/XNemJPQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.9.tgz", + "integrity": "sha512-9s0AZ8BFK5/n7B/TBoa2yJE3gI3KURrbXcPBlsAsvjU4VeJKgE90y1YtNxyEUIcHPQkg6/yfF3qihUrcM/Kf0Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.9.tgz", + "integrity": "sha512-P7VWAmV+WdJluH7ovnRGoiv2i8To7GAZ+kGzfGup635cyL7SyYl3lSUaA3Gp5THf0n/Co5EyEqb2zbqq+nMOHQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.9.tgz", + "integrity": "sha512-1qixtsE4BK8h+yS3BfmZ09UhA7O/N4IACva6YBr7EBvCJraByTuRcgOTaiA62Tm0vey3UcKXLOaoGHtYmNGEVg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.9.tgz", + "integrity": "sha512-ok8IQjcEPs1AKZfuEUznVBrJw+gK4soq+bx8b1X2XoMqVClarc1q5JDmVtWXY1xfr6ZuHTAsPXHTgTrqKTZeww==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.9.tgz", + "integrity": "sha512-Ip2mXoU0hM0boq3Rf+ekuT653OROSo6aSYcPT1VHE4q52KvyxgFkQgrgb/IEsxOuvQ2fZZbs8khJAyCEPM24/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@smithy/core": { + "version": "3.36.2", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.36.2.tgz", + "integrity": "sha512-oRw0rB9QSUiCZfEs23G5F4Af+b2rQt1lItIICWu5IejFNd+uPM8SWqiKLMpQ6bX1Q7slsLbjuoE2niErFtkVPQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz", + "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.2", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz", + "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.12.1", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz", + "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.3", + "@smithy/types": "^4.18.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.7.4", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz", + "integrity": "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.35.0", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.19.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz", + "integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@tokenizer/inflate": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz", + "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "token-types": "^6.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cookiejar": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz", + "integrity": "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/express": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", + "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "^2" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", + "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/methods": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", + "integrity": "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.13.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.5.tgz", + "integrity": "sha512-TXyindR+lBr22aJIdMQzCFHPHR6cR4js838mRDCSz5hOKWZvZwsXSSiXDmjRj4iJmgl+sR9O+1mkoVBSMadNug==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, + "node_modules/@types/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*" + } + }, + "node_modules/@types/superagent": { + "version": "8.1.11", + "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.11.tgz", + "integrity": "sha512-KA7srSW/HENDtOw9DOqaFLgWuMqN9WgjEw62lh9dpvRaZDkhdOkazASd7X7i2eMUYLHa1U37ZttnePsH5zTDHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/cookiejar": "^2.1.5", + "@types/methods": "^1.1.4", + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/supertest": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-7.2.1.tgz", + "integrity": "sha512-4CbBvoYVLHL7+yhbYrZET0vsvuyXTC05aRe7dNQkwMzm56auceoy6Yu3K50uZmwfHna1os3CMSgM/3QVkUtPTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/methods": "^1.1.4", + "@types/superagent": "^8.1.0" + } + }, + "node_modules/@types/validator": { + "version": "13.15.10", + "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.10.tgz", + "integrity": "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==", + "license": "MIT" + }, + "node_modules/@vitest/coverage-v8": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz", + "integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.1.11", + "ast-v8-to-istanbul": "^1.0.0", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "std-env": "^4.0.0-rc.1", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.1.11", + "vitest": "4.1.11" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.11", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.11", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/abstract-logging": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", + "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==", + "license": "MIT" + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/amqplib": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-2.2.1.tgz", + "integrity": "sha512-J3JjAydC2vJ/AgkgVAE0kVH5M4RNfm51zUaspHpwSai3W35lD3hKryvYY/xqMnYcNfR66NYL06Eik+Adn293dQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ansis": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ansis/-/ansis-4.4.0.tgz", + "integrity": "sha512-9k3v7xcHwgdO/DruxGIg4HtjvlAZlcnsX/mzqUb1t3NkYnl9kK2UJ+Gq0io+vQf7iT//BD/HB/NBkUR1LWxoeA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/argon2": { + "version": "0.45.1", + "resolved": "https://registry.npmjs.org/argon2/-/argon2-0.45.1.tgz", + "integrity": "sha512-skm+/WCjkGqCQxF7FG1LuZXM5yvbFjgbfiCGsud2oLgaDhh6b6dbH0b1EkghbM+xx4Bj8Ape+KKgixoIlWZicQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@phc/format": "^1.0.0", + "cross-env": "^10.1.0", + "node-addon-api": "^8.9.0", + "node-gyp-build": "^4.8.4" + }, + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/array-timsort": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz", + "integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.6.tgz", + "integrity": "sha512-fvpl29helSO2w/z7utIbrkNXILdrLwDwAMH2I/zPKlGf5244+gf+B4cyS1sANcrPY2h+hWCGSgC8N61s/+AF9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/avvio": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/avvio/-/avvio-9.3.0.tgz", + "integrity": "sha512-g2tQ7LE7oOSqDfwEm3M+ZCMTJc7KiZCdJ4UwyZJb5ckTKyYu50OYmvv0mCFXPuYXoM4zkSt8zM9XQ9KCvxA74A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/error": "^4.0.0", + "fastq": "^1.17.1" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bowser": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", + "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/chardet": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz", + "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==", + "dev": true, + "license": "MIT" + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/class-transformer": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz", + "integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==", + "license": "MIT" + }, + "node_modules/class-validator": { + "version": "0.15.1", + "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.15.1.tgz", + "integrity": "sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw==", + "license": "MIT", + "dependencies": { + "@types/validator": "^13.15.3", + "libphonenumber-js": "^1.11.1", + "validator": "^13.15.22" + } + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-progress": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/cli-progress/-/cli-progress-3.12.0.tgz", + "integrity": "sha512-tRkV3HJ1ASwm19THiiLIXLO7Im7wlTuKnvkYaTkyoAPefqjNg7W7DHKUlGRxy9vxDvbyCYQkQozvptuMkGCg8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "string-width": "^4.2.3" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cli-spinners": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", + "integrity": "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-table3": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz", + "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "string-width": "^4.2.0" + }, + "engines": { + "node": "10.* || >= 12.*" + }, + "optionalDependencies": { + "@colors/colors": "1.5.0" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "15.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz", + "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/comment-json": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/comment-json/-/comment-json-5.0.0.tgz", + "integrity": "sha512-uiqLcOiVDJtBP8WGkZHEP+FZIhTzP1dxvn59EfoYUi9gqupjrBWVQkO2atDrbnKPwLeotFYDsuNb26uBMqB+hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-timsort": "^1.0.3", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/component-emitter": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz", + "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cookiejar": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", + "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", + "dev": true, + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "license": "MIT", + "dependencies": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "bin": { + "cross-env": "dist/bin/cross-env.js", + "cross-env-shell": "dist/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/date-fns": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz", + "integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/defaults": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", + "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "clone": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dezalgo": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", + "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", + "dev": true, + "license": "ISC", + "dependencies": { + "asap": "^2.0.0", + "wrappy": "1" + } + }, + "node_modules/dotenv": { + "version": "18.0.5", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.5.tgz", + "integrity": "sha512-aBrGvt6KhjxbEnatqMWOMidftwsrCiCvqh1yNIGB9QyF0J+VcWkKDMsvYOEm7ZS82oiV+BT1sTOtIlAmUlTpwQ==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "dotenv": "dist/index.cjs" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dotenv-expand": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-13.0.0.tgz", + "integrity": "sha512-aBfBS8eYIeXmpHI9ThIlA7/WLq+SLt18iXUZhb52rW89QLKQFoIpPG1bPeewoPZsTyjSSO3T7234FBVUM1V2rA==", + "license": "BSD-2-Clause", + "dependencies": { + "dotenv": "^17.4.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dotenv-expand/node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/emojilib": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/emojilib/-/emojilib-2.4.0.tgz", + "integrity": "sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-toolkit": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.51.0.tgz", + "integrity": "sha512-zC2lQGkM7QX+Gm6iM3+WIdZJzthsEd14LvRNJneSO2hzyz/zNBENR8+YXWo1cKxgPBtV6ksPYHELbcwBRzmdCw==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true, + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/external-editor/node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true, + "license": "MIT" + }, + "node_modules/external-editor/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz", + "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stringify": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.0.1.tgz", + "integrity": "sha512-eRSayARSbbwlBjpP4vnTTIRD5QPcIrmihPxDeN1DtKnHPg66UuJLx+8hlK1kaFdjvzyQ/dzALoi4vwAQ+T+iZA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/merge-json-schemas": "^0.2.0", + "ajv": "^8.12.0", + "ajv-formats": "^3.0.1", + "fast-uri": "^4.0.0", + "json-schema-ref-resolver": "^3.0.0", + "rfdc": "^1.2.0" + } + }, + "node_modules/fast-json-stringify/node_modules/fast-uri": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.1.tgz", + "integrity": "sha512-TmHQgewjHtMq1E5QKA0tOE0yeYGQs25KZC/ziJpubRtWI15W92e6vPFydWOeZBVROSHBYw/QhD9d5OefdD6LDg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-querystring": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz", + "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==", + "license": "MIT", + "dependencies": { + "fast-decode-uri-component": "^1.0.1" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, + "node_modules/fastify": { + "version": "5.12.4", + "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.4.tgz", + "integrity": "sha512-zATD676fP6tBMsn+jQ7Q5/cO/Qo+149TXH0dUqUKel+1/hcZxwIbnflqtPa9EjlrvpY8eCZcL3M1UYrMc31Y7g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/ajv-compiler": "^4.0.5", + "@fastify/error": "^4.0.0", + "@fastify/fast-json-stringify-compiler": "^5.0.0", + "@fastify/proxy-addr": "^5.0.0", + "abstract-logging": "^2.0.1", + "avvio": "^9.0.0", + "fast-json-stringify": "^7.0.0", + "find-my-way": "^9.6.0", + "light-my-request": "^6.0.0", + "pino": "^9.14.0 || ^10.1.0", + "process-warning": "^5.1.0", + "rfdc": "^1.3.1", + "secure-json-parse": "^4.0.0", + "semver": "^7.6.0", + "toad-cache": "^3.7.0" + } + }, + "node_modules/fastify-plugin": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.0.tgz", + "integrity": "sha512-fZOty7z3O7vOliF6d8bHE3wiEh1KcNnKEQensSgTk9C1DvN6nRLS++XVd86v33Hw/8u9Un8A1zDrQ8ujcQDHEg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/file-type": { + "version": "22.1.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-22.1.0.tgz", + "integrity": "sha512-fbvf9u6jnHWr1EP6V8R99E9iLMhNLXgZkUzWBiPpJ5/89UJ/Atuxjn5YXR+XaZWo2hc2/8mGfTez+NDAgOcpLA==", + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.4.1", + "strtok3": "^10.3.5", + "token-types": "^6.1.2", + "uint8array-extras": "^1.5.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-my-way": { + "version": "9.9.0", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.9.0.tgz", + "integrity": "sha512-sJsgZ1sQH2UDuowPuMKg8az7Qc8F0jnj+SKkFWU/+T0xcFlgV5skgXOGUqmQzOdmW6ALA7AhJINWx3qFBkbLHA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^5.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/form-data/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/formidable": { + "version": "3.5.4", + "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz", + "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@paralleldrive/cuid2": "^2.2.2", + "dezalgo": "^1.0.4", + "once": "^1.4.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "url": "https://ko-fi.com/tunnckoCore/commissions" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/globrex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/globrex/-/globrex-0.1.2.tgz", + "integrity": "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==", + "dev": true, + "license": "MIT" + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/inquirer": { + "version": "8.2.6", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.6.tgz", + "integrity": "sha512-M1WuAmb7pn9zdFRtQYk26ZBoY043Sse0wVDdk4Bppr+JOXyQYybdtvK+l9wUibhtjdjvtoiNy8tk+EgsYIUqKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.1", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^5.4.1", + "run-async": "^2.4.0", + "rxjs": "^7.5.5", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6", + "wrap-ansi": "^6.0.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/inquirer/node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10" + } + }, + "node_modules/inquirer/node_modules/is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inquirer/node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true, + "license": "ISC" + }, + "node_modules/inquirer/node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/iterare": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", + "integrity": "sha512-RKYVTCjAnRthyJes037NX/IiqeidgN1xc3j1RjFfECFp28A1GVwK9nA+i0rJPaHqSZwygLzRnFlzUuHFoWWy+Q==", + "license": "ISC", + "engines": { + "node": ">=6" + } + }, + "node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-ref-resolver": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz", + "integrity": "sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/libphonenumber-js": { + "version": "1.13.13", + "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.13.13.tgz", + "integrity": "sha512-hV6SmWnyQ8U1QXhhqbqYBHIStNnscG7A5XbGodgdHhf/8N5PwhYpJA5U/yHDjYwPYTd8uNGXqq416XctuvK2PA==", + "license": "MIT" + }, + "node_modules/light-my-request": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz", + "integrity": "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "dependencies": { + "cookie": "^1.0.1", + "process-warning": "^4.0.0", + "set-cookie-parser": "^2.6.0" + } + }, + "node_modules/light-my-request/node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/light-my-request/node_modules/process-warning": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-4.0.1.tgz", + "integrity": "sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/load-esm": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.3.tgz", + "integrity": "sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "engines": { + "node": ">=13.2.0" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", + "integrity": "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/magic-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.0.0.tgz", + "integrity": "sha512-CGvjzMN08iv6w1mm4/x3Gh1hLb4VnyRUA15FFpl6CsCIGGoe36k7kY5KNz9QDbSBN5I/fWHM6ZlIkUTa5xdUEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.4.0.tgz", + "integrity": "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/nestjs-spelunker": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/nestjs-spelunker/-/nestjs-spelunker-1.3.2.tgz", + "integrity": "sha512-tVQZvPvlYNRW9PFkl2dj/hCEzUjC/NbJdayhnr/0dBuebFu4fqJNICPQF1BWJgK8GxJARe1kvDAw/GoyvINvOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ogma/styler": "^1.0.0" + }, + "peerDependencies": { + "@nestjs/common": ">6.11.0", + "@nestjs/core": ">6.11.0" + } + }, + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-emoji": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-2.2.0.tgz", + "integrity": "sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.6.0", + "char-regex": "^1.0.2", + "emojilib": "^2.4.0", + "skin-tone": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-9.4.1.tgz", + "integrity": "sha512-6VlU9MLXbjVQD04AZCMX28hVtA5bUoadvUqO76MUCVA0ilwJbMiHsITRPfyVm6p/BC0Av/BXMujx39WCe1LEqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.6.2", + "cli-cursor": "^5.0.0", + "cli-spinners": "^3.2.0", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.1.0", + "log-symbols": "^7.0.1", + "stdin-discarder": "^0.3.2", + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/ansi-regex": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", + "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ora/node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/string-width": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz", + "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/oxlint": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.83.0.tgz", + "integrity": "sha512-cyDzSzaw3uzP0TeCeq3lLRPPoaUxkbB4ZOXj+kn+5r+BX9V+4bNVGk9lxer+WrgcpebH4JxLlJ3KQjveVztOLQ==", + "dev": true, + "license": "MIT", + "bin": { + "oxlint": "bin/oxlint" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxlint/binding-android-arm-eabi": "1.83.0", + "@oxlint/binding-android-arm64": "1.83.0", + "@oxlint/binding-darwin-arm64": "1.83.0", + "@oxlint/binding-darwin-x64": "1.83.0", + "@oxlint/binding-freebsd-x64": "1.83.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.83.0", + "@oxlint/binding-linux-arm-musleabihf": "1.83.0", + "@oxlint/binding-linux-arm64-gnu": "1.83.0", + "@oxlint/binding-linux-arm64-musl": "1.83.0", + "@oxlint/binding-linux-ppc64-gnu": "1.83.0", + "@oxlint/binding-linux-riscv64-gnu": "1.83.0", + "@oxlint/binding-linux-riscv64-musl": "1.83.0", + "@oxlint/binding-linux-s390x-gnu": "1.83.0", + "@oxlint/binding-linux-x64-gnu": "1.83.0", + "@oxlint/binding-linux-x64-musl": "1.83.0", + "@oxlint/binding-openharmony-arm64": "1.83.0", + "@oxlint/binding-win32-arm64-msvc": "1.83.0", + "@oxlint/binding-win32-ia32-msvc": "1.83.0", + "@oxlint/binding-win32-x64-msvc": "1.83.0" + }, + "peerDependencies": { + "oxlint-tsgolint": ">=7.0.2001", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "oxlint-tsgolint": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.14.1", + "pg-pool": "^3.14.0", + "pg-protocol": "^1.16.1", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.4.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz", + "integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz", + "integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pino": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", + "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/prettier": { + "version": "3.9.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.8.tgz", + "integrity": "sha512-WRFq3Wn3WId7LLROfMLdH7xaFr2jR62wU8nLO6rQUOLOxNZUviyJQs1M0iIhLexSFy+L+w0ch66wtoO2jRjG0A==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/process-warning": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.0.tgz", + "integrity": "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/redis": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/redis/-/redis-6.3.0.tgz", + "integrity": "sha512-XFQbPie1lGpKeUZ8ySYY43yLnQy/iIQtHNvIr/1XdaABpb96rUSdm3Mfl+98FEVbv9ZJIzINMno5s0Nh8E5LEw==", + "license": "MIT", + "dependencies": { + "@redis/bloom": "6.3.0", + "@redis/client": "6.3.0", + "@redis/json": "6.3.0", + "@redis/search": "6.3.0", + "@redis/time-series": "6.3.0" + }, + "engines": { + "node": ">= 20.0.0" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ret": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.5.0.tgz", + "integrity": "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/rolldown": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.9.tgz", + "integrity": "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.150.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.9", + "@rolldown/binding-android-arm64": "1.2.9", + "@rolldown/binding-darwin-arm64": "1.2.9", + "@rolldown/binding-darwin-x64": "1.2.9", + "@rolldown/binding-freebsd-x64": "1.2.9", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.9", + "@rolldown/binding-linux-arm64-gnu": "1.2.9", + "@rolldown/binding-linux-arm64-musl": "1.2.9", + "@rolldown/binding-linux-ppc64-gnu": "1.2.9", + "@rolldown/binding-linux-s390x-gnu": "1.2.9", + "@rolldown/binding-linux-x64-gnu": "1.2.9", + "@rolldown/binding-linux-x64-musl": "1.2.9", + "@rolldown/binding-openharmony-arm64": "1.2.9", + "@rolldown/binding-win32-arm64-msvc": "1.2.9", + "@rolldown/binding-win32-x64-msvc": "1.2.9" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-regex2": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz", + "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "ret": "~0.5.0" + }, + "bin": { + "safe-regex2": "bin/safe-regex2.js" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/secure-json-parse": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", + "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "license": "MIT" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/skin-tone": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/skin-tone/-/skin-tone-2.0.0.tgz", + "integrity": "sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "unicode-emoji-modifier-base": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, + "node_modules/stdin-discarder": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.3.2.tgz", + "integrity": "sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strtok3": { + "version": "10.3.5", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz", + "integrity": "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/superagent": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz", + "integrity": "sha512-B+4Ik7ROgVKrQsXTV0Jwp2u+PXYLSlqtDAhYnkkD+zn3yg8s/zjA2MeGayPoY/KICrbitwneDHrjSotxKL+0XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "component-emitter": "^1.3.1", + "cookiejar": "^2.1.4", + "debug": "^4.3.7", + "fast-safe-stringify": "^2.1.1", + "form-data": "^4.0.5", + "formidable": "^3.5.4", + "methods": "^1.1.2", + "mime": "2.6.0", + "qs": "^6.14.1" + }, + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/supertest": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/supertest/-/supertest-7.2.2.tgz", + "integrity": "sha512-oK8WG9diS3DlhdUkcFn4tkNIiIbBx9lI2ClF8K+b2/m8Eyv47LSawxUzZQSNKUrVb2KsqeTDCcjAAVPYaSLVTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cookie-signature": "^1.2.2", + "methods": "^1.1.2", + "superagent": "^10.3.0" + }, + "engines": { + "node": ">=14.18.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/thread-stream": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz", + "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==", + "license": "MIT", + "dependencies": { + "real-require": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/thread-stream/node_modules/real-require": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", + "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", + "license": "MIT" + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", + "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/toad-cache": { + "version": "3.7.4", + "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.4.tgz", + "integrity": "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/token-types": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz", + "integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==", + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.2.1", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tsconfig-paths": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-4.2.0.tgz", + "integrity": "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "json5": "^2.2.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uid": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/uid/-/uid-2.0.2.tgz", + "integrity": "sha512-u3xV3X7uzvi5b1MncmZo3i2Aw222Zk1keqLA1YkHldREkAhAqi65wuPfe7lHx8H/Wzy+8CE7S7uS3jekIM5s8g==", + "license": "MIT", + "dependencies": { + "@lukeed/csprng": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/uint8array-extras": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/undici": { + "version": "6.20.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.20.1.tgz", + "integrity": "sha512-AjQF1QsmqfJys+LXfGTNum+qw4S88CojRInG/6t31W/1fk6G59s92bnAvGz5Cmur+kQv2SURXEvvudLmbrE8QA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "license": "MIT" + }, + "node_modules/unicode-emoji-modifier-base": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unicode-emoji-modifier-base/-/unicode-emoji-modifier-base-1.0.0.tgz", + "integrity": "sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/validator": { + "version": "13.15.35", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.15.35.tgz", + "integrity": "sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.0.tgz", + "integrity": "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.6", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-tsconfig-paths": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/vite-tsconfig-paths/-/vite-tsconfig-paths-5.1.4.tgz", + "integrity": "sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "globrex": "^0.1.2", + "tsconfck": "^3.0.3" + }, + "peerDependencies": { + "vite": "*" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/vite-tsconfig-paths/node_modules/tsconfck": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/tsconfck/-/tsconfck-3.1.6.tgz", + "integrity": "sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==", + "deprecated": "unmaintained", + "dev": true, + "license": "MIT", + "bin": { + "tsconfck": "bin/tsconfck.js" + }, + "engines": { + "node": "^18 || >=20" + }, + "peerDependencies": { + "typescript": "^5.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vitest": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", + "dev": true, + "license": "MIT", + "dependencies": { + "defaults": "^1.0.3" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/app/package.json b/app/package.json new file mode 100644 index 0000000..324d7c4 --- /dev/null +++ b/app/package.json @@ -0,0 +1,84 @@ +{ + "name": "app", + "version": "0.0.1", + "description": "", + "author": "", + "private": true, + "license": "UNLICENSED", + "type": "module", + "scripts": { + "build": "nest build", + "deploy": "nest deploy", + "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", + "start": "nest start", + "start:dev": "nest start --watch", + "start:debug": "nest start --debug --watch", + "start:prod": "node dist/main", + "lint": "oxlint src/ test/", + "test": "vitest run", + "test:unit": "vitest run src/", + "test:watch": "vitest", + "test:cov": "vitest run --coverage", + "test:debug": "vitest --inspect-brk --no-file-parallelism", + "graph": "npm run build && DATABASE_URL=postgresql://graph-only.invalid/messenger REDIS_URL=redis://graph-only.invalid:6379 tsx scripts/graph-modules.ts", + "test:e2e": "vitest run --config ./vitest.config.e2e.ts", + "test:dependencies": "E2E_DEPENDENCY_FAULTS=1 vitest run --config ./vitest.config.e2e.ts dependency-failures", + "attachments:sweep": "tsx src/attachments/attachments-sweep.cli.ts", + "idempotency:gc": "tsx src/messages/idempotency/idempotency-gc.cli.ts", + "jobs": "node dist/jobs/jobs.cli.js" + }, + "dependencies": { + "@aws-sdk/client-s3": "^3.1156.0", + "@aws-sdk/s3-request-presigner": "^3.1156.0", + "@nestjs/common": "^12.0.1", + "@nestjs/config": "^12.0.0", + "@nestjs/core": "^12.0.1", + "@nestjs/platform-express": "^12.0.1", + "@nestjs/platform-fastify": "^12.0.3", + "@opentelemetry/api": "1.9.0", + "@opentelemetry/api-logs": "0.203.0", + "@opentelemetry/core": "2.0.1", + "@opentelemetry/exporter-logs-otlp-proto": "0.203.0", + "@opentelemetry/exporter-metrics-otlp-proto": "0.203.0", + "@opentelemetry/exporter-trace-otlp-proto": "0.203.0", + "@opentelemetry/resources": "2.0.1", + "@opentelemetry/sdk-logs": "0.203.0", + "@opentelemetry/sdk-metrics": "2.0.1", + "@opentelemetry/sdk-trace-base": "2.0.1", + "@opentelemetry/sdk-trace-node": "2.0.1", + "@smithy/node-http-handler": "^4.12.1", + "amqplib": "^2.2.1", + "argon2": "^0.45.1", + "class-transformer": "^0.5.1", + "class-validator": "^0.15.1", + "date-fns": "^4.4.0", + "fastify": "5.12.4", + "pg": "^8.23.1", + "redis": "^6.3.0", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "sharp": "^0.35.5", + "zod": "^4.6.5" + }, + "devDependencies": { + "@nestjs/cli": "^12.0.0", + "@nestjs/mau": "^0.2.6", + "@nestjs/schematics": "^12.0.0", + "@nestjs/testing": "^12.0.1", + "@types/express": "^5.0.0", + "@types/node": "^24.0.0", + "@types/pg": "^8.23.1", + "@types/supertest": "^7.0.0", + "@vitest/coverage-v8": "^4.1.2", + "dotenv": "^18.0.5", + "nestjs-spelunker": "^1.3.2", + "oxlint": "^1.58.0", + "prettier": "^3.4.2", + "source-map-support": "^0.5.21", + "supertest": "^7.2.2", + "tsx": "^4.23.15", + "typescript": "^6.0.3", + "vite-tsconfig-paths": "^5.1.4", + "vitest": "^4.1.2" + } +} diff --git a/app/scripts/graph-modules.ts b/app/scripts/graph-modules.ts new file mode 100644 index 0000000..5e8e6d8 --- /dev/null +++ b/app/scripts/graph-modules.ts @@ -0,0 +1,123 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import 'reflect-metadata'; +import { SpelunkerModule, type DebuggedTree } from 'nestjs-spelunker'; +import { AppModule } from '../dist/app.module.js'; + +function mermaidId(name: string): string { + return name.replace(/[^a-zA-Z0-9_]/gu, '_'); +} + +function findDependencyModule( + tree: DebuggedTree[], + dependency: string, +): DebuggedTree | undefined { + return tree.find( + (candidate) => + candidate.providers.some((item) => item.name === dependency) || + candidate.controllers.some((item) => item.name === dependency), + ); +} + +function renderMermaid(tree: DebuggedTree[]): string { + const lines = [ + 'flowchart LR', + ' %% Generated by scripts/graph-modules.ts', + ' %% Solid arrows: module imports; dotted arrows: constructor dependencies', + ]; + const moduleNames = tree.map((module) => module.name); + + for (const module of tree) { + const moduleId = mermaidId(module.name); + lines.push(` subgraph ${moduleId}["${module.name}"]`); + for (const provider of module.providers) { + lines.push( + ` ${moduleId}_${mermaidId(provider.name)}["provider: ${provider.name}"]`, + ); + } + for (const controller of module.controllers) { + lines.push( + ` ${moduleId}_${mermaidId(controller.name)}["controller: ${controller.name}"]`, + ); + } + lines.push(' end'); + } + + for (const module of tree) { + for (const imported of module.imports) { + if (moduleNames.includes(imported)) { + lines.push( + ` ${mermaidId(module.name)} -->|imports| ${mermaidId(imported)}`, + ); + } + } + for (const item of [...module.providers, ...module.controllers]) { + for (const dependency of item.dependencies) { + const targetModule = findDependencyModule(tree, dependency); + if (targetModule) { + const source = `${mermaidId(module.name)}_${mermaidId(item.name)}`; + const target = `${mermaidId(targetModule.name)}_${mermaidId(dependency)}`; + lines.push(` ${source} -.->|injects| ${target}`); + } + } + } + } + + return `${lines.join('\n')}\n`; +} + +function renderMarkdown(tree: DebuggedTree[], mermaid: string): string { + const lines = [ + '# NestJS dependency graph', + '', + 'Generated from `AppModule` with `nestjs-spelunker` static module debugging.', + '', + '- Solid arrows: module imports.', + '- Dotted arrows: constructor dependencies.', + '- The generator does not boot PostgreSQL or Redis.', + '', + '```mermaid', + mermaid.trim(), + '```', + '', + '## Module details', + '', + ]; + + for (const module of tree) { + lines.push( + `### ${module.name}`, + '', + `- Imports: ${module.imports.join(', ') || 'none'}`, + ); + lines.push( + `- Exports: ${module.exports.map((item) => `${item.name} (${item.type})`).join(', ') || 'none'}`, + ); + lines.push('', '| Kind | Name | Dependencies |', '| --- | --- | --- |'); + for (const provider of module.providers) { + lines.push( + `| provider | ${provider.name} | ${provider.dependencies.join(', ') || 'none'} |`, + ); + } + for (const controller of module.controllers) { + lines.push( + `| controller | ${controller.name} | ${controller.dependencies.join(', ') || 'none'} |`, + ); + } + lines.push(''); + } + + return lines.join('\n'); +} + +const tree = await SpelunkerModule.debug(AppModule); +const mermaid = renderMermaid(tree); +await mkdir('../docs/architecture', { recursive: true }); +await writeFile( + '../docs/architecture/nest-module-details.json', + JSON.stringify(tree, null, 2), +); +await writeFile('../docs/architecture/nest-module-graph.mmd', mermaid); +await writeFile( + '../docs/architecture/nest-dependency-graph.md', + renderMarkdown(tree, mermaid), +); diff --git a/app/src/app.module.ts b/app/src/app.module.ts new file mode 100644 index 0000000..a1b259c --- /dev/null +++ b/app/src/app.module.ts @@ -0,0 +1,39 @@ +import { Module } from '@nestjs/common'; +import { AppConfigModule } from './config/app-config.module.js'; +import { DatabaseModule } from './database/database.module.js'; +import { RedisModule } from './redis/redis.module.js'; +import { AuthModule } from './auth/auth.module.js'; +import { ChatsModule } from './chats/chats.module.js'; +import { HealthModule } from './health/health.module.js'; +import { AttachmentsModule } from './attachments/attachments.module.js'; +import { MessagesModule } from './messages/messages.module.js'; +import { MetricsModule } from './metrics/metrics.module.js'; +import { UsersModule } from './users/users.module.js'; +import { APP_FILTER } from '@nestjs/core'; +import { ApiExceptionFilter } from './common/errors/api-exception.filter.js'; +import { QueueStatsService } from './telemetry/queue-stats.service.js'; + +@Module({ + imports: [ + AppConfigModule, + DatabaseModule, + RedisModule, + UsersModule, + AuthModule, + HealthModule, + ChatsModule, + MessagesModule, + AttachmentsModule, + MetricsModule, + ], + providers: [ + { + provide: APP_FILTER, + useClass: ApiExceptionFilter, + }, + // Queue depth/age gauges are published by the API so that they keep + // reporting while the worker is down. + QueueStatsService, + ], +}) +export class AppModule {} diff --git a/app/src/attachments/attachment-sweeper.service.ts b/app/src/attachments/attachment-sweeper.service.ts new file mode 100644 index 0000000..ba17ae3 --- /dev/null +++ b/app/src/attachments/attachment-sweeper.service.ts @@ -0,0 +1,80 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { ObjectStorage } from '../storage/object-storage.js'; +import { AttachmentsRepository } from './attachments.repository.js'; + +const SWEEP_BATCH = 100; + +/** + * Removes unfinished uploads (pending past expiry + grace) and rows whose + * deletion was claimed but never finished. A live upload is never touched: + * its expiry is a hard request deadline and the grace period is far longer. + */ +@Injectable() +export class AttachmentSweeper implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(AttachmentSweeper.name); + private timer: NodeJS.Timeout | undefined; + private running = false; + + constructor( + private readonly config: ConfigService, + private readonly repository: AttachmentsRepository, + private readonly storage: ObjectStorage, + private readonly metrics: MetricsService, + ) {} + + onModuleInit(): void { + const interval = this.config.getOrThrow('ATTACHMENT_SWEEP_INTERVAL_MS'); + if (interval <= 0) return; + this.timer = setInterval(() => { + if (this.running) return; + this.running = true; + this.sweepOnce() + .catch((error: unknown) => { + this.logger.warn( + `Sweep failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + }) + .finally(() => { + this.running = false; + }); + }, interval); + this.timer.unref(); + } + + onModuleDestroy(): void { + if (this.timer) clearInterval(this.timer); + this.timer = undefined; + } + + async sweepOnce(): Promise<{ claimed: number; deleted: number }> { + const claimed = await this.repository.claimExpired( + this.config.getOrThrow('ATTACHMENT_SWEEP_GRACE_SECONDS'), + SWEEP_BATCH, + ); + let deleted = 0; + for (const item of claimed) { + try { + // New uploads live in staging; lab4 rows have no staging key and + // their final object is the only copy. + await this.storage.delete(item.staging_key ?? item.object_key); + await this.repository.deleteClaimed(item.id); + deleted += 1; + this.metrics.increment('attachments.sweep.deleted'); + } catch (error) { + this.metrics.increment('attachments.sweep.error'); + this.logger.warn( + `Sweep of attachment ${item.id} failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + } + return { claimed: claimed.length, deleted }; + } +} diff --git a/app/src/attachments/attachment.ts b/app/src/attachments/attachment.ts new file mode 100644 index 0000000..999c97d --- /dev/null +++ b/app/src/attachments/attachment.ts @@ -0,0 +1,109 @@ +export type AttachmentStatus = 'queued' | 'processing' | 'ready' | 'failed'; +export type VariantName = 'thumbnail' | 'crop' | 'optimized'; + +export const VARIANT_ORDER: VariantName[] = ['thumbnail', 'crop', 'optimized']; + +export type Variant = { + name: VariantName; + content_type: 'image/jpeg' | 'image/png' | 'image/webp'; + size_bytes: number; + width: number; + height: number; + sha256: string; +}; + +export type Attachment = { + id: string; + chat_id: string; + owner_id: string; + filename: string; + content_type: 'image/png' | 'image/jpeg'; + size_bytes: number; + sha256: string; + status: AttachmentStatus; + variants: Variant[]; + error_code: string | null; + created_at: string; + updated_at: string; +}; + +export type AttachmentRow = { + id: string; + chat_id: string; + owner_id: string; + filename: string; + content_type: 'image/png' | 'image/jpeg'; + upload_mode: 'proxy' | 'direct'; + status: + | 'pending' + | 'queued' + | 'processing' + | 'ready' + | 'failed' + | 'deleting' + | 'rejected'; + object_key: string; + staging_key: string | null; + size_bytes: string | number | null; + sha256: string | null; + width: number | null; + height: number | null; + error_code: string | null; + ready_pipeline_version: number | null; + expires_at: Date | null; + created_at: Date; + updated_at: Date; +}; + +export type VariantRow = { + attachment_id: string; + pipeline_version: number; + variant: VariantName; + object_key: string; + content_type: 'image/jpeg' | 'image/png' | 'image/webp'; + size_bytes: string | number; + width: number; + height: number; + sha256: string; + job_id: string; + created_at: Date; +}; + +function toVariant(row: VariantRow): Variant { + return { + name: row.variant, + content_type: row.content_type, + size_bytes: Number(row.size_bytes), + width: row.width, + height: row.height, + sha256: row.sha256, + }; +} + +export function toAttachment( + row: AttachmentRow, + variants: VariantRow[] = [], +): Attachment { + const ordered = + row.status === 'ready' + ? [...variants].sort( + (left, right) => + VARIANT_ORDER.indexOf(left.variant) - + VARIANT_ORDER.indexOf(right.variant), + ) + : []; + return { + id: row.id, + chat_id: row.chat_id, + owner_id: row.owner_id, + filename: row.filename, + content_type: row.content_type, + size_bytes: Number(row.size_bytes), + sha256: row.sha256 as string, + status: row.status as AttachmentStatus, + variants: ordered.map(toVariant), + error_code: row.status === 'failed' ? row.error_code : null, + created_at: row.created_at.toISOString(), + updated_at: row.updated_at.toISOString(), + }; +} diff --git a/app/src/attachments/attachments-sweep.cli.ts b/app/src/attachments/attachments-sweep.cli.ts new file mode 100644 index 0000000..91d0c36 --- /dev/null +++ b/app/src/attachments/attachments-sweep.cli.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url'; +import { parseAppConfig } from '../config/app-config.schema.js'; +import { DatabaseClient } from '../database/database.client.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { ObjectStorage } from '../storage/object-storage.js'; +import { AttachmentSweeper } from './attachment-sweeper.service.js'; +import { AttachmentsRepository } from './attachments.repository.js'; + +// Manual operator pass over unfinished uploads (the API also sweeps in the +// background). Never touches rows before expiry + ATTACHMENT_SWEEP_GRACE_SECONDS. +// in the stand: docker compose exec api node dist/attachments/attachments-sweep.cli.js +// on the host: npm run attachments:sweep (needs reachable DATABASE_URL and S3) +async function main(): Promise { + const config = parseAppConfig(process.env as Record); + const configService = { + getOrThrow: (key: keyof typeof config) => config[key], + } as never; + const metrics = new MetricsService(); + const database = new DatabaseClient(configService, metrics); + try { + const sweeper = new AttachmentSweeper( + configService, + new AttachmentsRepository(database), + new ObjectStorage(configService), + metrics, + ); + let total = 0; + for (;;) { + const { claimed, deleted } = await sweeper.sweepOnce(); + total += deleted; + // A pass that claimed rows but could not delete any would loop forever. + if (claimed === 0 || deleted === 0) break; + } + process.stdout.write( + `Swept ${total} attachment(s) older than ${config.ATTACHMENT_SWEEP_GRACE_SECONDS} seconds past expiry\n`, + ); + } finally { + await database.onModuleDestroy(); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) await main(); diff --git a/app/src/attachments/attachments.controller.ts b/app/src/attachments/attachments.controller.ts new file mode 100644 index 0000000..6335d6e --- /dev/null +++ b/app/src/attachments/attachments.controller.ts @@ -0,0 +1,109 @@ +import { + Body, + Controller, + Get, + Headers, + HttpCode, + Param, + ParseUUIDPipe, + Post, + Query, + Req, + Res, + StreamableFile, + UseGuards, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { FastifyReply, FastifyRequest } from 'fastify'; +import type { Readable } from 'node:stream'; +import { CurrentUser } from '../common/auth/current-user.decorator.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import type { AppConfig } from '../config/app-config.schema.js'; +import type { User } from '../users/user.js'; +import { AttachmentsService } from './attachments.service.js'; +import { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js'; +import { DirectUploadsService } from './direct-uploads.service.js'; +import type { UploadRequest } from './upload-request.js'; +import { contentDisposition } from './filename.js'; + +@Controller('api/v1') +@UseGuards(CurrentUserGuard) +export class AttachmentsController { + private readonly maxUploadBytes: number; + + constructor( + private readonly attachments: AttachmentsService, + private readonly directUploads: DirectUploadsService, + config: ConfigService, + ) { + this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES'); + } + + @Post('chats/:chatId/attachments') + @HttpCode(202) + upload( + @Param('chatId', new ParseUUIDPipe()) chatId: string, + @CurrentUser() user: User, + @Query('filename') filename: unknown, + @Headers('content-length') contentLength: string | undefined, + @Req() request: FastifyRequest & UploadRequest, + @Res({ passthrough: true }) reply: FastifyReply, + ) { + // A gigantic body is not worth draining: close the connection after the answer. + if (Number(contentLength) > 2 * this.maxUploadBytes) + reply.header('Connection', 'close'); + return this.attachments.uploadProxy( + chatId, + user, + filename, + request.uploadContentType, + contentLength, + request.body as Readable | undefined, + ); + } + + @Post('chats/:chatId/attachments/direct-uploads') + @HttpCode(201) + initDirectUpload( + @Param('chatId', new ParseUUIDPipe()) chatId: string, + @CurrentUser() user: User, + @Body() body: CreateDirectUploadDto, + ) { + return this.directUploads.init(chatId, user, body); + } + + @Post('attachments/:attachmentId/complete') + @HttpCode(200) + completeDirectUpload( + @Param('attachmentId', new ParseUUIDPipe()) attachmentId: string, + @CurrentUser() user: User, + ) { + return this.directUploads.complete(attachmentId, user); + } + + @Get('attachments/:attachmentId') + metadata( + @Param('attachmentId', new ParseUUIDPipe()) attachmentId: string, + @CurrentUser() user: User, + ) { + return this.attachments.getMetadata(attachmentId, user); + } + + @Get('attachments/:attachmentId/content') + async content( + @Param('attachmentId', new ParseUUIDPipe()) attachmentId: string, + @CurrentUser() user: User, + @Res({ passthrough: true }) reply: FastifyReply, + @Query('variant') variant?: string, + ) { + const { row, contentType, sizeBytes, stream } = + await this.attachments.openContent(attachmentId, user, variant); + reply.header('X-Content-Type-Options', 'nosniff'); + reply.header('Cache-Control', 'private, no-store'); + return new StreamableFile(stream, { + type: contentType, + length: sizeBytes, + disposition: contentDisposition(row.filename), + }); + } +} diff --git a/app/src/attachments/attachments.module.ts b/app/src/attachments/attachments.module.ts new file mode 100644 index 0000000..7a8fbdc --- /dev/null +++ b/app/src/attachments/attachments.module.ts @@ -0,0 +1,42 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module.js'; +import { ChatsModule } from '../chats/chats.module.js'; +import { UsersModule } from '../users/users.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { StorageModule } from '../storage/storage.module.js'; +import { JobsModule } from '../jobs/jobs.module.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { AttachmentSweeper } from './attachment-sweeper.service.js'; +import { AttachmentsController } from './attachments.controller.js'; +import { AttachmentsRepository } from './attachments.repository.js'; +import { ImageDecoder } from './image/image-decoder.js'; +import { UploadSlots } from './upload-slots.js'; +import { DirectUploadsService } from './direct-uploads.service.js'; +import { AttachmentsService } from './attachments.service.js'; + +@Module({ + imports: [ + DatabaseModule, + ChatsModule, + UsersModule, + RedisModule, + MetricsModule, + StorageModule, + JobsModule, + ], + controllers: [AttachmentsController], + providers: [ + AttachmentsRepository, + AttachmentsService, + DirectUploadsService, + ImageDecoder, + UploadSlots, + AttachmentSweeper, + // The relay runs only in the API process; the worker never imports + // AttachmentsModule. + OutboxRelay, + ], + exports: [AttachmentsRepository], +}) +export class AttachmentsModule {} diff --git a/app/src/attachments/attachments.repository.ts b/app/src/attachments/attachments.repository.ts new file mode 100644 index 0000000..dc4b902 --- /dev/null +++ b/app/src/attachments/attachments.repository.ts @@ -0,0 +1,216 @@ +import { Injectable } from '@nestjs/common'; +import { DatabaseClient } from '../database/database.client.js'; +import type { AttachmentRow } from './attachment.js'; + +export type InsertPending = { + id: string; + chatId: string; + ownerId: string; + filename: string; + contentType: string; + uploadMode: 'proxy' | 'direct'; + objectKey: string; + stagingKey: string | null; + sizeBytes: number | null; + sha256: string | null; + ttlMs: number; +}; + +const VISIBLE_MEMBER = `JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2`; + +const INSERT_PENDING_SQL = `INSERT INTO attachments + (id, chat_id, owner_id, filename, content_type, upload_mode, status, + object_key, staging_key, size_bytes, sha256, expires_at) +VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, $8, $9, $10, + now() + make_interval(secs => $11::double precision / 1000.0))`; + +@Injectable() +export class AttachmentsRepository { + constructor(private readonly database: DatabaseClient) {} + + private values(input: InsertPending): unknown[] { + return [ + input.id, + input.chatId, + input.ownerId, + input.filename, + input.contentType, + input.uploadMode, + input.objectKey, + input.stagingKey, + input.sizeBytes, + input.sha256, + input.ttlMs, + ]; + } + + async insertPending(input: InsertPending): Promise { + await this.database.query( + 'attachments.insert_pending', + INSERT_PENDING_SQL, + this.values(input), + ); + } + + /** + * Serializes the per-owner pending check with the insert. Two parallel + * `init` calls cannot both pass the limit. + */ + async insertPendingLimited( + input: InsertPending, + maxPending: number, + ): Promise { + return this.database.withTransaction(async (client) => { + await client.query( + `SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, + [input.ownerId], + ); + const count = await client.query<{ count: string }>( + `SELECT count(*) AS count FROM attachments + WHERE owner_id = $1 AND status IN ('pending', 'rejected') + AND upload_mode = 'direct' AND expires_at > now()`, + [input.ownerId], + ); + if (Number(count.rows[0].count) >= maxPending) return false; + await client.query(INSERT_PENDING_SQL, this.values(input)); + return true; + }); + } + + async deletePending(id: string): Promise { + await this.database.query( + 'attachments.delete_pending', + `DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, + [id], + ); + } + + async rejectPending(id: string): Promise { + const result = await this.database.query( + 'attachments.reject_pending', + `UPDATE attachments SET status = 'rejected', updated_at = now() + WHERE id = $1 AND status = 'pending'`, + [id], + ); + return result.rowCount === 1; + } + + /** + * Takes a pending row out of play before its object is deleted. The object + * is deleted only when this returns true: a row that is already `ready` + * (its commit succeeded even if the reply was lost) keeps its object. + */ + async claimForCompensation(id: string): Promise { + const result = await this.database.query( + 'attachments.claim_for_compensation', + `UPDATE attachments SET status = 'deleting', updated_at = now() + WHERE id = $1 AND status = 'pending'`, + [id], + ); + return result.rowCount === 1; + } + + async findById(id: string): Promise { + const result = await this.database.query( + 'attachments.find_by_id', + 'SELECT * FROM attachments WHERE id = $1', + [id], + ); + return result.rows[0]; + } + + async findVisible( + id: string, + userId: string, + ): Promise { + const result = await this.database.query( + 'attachments.find_visible', + `SELECT a.* FROM attachments a ${VISIBLE_MEMBER} + WHERE a.id = $1 AND a.status IN ('queued','processing','ready','failed')`, + [id, userId], + ); + return result.rows[0]; + } + + async findForComplete( + id: string, + userId: string, + ): Promise { + const result = await this.database.query( + 'attachments.find_for_complete', + `SELECT a.* FROM attachments a ${VISIBLE_MEMBER} + WHERE a.id = $1 AND a.upload_mode = 'direct' AND a.owner_id = $2 + AND a.status IN ('pending','queued','processing','ready','failed')`, + [id, userId], + ); + return result.rows[0]; + } + + async countPendingDirect(ownerId: string): Promise { + const result = await this.database.query<{ count: string }>( + 'attachments.count_pending_direct', + `SELECT count(*) AS count FROM attachments + WHERE owner_id = $1 AND status IN ('pending', 'rejected') + AND upload_mode = 'direct' AND expires_at > now()`, + [ownerId], + ); + return Number(result.rows[0].count); + } + + async linkState( + chatId: string, + ids: string[], + ): Promise<'ok' | 'failed' | 'missing'> { + const result = await this.database.query<{ + linkable: string; + failed: string; + }>( + 'attachments.link_state', + `SELECT count(*) FILTER (WHERE status IN ('queued','processing','ready')) AS linkable, + count(*) FILTER (WHERE status = 'failed') AS failed + FROM attachments + WHERE chat_id = $1 AND id = ANY($2::uuid[])`, + [chatId, ids], + ); + const linkable = Number(result.rows[0]?.linkable ?? 0); + const failed = Number(result.rows[0]?.failed ?? 0); + if (linkable === ids.length) return 'ok'; + if (linkable + failed === ids.length) return 'failed'; + return 'missing'; + } + + async claimExpired( + graceSeconds: number, + limit: number, + ): Promise< + { id: string; object_key: string; staging_key: string | null }[] + > { + const result = await this.database.query<{ + id: string; + object_key: string; + staging_key: string | null; + }>( + 'attachments.claim_expired', + `UPDATE attachments SET status = 'deleting', updated_at = now() + WHERE id IN ( + SELECT id FROM attachments + WHERE (status IN ('pending', 'rejected') + AND expires_at < now() - make_interval(secs => $1::double precision)) + OR (status = 'deleting' AND updated_at < now() - interval '1 minute') + ORDER BY expires_at NULLS FIRST + LIMIT $2 + FOR UPDATE SKIP LOCKED) + RETURNING id, object_key, staging_key`, + [graceSeconds, limit], + ); + return result.rows; + } + + async deleteClaimed(id: string): Promise { + await this.database.query( + 'attachments.delete_claimed', + `DELETE FROM attachments WHERE id = $1 AND status = 'deleting'`, + [id], + ); + } +} diff --git a/app/src/attachments/attachments.service.spec.ts b/app/src/attachments/attachments.service.spec.ts new file mode 100644 index 0000000..2aac0ae --- /dev/null +++ b/app/src/attachments/attachments.service.spec.ts @@ -0,0 +1,133 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { Readable } from 'node:stream'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it, vi } from 'vitest'; +import type { AttachmentRow } from './attachment.js'; +import { AttachmentsService } from './attachments.service.js'; + +const here = dirname(fileURLToPath(import.meta.url)); +const png = readFileSync(join(here, '../../../tests/fixtures/sample.png')); +const lostReply = () => + Object.assign(new Error('Connection terminated unexpectedly'), {}); + +const settings: Record = { + MAX_UPLOAD_BYTES: 10_485_760, + MAX_IMAGE_PIXELS: 40_000_000, + UPLOAD_TIMEOUT_MS: 10_000, + PIPELINE_VERSION: 1, + JOB_MAX_ATTEMPTS: 5, +}; + +function setup( + repository: Record, + jobs: Record = {}, +) { + const storage = { + objectKey: (id: string) => `attachments/${id}/original`, + stagingKey: (id: string) => `staging/${id}/original`, + putStream: vi.fn(async (_key: string, body: Readable) => { + for await (const _chunk of body) { + // drain like S3 does + } + }), + delete: vi.fn().mockResolvedValue(undefined), + }; + const service = new AttachmentsService( + { getOrThrow: (key: string) => settings[key] } as never, + { + insertPending: vi.fn(), + deleteClaimed: vi.fn(), + ...repository, + } as never, + { acceptUpload: vi.fn(), ...jobs } as never, + { kick: vi.fn() } as never, + { point: vi.fn() } as never, + storage as never, + { getForUser: vi.fn() } as never, + { increment: vi.fn(), add: vi.fn() } as never, + { verify: vi.fn() } as never, + { + run: (_user: string, work: () => Promise) => work(), + } as never, + ); + const upload = () => + service.uploadProxy( + 'chat', + { id: 'user' } as never, + 'a.png', + 'image/png', + String(png.length), + Readable.from([png]), + ); + return { storage, upload }; +} + +const readyRow = (id: string): AttachmentRow => ({ + id, + chat_id: 'chat', + owner_id: 'user', + filename: 'a.png', + content_type: 'image/png', + upload_mode: 'proxy', + status: 'ready', + object_key: `attachments/${id}/original`, + staging_key: `staging/${id}/original`, + size_bytes: png.length, + sha256: 'a'.repeat(64), + width: 320, + height: 200, + error_code: null, + ready_pipeline_version: 1, + expires_at: null, + created_at: new Date(), + updated_at: new Date(), +}); + +describe('AttachmentsService compensation', () => { + it('keeps the object and answers 202 when the job commit reply was lost', async () => { + const { storage, upload } = setup( + { + claimForCompensation: vi.fn().mockResolvedValue(false), + findById: vi.fn((id: string) => Promise.resolve(readyRow(id))), + }, + { acceptUpload: vi.fn().mockRejectedValue(lostReply()) }, + ); + const attachment = await upload(); + expect(attachment.status).toBe('ready'); + expect(storage.delete).not.toHaveBeenCalled(); + }); + + it('deletes nothing while PostgreSQL is unreachable', async () => { + const { storage, upload } = setup( + { + claimForCompensation: vi.fn().mockRejectedValue(lostReply()), + findById: vi.fn().mockRejectedValue(lostReply()), + }, + { acceptUpload: vi.fn().mockRejectedValue(lostReply()) }, + ); + await expect(upload()).rejects.toThrow(); + expect(storage.delete).not.toHaveBeenCalled(); + }); + + it('deletes the object only after claiming the pending row', async () => { + const order: string[] = []; + const { storage, upload } = setup( + { + claimForCompensation: vi.fn(async () => { + order.push('claim'); + return true; + }), + deleteClaimed: vi.fn(async () => { + order.push('delete-row'); + }), + }, + { acceptUpload: vi.fn().mockRejectedValue(lostReply()) }, + ); + storage.delete.mockImplementation(async () => { + order.push('delete-object'); + }); + await expect(upload()).rejects.toThrow(); + expect(order).toEqual(['claim', 'delete-object', 'delete-row']); + }); +}); diff --git a/app/src/attachments/attachments.service.ts b/app/src/attachments/attachments.service.ts new file mode 100644 index 0000000..72a9b56 --- /dev/null +++ b/app/src/attachments/attachments.service.ts @@ -0,0 +1,435 @@ +import { + BadRequestException, + ConflictException, + HttpException, + Injectable, + InternalServerErrorException, + Logger, + NotFoundException, + PayloadTooLargeException, + ServiceUnavailableException, + UnsupportedMediaTypeException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { createHash, randomUUID } from 'node:crypto'; +import { pipeline, Readable, Transform } from 'node:stream'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { ChatsService } from '../chats/chats.service.js'; +import { FaultInjector } from '../jobs/fault-injector.js'; +import { JobsRepository } from '../jobs/jobs.repository.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { ObjectStorage } from '../storage/object-storage.js'; +import type { User } from '../users/user.js'; +import { + toAttachment, + type Attachment, + type AttachmentRow, +} from './attachment.js'; +import { validateFilename } from './filename.js'; +import { + ImageHeader, + ImageInspector, + ImageRejectedError, +} from './image/image-inspector.js'; +import { AttachmentsRepository } from './attachments.repository.js'; +import { ImageDecoder } from './image/image-decoder.js'; +import { UploadSlots } from './upload-slots.js'; + +const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']); + +export function mediaType(header: unknown): string | undefined { + if (typeof header !== 'string') return undefined; + return header.split(';', 1)[0].trim().toLowerCase(); +} + +export function imageRejection(error: ImageRejectedError): HttpException { + return error.reason === 'too_many_pixels' + ? new PayloadTooLargeException(error.message) + : new UnsupportedMediaTypeException(error.message); +} + +class UploadInterruptedError extends Error {} + +@Injectable() +export class AttachmentsService { + private readonly logger = new Logger(AttachmentsService.name); + private readonly maxUploadBytes: number; + private readonly maxPixels: number; + private readonly uploadTimeoutMs: number; + private readonly pipelineVersion: number; + private readonly maxAttempts: number; + + constructor( + config: ConfigService, + private readonly repository: AttachmentsRepository, + private readonly jobs: JobsRepository, + private readonly relay: OutboxRelay, + private readonly faults: FaultInjector, + private readonly storage: ObjectStorage, + private readonly chats: ChatsService, + private readonly metrics: MetricsService, + private readonly decoder: ImageDecoder, + private readonly slots: UploadSlots, + ) { + this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES'); + this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS'); + this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS'); + this.pipelineVersion = config.getOrThrow('PIPELINE_VERSION'); + this.maxAttempts = config.getOrThrow('JOB_MAX_ATTEMPTS'); + } + + async uploadProxy( + chatId: string, + user: User, + rawFilename: unknown, + contentTypeHeader: unknown, + contentLengthHeader: unknown, + body: Readable | undefined, + ): Promise { + const filename = validateFilename(rawFilename); + const declared = mediaType(contentTypeHeader); + if (declared === undefined || !MEDIA_TYPES.has(declared)) + throw new UnsupportedMediaTypeException( + 'Content-Type must be image/png or image/jpeg', + ); + if ( + typeof contentLengthHeader !== 'string' || + !/^\d{1,15}$/u.test(contentLengthHeader) + ) + throw new BadRequestException('Content-Length is required'); + const contentLength = Number(contentLengthHeader); + if (contentLength === 0 || body === undefined) + throw new UnsupportedMediaTypeException('Image body is empty'); + if (contentLength > this.maxUploadBytes) + throw new PayloadTooLargeException('Image is too large'); + + return this.slots.run(user.id, async () => { + await this.chats.getForUser(chatId, user); + return this.receive( + chatId, + user, + filename, + declared, + contentLength, + body, + ); + }); + } + + private async receive( + chatId: string, + user: User, + filename: string, + declared: string, + contentLength: number, + body: Readable, + ): Promise { + const controller = new AbortController(); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + body.destroy(new Error('upload timeout')); + controller.abort(); + }, this.uploadTimeoutMs); + const iterator = body[Symbol.asyncIterator]() as AsyncIterator; + const next = async (): Promise> => { + try { + return await iterator.next(); + } catch { + throw new UploadInterruptedError('Upload was interrupted'); + } + }; + + const inspector = new ImageInspector(this.maxPixels); + const head: Buffer[] = []; + let id: string | undefined; + let key = ''; + let rejection: unknown; + try { + // Header phase: nothing exists in the database or S3 yet. It is + // bounded by Content-Length (<= MAX_UPLOAD_BYTES): a JPEG may carry + // megabytes of APPn metadata before its frame header. + try { + while (inspector.header === undefined) { + const step = await next(); + if (step.done) { + inspector.finish(); + throw new ImageRejectedError( + 'unsupported_media_type', + 'Image header is missing', + ); + } + head.push(step.value); + inspector.push(step.value); + } + } catch (error) { + throw this.mapUploadError(error, timedOut); + } + const header = inspector.header as ImageHeader; + if (header.contentType !== declared) + throw new UnsupportedMediaTypeException( + 'Image content does not match Content-Type', + ); + + id = randomUUID(); + key = this.storage.stagingKey(id); + await this.repository.insertPending({ + id, + chatId, + ownerId: user.id, + filename, + contentType: declared, + uploadMode: 'proxy', + objectKey: this.storage.objectKey(id), + stagingKey: key, + sizeBytes: null, + sha256: null, + ttlMs: this.uploadTimeoutMs, + }); + + const sha256 = createHash('sha256'); + const decoder = this.decoder; + // Copy for the full decode check; bounded by MAX_UPLOAD_BYTES and + // UPLOAD_MAX_IN_FLIGHT, released as soon as the decode starts. + const copy: Buffer[] = []; + let total = 0; + let allSent = false; + const account = (chunk: Buffer, inspect: boolean): boolean => { + total += chunk.length; + if (total > contentLength) + throw new UploadInterruptedError( + 'Body exceeds Content-Length', + ); + if (inspect) inspector.push(chunk); + sha256.update(chunk); + this.metrics.add('attachments.proxy.bytes_in', chunk.length); + copy.push(chunk); + return total === contentLength; + }; + // Validate before the last bytes reach S3: it cannot commit an object + // whose body is incomplete, so an invalid image never becomes an object. + const finalize = async (): Promise => { + inspector.finish(); + const data = Buffer.concat(copy, total); + copy.length = 0; + await decoder.verify(data, controller.signal); + // From here S3 may receive the whole body and commit the object + // even if this request fails or times out afterwards. + allSent = true; + }; + async function* generate(): AsyncGenerator { + for (const chunk of head) { + if (account(chunk, false)) await finalize(); + yield chunk; + } + for (;;) { + const step = await next(); + if (step.done) break; + if (account(step.value, true)) await finalize(); + yield step.value; + } + if (total < contentLength) + throw new UploadInterruptedError('Upload was interrupted'); + } + const readable = Readable.from( + (async function* () { + try { + yield* generate(); + } catch (error) { + rejection = error; + throw error; + } + })(), + ); + + // A failing body must abort the PUT at once: the SDK does not end a + // request whose Content-Length can no longer be satisfied, it would + // hang until the request timeout. The error itself is reported via + // `rejection`; the listener also keeps a late error from crashing us. + readable.on('error', () => controller.abort()); + let claimed = false; + let stored = false; + try { + await this.storage.putStream( + key, + readable, + contentLength, + declared, + controller.signal, + ); + this.metrics.add( + 'attachments.proxy.bytes_to_s3', + contentLength, + ); + stored = true; + const row = await this.jobs.acceptUpload( + id, + { + sizeBytes: total, + sha256: sha256.digest('hex'), + width: header.width, + height: header.height, + }, + this.pipelineVersion, + this.maxAttempts, + ); + if (row === undefined) { + claimed = true; + throw new ServiceUnavailableException(); + } + // Durable: staging object + attachment + job + outbox are committed. + // The fault point deliberately sits between COMMIT and publish; the + // relay recovers the outbox row after a crash. + await this.faults.point('api.after_commit_before_publish'); + this.relay.kick(); + this.metrics.increment('attachments.upload.queued'); + return toAttachment(row); + } catch (error) { + readable.destroy(); + if (!claimed) { + // After the last byte was handed to S3, a PUT aborted on our + // side may still be committed by S3 after our DELETE: keep the + // row so the sweeper deletes the key again later. + const outcome = await this.compensate(id, key, { + keepRow: allSent && !stored, + }); + // acceptUpload failed on our side, but the row is no longer + // pending: the commit may have succeeded with its reply lost. + // If so, the upload is accepted and 202 is the truth. + if (outcome === 'not_pending' && stored) { + const row = await this.repository + .findById(id) + .catch(() => undefined); + if ( + row && + [ + 'queued', + 'processing', + 'ready', + 'failed', + ].includes(row.status) + ) { + this.metrics.increment( + 'attachments.upload.recovered', + ); + return toAttachment(row); + } + } + } + throw this.mapUploadError(rejection ?? error, timedOut); + } + } finally { + clearTimeout(timer); + } + } + + private mapUploadError(error: unknown, timedOut: boolean): unknown { + if (error instanceof ImageRejectedError) return imageRejection(error); + if (error instanceof UploadInterruptedError || timedOut) + return new BadRequestException('Upload was interrupted'); + return error; + } + + /** + * Undoes an upload that did not reach `ready`. The row is claimed first + * (pending -> deleting) and the object is deleted only after a successful + * claim: if PostgreSQL committed `ready` but the reply was lost, the claim + * matches nothing and the object stays. If PostgreSQL is unreachable, + * nothing is deleted; the sweeper finishes the job after expiry + grace + * (a row stuck in `deleting` is re-claimed after a minute). + */ + async compensate( + id: string, + key: string, + options: { keepRow?: boolean } = {}, + ): Promise<'compensated' | 'not_pending' | 'deferred'> { + try { + if (!(await this.repository.claimForCompensation(id))) { + this.metrics.increment('attachments.compensation_skipped'); + return 'not_pending'; + } + await this.storage.delete(key); + // A kept `deleting` row is re-claimed by the sweeper after a minute, + // which deletes the key once more and only then the row. + if (!options.keepRow) await this.repository.deleteClaimed(id); + this.metrics.increment('attachments.compensated'); + return 'compensated'; + } catch (error) { + this.metrics.increment('attachments.compensation_deferred'); + this.logger.warn( + `Compensation of attachment ${id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + return 'deferred'; + } + } + + async getMetadata(id: string, user: User): Promise { + const row = await this.repository.findVisible(id, user.id); + if (!row) throw new NotFoundException(); + const variants = + row.status === 'ready' && row.ready_pipeline_version !== null + ? await this.jobs.variantsFor( + row.id, + row.ready_pipeline_version, + ) + : []; + return toAttachment(row, variants); + } + + async openContent( + id: string, + user: User, + variant: string | undefined, + ): Promise<{ + row: AttachmentRow; + contentType: string; + sizeBytes: number; + stream: Readable; + }> { + if ( + variant !== undefined && + !['original', 'thumbnail', 'crop', 'optimized'].includes(variant) + ) + throw new BadRequestException('variant is invalid'); + const row = await this.repository.findVisible(id, user.id); + if (!row) throw new NotFoundException(); + if (row.status !== 'ready') + throw new ConflictException('Attachment is not ready'); + + let key = row.object_key; + let contentType: string = row.content_type; + let sizeBytes = Number(row.size_bytes); + if (variant !== undefined && variant !== 'original') { + if (row.ready_pipeline_version === null) + throw new NotFoundException(); + const variants = await this.jobs.variantsFor( + row.id, + row.ready_pipeline_version, + ); + const match = variants.find((item) => item.variant === variant); + if (!match) throw new NotFoundException(); + key = match.object_key; + contentType = match.content_type; + sizeBytes = Number(match.size_bytes); + } + + const source = await this.storage.getStream(key); + if (source === null) { + this.metrics.increment('attachments.object_missing'); + this.logger.error( + `Object for ready attachment ${row.id} is missing in storage`, + ); + throw new InternalServerErrorException(); + } + const metrics = this.metrics; + const counter = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + metrics.add('attachments.download.bytes_out', chunk.length); + callback(null, chunk); + }, + }); + pipeline(source, counter, () => undefined); + return { row, contentType, sizeBytes, stream: counter }; + } +} diff --git a/app/src/attachments/direct-uploads.service.ts b/app/src/attachments/direct-uploads.service.ts new file mode 100644 index 0000000..b431ef8 --- /dev/null +++ b/app/src/attachments/direct-uploads.service.ts @@ -0,0 +1,293 @@ +import { + ConflictException, + HttpException, + Injectable, + NotFoundException, + PayloadTooLargeException, + UnsupportedMediaTypeException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { randomUUID } from 'node:crypto'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { ChatsService } from '../chats/chats.service.js'; +import { JobsRepository } from '../jobs/jobs.repository.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { + ObjectStorage, + ObjectStorageUnavailableError, +} from '../storage/object-storage.js'; +import type { User } from '../users/user.js'; +import { + toAttachment, + type Attachment, + type AttachmentRow, +} from './attachment.js'; +import { AttachmentsRepository } from './attachments.repository.js'; +import { imageRejection } from './attachments.service.js'; +import type { CreateDirectUploadDto } from './dto/create-direct-upload.dto.js'; +import { validateFilename } from './filename.js'; +import { ImageDecoder } from './image/image-decoder.js'; +import { UploadSlots } from './upload-slots.js'; +import { + ImageInspector, + ImageRejectedError, + type ImageHeader, +} from './image/image-inspector.js'; + +export type DirectUpload = { + attachment_id: string; + method: 'PUT'; + url: string; + headers: Record; + expires_at: string; +}; + +const MEDIA_TYPES = new Set(['image/png', 'image/jpeg']); + +@Injectable() +export class DirectUploadsService { + private readonly maxUploadBytes: number; + private readonly maxPixels: number; + private readonly uploadTimeoutMs: number; + private readonly ttlSeconds: number; + private readonly maxPending: number; + private readonly pipelineVersion: number; + private readonly maxAttempts: number; + + constructor( + config: ConfigService, + private readonly repository: AttachmentsRepository, + private readonly jobs: JobsRepository, + private readonly relay: OutboxRelay, + private readonly storage: ObjectStorage, + private readonly chats: ChatsService, + private readonly metrics: MetricsService, + private readonly decoder: ImageDecoder, + private readonly slots: UploadSlots, + ) { + this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES'); + this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS'); + this.uploadTimeoutMs = config.getOrThrow('UPLOAD_TIMEOUT_MS'); + this.ttlSeconds = config.getOrThrow('DIRECT_UPLOAD_URL_TTL_SECONDS'); + this.maxPending = config.getOrThrow( + 'DIRECT_UPLOAD_MAX_PENDING_PER_USER', + ); + this.pipelineVersion = config.getOrThrow('PIPELINE_VERSION'); + this.maxAttempts = config.getOrThrow('JOB_MAX_ATTEMPTS'); + } + + async init( + chatId: string, + user: User, + dto: CreateDirectUploadDto, + ): Promise { + const filename = validateFilename(dto.filename); + if (!MEDIA_TYPES.has(dto.content_type)) + throw new UnsupportedMediaTypeException( + 'content_type must be image/png or image/jpeg', + ); + if (dto.size_bytes > this.maxUploadBytes) + throw new PayloadTooLargeException('Image is too large'); + await this.chats.getForUser(chatId, user); + const id = randomUUID(); + const stagingKey = this.storage.stagingKey(id); + const inserted = await this.repository.insertPendingLimited( + { + id, + chatId, + ownerId: user.id, + filename, + contentType: dto.content_type, + uploadMode: 'direct', + objectKey: this.storage.objectKey(id), + stagingKey, + sizeBytes: dto.size_bytes, + sha256: dto.sha256, + ttlMs: this.ttlSeconds * 1000, + }, + this.maxPending, + ); + if (!inserted) + throw new HttpException( + { + message: 'Too many unfinished direct uploads', + retryAfter: this.ttlSeconds, + }, + 429, + ); + const checksum = Buffer.from(dto.sha256, 'hex').toString('base64'); + let url: string; + try { + url = await this.storage.presignPut(stagingKey, { + contentType: dto.content_type, + contentLength: dto.size_bytes, + checksumSha256Base64: checksum, + expiresInSeconds: this.ttlSeconds, + }); + } catch (error) { + await this.repository.deletePending(id); + throw error; + } + this.metrics.increment('attachments.direct.initiated'); + return { + attachment_id: id, + method: 'PUT', + url, + headers: { + 'Content-Type': dto.content_type, + 'x-amz-checksum-sha256': checksum, + }, + expires_at: new Date( + Date.now() + this.ttlSeconds * 1000, + ).toISOString(), + }; + } + + async complete(attachmentId: string, user: User): Promise { + const row = await this.repository.findForComplete( + attachmentId, + user.id, + ); + if (!row) throw new NotFoundException(); + if (row.status !== 'pending') return this.describe(row); + return this.slots.run(user.id, () => this.verifyAndAccept(row)); + } + + private async describe(row: AttachmentRow): Promise { + const variants = + row.status === 'ready' && row.ready_pipeline_version !== null + ? await this.jobs.variantsFor( + row.id, + row.ready_pipeline_version, + ) + : []; + return toAttachment(row, variants); + } + + private async verifyAndAccept(row: AttachmentRow): Promise { + const size = Number(row.size_bytes); + const stagingKey = row.staging_key; + if (stagingKey === null) + throw new ConflictException('Upload has not been received'); + const expectedChecksum = Buffer.from( + row.sha256 as string, + 'hex', + ).toString('base64'); + const head = await this.storage.head(stagingKey); + if (head === null) + throw new ConflictException('Upload has not been received'); + if (head.size !== size || head.checksumSha256 !== expectedChecksum) { + await this.reject(row, stagingKey); + throw new ConflictException( + 'Uploaded object does not match the declaration', + ); + } + + let header: ImageHeader; + try { + header = await this.verifyObject(stagingKey, size); + } catch (error) { + if (error instanceof ImageRejectedError) { + await this.reject(row, stagingKey); + throw imageRejection(error); + } + throw error; + } + if (header.contentType !== row.content_type) { + await this.reject(row, stagingKey); + throw new UnsupportedMediaTypeException( + 'Image content does not match content_type', + ); + } + const accepted = await this.jobs.acceptUpload( + row.id, + { + sizeBytes: size, + sha256: row.sha256 as string, + width: header.width, + height: header.height, + }, + this.pipelineVersion, + this.maxAttempts, + ); + if (!accepted) { + // A parallel complete of the same upload won: answer like a repeat. + const current = await this.repository.findForComplete( + row.id, + row.owner_id, + ); + if (current && current.status !== 'pending') + return this.describe(current); + throw new ConflictException('Upload is no longer pending'); + } + this.relay.kick(); + this.metrics.increment('attachments.direct.completed'); + return toAttachment(accepted); + } + + /** + * Reads the whole object: a correct signed checksum only proves that the + * bytes are the ones the client declared, not that they form an image. The + * stream goes through ImageInspector (structure, CRCs, completeness), then + * the copy is fully decoded. Memory is bounded like a proxy upload. + */ + private async verifyObject( + key: string, + size: number, + ): Promise { + // Same deadline as a proxy upload: a slow or hung read releases its slot. + const signal = AbortSignal.timeout(this.uploadTimeoutMs); + const stream = await this.storage.getStream(key, signal); + if (stream === null) + throw new ConflictException('Upload has not been received'); + const inspector = new ImageInspector(this.maxPixels); + const chunks: Buffer[] = []; + let read = 0; + try { + for await (const chunk of stream as AsyncIterable) { + read += chunk.length; + if (read > size) + throw new ImageRejectedError( + 'unsupported_media_type', + 'Object is larger than declared', + ); + inspector.push(chunk); + chunks.push(chunk); + } + } catch (error) { + if (error instanceof ImageRejectedError) throw error; + // The object stream broke mid-read (S3 outage, timeout): the image + // was not judged, so this is an outage, not a client error. + throw new ObjectStorageUnavailableError(); + } finally { + stream.destroy(); + this.metrics.add('attachments.direct.verify_bytes', read); + } + const header = inspector.finish(); + const data = Buffer.concat(chunks, read); + chunks.length = 0; + await this.decoder.verify(data, signal); + return header; + } + + /** + * A rejected claim keeps its row (status `rejected`, original expiry) while + * the signed URL may still be used: a later re-PUT would otherwise leave an + * object that no row refers to. The sweeper removes both after expiry + grace. + */ + private async reject( + row: AttachmentRow, + stagingKey: string, + ): Promise { + // Row first: a row that is not pending any more (accepted after a parallel + // complete, or claimed by the sweeper) keeps its object. + if (!(await this.repository.rejectPending(row.id))) return; + try { + await this.storage.delete(stagingKey); + } catch { + // The sweeper deletes the object again after expiry. + } + this.metrics.increment('attachments.direct.rejected'); + } +} diff --git a/app/src/attachments/dto/create-direct-upload.dto.ts b/app/src/attachments/dto/create-direct-upload.dto.ts new file mode 100644 index 0000000..f883a12 --- /dev/null +++ b/app/src/attachments/dto/create-direct-upload.dto.ts @@ -0,0 +1,16 @@ +import { IsInt, IsString, Matches, Min } from 'class-validator'; + +export class CreateDirectUploadDto { + @IsString() + filename!: string; + + @IsString() + content_type!: string; + + @IsInt() + @Min(1) + size_bytes!: number; + + @Matches(/^[a-f0-9]{64}$/u) + sha256!: string; +} diff --git a/app/src/attachments/filename.ts b/app/src/attachments/filename.ts new file mode 100644 index 0000000..b4cb3b9 --- /dev/null +++ b/app/src/attachments/filename.ts @@ -0,0 +1,34 @@ +import { BadRequestException } from '@nestjs/common'; + +const FORBIDDEN = + // eslint-disable-next-line no-control-regex + /[/\\\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/u; + +/** The name is stored as-is and used for display only, never in paths or keys. */ +export function validateFilename(value: unknown): string { + if (typeof value !== 'string') throw invalid(); + const length = [...value].length; + if ( + length < 1 || + length > 255 || + /^\s*$/u.test(value) || + value === '.' || + value === '..' || + FORBIDDEN.test(value) + ) + throw invalid(); + return value; +} + +function invalid(): BadRequestException { + return new BadRequestException('filename is invalid'); +} + +export function contentDisposition(filename: string): string { + const fallback = filename.replace(/[^\x20-\x7e]|["\\]/gu, '_'); + const encoded = encodeURIComponent(filename).replace( + /['()*]/gu, + (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`, + ); + return `inline; filename="${fallback}"; filename*=UTF-8''${encoded}`; +} diff --git a/app/src/attachments/image/image-decoder.spec.ts b/app/src/attachments/image/image-decoder.spec.ts new file mode 100644 index 0000000..cc98444 --- /dev/null +++ b/app/src/attachments/image/image-decoder.spec.ts @@ -0,0 +1,70 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { jpegWithoutScanData } from '../../../test/support/jpeg.js'; +import { + maxPixelsRgba16Png, + noisePng, + pngWithGarbageIdat, +} from '../../../test/support/png.js'; +import { ImageDecoder } from './image-decoder.js'; +import { ImageInspector, ImageRejectedError } from './image-inspector.js'; + +const here = dirname(fileURLToPath(import.meta.url)); +const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png')); +const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg')); +const progressive = readFileSync( + join(here, '../../../test/fixtures/sample-progressive.jpg'), +); + +const settings: Record = { + MAX_IMAGE_PIXELS: 40_000_000, + IMAGE_DECODE_MAX_CONCURRENT: 1, +}; +const decoder = new ImageDecoder( + { getOrThrow: (key: string) => settings[key] } as never, + { increment: () => undefined, add: () => undefined } as never, +); + +describe('ImageDecoder', () => { + it('accepts valid PNG and JPEG files, also concurrently', async () => { + await Promise.all( + [png, jpeg, progressive, noisePng(1_048_576)].map((data) => + decoder.verify(data), + ), + ); + }); + + // These files pass the structural inspector; only a decode catches them. + it.each([ + ['PNG with a garbage zlib stream', pngWithGarbageIdat()], + ['JPEG without scan data', jpegWithoutScanData(jpeg)], + [ + 'progressive JPEG without scan data', + jpegWithoutScanData(progressive), + ], + ])('rejects a %s', async (_name, data) => { + const inspector = new ImageInspector(40_000_000); + inspector.push(data); + expect(inspector.finish().width).toBe(320); + await expect(decoder.verify(data)).rejects.toBeInstanceOf( + ImageRejectedError, + ); + }); + + it('accepts the heaviest valid input: 40 MP RGBA 16-bit', async () => { + await decoder.verify(await maxPixelsRgba16Png()); + }, 30_000); + + it('drops an aborted waiter from the queue without running its decode', async () => { + const busy = decoder.verify(noisePng(4_000_000)); + const controller = new AbortController(); + const waiting = decoder.verify(png, controller.signal); + controller.abort(); + await expect(waiting).rejects.toMatchObject({ status: 503 }); + await busy; + // The slot was not leaked: the next decode runs. + await decoder.verify(png); + }); +}); diff --git a/app/src/attachments/image/image-decoder.ts b/app/src/attachments/image/image-decoder.ts new file mode 100644 index 0000000..c383101 --- /dev/null +++ b/app/src/attachments/image/image-decoder.ts @@ -0,0 +1,119 @@ +import { + Injectable, + InternalServerErrorException, + Logger, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import sharp from 'sharp'; +import type { AppConfig } from '../../config/app-config.schema.js'; +import { MetricsService } from '../../metrics/metrics.service.js'; +import { ImageRejectedError } from './image-inspector.js'; + +// One libvips worker per decode and no operation cache: decodes are one-off, +// and memory must stay predictable under the per-replica limit. +sharp.cache(false); +sharp.concurrency(1); + +// Failures of the replica itself, not of the image: they must not turn into a +// client 415. libvips spills large images to a temp file unless +// VIPS_DISC_THRESHOLD (compose.yaml) keeps them in memory; a full /tmp or an +// allocation failure ends up here. +export const SERVER_FAULT = + /no space left|out of memory|unable to allocate|cannot allocate|write failed|unable to open|tmp/iu; + +/** + * Full decode check. ImageInspector only proves the container structure + * (signature, chunk CRCs, markers, dimensions); a PNG with a garbage zlib stream + * or a JPEG without scan data passes it. Decoding every scanline with + * failOn=warning rejects those, including truncated or corrupted compressed + * data. A downscale to a thumbnail is the sink: it decodes all input but keeps + * far less in memory than a full-size pipeline (measured in + * evidence/lab4/decode-memory.txt). Decodes are bounded by + * IMAGE_DECODE_MAX_CONCURRENT; a waiter whose request was aborted leaves the + * queue and releases its buffer. + */ +@Injectable() +export class ImageDecoder { + private readonly logger = new Logger(ImageDecoder.name); + private readonly maxPixels: number; + private readonly maxConcurrent: number; + private active = 0; + private readonly waiting = new Set<() => void>(); + + constructor( + config: ConfigService, + private readonly metrics: MetricsService, + ) { + this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS'); + this.maxConcurrent = config.getOrThrow('IMAGE_DECODE_MAX_CONCURRENT'); + } + + async verify(data: Buffer, signal?: AbortSignal): Promise { + await this.acquire(signal); + const started = performance.now(); + try { + await sharp(data, { + failOn: 'warning', + sequentialRead: true, + limitInputPixels: this.maxPixels, + }) + .resize(64, 64, { fit: 'inside' }) + .toBuffer(); + } catch (error) { + const message = + error instanceof Error ? error.message : String(error); + if (SERVER_FAULT.test(message)) { + this.metrics.increment('attachments.decode.server_error'); + this.logger.error( + `Image decode failed on the server: ${message}`, + ); + throw new InternalServerErrorException(); + } + this.metrics.increment('attachments.decode.rejected'); + throw new ImageRejectedError( + 'unsupported_media_type', + 'Image data cannot be decoded', + ); + } finally { + this.metrics.add( + 'attachments.decode.ms', + performance.now() - started, + ); + this.release(); + } + } + + private acquire(signal?: AbortSignal): Promise { + const abandoned = new ServiceUnavailableException( + 'Image check was abandoned', + ); + if (signal?.aborted) return Promise.reject(abandoned); + if (this.active < this.maxConcurrent) { + this.active += 1; + return Promise.resolve(); + } + const { promise, resolve, reject } = Promise.withResolvers(); + const cancel = () => { + this.waiting.delete(grant); + reject(abandoned); + }; + const grant = () => { + signal?.removeEventListener('abort', cancel); + resolve(); + }; + this.waiting.add(grant); + signal?.addEventListener('abort', cancel, { once: true }); + return promise; + } + + private release(): void { + const next = this.waiting.values().next(); + if (next.done) { + this.active -= 1; + return; + } + this.waiting.delete(next.value); + next.value(); + } +} diff --git a/app/src/attachments/image/image-inspector.spec.ts b/app/src/attachments/image/image-inspector.spec.ts new file mode 100644 index 0000000..9e74959 --- /dev/null +++ b/app/src/attachments/image/image-inspector.spec.ts @@ -0,0 +1,109 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { noisePng, pixelBombPng } from '../../../test/support/png.js'; +import { ImageInspector, ImageRejectedError } from './image-inspector.js'; + +const here = dirname(fileURLToPath(import.meta.url)); +const png = readFileSync(join(here, '../../../../tests/fixtures/sample.png')); +const jpeg = readFileSync(join(here, '../../../test/fixtures/sample.jpg')); +const progressive = readFileSync( + join(here, '../../../test/fixtures/sample-progressive.jpg'), +); +const MAX = 40_000_000; + +function inspect(data: Buffer, step = data.length, max = MAX) { + const inspector = new ImageInspector(max); + for (let offset = 0; offset < data.length; offset += step) + inspector.push(data.subarray(offset, offset + step)); + return inspector.finish(); +} + +function rejection(action: () => unknown): ImageRejectedError { + try { + action(); + } catch (error) { + expect(error).toBeInstanceOf(ImageRejectedError); + return error as ImageRejectedError; + } + throw new Error('expected rejection'); +} + +describe('ImageInspector', () => { + it.each([ + ['png', png, 'image/png'], + ['jpeg', jpeg, 'image/jpeg'], + ['progressive jpeg', progressive, 'image/jpeg'], + ])('accepts %s and reports its size', (_name, data, contentType) => { + const expected = { contentType, width: 320, height: 200 }; + expect(inspect(data)).toEqual(expected); + expect(inspect(data, 1)).toEqual(expected); + expect(inspect(data, 7)).toEqual(expected); + }); + + it('rejects truncated files on finish', () => { + for (const data of [png, jpeg, progressive]) + for (const cut of [10, 40, data.length - 100, data.length - 1]) { + const reason = rejection(() => + inspect(data.subarray(0, cut)), + ).reason; + expect(reason).toBe('unsupported_media_type'); + } + }); + + it('rejects a flipped byte inside IDAT by checksum', () => { + const damaged = Buffer.from(png); + damaged[Math.floor(png.length / 2)] ^= 0xff; + expect(rejection(() => inspect(damaged)).reason).toBe( + 'unsupported_media_type', + ); + }); + + it('rejects a pixel bomb right after IHDR, before any IDAT', () => { + const bomb = pixelBombPng(); + const inspector = new ImageInspector(MAX); + // signature + IHDR chunk = 8 + 25 bytes + const reason = rejection(() => + inspector.push(bomb.subarray(0, 33)), + ).reason; + expect(reason).toBe('too_many_pixels'); + expect(inspector.header).toBeUndefined(); + }); + + it('applies the pixel limit to JPEG frame headers', () => { + expect(rejection(() => inspect(jpeg, jpeg.length, 63_999)).reason).toBe( + 'too_many_pixels', + ); + expect(inspect(jpeg, jpeg.length, 64_000).width).toBe(320); + }); + + it('rejects foreign formats and trailing data after IEND', () => { + for (const data of [ + Buffer.from('GIF89a' + 'x'.repeat(40)), + Buffer.from('plain text, not an image'), + Buffer.alloc(0), + ]) + expect(rejection(() => inspect(data)).reason).toBe( + 'unsupported_media_type', + ); + expect( + rejection(() => inspect(Buffer.concat([png, Buffer.from([0])]))) + .reason, + ).toBe('unsupported_media_type'); + }); + + it('accepts padded and noise PNGs of exact sizes', () => { + for (const size of [131_072, 1_048_576]) { + const data = noisePng(size); + expect(data.length).toBe(size); + expect(inspect(data).width).toBe(1024); + } + }); + + it('tolerates trailing data after JPEG EOI', () => { + expect( + inspect(Buffer.concat([jpeg, Buffer.from('MPF trailer')])).height, + ).toBe(200); + }); +}); diff --git a/app/src/attachments/image/image-inspector.ts b/app/src/attachments/image/image-inspector.ts new file mode 100644 index 0000000..aeb88fe --- /dev/null +++ b/app/src/attachments/image/image-inspector.ts @@ -0,0 +1,387 @@ +import { crc32 } from 'node:zlib'; + +export type ImageHeader = { + contentType: 'image/png' | 'image/jpeg'; + width: number; + height: number; +}; + +export class ImageRejectedError extends Error { + constructor( + readonly reason: 'unsupported_media_type' | 'too_many_pixels', + message: string, + ) { + super(message); + this.name = 'ImageRejectedError'; + } +} + +const PNG_SIGNATURE = Buffer.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, +]); +const PNG_MAX_DIMENSION = 2 ** 31 - 1; +const PNG_BIT_DEPTHS: Record = { + 0: [1, 2, 4, 8, 16], + 2: [8, 16], + 3: [1, 2, 4, 8], + 4: [8, 16], + 6: [8, 16], +}; +const SOF_MARKERS = new Set([ + 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, + 0xcf, +]); + +type State = + | 'start' + // PNG + | 'png_chunk_head' + | 'png_ihdr' + | 'png_skip' + | 'png_crc' + | 'png_done' + // JPEG + | 'jpeg_marker' + | 'jpeg_code' + | 'jpeg_length' + | 'jpeg_sof' + | 'jpeg_skip' + | 'jpeg_entropy' + | 'jpeg_entropy_ff' + | 'jpeg_trailer'; + +function unsupported(message: string): ImageRejectedError { + return new ImageRejectedError('unsupported_media_type', message); +} + +/** + * Streaming structural validator for PNG and JPEG. It never buffers the body: + * only fixed-size fields (chunk headers, IHDR, SOF) are accumulated, and + * nothing is decompressed. It is the early gate (type, dimensions, pixel limit + * before anything is stored), not proof of a valid image: compressed pixel + * data is checked by ImageDecoder. + */ +export class ImageInspector { + private state: State = 'start'; + private imageHeader: ImageHeader | undefined; + + // Accumulator for fixed-length fields. + private field = Buffer.alloc(16); + private fieldNeed = 0; + private fieldLength = 0; + + // Remaining bytes to skip in png_skip / jpeg_skip. + private skip = 0; + + // PNG + private chunkType = ''; + private chunkLength = 0; + private crc = 0; + private firstChunk = true; + private seenIdat = false; + + // JPEG + private marker = 0; + private scans = 0; + private afterSkip: State = 'jpeg_marker'; + + constructor(private readonly maxPixels: number) {} + + get header(): ImageHeader | undefined { + return this.imageHeader; + } + + push(chunk: Buffer): void { + let offset = 0; + while (offset < chunk.length) offset = this.step(chunk, offset); + } + + finish(): ImageHeader { + const done = this.state === 'png_done' || this.state === 'jpeg_trailer'; + if (!done || this.imageHeader === undefined) + throw unsupported('Image data is incomplete'); + return this.imageHeader; + } + + private collect(need: number): void { + this.fieldNeed = need; + this.fieldLength = 0; + } + + /** Copies up to fieldNeed bytes; returns new offset and whether complete. */ + private fill(chunk: Buffer, offset: number): [number, boolean] { + const take = Math.min( + this.fieldNeed - this.fieldLength, + chunk.length - offset, + ); + chunk.copy(this.field, this.fieldLength, offset, offset + take); + this.fieldLength += take; + return [offset + take, this.fieldLength === this.fieldNeed]; + } + + private step(chunk: Buffer, offset: number): number { + switch (this.state) { + case 'start': + return this.stepStart(chunk, offset); + case 'png_chunk_head': + case 'png_ihdr': + case 'png_crc': + case 'jpeg_length': + case 'jpeg_sof': { + const [next, complete] = this.fill(chunk, offset); + if (complete) this.fieldDone(); + return next; + } + case 'png_skip': + case 'jpeg_skip': { + const take = Math.min(this.skip, chunk.length - offset); + if (this.state === 'png_skip') + this.crc = crc32( + chunk.subarray(offset, offset + take), + this.crc, + ); + this.skip -= take; + if (this.skip === 0) this.skipDone(); + return offset + take; + } + case 'png_done': + throw unsupported('Data after the PNG end chunk'); + case 'jpeg_marker': + if (chunk[offset] !== 0xff) + throw unsupported('Unexpected byte between JPEG segments'); + this.state = 'jpeg_code'; + return offset + 1; + case 'jpeg_code': + this.onMarkerCode(chunk[offset]); + return offset + 1; + case 'jpeg_entropy': { + const next = chunk.indexOf(0xff, offset); + if (next === -1) return chunk.length; + this.state = 'jpeg_entropy_ff'; + return next + 1; + } + case 'jpeg_entropy_ff': { + const byte = chunk[offset]; + if (byte === 0xff) return offset + 1; + if (byte === 0x00 || (byte >= 0xd0 && byte <= 0xd7)) { + this.state = 'jpeg_entropy'; + return offset + 1; + } + this.onMarkerCode(byte); + return offset + 1; + } + case 'jpeg_trailer': + return chunk.length; + } + } + + private stepStart(chunk: Buffer, offset: number): number { + // Accumulate until the type is certain: 3 bytes for JPEG, 8 for PNG. + if (this.fieldLength === 0 && this.fieldNeed === 0) this.collect(8); + const have = this.fieldLength; + const take = Math.min(this.fieldNeed - have, chunk.length - offset); + chunk.copy(this.field, have, offset, offset + take); + this.fieldLength += take; + const first = this.field[0]; + if (first === 0xff) { + if (this.fieldLength >= 3) { + if (this.field[1] !== 0xd8 || this.field[2] !== 0xff) + throw unsupported('Not a JPEG file'); + // The third byte opens the next marker. + this.state = 'jpeg_code'; + this.fieldNeed = 0; + this.fieldLength = 0; + return offset + (3 - have); + } + return offset + take; + } + if (first === PNG_SIGNATURE[0]) { + for (let index = 0; index < this.fieldLength; index += 1) + if (this.field[index] !== PNG_SIGNATURE[index]) + throw unsupported('Not a PNG file'); + if (this.fieldLength === 8) { + this.state = 'png_chunk_head'; + this.collect(8); + } + return offset + take; + } + throw unsupported('Unsupported image format'); + } + + private fieldDone(): void { + switch (this.state) { + case 'png_chunk_head': + this.onPngChunkHead(); + return; + case 'png_ihdr': + this.crc = crc32(this.field.subarray(0, 13), this.crc); + this.parseIhdr(); + this.state = 'png_crc'; + this.collect(4); + return; + case 'png_crc': { + const expected = this.field.readUInt32BE(0); + if (this.crc >>> 0 !== expected) + throw unsupported('PNG chunk checksum mismatch'); + this.onPngChunkEnd(); + return; + } + case 'jpeg_length': + this.onJpegLength(); + return; + case 'jpeg_sof': + this.onJpegSof(); + return; + default: + return; + } + } + + private skipDone(): void { + if (this.state === 'png_skip') { + this.state = 'png_crc'; + this.collect(4); + } else { + this.state = this.afterSkip; + } + } + + // ---- PNG ---- + + private onPngChunkHead(): void { + const length = this.field.readUInt32BE(0); + const type = this.field.toString('latin1', 4, 8); + if (length > PNG_MAX_DIMENSION) + throw unsupported('PNG chunk is too long'); + if (!/^[A-Za-z]{4}$/u.test(type)) + throw unsupported('PNG chunk type is invalid'); + if (this.firstChunk) { + if (type !== 'IHDR' || length !== 13) + throw unsupported('PNG must start with IHDR'); + this.firstChunk = false; + } else if (type === 'IHDR') { + throw unsupported('Duplicate PNG IHDR'); + } + if (type === 'IEND') { + if (length !== 0 || !this.seenIdat) + throw unsupported('PNG IEND is invalid'); + } + if (type === 'IDAT') this.seenIdat = true; + this.chunkType = type; + this.chunkLength = length; + this.crc = crc32(this.field.subarray(4, 8), 0); + if (type === 'IHDR') { + this.state = 'png_ihdr'; + this.collect(13); + } else if (length === 0) { + this.state = 'png_crc'; + this.collect(4); + } else { + this.state = 'png_skip'; + this.skip = length; + } + } + + private parseIhdr(): void { + const width = this.field.readUInt32BE(0); + const height = this.field.readUInt32BE(4); + const bitDepth = this.field[8]; + const colorType = this.field[9]; + if (width < 1 || width > PNG_MAX_DIMENSION) + throw unsupported('PNG width is invalid'); + if (height < 1 || height > PNG_MAX_DIMENSION) + throw unsupported('PNG height is invalid'); + if (!PNG_BIT_DEPTHS[colorType]?.includes(bitDepth)) + throw unsupported('PNG color type / bit depth is invalid'); + if (this.field[10] !== 0 || this.field[11] !== 0) + throw unsupported('PNG compression/filter method is invalid'); + if (this.field[12] > 1) + throw unsupported('PNG interlace method is invalid'); + this.pendingHeader = { contentType: 'image/png', width, height }; + } + + private pendingHeader: ImageHeader | undefined; + + private onPngChunkEnd(): void { + if (this.chunkType === 'IHDR' && this.pendingHeader) { + const { width, height } = this.pendingHeader; + if (width * height > this.maxPixels) + throw new ImageRejectedError( + 'too_many_pixels', + 'Image has too many pixels', + ); + this.imageHeader = this.pendingHeader; + } + if (this.chunkType === 'IEND') { + this.state = 'png_done'; + return; + } + this.state = 'png_chunk_head'; + this.collect(8); + } + + // ---- JPEG ---- + + private onMarkerCode(code: number): void { + if (code === 0xff) return; // fill byte + this.marker = code; + if (code === 0x00 || code === 0xd8) + throw unsupported('Unexpected JPEG marker'); + if (code === 0x01 || (code >= 0xd0 && code <= 0xd7)) { + this.state = 'jpeg_marker'; + return; + } + if (code === 0xd9) { + if (this.imageHeader === undefined || this.scans === 0) + throw unsupported('JPEG ended before image data'); + this.state = 'jpeg_trailer'; + return; + } + if (code === 0xda && this.imageHeader === undefined) + throw unsupported('JPEG scan before frame header'); + this.state = 'jpeg_length'; + this.collect(2); + } + + private onJpegLength(): void { + const length = this.field.readUInt16BE(0); + if (length < 2) throw unsupported('JPEG segment length is invalid'); + const dataLength = length - 2; + if (SOF_MARKERS.has(this.marker)) { + if (this.imageHeader !== undefined || this.pendingHeader) + throw unsupported('Duplicate JPEG frame header'); + if (dataLength < 6) throw unsupported('JPEG frame header is short'); + this.skip = dataLength - 6; + this.afterSkip = 'jpeg_marker'; + this.state = 'jpeg_sof'; + this.collect(6); + return; + } + if (this.marker === 0xda) { + this.scans += 1; + this.afterSkip = 'jpeg_entropy'; + } else { + this.afterSkip = 'jpeg_marker'; + } + if (dataLength === 0) this.state = this.afterSkip; + else { + this.skip = dataLength; + this.state = 'jpeg_skip'; + } + } + + private onJpegSof(): void { + const height = this.field.readUInt16BE(1); + const width = this.field.readUInt16BE(3); + if (width === 0 || height === 0 || this.field[5] === 0) + throw unsupported('JPEG dimensions are invalid'); + if (width * height > this.maxPixels) + throw new ImageRejectedError( + 'too_many_pixels', + 'Image has too many pixels', + ); + this.imageHeader = { contentType: 'image/jpeg', width, height }; + if (this.skip === 0) this.state = 'jpeg_marker'; + else this.state = 'jpeg_skip'; + } +} diff --git a/app/src/attachments/upload-request.ts b/app/src/attachments/upload-request.ts new file mode 100644 index 0000000..3479cc3 --- /dev/null +++ b/app/src/attachments/upload-request.ts @@ -0,0 +1,9 @@ +/** Request of the upload route; see the onRequest hook in main.ts. */ +export type UploadRequest = { + method: string; + routeOptions?: { url?: string }; + headers: Record; + /** Content-Type as sent by the client (the header itself is rewritten). */ + uploadContentType?: string | string[]; + body?: unknown; +}; diff --git a/app/src/attachments/upload-slots.spec.ts b/app/src/attachments/upload-slots.spec.ts new file mode 100644 index 0000000..9910b9a --- /dev/null +++ b/app/src/attachments/upload-slots.spec.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest'; +import { UploadSlots } from './upload-slots.js'; + +const slots = (max: number, perUser: number) => + new UploadSlots({ + getOrThrow: (key: string) => + key === 'UPLOAD_MAX_IN_FLIGHT' ? max : perUser, + } as never); + +function hold() { + const { promise, resolve } = Promise.withResolvers(); + return { work: () => promise, release: resolve }; +} + +describe('UploadSlots', () => { + it('caps one user without starving others, and frees slots after work', async () => { + const limiter = slots(10, 2); + const held = [hold(), hold()]; + const running = held.map((h) => limiter.run('a', h.work)); + await expect(limiter.run('a', async () => 'x')).rejects.toMatchObject({ + status: 429, + }); + await expect(limiter.run('b', async () => 'ok')).resolves.toBe('ok'); + held.forEach((h) => h.release()); + await Promise.all(running); + await expect(limiter.run('a', async () => 'again')).resolves.toBe( + 'again', + ); + }); + + it('applies the replica-wide cap across users', async () => { + const limiter = slots(2, 2); + const held = [hold(), hold()]; + const running = [ + limiter.run('a', held[0].work), + limiter.run('b', held[1].work), + ]; + await expect(limiter.run('c', async () => 'x')).rejects.toMatchObject({ + status: 429, + }); + held.forEach((h) => h.release()); + await Promise.all(running); + }); + + it('releases a slot when the work fails', async () => { + const limiter = slots(1, 1); + await expect( + limiter.run('a', async () => { + throw new Error('boom'); + }), + ).rejects.toThrow('boom'); + await expect(limiter.run('a', async () => 'ok')).resolves.toBe('ok'); + }); +}); diff --git a/app/src/attachments/upload-slots.ts b/app/src/attachments/upload-slots.ts new file mode 100644 index 0000000..bc4129f --- /dev/null +++ b/app/src/attachments/upload-slots.ts @@ -0,0 +1,41 @@ +import { HttpException, Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; + +/** + * Per-replica caps on requests that hold an image in memory (proxy upload, + * direct complete): each may keep up to MAX_UPLOAD_BYTES for the decode check. + * The per-user cap keeps one client (e.g. slow senders holding slots until + * UPLOAD_TIMEOUT_MS) from starving everyone else. + */ +@Injectable() +export class UploadSlots { + private inFlight = 0; + private readonly perUser = new Map(); + private readonly max: number; + private readonly maxPerUser: number; + + constructor(config: ConfigService) { + this.max = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT'); + this.maxPerUser = config.getOrThrow('UPLOAD_MAX_IN_FLIGHT_PER_USER'); + } + + async run(userId: string, work: () => Promise): Promise { + const mine = this.perUser.get(userId) ?? 0; + if (this.inFlight >= this.max || mine >= this.maxPerUser) + throw new HttpException( + { message: 'Too many concurrent uploads', retryAfter: 1 }, + 429, + ); + this.inFlight += 1; + this.perUser.set(userId, mine + 1); + try { + return await work(); + } finally { + this.inFlight -= 1; + const left = (this.perUser.get(userId) ?? 1) - 1; + if (left === 0) this.perUser.delete(userId); + else this.perUser.set(userId, left); + } + } +} diff --git a/app/src/auth/auth.controller.ts b/app/src/auth/auth.controller.ts new file mode 100644 index 0000000..265696d --- /dev/null +++ b/app/src/auth/auth.controller.ts @@ -0,0 +1,79 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Headers, + HttpCode, + HttpStatus, + Post, + UnauthorizedException, + UseGuards, +} from '@nestjs/common'; +import { TextDecoder } from 'node:util'; +import { AuthService } from './auth.service.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; + +const BASE64 = + /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u; +const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'; + +function basicUnauthorized(): UnauthorizedException { + return new UnauthorizedException({ + message: 'Unauthorized', + challenge: BASIC_CHALLENGE, + }); +} + +function bearerUnauthorized(): UnauthorizedException { + return new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="messenger"', + }); +} + +function parseBasic(value: string | undefined): [string, string] { + if (typeof value !== 'string') throw basicUnauthorized(); + const match = /^Basic[ \t]+([^ \t]+)$/iu.exec(value); + if (!match || !BASE64.test(match[1])) throw basicUnauthorized(); + const bytes = Buffer.from(match[1], 'base64'); + if (bytes.toString('base64') !== match[1]) throw basicUnauthorized(); + let decoded: string; + try { + decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes); + } catch { + throw basicUnauthorized(); + } + const separator = decoded.indexOf(':'); + if (separator < 1) throw basicUnauthorized(); + return [decoded.slice(0, separator), decoded.slice(separator + 1)]; +} + +@Controller('api/v1/auth/sessions') +export class AuthController { + constructor(private readonly auth: AuthService) {} + + @Post() + create( + @Headers('authorization') authorization: string | undefined, + @Body() body: unknown, + ) { + const [username, password] = parseBasic(authorization); + if (body !== undefined) + throw new BadRequestException( + 'Session creation does not accept a body', + ); + return this.auth.createSession(username, password); + } + + @Delete('current') + @UseGuards(CurrentUserGuard) + @HttpCode(HttpStatus.NO_CONTENT) + async delete( + @Headers('authorization') authorization: string | undefined, + ): Promise { + if (!authorization || !/^Bearer\s+[^\s]+$/iu.test(authorization)) + throw bearerUnauthorized(); + await this.auth.deleteSession(authorization.slice(7).trim()); + } +} diff --git a/app/src/auth/auth.module.ts b/app/src/auth/auth.module.ts new file mode 100644 index 0000000..c29483b --- /dev/null +++ b/app/src/auth/auth.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { UsersModule } from '../users/users.module.js'; +import { AuthController } from './auth.controller.js'; +import { AuthService } from './auth.service.js'; +import { SessionRepository } from './session.repository.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; + +@Module({ + imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule], + controllers: [AuthController], + providers: [AuthService, SessionRepository], + exports: [AuthService, SessionRepository], +}) +export class AuthModule {} diff --git a/app/src/auth/auth.service.ts b/app/src/auth/auth.service.ts new file mode 100644 index 0000000..f983358 --- /dev/null +++ b/app/src/auth/auth.service.ts @@ -0,0 +1,63 @@ +import { + Injectable, + ServiceUnavailableException, + UnauthorizedException, +} from '@nestjs/common'; +import argon2 from 'argon2'; +import type { User } from '../users/user.js'; +import { UsersService } from '../users/users.service.js'; +import { SessionRepository } from './session.repository.js'; + +export type SessionResponse = { + token: string; + token_type: 'Bearer'; + expires_at: string; + user: User; +}; + +@Injectable() +export class AuthService { + constructor( + private readonly users: UsersService, + private readonly sessions: SessionRepository, + ) {} + + async createSession( + username: string, + password: string, + ): Promise { + const storedUser = await this.users.findByUsername(username); + if ( + !storedUser || + !(await argon2.verify(storedUser.password_hash, password)) + ) { + throw new UnauthorizedException(); + } + const user: User = { + id: storedUser.id, + username: storedUser.username, + display_name: storedUser.display_name, + created_at: storedUser.created_at, + }; + let session: { token: string; expiresAt: string }; + try { + session = await this.sessions.create(user.id); + } catch { + throw new ServiceUnavailableException('Session store unavailable'); + } + return { + token: session.token, + token_type: 'Bearer', + expires_at: session.expiresAt, + user, + }; + } + + async deleteSession(token: string): Promise { + try { + await this.sessions.delete(token); + } catch { + throw new ServiceUnavailableException('Session store unavailable'); + } + } +} diff --git a/app/src/auth/session.repository.ts b/app/src/auth/session.repository.ts new file mode 100644 index 0000000..57eb282 --- /dev/null +++ b/app/src/auth/session.repository.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { randomBytes } from 'node:crypto'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { RedisClient } from '../redis/redis.client.js'; +import { MetricsService } from '../metrics/metrics.service.js'; + +@Injectable() +export class SessionRepository { + constructor( + private readonly redis: RedisClient, + private readonly config: ConfigService, + private readonly metrics: MetricsService, + ) {} + + async create( + userId: string, + ): Promise<{ token: string; expiresAt: string }> { + const token = randomBytes(32).toString('base64url'); + const ttl = this.config.getOrThrow('SESSION_TTL_SECONDS'); + const expiresAt = new Date(Date.now() + ttl * 1000).toISOString(); + this.metrics.increment('session_set'); + await this.redis.set( + `session:${token}`, + JSON.stringify({ user_id: userId, expires_at: expiresAt }), + { EX: ttl }, + ); + return { token, expiresAt }; + } + + delete(token: string): Promise { + this.metrics.increment('session_del'); + return this.redis.del(`session:${token}`); + } +} diff --git a/app/src/chats/chat.ts b/app/src/chats/chat.ts new file mode 100644 index 0000000..fb2e262 --- /dev/null +++ b/app/src/chats/chat.ts @@ -0,0 +1,6 @@ +export type Chat = { + id: string; + title: string; + member_ids: string[]; + created_at: string; +}; diff --git a/app/src/chats/chats.controller.ts b/app/src/chats/chats.controller.ts new file mode 100644 index 0000000..53dcd86 --- /dev/null +++ b/app/src/chats/chats.controller.ts @@ -0,0 +1,49 @@ +import { + BadRequestException, + Body, + Controller, + DefaultValuePipe, + Get, + Param, + ParseIntPipe, + ParseUUIDPipe, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import { CurrentUser } from '../common/auth/current-user.decorator.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import { ChatsService } from './chats.service.js'; +import { CreateChatDto } from './dto/create-chat.dto.js'; +import type { User } from '../users/user.js'; + +@Controller('api/v1/chats') +@UseGuards(CurrentUserGuard) +export class ChatsController { + constructor(private readonly chatsService: ChatsService) {} + + @Post() + create(@Body() body: CreateChatDto, @CurrentUser() currentUser: User) { + return this.chatsService.create(body, currentUser); + } + + @Get() + list( + @CurrentUser() currentUser: User, + @Query('limit', new DefaultValuePipe(50), new ParseIntPipe()) + limit: number, + @Query('cursor') cursor?: string, + ) { + if (limit < 1 || limit > 100) + throw new BadRequestException('limit must be between 1 and 100'); + return this.chatsService.listForUser(currentUser, limit, cursor); + } + + @Get(':chatId') + get( + @Param('chatId', new ParseUUIDPipe()) chatId: string, + @CurrentUser() currentUser: User, + ) { + return this.chatsService.getForUser(chatId, currentUser); + } +} diff --git a/app/src/chats/chats.module.ts b/app/src/chats/chats.module.ts new file mode 100644 index 0000000..5bc65a3 --- /dev/null +++ b/app/src/chats/chats.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { UsersModule } from '../users/users.module.js'; +import { ChatsController } from './chats.controller.js'; +import { ChatsRepository } from './chats.repository.js'; +import { ChatsService } from './chats.service.js'; + +@Module({ + imports: [UsersModule, DatabaseModule, RedisModule, MetricsModule], + controllers: [ChatsController], + providers: [ChatsRepository, ChatsService], + exports: [ChatsService], +}) +export class ChatsModule {} diff --git a/app/src/chats/chats.repository.ts b/app/src/chats/chats.repository.ts new file mode 100644 index 0000000..7f724bc --- /dev/null +++ b/app/src/chats/chats.repository.ts @@ -0,0 +1,109 @@ +import { BadRequestException, Injectable } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; +import { DatabaseClient } from '../database/database.client.js'; +import type { Cursor } from '../common/http/cursor.js'; +import type { User } from '../users/user.js'; +import type { Chat } from './chat.js'; + +type ChatRow = { + id: string; + title: string; + created_at: Date | string; + member_ids: string[]; +}; + +function toChat(row: ChatRow): Chat { + return { + id: row.id, + title: row.title, + created_at: new Date(row.created_at).toISOString(), + member_ids: row.member_ids, + }; +} + +@Injectable() +export class ChatsRepository { + constructor(private readonly database: DatabaseClient) {} + + async create(title: string, memberIds: string[]): Promise { + const id = randomUUID(); + return this.database.withTransaction(async (client) => { + const users = await client.query<{ id: string }>({ + name: 'chats.validateMembers', + text: 'SELECT id FROM users WHERE id = ANY($1::uuid[])', + values: [memberIds], + }); + if (users.rowCount !== memberIds.length) + throw new BadRequestException('Chat member does not exist'); + const inserted = await client.query({ + name: 'chats.insert', + text: 'INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at', + values: [id, title], + }); + for (const memberId of memberIds) { + await client.query({ + name: 'chats.insertMember', + text: 'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)', + values: [id, memberId], + }); + } + return { + ...toChat({ ...inserted.rows[0], member_ids: memberIds }), + member_ids: memberIds, + }; + }); + } + + async findForUser(id: string, user: User): Promise { + const result = await this.database.query( + 'chats.findForUser', + `SELECT c.id, c.title, c.created_at, + COALESCE(array_agg(cm.user_id ORDER BY cm.user_id) + FILTER (WHERE cm.user_id IS NOT NULL), '{}') AS member_ids + FROM chats c + LEFT JOIN chat_members cm ON cm.chat_id = c.id + WHERE c.id = $1 + AND EXISTS ( + SELECT 1 FROM chat_members own + WHERE own.chat_id = c.id AND own.user_id = $2 + ) + GROUP BY c.id`, + [id, user.id], + ); + return result.rows[0] ? toChat(result.rows[0]) : undefined; + } + + async findPageForUser( + user: User, + limit: number, + cursor?: Cursor, + ): Promise<{ items: Chat[]; hasMore: boolean }> { + const values: unknown[] = [user.id]; + let predicate = ''; + if (cursor) { + values.push(cursor.created_at, cursor.id); + predicate = + 'AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)'; + } + values.push(limit + 1); + const result = await this.database.query( + 'chats.listForUser', + `SELECT c.id, c.title, c.created_at, + COALESCE(array_agg(cm.user_id ORDER BY cm.user_id) + FILTER (WHERE cm.user_id IS NOT NULL), '{}') AS member_ids + FROM chats c + LEFT JOIN chat_members cm ON cm.chat_id = c.id + WHERE EXISTS ( + SELECT 1 FROM chat_members own + WHERE own.chat_id = c.id AND own.user_id = $1 + ) + ${predicate} + GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $${values.length}`, + values, + ); + return { + items: result.rows.slice(0, limit).map(toChat), + hasMore: result.rows.length > limit, + }; + } +} diff --git a/app/src/chats/chats.service.ts b/app/src/chats/chats.service.ts new file mode 100644 index 0000000..2a78c65 --- /dev/null +++ b/app/src/chats/chats.service.ts @@ -0,0 +1,61 @@ +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { encodeCursor, decodeCursor } from '../common/http/cursor.js'; +import type { Page } from '../common/http/page.js'; +import type { User } from '../users/user.js'; +import type { CreateChatDto } from './dto/create-chat.dto.js'; +import type { Chat } from './chat.js'; +import { ChatsRepository } from './chats.repository.js'; + +@Injectable() +export class ChatsService { + constructor(private readonly chatsRepository: ChatsRepository) {} + + create(input: CreateChatDto, currentUser: User): Promise { + if (!input.member_ids.includes(currentUser.id)) + throw new BadRequestException('Current user must be a chat member'); + if (new Set(input.member_ids).size !== input.member_ids.length) + throw new BadRequestException('Duplicate chat member'); + return this.chatsRepository.create(input.title, input.member_ids); + } + + async getForUser(chatId: string, currentUser: User): Promise { + const chat = await this.chatsRepository.findForUser( + chatId, + currentUser, + ); + if (!chat) throw new NotFoundException(); + return chat; + } + + async listForUser( + currentUser: User, + limit: number, + cursorValue?: string, + ): Promise> { + const scope = `chats:${currentUser.id}`; + const cursor = cursorValue + ? decodeCursor(cursorValue, scope) + : undefined; + const page = await this.chatsRepository.findPageForUser( + currentUser, + limit, + cursor, + ); + const last = page.items.at(-1); + return { + items: page.items, + next_cursor: + page.hasMore && last + ? encodeCursor({ + scope, + created_at: last.created_at, + id: last.id, + }) + : null, + }; + } +} diff --git a/app/src/chats/dto/create-chat.dto.ts b/app/src/chats/dto/create-chat.dto.ts new file mode 100644 index 0000000..37ff853 --- /dev/null +++ b/app/src/chats/dto/create-chat.dto.ts @@ -0,0 +1,26 @@ +import { + ArrayMaxSize, + ArrayMinSize, + ArrayUnique, + IsArray, + IsString, + IsUUID, + Matches, +} from 'class-validator'; +import { CodePointLength } from '../../common/validation/code-point-length.js'; + +export class CreateChatDto { + @IsString() + @CodePointLength(1, 100) + @Matches(/\S/, { + message: 'title must contain a non-whitespace character', + }) + title: string; + + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(100) + @ArrayUnique() + @IsUUID('4', { each: true }) + member_ids: string[]; +} diff --git a/app/src/common/auth/current-user.decorator.ts b/app/src/common/auth/current-user.decorator.ts new file mode 100644 index 0000000..dc05421 --- /dev/null +++ b/app/src/common/auth/current-user.decorator.ts @@ -0,0 +1,10 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import type { User } from '../../users/user.js'; +import { FastifyRequest } from 'fastify'; + +export const CurrentUser = createParamDecorator( + (_data: unknown, context: ExecutionContext): User => { + const request = context.switchToHttp().getRequest(); + return request.currentUser!; + }, +); diff --git a/app/src/common/auth/current-user.guard.ts b/app/src/common/auth/current-user.guard.ts new file mode 100644 index 0000000..ae400b1 --- /dev/null +++ b/app/src/common/auth/current-user.guard.ts @@ -0,0 +1,85 @@ +import { + CanActivate, + ExecutionContext, + Injectable, + ServiceUnavailableException, + UnauthorizedException, +} from '@nestjs/common'; +import type { FastifyRequest } from 'fastify'; +import type { User } from '../../users/user.js'; +import { RedisClient } from '../../redis/redis.client.js'; +import { UsersService } from '../../users/users.service.js'; +import { MetricsService } from '../../metrics/metrics.service.js'; + +@Injectable() +export class CurrentUserGuard implements CanActivate { + constructor( + private readonly redis: RedisClient, + private readonly users: UsersService, + private readonly metrics: MetricsService, + ) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const authorization = request.headers.authorization; + if ( + typeof authorization !== 'string' || + !/^Bearer\s+[^\s]+$/u.test(authorization) + ) { + throw new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="messenger"', + }); + } + let session: string | null; + try { + this.metrics.increment('session_get'); + session = await this.redis.get( + `session:${authorization.slice(7).trim()}`, + ); + } catch { + throw new ServiceUnavailableException('Session store unavailable'); + } + if (!session) + throw new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="messenger"', + }); + let userId: string; + try { + const parsed: unknown = JSON.parse(session); + if ( + typeof parsed !== 'object' || + parsed === null || + !('user_id' in parsed) || + typeof parsed.user_id !== 'string' || + !('expires_at' in parsed) || + typeof parsed.expires_at !== 'string' || + !/^(?:\d{4})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u.test( + parsed.expires_at, + ) + ) + throw new Error('invalid session'); + const expiresAt = Date.parse(parsed.expires_at); + if (!Number.isFinite(expiresAt) || Date.now() >= expiresAt) + throw new Error('expired session'); + userId = parsed.user_id; + } catch { + throw new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="messenger"', + }); + } + let user: User | undefined; + try { + user = await this.users.findById(userId); + } catch { + throw new ServiceUnavailableException( + 'Authentication service unavailable', + ); + } + if (!user) throw new UnauthorizedException(); + request.currentUser = user; + return true; + } +} diff --git a/app/src/common/errors/api-error.ts b/app/src/common/errors/api-error.ts new file mode 100644 index 0000000..b26ece9 --- /dev/null +++ b/app/src/common/errors/api-error.ts @@ -0,0 +1,7 @@ +export type ApiErrorBody = { + error: { + code: string; + message: string; + request_id: string; + }; +}; diff --git a/app/src/common/errors/api-exception.filter.ts b/app/src/common/errors/api-exception.filter.ts new file mode 100644 index 0000000..303e4d4 --- /dev/null +++ b/app/src/common/errors/api-exception.filter.ts @@ -0,0 +1,196 @@ +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + HttpStatus, + Logger, +} from '@nestjs/common'; +import { HttpAdapterHost } from '@nestjs/core'; +import { ConfigService } from '@nestjs/config'; +import { randomUUID } from 'node:crypto'; +import { trace } from '@opentelemetry/api'; +import type { AppConfig } from '../../config/app-config.schema.js'; +import { resolveInstanceId } from '../../config/instance-id.js'; +import { routeTemplate } from '../../telemetry/http.js'; +import { errorType } from '../../telemetry/tracing.js'; +import type { ApiErrorBody } from './api-error.js'; + +type RequestWithId = { + requestId?: string; + method?: string; + url?: string; + // Fastify route template: logs must not carry raw URLs (they hold ids). + routeOptions?: { url?: string }; +}; +type ExceptionBody = { + message?: unknown; + challenge?: unknown; + retryAfter?: unknown; +}; + +// Connection/session loss codes reported by node-postgres and the network layer. +const UNAVAILABLE_ERROR_CODES: Record = { + ECONNREFUSED: true, + ECONNRESET: true, + ENOTFOUND: true, + // Resolver timeout for a stopped dependency (compose sets dns_opt timeout:1). + EAI_AGAIN: true, + ETIMEDOUT: true, + EPIPE: true, + '08000': true, + '08001': true, + '08003': true, + '08004': true, + '08006': true, + '57P01': true, + '57P02': true, + '57P03': true, + '53300': true, + // Transient aborts: the statement was cancelled by statement_timeout, the + // transaction was rolled back by a serialization failure or a deadlock. The + // work was never confirmed, so callers see a retryable 503 instead of an + // internal error. Without this, such an abort would be recorded as the final + // result of an idempotent operation. + '57014': true, + '40001': true, + '40P01': true, +}; + +// Some driver failures carry no `code` at all: node-postgres raises plain errors +// when a connection dies or its pool attempt times out, and node-redis reports a +// closed socket the same way. Without these patterns a stopped database would +// surface as an internal fault instead of a bounded outage. +const UNAVAILABLE_ERROR_MESSAGES = [ + 'Connection terminated unexpectedly', + 'Connection terminated due to connection timeout', + 'timeout exceeded when trying to connect', + 'Client has encountered a connection error and is not queryable', + 'Socket closed unexpectedly', + 'Connection is closed', +]; + +function isDependencyOutage(exception: unknown): boolean { + if (typeof exception !== 'object' || exception === null) return false; + const code = (exception as { code?: unknown }).code; + if (typeof code === 'string' && UNAVAILABLE_ERROR_CODES[code] === true) + return true; + const message = (exception as { message?: unknown }).message; + return ( + typeof message === 'string' && + UNAVAILABLE_ERROR_MESSAGES.some((pattern) => message.includes(pattern)) + ); +} + +function errorCodeForStatus(status: number): string { + const codes: Record = { + [HttpStatus.BAD_REQUEST]: 'invalid_request', + [HttpStatus.UNAUTHORIZED]: 'unauthorized', + [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', + }; + return codes[status] ?? 'internal_error'; +} + +@Catch() +export class ApiExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(ApiExceptionFilter.name); + // Guards and pipes run before interceptors, so an error response may be the + // first thing the filter writes: it must carry the replica identity too. + private readonly instanceId: string; + + constructor( + private readonly adapterHost: HttpAdapterHost, + config: ConfigService, + ) { + this.instanceId = resolveInstanceId(config); + } + + catch(exception: unknown, host: ArgumentsHost): void { + const http = host.switchToHttp(); + const request = http.getRequest(); + const response = http.getResponse(); + const adapter = this.adapterHost.httpAdapter; + const requestId = request.requestId ?? randomUUID(); + request.requestId = requestId; + + let status = HttpStatus.INTERNAL_SERVER_ERROR; + let message = 'Internal server error'; + let challenge: string | undefined; + let retryAfter = 1; + if (exception instanceof HttpException) { + status = exception.getStatus(); + const body = exception.getResponse(); + const details: ExceptionBody = + typeof body === 'object' && body !== null + ? (body as ExceptionBody) + : {}; + const rawMessage = + 'message' in details ? details.message : undefined; + challenge = + typeof details.challenge === 'string' + ? details.challenge + : undefined; + if ( + typeof details.retryAfter === 'number' && + Number.isFinite(details.retryAfter) && + details.retryAfter >= 1 + ) + retryAfter = Math.ceil(details.retryAfter); + message = Array.isArray(rawMessage) + ? rawMessage.join('; ') + : typeof rawMessage === 'string' + ? rawMessage + : 'Request failed'; + if (status === HttpStatus.NOT_FOUND) message = 'Resource not found'; + if (status >= HttpStatus.INTERNAL_SERVER_ERROR) + message = + status === HttpStatus.SERVICE_UNAVAILABLE + ? 'Service unavailable' + : 'Internal server error'; + } else if (isDependencyOutage(exception)) { + // A dropped dependency is a bounded outage, not an internal fault. + status = HttpStatus.SERVICE_UNAVAILABLE; + message = 'Service unavailable'; + this.logger.warn( + `Dependency outage on ${request.method ?? ''} ${routeTemplate(request.routeOptions?.url)}: ${exception instanceof Error ? exception.message : 'unknown error'}`, + ); + } else { + this.logger.error( + `Unhandled exception on ${request.method ?? ''} ${routeTemplate(request.routeOptions?.url)}`, + exception instanceof Error + ? exception.stack + : String(exception), + ); + } + if (status === HttpStatus.UNAUTHORIZED) { + const authChallenge = + challenge ?? + (request.method === 'POST' && + request.url?.startsWith('/api/v1/auth/sessions') + ? 'Basic realm="messenger", charset="UTF-8"' + : 'Bearer realm="messenger"'); + adapter.setHeader(response, 'WWW-Authenticate', authChallenge); + } + if (status === HttpStatus.TOO_MANY_REQUESTS) + adapter.setHeader(response, 'Retry-After', String(retryAfter)); + adapter.setHeader(response, 'X-Request-Id', requestId); + adapter.setHeader(response, 'X-Instance-Id', this.instanceId); + const payload: ApiErrorBody = { + error: { + code: errorCodeForStatus(status), + message, + request_id: requestId, + }, + }; + if (status >= HttpStatus.INTERNAL_SERVER_ERROR) + trace + .getActiveSpan() + ?.setAttribute('error.type', errorType(exception)); + adapter.reply(response, payload, status); + } +} diff --git a/app/src/common/http/cursor.spec.ts b/app/src/common/http/cursor.spec.ts new file mode 100644 index 0000000..f4e7823 --- /dev/null +++ b/app/src/common/http/cursor.spec.ts @@ -0,0 +1,85 @@ +import { BadRequestException } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { decodeCursor, encodeCursor } from './cursor.js'; + +const scope = 'messages:6f1c2a3e-1111-4222-8333-444455556666'; + +function encode(createdAt: string, cursorScope = scope): string { + return encodeCursor({ + scope: cursorScope, + created_at: createdAt, + id: randomUUID(), + }); +} + +describe('decodeCursor', () => { + it('accepts valid instants and normalizes them to canonical milliseconds', () => { + const accepted: Array<[string, string]> = [ + ['2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'], + ['2026-01-01T00:00:00Z', '2026-01-01T00:00:00.000Z'], + ['2026-01-01T00:00:00.999999Z', '2026-01-01T00:00:00.999Z'], + ['2024-02-29T23:59:59.000Z', '2024-02-29T23:59:59.000Z'], + ['2026-12-31T23:59:59.999Z', '2026-12-31T23:59:59.999Z'], + ]; + for (const [createdAt, expected] of accepted) { + const decoded = decodeCursor(encode(createdAt), scope); + expect(decoded.created_at).toBe(expected); + expect(decoded.scope).toBe(scope); + } + }); + + it('rejects calendar dates that the platform parser rolls over', () => { + // 2026-02-31 would silently become 2026-03-03 and then fail inside SQL. + for (const createdAt of [ + '2026-02-31T00:00:00.000Z', + '2025-02-29T00:00:00.000Z', + '2026-04-31T00:00:00.000Z', + '2026-06-31T12:00:00.000Z', + ]) { + expect(() => decodeCursor(encode(createdAt), scope)).toThrow( + BadRequestException, + ); + } + }); + + it('rejects out-of-range and malformed timestamps', () => { + for (const createdAt of [ + '2026-01-01T24:00:00.000Z', + '2026-01-01T00:00:60.000Z', + '2026-13-01T00:00:00.000Z', + '2026-00-01T00:00:00.000Z', + '2026-01-01T00:00:00', + '2026-01-01T00:00:00+02:00', + '2026-1-1T00:00:00.000Z', + '2026-01-01', + 'not-a-timestamp', + ]) { + expect(() => decodeCursor(encode(createdAt), scope)).toThrow( + BadRequestException, + ); + } + }); + + it('rejects a cursor from another scope, a malformed id, and non-cursor input', () => { + expect(() => + decodeCursor( + encode('2026-01-01T00:00:00.000Z', 'messages:other'), + scope, + ), + ).toThrow(BadRequestException); + expect(() => + decodeCursor( + encodeCursor({ + scope, + created_at: '2026-01-01T00:00:00.000Z', + id: 'not-a-uuid', + }), + scope, + ), + ).toThrow(BadRequestException); + expect(() => decodeCursor('not-a-cursor', scope)).toThrow( + BadRequestException, + ); + }); +}); diff --git a/app/src/common/http/cursor.ts b/app/src/common/http/cursor.ts new file mode 100644 index 0000000..037d4a4 --- /dev/null +++ b/app/src/common/http/cursor.ts @@ -0,0 +1,54 @@ +import { BadRequestException } from '@nestjs/common'; +import { isValid, parseISO } from 'date-fns'; + +export type Cursor = { + scope: string; + created_at: string; + id: string; +}; + +// Format check for the canonical API shape: `Date.prototype.toISOString()` with +// optional fractional seconds. Explicit ranges reject values such as 24:00:00. +// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by +// date-fns `parseISO`, which refuses impossible dates that the platform parser +// would silently roll over into another day. +const CURSOR_TIMESTAMP = + /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z$/u; + +export function encodeCursor(cursor: Cursor): string { + return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url'); +} + +export function decodeCursor(value: string, expectedScope: string): Cursor { + try { + const parsed: unknown = JSON.parse( + Buffer.from(value, 'base64url').toString('utf8'), + ); + if ( + typeof parsed !== 'object' || + parsed === null || + !('scope' in parsed) || + !('created_at' in parsed) || + !('id' in parsed) || + typeof parsed.scope !== 'string' || + typeof parsed.created_at !== 'string' || + typeof parsed.id !== 'string' || + parsed.scope !== expectedScope || + !/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test( + parsed.id, + ) || + !CURSOR_TIMESTAMP.test(parsed.created_at) + ) + throw new Error('invalid cursor'); + const instant = parseISO(parsed.created_at); + if (!isValid(instant)) throw new Error('invalid cursor'); + + return { + scope: parsed.scope, + created_at: instant.toISOString(), + id: parsed.id, + }; + } catch { + throw new BadRequestException('Invalid cursor'); + } +} diff --git a/app/src/common/http/page.ts b/app/src/common/http/page.ts new file mode 100644 index 0000000..55c9ff8 --- /dev/null +++ b/app/src/common/http/page.ts @@ -0,0 +1,4 @@ +export type Page = { + items: T[]; + next_cursor: string | null; +}; diff --git a/app/src/common/http/request-id.interceptor.ts b/app/src/common/http/request-id.interceptor.ts new file mode 100644 index 0000000..e1ed4d8 --- /dev/null +++ b/app/src/common/http/request-id.interceptor.ts @@ -0,0 +1,59 @@ +import { + CallHandler, + ExecutionContext, + Injectable, + NestInterceptor, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { HttpAdapterHost } from '@nestjs/core'; +import { randomUUID } from 'node:crypto'; +import { finalize, Observable } from 'rxjs'; +import type { AppConfig } from '../../config/app-config.schema.js'; +import { resolveInstanceId } from '../../config/instance-id.js'; +import { MetricsService } from '../../metrics/metrics.service.js'; + +type RequestWithId = { requestId?: string }; + +@Injectable() +export class RequestIdInterceptor implements NestInterceptor { + // Resolved once: the identity must be stable for the whole process lifetime, + // otherwise a client cannot tell whether it moved to another replica. + private readonly instanceId: string; + + constructor( + private readonly adapterHost: HttpAdapterHost, + private readonly metrics: MetricsService, + config: ConfigService, + ) { + this.instanceId = resolveInstanceId(config); + } + + intercept( + context: ExecutionContext, + next: CallHandler, + ): Observable { + const request = context.switchToHttp().getRequest(); + const response = context.switchToHttp().getResponse(); + const requestId = randomUUID(); + const startedAt = performance.now(); + request.requestId = requestId; + this.adapterHost.httpAdapter.setHeader( + response, + 'X-Request-Id', + requestId, + ); + this.adapterHost.httpAdapter.setHeader( + response, + 'X-Instance-Id', + this.instanceId, + ); + this.metrics.increment('request_count'); + return next + .handle() + .pipe( + finalize(() => + this.metrics.observeLatency(performance.now() - startedAt), + ), + ); + } +} diff --git a/app/src/common/validation/code-point-length.spec.ts b/app/src/common/validation/code-point-length.spec.ts new file mode 100644 index 0000000..2daa830 --- /dev/null +++ b/app/src/common/validation/code-point-length.spec.ts @@ -0,0 +1,43 @@ +import { validate } from 'class-validator'; +import { describe, expect, it } from 'vitest'; +import { CodePointLength } from './code-point-length.js'; + +class Sample { + @CodePointLength(3, 5) + value!: string; +} + +async function fails(value: unknown): Promise { + const sample = new Sample(); + (sample as { value: unknown }).value = value; + const errors = await validate(sample); + return errors.length > 0; +} + +describe('CodePointLength', () => { + it('counts Unicode code points instead of UTF-16 units', async () => { + // '🔐' is one code point but two UTF-16 units. + expect(await fails('🔐🔐')).toBe(true); + expect(await fails('🔐🔐🔐')).toBe(false); + expect(await fails('🔐🔐🔐🔐🔐')).toBe(false); + expect(await fails('🔐🔐🔐🔐🔐🔐')).toBe(true); + // Combining marks are separate code points, not grapheme clusters: + // three 'é' sequences are six code points and exceed the maximum. + expect(await fails('e\u0301e\u0301')).toBe(false); + expect(await fails('e\u0301e\u0301e\u0301')).toBe(true); + }); + + it('applies to BMP text boundaries', async () => { + expect(await fails('ab')).toBe(true); + expect(await fails('abc')).toBe(false); + expect(await fails('abcde')).toBe(false); + expect(await fails('abcdef')).toBe(true); + }); + + it('rejects empty and non-string values', async () => { + expect(await fails('')).toBe(true); + expect(await fails(undefined)).toBe(true); + expect(await fails(12345)).toBe(true); + expect(await fails(['a', 'b', 'c'])).toBe(true); + }); +}); diff --git a/app/src/common/validation/code-point-length.ts b/app/src/common/validation/code-point-length.ts new file mode 100644 index 0000000..5b3fa3a --- /dev/null +++ b/app/src/common/validation/code-point-length.ts @@ -0,0 +1,38 @@ +import { + registerDecorator, + ValidatorConstraint, + type ValidationArguments, + type ValidatorConstraintInterface, +} from 'class-validator'; + +// JSON Schema (and the course contract) measure string lengths in Unicode code +// points, while String.prototype.length counts UTF-16 units: one emoji outside +// the BMP is two units. `@Length` therefore accepted an 11-emoji password +// (22 units) and rejected 4000 emoji (8000 units), so these fields use an +// explicit code-point validator instead. +@ValidatorConstraint({ name: 'codePointLength', async: false }) +class CodePointLengthConstraint implements ValidatorConstraintInterface { + validate(value: unknown, args: ValidationArguments): boolean { + const [min, max] = args.constraints as [number, number]; + if (typeof value !== 'string') return false; + const length = [...value].length; + return length >= min && length <= max; + } + + defaultMessage(args: ValidationArguments): string { + const [min, max] = args.constraints as [number, number]; + return `${args.property} must be between ${min} and ${max} code points`; + } +} + +export function CodePointLength(min: number, max: number): PropertyDecorator { + return (target, propertyKey) => { + registerDecorator({ + name: 'codePointLength', + target: target.constructor, + propertyName: String(propertyKey), + constraints: [min, max], + validator: CodePointLengthConstraint, + }); + }; +} diff --git a/app/src/config/app-config.module.ts b/app/src/config/app-config.module.ts new file mode 100644 index 0000000..567ea6a --- /dev/null +++ b/app/src/config/app-config.module.ts @@ -0,0 +1,16 @@ +import { Global, Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { parseAppConfig } from './app-config.schema.js'; + +@Global() +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + cache: true, + validate: parseAppConfig, + }), + ], + exports: [ConfigModule], +}) +export class AppConfigModule {} diff --git a/app/src/config/app-config.schema.ts b/app/src/config/app-config.schema.ts new file mode 100644 index 0000000..4e0949c --- /dev/null +++ b/app/src/config/app-config.schema.ts @@ -0,0 +1,263 @@ +import { readFileSync } from 'node:fs'; +import { z } from 'zod'; + +function numeric( + name: string, + minimum: number, + maximum: number | undefined, + fallback: number, +) { + let schema = z + .number({ message: `${name} must be a number` }) + .int() + .min(minimum); + if (maximum !== undefined) schema = schema.max(maximum); + return z.preprocess( + (value) => + typeof value === 'string' && value.trim() !== '' + ? Number(value) + : value, + schema.default(fallback), + ); +} + +function requiredString(name: string) { + return z + .string({ message: `${name} is required` }) + .min(1, `${name} is required`); +} + +export const appConfigSchema = z + .object({ + APP_HOST: z.string().min(1).default('0.0.0.0'), + APP_PORT: numeric('APP_PORT', 1, 65535, 8080), + APP_ENV: z.string().min(1).default('lab'), + SESSION_TTL_SECONDS: numeric('SESSION_TTL_SECONDS', 2, undefined, 3600), + DATABASE_URL: requiredString('DATABASE_URL'), + REDIS_URL: requiredString('REDIS_URL'), + BROKER_URL: requiredString('BROKER_URL'), + BROKER_PUBLISH_TIMEOUT_MS: numeric( + 'BROKER_PUBLISH_TIMEOUT_MS', + 100, + 60000, + 5000, + ), + DATABASE_POOL_MAX: numeric('DATABASE_POOL_MAX', 1, 100, 10), + DATABASE_CONNECTION_TIMEOUT_MS: numeric( + 'DATABASE_CONNECTION_TIMEOUT_MS', + 1, + undefined, + 5000, + ), + DATABASE_STATEMENT_TIMEOUT_MS: numeric( + 'DATABASE_STATEMENT_TIMEOUT_MS', + 1, + undefined, + 5000, + ), + DATABASE_IDLE_TX_TIMEOUT_MS: numeric( + 'DATABASE_IDLE_TX_TIMEOUT_MS', + 1000, + undefined, + 30000, + ), + // Бюджет зависимостей в /health/ready: LB проверяет ту же ручку, поэтому + // проба готовности обязана уложиться в timeout check HAProxy (500 ms). + HEALTH_TIMEOUT_MS: numeric('HEALTH_TIMEOUT_MS', 1, undefined, 400), + CACHE_TTL_SECONDS: numeric('CACHE_TTL_SECONDS', 1, undefined, 30), + CACHE_MODE: z.enum(['protected', 'naive']).default('protected'), + CACHE_LOCK_TTL_MS: numeric('CACHE_LOCK_TTL_MS', 1, undefined, 1000), + CACHE_MISS_DELAY_MS: numeric('CACHE_MISS_DELAY_MS', 0, undefined, 0), + METRICS_TOKEN: z.string().min(1).optional(), + DRAIN_DELAY_MS: numeric('DRAIN_DELAY_MS', 0, undefined, 5000), + INSTANCE_ID: z.string().min(1).optional(), + IDEMPOTENCY_TTL_SECONDS: numeric( + 'IDEMPOTENCY_TTL_SECONDS', + 60, + undefined, + 86400, + ), + S3_ENDPOINT: requiredString('S3_ENDPOINT'), + S3_PUBLIC_ENDPOINT: requiredString('S3_PUBLIC_ENDPOINT'), + S3_REGION: z.string().min(1).default('us-east-1'), + S3_BUCKET: requiredString('S3_BUCKET'), + S3_ACCESS_KEY_ID: requiredString('S3_ACCESS_KEY_ID'), + S3_SECRET_ACCESS_KEY: requiredString('S3_SECRET_ACCESS_KEY'), + S3_CONNECT_TIMEOUT_MS: numeric( + 'S3_CONNECT_TIMEOUT_MS', + 1, + undefined, + 1000, + ), + S3_REQUEST_TIMEOUT_MS: numeric( + 'S3_REQUEST_TIMEOUT_MS', + 1, + undefined, + 15000, + ), + MAX_UPLOAD_BYTES: numeric('MAX_UPLOAD_BYTES', 1, 10485760, 10485760), + MAX_IMAGE_PIXELS: numeric('MAX_IMAGE_PIXELS', 1, 40000000, 40000000), + UPLOAD_TIMEOUT_MS: numeric('UPLOAD_TIMEOUT_MS', 1000, undefined, 25000), + UPLOAD_MAX_IN_FLIGHT: numeric('UPLOAD_MAX_IN_FLIGHT', 1, 1024, 16), + UPLOAD_MAX_IN_FLIGHT_PER_USER: numeric( + 'UPLOAD_MAX_IN_FLIGHT_PER_USER', + 1, + 1024, + 4, + ), + IMAGE_DECODE_MAX_CONCURRENT: numeric( + 'IMAGE_DECODE_MAX_CONCURRENT', + 1, + 64, + 1, + ), + // 0 отключает фоновый проход уборщика (остаётся ручной CLI). + ATTACHMENT_SWEEP_INTERVAL_MS: numeric( + 'ATTACHMENT_SWEEP_INTERVAL_MS', + 0, + undefined, + 60000, + ), + ATTACHMENT_SWEEP_GRACE_SECONDS: numeric( + 'ATTACHMENT_SWEEP_GRACE_SECONDS', + 0, + undefined, + 900, + ), + DIRECT_UPLOAD_URL_TTL_SECONDS: numeric( + 'DIRECT_UPLOAD_URL_TTL_SECONDS', + 1, + 3600, + 300, + ), + DIRECT_UPLOAD_MAX_PENDING_PER_USER: numeric( + 'DIRECT_UPLOAD_MAX_PENDING_PER_USER', + 1, + 1000, + 10, + ), + WORKER_CONCURRENCY: numeric('WORKER_CONCURRENCY', 1, 16, 2), + JOB_MAX_ATTEMPTS: numeric('JOB_MAX_ATTEMPTS', 1, 20, 5), + JOB_TIMEOUT_SECONDS: numeric('JOB_TIMEOUT_SECONDS', 1, 600, 60), + JOB_LEASE_SECONDS: numeric('JOB_LEASE_SECONDS', 3, 600, 30), + JOB_RETRY_BASE_MS: numeric('JOB_RETRY_BASE_MS', 10, undefined, 1000), + JOB_RETRY_MAX_MS: numeric('JOB_RETRY_MAX_MS', 10, undefined, 30000), + PIPELINE_VERSION: numeric('PIPELINE_VERSION', 1, 2, 1), + BROKER_DELIVERY_LIMIT: numeric('BROKER_DELIVERY_LIMIT', 1, 100, 10), + OUTBOX_POLL_INTERVAL_MS: numeric( + 'OUTBOX_POLL_INTERVAL_MS', + 50, + undefined, + 500, + ), + LEASE_REAPER_INTERVAL_MS: numeric( + 'LEASE_REAPER_INTERVAL_MS', + 100, + undefined, + 2000, + ), + // 0 отключает фоновую уборку staging (ручной запуск остаётся). + STAGING_CLEANUP_INTERVAL_MS: numeric( + 'STAGING_CLEANUP_INTERVAL_MS', + 0, + undefined, + 60000, + ), + STAGING_RETENTION_SECONDS: numeric( + 'STAGING_RETENTION_SECONDS', + 60, + undefined, + 86400, + ), + WORKER_HEALTH_PORT: numeric('WORKER_HEALTH_PORT', 1, 65535, 8081), + // lab6: как часто API пересчитывает глубину и возраст очереди задач для + // метрик messenger.jobs.queue.* (один дешёвый агрегат по частичным индексам). + QUEUE_STATS_INTERVAL_MS: numeric( + 'QUEUE_STATS_INTERVAL_MS', + 1000, + 600000, + 10000, + ), + FAULT_INJECTION_ENABLED: numeric('FAULT_INJECTION_ENABLED', 0, 1, 0), + QUEUED_RECONCILE_GRACE_SECONDS: numeric( + 'QUEUED_RECONCILE_GRACE_SECONDS', + 5, + 3600, + 15, + ), + OUTBOX_RETENTION_SECONDS: numeric( + 'OUTBOX_RETENTION_SECONDS', + 60, + undefined, + 86400, + ), + JOB_EVENTS_RETENTION_SECONDS: numeric( + 'JOB_EVENTS_RETENTION_SECONDS', + 3600, + undefined, + 2592000, + ), + }) + .strip(); + +export const databaseConfigSchema = appConfigSchema.pick({ + DATABASE_URL: true, + DATABASE_POOL_MAX: true, + DATABASE_CONNECTION_TIMEOUT_MS: true, + DATABASE_STATEMENT_TIMEOUT_MS: true, + DATABASE_IDLE_TX_TIMEOUT_MS: true, + HEALTH_TIMEOUT_MS: true, + IDEMPOTENCY_TTL_SECONDS: true, +}); +export type DatabaseConfig = z.infer; + +export type AppConfig = z.infer; +export type AppConfigKey = keyof AppConfig; + +function resolveSecret( + raw: Record, + key: + | 'DATABASE_URL' + | 'REDIS_URL' + | 'BROKER_URL' + | 'S3_ACCESS_KEY_ID' + | 'S3_SECRET_ACCESS_KEY', +): unknown { + const fileKey = `${key}_FILE`; + const path = raw[fileKey]; + if (typeof path !== 'string' || path.length === 0) return raw[key]; + try { + const value = readFileSync(path, 'utf8').trim(); + if (value.length === 0) + throw new Error(`${fileKey} contains an empty value`); + return value; + } catch (error) { + if ( + error instanceof Error && + error.message.includes('contains an empty value') + ) + throw error; + throw new Error(`${fileKey} could not be read`); + } +} + +export function parseAppConfig(raw: Record): AppConfig { + return appConfigSchema.parse({ + ...raw, + DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'), + REDIS_URL: resolveSecret(raw, 'REDIS_URL'), + BROKER_URL: resolveSecret(raw, 'BROKER_URL'), + S3_ACCESS_KEY_ID: resolveSecret(raw, 'S3_ACCESS_KEY_ID'), + S3_SECRET_ACCESS_KEY: resolveSecret(raw, 'S3_SECRET_ACCESS_KEY'), + }); +} + +// Для процессов, которым нужна только БД (миграции, GC идемпотентности). +export function parseDatabaseConfig( + raw: Record, +): DatabaseConfig { + return databaseConfigSchema.parse({ + ...raw, + DATABASE_URL: resolveSecret(raw, 'DATABASE_URL'), + }); +} diff --git a/app/src/config/instance-id.ts b/app/src/config/instance-id.ts new file mode 100644 index 0000000..e42f2f4 --- /dev/null +++ b/app/src/config/instance-id.ts @@ -0,0 +1,14 @@ +import { randomUUID } from 'node:crypto'; +import { hostname } from 'node:os'; +import type { ConfigService } from '@nestjs/config'; +import type { AppConfig } from './app-config.schema.js'; + +// A replica must be identifiable from the outside. Inside Docker the hostname is +// the short container ID, so X-Instance-Id can be mapped back to exactly one +// container; INSTANCE_ID exists for platforms where that mapping is not useful. +export function resolveInstanceId(config: ConfigService): string { + const configured = config.get('INSTANCE_ID'); + if (configured) return configured; + const host = hostname(); + return host.length > 0 ? host : randomUUID(); +} diff --git a/app/src/database/database.client.ts b/app/src/database/database.client.ts new file mode 100644 index 0000000..9238cc9 --- /dev/null +++ b/app/src/database/database.client.ts @@ -0,0 +1,325 @@ +import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { SpanKind, type Attributes, type Span } from '@opentelemetry/api'; +import pg from 'pg'; +import { MetricsService } from '../metrics/metrics.service.js'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { instruments, meter } from '../telemetry/instruments.js'; +import { errorType, withChildSpan } from '../telemetry/tracing.js'; + +const DB_SYSTEM = 'postgresql'; +const POOL_NAME = 'main'; +const TRANSACTION_CONTROL = + /^\s*(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/iu; +const SQL_TARGET = + /\b(?:FROM|INTO|UPDATE|JOIN)\s+"?([A-Za-z_][A-Za-z0-9_]*)"?/iu; + +/** First SQL keyword (SELECT, INSERT, WITH, …): a bounded attribute. */ +function sqlOperation(text: string): string { + const match = /^\s*([A-Za-z]+)/u.exec(text); + return match ? match[1].toUpperCase() : 'OTHER'; +} + +/** Best-effort table name for span names; never used as a metric label. */ +function sqlTarget(text: string): string | undefined { + return SQL_TARGET.exec(text)?.[1]?.toLowerCase(); +} + +function queryText(args: readonly unknown[]): string { + const first = args[0]; + if (typeof first === 'string') return first; + if (typeof first === 'object' && first !== null) { + const text = (first as { text?: unknown }).text; + if (typeof text === 'string') return text; + } + return ''; +} + +function isPassThrough(args: readonly unknown[]): boolean { + const first = args[0]; + return ( + typeof args[args.length - 1] === 'function' || + (typeof first === 'object' && + first !== null && + typeof (first as { submit?: unknown }).submit === 'function') + ); +} + +function elapsedSeconds(started: bigint): number { + return Number(process.hrtime.bigint() - started) / 1e9; +} + +function statementAttributes( + label: string, + operation: string, + target: string | undefined, +): Attributes { + return { + 'db.system.name': DB_SYSTEM, + 'db.operation.name': operation, + 'db.query.summary': label, + ...(target ? { 'db.collection.name': target } : {}), + }; +} + +/** + * Inside a traced transaction every statement gets its own CLIENT span + * (`UPDATE attachment_jobs`, `INSERT job_outbox`, …) while repository code + * stays unaware of tracing. Transaction control, callback-style calls and + * submittables (cursors, streams) pass through untouched. SQL text and + * parameter values are never recorded. + */ +function tracedClient(client: pg.PoolClient, label: string): pg.PoolClient { + return new Proxy(client, { + get(target, property) { + const value: unknown = Reflect.get(target, property, target); + if (typeof value !== 'function') return value; + const method = value as (...args: unknown[]) => unknown; + if (property !== 'query') return method.bind(target); + return (...args: unknown[]): unknown => { + const text = queryText(args); + if (isPassThrough(args) || TRANSACTION_CONTROL.test(text)) + return method.apply(target, args); + const operation = sqlOperation(text); + const table = sqlTarget(text); + return withChildSpan( + `${operation} ${table ?? label}`, + SpanKind.CLIENT, + statementAttributes(label, operation, table), + async () => method.apply(target, args), + ); + }; + }, + }); +} + +@Injectable() +export class DatabaseClient implements OnModuleDestroy { + readonly pool: pg.Pool; + private readonly healthPool: pg.Pool; + private readonly logger = new Logger(DatabaseClient.name); + + constructor( + private readonly config: ConfigService, + private readonly metrics: MetricsService, + ) { + this.pool = new pg.Pool({ + connectionString: this.config.getOrThrow('DATABASE_URL'), + max: this.config.getOrThrow('DATABASE_POOL_MAX'), + connectionTimeoutMillis: this.config.getOrThrow( + 'DATABASE_CONNECTION_TIMEOUT_MS', + ), + statement_timeout: this.config.getOrThrow( + 'DATABASE_STATEMENT_TIMEOUT_MS', + ), + // A relay that waits on the broker must not leave the transaction + // idle forever if confirm handling stalls. + options: `-c idle_in_transaction_session_timeout=${this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS')}`, + }); + // Idle clients emit 'error' on the pool when the database drops; without a + // listener Node treats it as uncaught and terminates the process. + this.pool.on('error', (error: Error) => { + this.metrics.increment('database.pool_error'); + this.logger.warn(`PostgreSQL pool error: ${error.message}`); + }); + // Проба готовности не должна стоять в очереди за бизнес-запросами: занятый + // общий пул — это перегрузка, а не потеря зависимости. + this.healthPool = new pg.Pool({ + connectionString: this.config.getOrThrow('DATABASE_URL'), + max: 1, + idleTimeoutMillis: 0, + connectionTimeoutMillis: + this.config.getOrThrow('HEALTH_TIMEOUT_MS'), + query_timeout: this.config.getOrThrow('HEALTH_TIMEOUT_MS'), + }); + this.healthPool.on('error', (error: Error) => { + this.metrics.increment('database.health_pool_error'); + this.logger.warn( + `PostgreSQL health connection error: ${error.message}`, + ); + }); + this.observePool(this.config.getOrThrow('DATABASE_POOL_MAX')); + } + + /** + * Same contract as pg.Pool#query — a failed query destroys its connection — + * but the checkout is explicit, so the wait for a pooled connection is + * measured apart from the statement: «the pool is exhausted» and «the + * database is slow» are different incidents with different runbooks. + */ + query( + label: string, + text: string, + values: readonly unknown[] = [], + ): Promise> { + this.metrics.increment(label); + return this.observe( + label, + sqlOperation(text), + sqlTarget(text), + async () => { + const client = await this.checkout(); + let failure: Error | undefined; + const onError = (error: Error): void => { + failure = error; + }; + client.on('error', onError); + try { + return await client.query({ text, values: [...values] }); + } catch (error) { + failure ??= + error instanceof Error ? error : new Error('Query failed'); + throw error; + } finally { + client.removeListener('error', onError); + client.release(failure); + } + }, + ); + } + + async health(): Promise { + this.metrics.increment('health.database'); + await this.healthPool.query('SELECT 1'); + } + + withTransaction( + work: (client: pg.PoolClient) => Promise, + ): Promise { + return this.transaction('transaction', work); + } + + /** + * A labelled transaction: one span for the unit of work with a child span + * per statement and one db.client.operation.duration sample (pool wait + * included) with db.operation.name = TRANSACTION. + */ + transaction( + label: string, + work: (client: pg.PoolClient) => Promise, + ): Promise { + return this.observe(label, 'TRANSACTION', undefined, async (span) => { + const client = await this.checkout(); + // A server-side idle_in_transaction_session_timeout or a network drop + // can emit 'error' on a checked-out client after pg-pool removed its + // idle listener. Without this listener Node treats it as uncaught. + let fatal: Error | undefined; + const onError = (error: Error): void => { + fatal = error; + }; + client.on('error', onError); + try { + await client.query('BEGIN'); + const result = await work( + span ? tracedClient(client, label) : client, + ); + await client.query('COMMIT'); + return result; + } catch (error) { + try { + await client.query('ROLLBACK'); + } catch (rollbackError) { + this.metrics.increment('database.rollback_error'); + this.logger.warn( + `Rollback failed: ${rollbackError instanceof Error ? rollbackError.message : 'unknown error'}`, + ); + } + // Callers must see the operation error, not the rollback error. + throw error; + } finally { + client.removeListener('error', onError); + client.release(fatal); + } + }); + } + + async onModuleDestroy(): Promise { + await Promise.all([this.pool.end(), this.healthPool.end()]); + } + + private observe( + label: string, + operation: string, + target: string | undefined, + work: (span: Span | undefined) => Promise, + ): Promise { + const started = process.hrtime.bigint(); + return withChildSpan( + `${operation} ${target ?? label}`, + SpanKind.CLIENT, + statementAttributes(label, operation, target), + async (span) => { + let failure: string | undefined; + try { + return await work(span); + } catch (error) { + failure = errorType(error); + throw error; + } finally { + instruments().dbOperationDuration.record(elapsedSeconds(started), { + 'db.system.name': DB_SYSTEM, + 'db.operation.name': operation, + 'db.query.summary': label, + ...(failure ? { 'error.type': failure } : {}), + }); + } + }, + ); + } + + private async checkout(): Promise { + const started = process.hrtime.bigint(); + let failure: string | undefined; + try { + return await this.pool.connect(); + } catch (error) { + failure = errorType(error); + throw error; + } finally { + instruments().dbConnectionWait.record(elapsedSeconds(started), { + 'db.client.connection.pool.name': POOL_NAME, + ...(failure ? { 'error.type': failure } : {}), + }); + } + } + + /** Pool saturation: used vs max connections and callers queued for one. */ + private observePool(max: number): void { + const m = meter(); + const pool = { 'db.client.connection.pool.name': POOL_NAME }; + const count = m.createObservableUpDownCounter( + 'db.client.connection.count', + { + unit: '{connection}', + description: 'Connections in the main pool by state', + }, + ); + const limit = m.createObservableUpDownCounter('db.client.connection.max', { + unit: '{connection}', + description: 'Maximum size of the main pool (DATABASE_POOL_MAX)', + }); + const pending = m.createObservableUpDownCounter( + 'db.client.connection.pending_requests', + { + unit: '{request}', + description: 'Callers waiting for a connection from the main pool', + }, + ); + m.addBatchObservableCallback( + (result) => { + const idle = this.pool.idleCount; + result.observe(count, this.pool.totalCount - idle, { + ...pool, + 'db.client.connection.state': 'used', + }); + result.observe(count, idle, { + ...pool, + 'db.client.connection.state': 'idle', + }); + result.observe(limit, max, pool); + result.observe(pending, this.pool.waitingCount, pool); + }, + [count, limit, pending], + ); + } +} diff --git a/app/src/database/database.module.ts b/app/src/database/database.module.ts new file mode 100644 index 0000000..fe9f0b7 --- /dev/null +++ b/app/src/database/database.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { DatabaseClient } from './database.client.js'; + +@Module({ + imports: [MetricsModule], + providers: [DatabaseClient], + exports: [DatabaseClient], +}) +export class DatabaseModule {} diff --git a/app/src/database/migration.runner.ts b/app/src/database/migration.runner.ts new file mode 100644 index 0000000..5e101c3 --- /dev/null +++ b/app/src/database/migration.runner.ts @@ -0,0 +1,63 @@ +import { readdir, readFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { DatabaseClient } from './database.client.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { parseDatabaseConfig } from '../config/app-config.schema.js'; + +const migrationsDirectory = join( + dirname(fileURLToPath(import.meta.url)), + 'migrations', +); + +async function migrationFiles(): Promise { + const files = await readdir(migrationsDirectory); + return files.filter((file) => /^\d+_.+\.sql$/u.test(file)).sort(); +} + +export async function runMigrations(database: DatabaseClient): Promise { + await database.query( + 'migrations.ensure_table', + `CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() + )`, + ); + + for (const version of await migrationFiles()) { + await database.withTransaction(async (client) => { + const applied = await client.query({ + text: 'SELECT version FROM schema_migrations WHERE version = $1', + values: [version], + }); + if (applied.rowCount) return; + + const sql = await readFile( + join(migrationsDirectory, version), + 'utf8', + ); + await client.query(sql); + await client.query({ + text: 'INSERT INTO schema_migrations (version) VALUES ($1)', + values: [version], + }); + }); + } +} + +async function main(): Promise { + const config = parseDatabaseConfig(process.env as Record); + const database = new DatabaseClient( + { + getOrThrow: (key: keyof typeof config) => config[key], + } as never, + new MetricsService(), + ); + try { + await runMigrations(database); + } finally { + await database.onModuleDestroy(); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) await main(); diff --git a/app/src/database/migrations/001_initial.sql b/app/src/database/migrations/001_initial.sql new file mode 100644 index 0000000..1922529 --- /dev/null +++ b/app/src/database/migrations/001_initial.sql @@ -0,0 +1,41 @@ +CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + message_version bigint NOT NULL DEFAULT 0 +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE IF NOT EXISTS messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT messages_sender_member_fk + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) + ON DELETE RESTRICT +); + +CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx + ON messages (chat_id, created_at, id); +CREATE INDEX IF NOT EXISTS chat_members_user_chat_idx + ON chat_members (user_id, chat_id); diff --git a/app/src/database/migrations/002_timestamp_precision.sql b/app/src/database/migrations/002_timestamp_precision.sql new file mode 100644 index 0000000..e084dc6 --- /dev/null +++ b/app/src/database/migrations/002_timestamp_precision.sql @@ -0,0 +1,5 @@ +-- HTTP timestamps and keyset cursors use JavaScript millisecond precision. +-- Store the same precision so a returned cursor cannot point before its own row. +ALTER TABLE users ALTER COLUMN created_at TYPE timestamptz(3); +ALTER TABLE chats ALTER COLUMN created_at TYPE timestamptz(3); +ALTER TABLE messages ALTER COLUMN created_at TYPE timestamptz(3); diff --git a/app/src/database/migrations/003_idempotency_keys.sql b/app/src/database/migrations/003_idempotency_keys.sql new file mode 100644 index 0000000..aad214d --- /dev/null +++ b/app/src/database/migrations/003_idempotency_keys.sql @@ -0,0 +1,20 @@ +-- Shared idempotency ledger for POST /api/v1/chats/{id}/messages. +-- The key scope is (user, method, path, key): the same key from another user or +-- another chat is independent, as the contract requires. +-- claim + response are committed in one transaction, so a committed row always +-- carries status_code and response_body (there is no "poisoned" intermediate state). +CREATE TABLE IF NOT EXISTS idempotency_keys ( + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method text NOT NULL, + path text NOT NULL, + key text NOT NULL, + request_fingerprint text NOT NULL, + status_code integer, + response_body jsonb, + message_id uuid, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, method, path, key) +); + +CREATE INDEX IF NOT EXISTS idempotency_keys_created_at_idx + ON idempotency_keys (created_at); diff --git a/app/src/database/migrations/004_pg_stat_statements.sql b/app/src/database/migrations/004_pg_stat_statements.sql new file mode 100644 index 0000000..c70da49 --- /dev/null +++ b/app/src/database/migrations/004_pg_stat_statements.sql @@ -0,0 +1,9 @@ +-- Instrumentation for the scaling experiments. pg_stat_statements only works +-- when the server is started with shared_preload_libraries=pg_stat_statements +-- (compose.yaml does that); without the preload the CREATE fails with a plain +-- notice, so a database started without the preload still migrates cleanly. +DO $$ BEGIN + CREATE EXTENSION IF NOT EXISTS pg_stat_statements; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'pg_stat_statements unavailable: %', SQLERRM; +END $$; diff --git a/app/src/database/migrations/005_attachments.sql b/app/src/database/migrations/005_attachments.sql new file mode 100644 index 0000000..a6c9d81 --- /dev/null +++ b/app/src/database/migrations/005_attachments.sql @@ -0,0 +1,42 @@ +ALTER TABLE messages ADD CONSTRAINT messages_id_chat_key UNIQUE (id, chat_id); + +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255), + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + upload_mode text NOT NULL CHECK (upload_mode IN ('proxy', 'direct')), + status text NOT NULL CHECK (status IN ('pending', 'ready', 'deleting')), + object_key text NOT NULL UNIQUE, + size_bytes bigint CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 text CHECK (sha256 ~ '^[a-f0-9]{64}$'), + width integer CHECK (width > 0), + height integer CHECK (height > 0), + expires_at timestamptz(3), + created_at timestamptz(3) NOT NULL DEFAULT now(), + updated_at timestamptz(3) NOT NULL DEFAULT now(), + CONSTRAINT attachments_id_chat_key UNIQUE (id, chat_id), + CONSTRAINT attachments_owner_member_fk FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members (chat_id, user_id), + CONSTRAINT attachments_ready_complete CHECK (status <> 'ready' OR + (size_bytes IS NOT NULL AND sha256 IS NOT NULL AND width IS NOT NULL AND height IS NOT NULL)), + CONSTRAINT attachments_unfinished_expiry CHECK (status = 'ready' OR expires_at IS NOT NULL) +); +CREATE INDEX attachments_unfinished_idx ON attachments (expires_at) WHERE status <> 'ready'; +CREATE INDEX attachments_owner_direct_pending_idx ON attachments (owner_id) + WHERE status = 'pending' AND upload_mode = 'direct'; + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL, + chat_id uuid NOT NULL, + attachment_id uuid NOT NULL, + ordinal smallint NOT NULL CHECK (ordinal BETWEEN 1 AND 10), + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_ordinal_key UNIQUE (message_id, ordinal), + CONSTRAINT message_attachments_message_fk FOREIGN KEY (message_id, chat_id) + REFERENCES messages (id, chat_id) ON DELETE CASCADE, + CONSTRAINT message_attachments_attachment_fk FOREIGN KEY (attachment_id, chat_id) + REFERENCES attachments (id, chat_id) +); +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); diff --git a/app/src/database/migrations/006_attachment_rejected.sql b/app/src/database/migrations/006_attachment_rejected.sql new file mode 100644 index 0000000..6040217 --- /dev/null +++ b/app/src/database/migrations/006_attachment_rejected.sql @@ -0,0 +1,8 @@ +-- Rejected direct uploads keep their row until the signed URL can no longer be +-- used, so an object re-PUT after rejection is still found by the sweeper. +ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; +ALTER TABLE attachments ADD CONSTRAINT attachments_status_check + CHECK (status IN ('pending', 'ready', 'deleting', 'rejected')); +DROP INDEX attachments_owner_direct_pending_idx; +CREATE INDEX attachments_owner_direct_pending_idx ON attachments (owner_id) + WHERE status IN ('pending', 'rejected') AND upload_mode = 'direct'; diff --git a/app/src/database/migrations/007_attachment_pipeline.sql b/app/src/database/migrations/007_attachment_pipeline.sql new file mode 100644 index 0000000..c2244aa --- /dev/null +++ b/app/src/database/migrations/007_attachment_pipeline.sql @@ -0,0 +1,81 @@ +ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; +ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (status IN + ('pending','queued','processing','ready','failed','deleting','rejected')); +ALTER TABLE attachments DROP CONSTRAINT attachments_ready_complete; +ALTER TABLE attachments ADD CONSTRAINT attachments_accepted_complete CHECK ( + status NOT IN ('queued','processing','ready','failed') OR + (size_bytes IS NOT NULL AND sha256 IS NOT NULL AND width IS NOT NULL AND height IS NOT NULL)); +ALTER TABLE attachments DROP CONSTRAINT attachments_unfinished_expiry; +ALTER TABLE attachments ADD CONSTRAINT attachments_unfinished_expiry CHECK ( + status NOT IN ('pending','rejected','deleting') OR expires_at IS NOT NULL); +ALTER TABLE attachments + ADD COLUMN staging_key text UNIQUE, + ADD COLUMN error_code text CHECK (error_code ~ '^[a-z_]{1,64}$'), + ADD COLUMN ready_pipeline_version integer CHECK (ready_pipeline_version >= 1); +ALTER TABLE attachments ADD CONSTRAINT attachments_failed_code + CHECK (status <> 'failed' OR error_code IS NOT NULL); +DROP INDEX attachments_unfinished_idx; +CREATE INDEX attachments_unfinished_idx ON attachments (expires_at) + WHERE status IN ('pending','rejected','deleting'); +CREATE INDEX attachments_staging_idx ON attachments (updated_at) + WHERE staging_key IS NOT NULL AND status IN ('ready','failed'); + +-- Rows accepted by lab4 already have their final original and complete metadata. +UPDATE attachments SET ready_pipeline_version = 1 + WHERE status = 'ready' AND ready_pipeline_version IS NULL; + +CREATE TABLE attachment_jobs ( + job_id uuid PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version integer NOT NULL CHECK (pipeline_version >= 1), + status text NOT NULL CHECK (status IN ('queued','processing','succeeded','failed','superseded')), + attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1), + max_attempts integer NOT NULL CHECK (max_attempts >= 1), + next_attempt_at timestamptz(3) NOT NULL DEFAULT now(), + lease_owner text, lease_token uuid, lease_until timestamptz(3), + last_error_code text, + created_at timestamptz(3) NOT NULL DEFAULT now(), + updated_at timestamptz(3) NOT NULL DEFAULT now(), + finished_at timestamptz(3), + CONSTRAINT attachment_jobs_effect_key UNIQUE (attachment_id, pipeline_version), + CONSTRAINT attachment_jobs_lease CHECK ((status = 'processing') = + (lease_owner IS NOT NULL AND lease_token IS NOT NULL AND lease_until IS NOT NULL)) +); +CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs (lease_until) WHERE status = 'processing'; +CREATE INDEX attachment_jobs_failed_idx ON attachment_jobs (updated_at) WHERE status = 'failed'; + +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + pipeline_version integer NOT NULL CHECK (pipeline_version >= 1), + variant text NOT NULL CHECK (variant IN ('thumbnail','crop','optimized')), + object_key text NOT NULL UNIQUE, + content_type text NOT NULL CHECK (content_type IN ('image/jpeg','image/png','image/webp')), + size_bytes bigint NOT NULL CHECK (size_bytes >= 1), + width integer NOT NULL CHECK (width >= 1), + height integer NOT NULL CHECK (height >= 1), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + job_id uuid NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE, + created_at timestamptz(3) NOT NULL DEFAULT now(), + PRIMARY KEY (attachment_id, pipeline_version, variant) +); + +CREATE TABLE job_outbox ( + id bigserial PRIMARY KEY, + job_id uuid NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE, + payload jsonb NOT NULL, + available_at timestamptz(3) NOT NULL DEFAULT now(), + published_at timestamptz(3), + created_at timestamptz(3) NOT NULL DEFAULT now() +); +CREATE INDEX job_outbox_pending_idx ON job_outbox (available_at, id) WHERE published_at IS NULL; + +CREATE TABLE job_events ( + id bigserial PRIMARY KEY, + job_id uuid NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE, + event text NOT NULL CHECK (event IN ('created','claimed','retry_scheduled','lease_expired', + 'succeeded','failed','superseded','replayed','duplicate_skipped','staging_deleted')), + attempt integer NOT NULL, + detail jsonb NOT NULL DEFAULT '{}'::jsonb, + created_at timestamptz(3) NOT NULL DEFAULT now() +); +CREATE INDEX job_events_job_idx ON job_events (job_id, id); diff --git a/app/src/database/migrations/008_job_reconcile.sql b/app/src/database/migrations/008_job_reconcile.sql new file mode 100644 index 0000000..90cc697 --- /dev/null +++ b/app/src/database/migrations/008_job_reconcile.sql @@ -0,0 +1,37 @@ +ALTER TABLE attachment_jobs ADD COLUMN last_reconciled_at timestamptz(3); +CREATE INDEX job_outbox_job_idx ON job_outbox (job_id); + +-- lab4 rows are ready but predate variants. Requeue them once so the worker +-- materializes the same v1 variants every other ready attachment has. The +-- INSERT ... RETURNING CTE keeps the job, outbox and audit event atomic. +WITH legacy AS ( + INSERT INTO attachment_jobs + (job_id, attachment_id, pipeline_version, status, attempt, max_attempts, + next_attempt_at, created_at) + SELECT gen_random_uuid(), a.id, 1, 'queued', 1, 5, now(), now() + FROM attachments a + WHERE a.status = 'ready' + AND NOT EXISTS ( + SELECT 1 FROM attachment_variants v WHERE v.attachment_id = a.id) + AND NOT EXISTS ( + SELECT 1 FROM attachment_jobs j + WHERE j.attachment_id = a.id AND j.pipeline_version = 1) + RETURNING job_id, attachment_id, pipeline_version, attempt, created_at +), queued AS ( + INSERT INTO job_outbox (job_id, payload, available_at) + SELECT job_id, + jsonb_build_object( + 'schema_version', 1, + 'job_id', job_id, + 'type', 'attachment.process.v1', + 'attachment_id', attachment_id, + 'pipeline_version', pipeline_version, + 'attempt', attempt, + 'created_at', to_char(created_at AT TIME ZONE 'UTC', + 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')), + now() + FROM legacy + RETURNING job_id +) +INSERT INTO job_events (job_id, event, attempt, detail) +SELECT job_id, 'created', 1, '{"backfill":true}'::jsonb FROM legacy; diff --git a/app/src/database/migrations/009_queue_reconcile_indexes.sql b/app/src/database/migrations/009_queue_reconcile_indexes.sql new file mode 100644 index 0000000..73a5a86 --- /dev/null +++ b/app/src/database/migrations/009_queue_reconcile_indexes.sql @@ -0,0 +1,10 @@ +CREATE INDEX attachment_jobs_queued_idx + ON attachment_jobs (next_attempt_at) WHERE status = 'queued'; +CREATE INDEX job_events_created_idx ON job_events (created_at); +CREATE INDEX job_outbox_published_idx + ON job_outbox (published_at) WHERE published_at IS NOT NULL; + +ALTER TABLE job_events DROP CONSTRAINT job_events_event_check; +ALTER TABLE job_events ADD CONSTRAINT job_events_event_check CHECK (event IN + ('created','claimed','retry_scheduled','lease_expired','succeeded','failed', + 'superseded','replayed','duplicate_skipped','staging_deleted','reconciled')); diff --git a/app/src/health/health.controller.ts b/app/src/health/health.controller.ts new file mode 100644 index 0000000..f297b64 --- /dev/null +++ b/app/src/health/health.controller.ts @@ -0,0 +1,17 @@ +import { Controller, Get } from '@nestjs/common'; +import { HealthService } from './health.service.js'; + +@Controller('health') +export class HealthController { + constructor(private readonly healthService: HealthService) {} + + @Get('live') + getLive() { + return this.healthService.getLiveness(); + } + + @Get('ready') + async getReady() { + return this.healthService.getReadiness(); + } +} diff --git a/app/src/health/health.module.ts b/app/src/health/health.module.ts new file mode 100644 index 0000000..f5bbe7a --- /dev/null +++ b/app/src/health/health.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { HealthController } from './health.controller.js'; +import { HealthService } from './health.service.js'; +import { DatabaseModule } from '../database/database.module.js'; +import { RedisModule } from '../redis/redis.module.js'; + +@Module({ + imports: [DatabaseModule, RedisModule], + controllers: [HealthController], + providers: [HealthService], +}) +export class HealthModule {} diff --git a/app/src/health/health.service.spec.ts b/app/src/health/health.service.spec.ts new file mode 100644 index 0000000..91f3e43 --- /dev/null +++ b/app/src/health/health.service.spec.ts @@ -0,0 +1,91 @@ +import { describe, expect, it, vi } from 'vitest'; +import { ServiceUnavailableException } from '@nestjs/common'; +import { HealthService } from './health.service.js'; + +describe('HealthService', () => { + it('reports liveness and readiness when dependencies are healthy', async () => { + const database = { health: vi.fn().mockResolvedValue(undefined) }; + const redis = { health: vi.fn().mockResolvedValue(undefined) }; + const service = new HealthService( + database as never, + redis as never, + { getOrThrow: () => 50 } as never, + ); + expect(service.getLiveness()).toEqual({ status: 'ok' }); + await expect(service.getReadiness()).resolves.toEqual({ status: 'ok' }); + }); + + it('rejects readiness when a dependency is unavailable', async () => { + const database = { + health: vi.fn().mockRejectedValue(new Error('down')), + }; + const redis = { health: vi.fn().mockResolvedValue(undefined) }; + const service = new HealthService( + database as never, + redis as never, + { getOrThrow: () => 50 } as never, + ); + await expect(service.getReadiness()).rejects.toBeInstanceOf( + ServiceUnavailableException, + ); + }); + + it('rejects readiness when Redis alone is unavailable', async () => { + const database = { health: vi.fn().mockResolvedValue(undefined) }; + const redis = { + health: vi.fn().mockRejectedValue(new Error('down')), + }; + const service = new HealthService( + database as never, + redis as never, + { getOrThrow: () => 50 } as never, + ); + await expect(service.getReadiness()).rejects.toBeInstanceOf( + ServiceUnavailableException, + ); + }); + + it('keeps liveness healthy while draining', async () => { + const service = new HealthService( + { health: vi.fn() } as never, + { health: vi.fn() } as never, + { getOrThrow: () => 50 } as never, + ); + service.setDraining(); + expect(service.getLiveness()).toEqual({ status: 'ok' }); + await expect(service.getReadiness()).rejects.toThrow( + 'Service is shutting down', + ); + }); + + it('answers not-ready during drain without probing dependencies', async () => { + const database = { health: vi.fn().mockResolvedValue(undefined) }; + const redis = { health: vi.fn().mockResolvedValue(undefined) }; + const service = new HealthService( + database as never, + redis as never, + { getOrThrow: () => 50 } as never, + ); + service.setDraining(); + await expect(service.getReadiness()).rejects.toThrow( + 'Service is shutting down', + ); + // Дрейн обязан отвечать сразу: проба LB не должна ждать зависимости, + // когда реплика уже выходит из ротации. + expect(database.health).not.toHaveBeenCalled(); + expect(redis.health).not.toHaveBeenCalled(); + }); + + it('fails readiness within the budget when a dependency hangs', async () => { + const database = { health: vi.fn(() => new Promise(() => {})) }; + const redis = { health: vi.fn().mockResolvedValue(undefined) }; + const service = new HealthService( + database as never, + redis as never, + { getOrThrow: () => 20 } as never, + ); + await expect(service.getReadiness()).rejects.toBeInstanceOf( + ServiceUnavailableException, + ); + }); +}); diff --git a/app/src/health/health.service.ts b/app/src/health/health.service.ts new file mode 100644 index 0000000..b2e5640 --- /dev/null +++ b/app/src/health/health.service.ts @@ -0,0 +1,60 @@ +import { + Global, + Injectable, + Module, + ServiceUnavailableException, +} from '@nestjs/common'; +import { DatabaseClient } from '../database/database.client.js'; +import { RedisClient } from '../redis/redis.client.js'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; + +@Injectable() +export class HealthService { + private ready = true; + constructor( + private readonly database: DatabaseClient, + private readonly redis: RedisClient, + private readonly config: ConfigService, + ) {} + getLiveness() { + return { status: 'ok' as const }; + } + async getReadiness() { + if (!this.ready) + throw new ServiceUnavailableException('Service is shutting down'); + const dependencies = Promise.all([ + this.database.health(), + this.redis.health(), + ]); + // Поздний отказ после дедлайна не должен стать unhandled rejection. + dependencies.catch(() => undefined); + let timer: NodeJS.Timeout | undefined; + const deadline = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error('readiness budget exceeded')), + this.config.getOrThrow('HEALTH_TIMEOUT_MS'), + ); + }); + try { + await Promise.race([dependencies, deadline]); + } catch { + throw new ServiceUnavailableException('Dependencies unavailable'); + } finally { + clearTimeout(timer); + } + return { status: 'ok' as const }; + } + // Called on SIGTERM before the drain delay: the replica turns not-ready while + // it finishes in-flight requests, so the load balancer stops probing it + // successfully and removes it from rotation. The delay itself lives in + // main.ts, because Nest destroys providers (closing the pools) before this + // class could serve anyone. + setDraining() { + this.ready = false; + } +} + +@Global() +@Module({ providers: [HealthService], exports: [HealthService] }) +export class HealthServiceModule {} diff --git a/app/src/jobs/backoff.spec.ts b/app/src/jobs/backoff.spec.ts new file mode 100644 index 0000000..1255ae3 --- /dev/null +++ b/app/src/jobs/backoff.spec.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest'; +import { retryDelayMs } from './backoff.js'; + +describe('retryDelayMs', () => { + it('uses equal jitter', () => { + expect(retryDelayMs(1, 1000, 30000, () => 0)).toBe(500); + expect(retryDelayMs(1, 1000, 30000, () => 1)).toBe(1000); + expect(retryDelayMs(10, 1000, 30000, () => 1)).toBe(30000); + }); + + it('never exceeds the cap and grows monotonically at random 0.5', () => { + const values = Array.from({ length: 6 }, (_, index) => + retryDelayMs(index + 1, 1000, 30000, () => 0.5), + ); + for (const value of values) expect(value).toBeLessThanOrEqual(30000); + for (let index = 1; index < values.length; index += 1) + expect(values[index]).toBeGreaterThanOrEqual(values[index - 1]); + }); +}); diff --git a/app/src/jobs/backoff.ts b/app/src/jobs/backoff.ts new file mode 100644 index 0000000..33645ff --- /dev/null +++ b/app/src/jobs/backoff.ts @@ -0,0 +1,14 @@ +/** + * Equal jitter: half of the exponential delay is fixed, half is random. The + * result never exceeds `capMs`, so `max_attempts` bounds both attempts and + * total wait time. + */ +export function retryDelayMs( + attempt: number, + baseMs: number, + capMs: number, + random: () => number = Math.random, +): number { + const exponential = Math.min(capMs, baseMs * 2 ** (attempt - 1)); + return Math.floor(exponential * (0.5 + 0.5 * random())); +} diff --git a/app/src/jobs/broker.client.ts b/app/src/jobs/broker.client.ts new file mode 100644 index 0000000..e74185c --- /dev/null +++ b/app/src/jobs/broker.client.ts @@ -0,0 +1,478 @@ +import { + connect as amqpConnect, + type Channel, + type ChannelModel, + type ConfirmChannel, + type ConsumeMessage, +} from 'amqplib'; +import { + context, + propagation, + SpanKind, + type Span, +} from '@opentelemetry/api'; +import { + Injectable, + Logger, + OnModuleDestroy, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { randomUUID } from 'node:crypto'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { + assertTopology, + JOB_EXCHANGE, + JOB_QUEUE, + JOB_ROUTING_KEY, +} from './broker.topology.js'; +import type { JobMessage } from './job-message.js'; +import { instruments } from '../telemetry/instruments.js'; +import { markSpanError, tracer } from '../telemetry/tracing.js'; + +export class BrokerUnavailableError extends ServiceUnavailableException { + constructor() { + super('Broker unavailable'); + } +} + +export type ConsumeHandler = ( + message: ConsumeMessage, + channel: Channel, +) => Promise; + +const MAX_RECONNECT_DELAY_MS = 10_000; + +@Injectable() +export class BrokerClient implements OnModuleDestroy { + private readonly logger = new Logger(BrokerClient.name); + private readonly url: string; + private readonly deliveryLimit: number; + private readonly publishTimeoutMs: number; + private connection: ChannelModel | undefined; + private confirmChannel: ConfirmChannel | undefined; + private consumeChannel: Channel | undefined; + private consumerTag: string | undefined; + private prefetch = 0; + private handler: ConsumeHandler | undefined; + private connecting: Promise | undefined; + private subscribing: Promise | undefined; + private reconnectTimer: NodeJS.Timeout | undefined; + private subscribeTimer: NodeJS.Timeout | undefined; + private reconnectDelayMs = 1000; + private subscribeDelayMs = 1000; + private closing = false; + // Unroutable messages are returned before their confirm; the map lets the + // return listener reject the exact publish that produced it. + private readonly returned = new Map void>(); + + constructor( + config: ConfigService, + private readonly metrics: MetricsService, + ) { + this.url = config.getOrThrow('BROKER_URL'); + this.deliveryLimit = config.getOrThrow('BROKER_DELIVERY_LIMIT'); + this.publishTimeoutMs = config.getOrThrow( + 'BROKER_PUBLISH_TIMEOUT_MS', + ); + } + + /** + * PRODUCER span around publish + broker confirm. Its context goes into the + * AMQP headers (W3C traceparent/tracestate), so the worker's CONSUMER span + * becomes its child; the body keeps the context of the transaction that + * wrote the outbox row. + */ + async publish(message: JobMessage | Buffer): Promise { + const attributes = { + 'messaging.system': 'rabbitmq', + 'messaging.operation.type': 'send', + 'messaging.operation.name': 'publish', + 'messaging.destination.name': JOB_EXCHANGE, + 'messaging.rabbitmq.destination.routing_key': JOB_ROUTING_KEY, + ...(Buffer.isBuffer(message) + ? {} + : { + 'messaging.message.id': message.job_id, + 'messenger.job.id': message.job_id, + 'messenger.job.attempt': message.attempt, + }), + }; + return tracer().startActiveSpan( + `publish ${JOB_EXCHANGE}`, + { kind: SpanKind.PRODUCER, attributes }, + async (span: Span) => { + const traceHeaders: Record = {}; + propagation.inject(context.active(), traceHeaders); + const labels = { 'messaging.destination.name': JOB_EXCHANGE }; + try { + await this.publishConfirmed(message, traceHeaders); + instruments().brokerPublished.add(1, { + ...labels, + outcome: 'success', + }); + } catch (error) { + instruments().brokerPublished.add(1, { + ...labels, + outcome: 'failed', + }); + markSpanError(span, error); + throw error; + } finally { + span.end(); + } + }, + ); + } + + private async publishConfirmed( + message: JobMessage | Buffer, + traceHeaders: Record, + ): Promise { + const channel = await this.withTimeout( + this.ensureConnected(), + this.publishTimeoutMs, + ); + const content = Buffer.isBuffer(message) + ? message + : Buffer.from(JSON.stringify(message)); + const correlationId = randomUUID(); + const options = { + persistent: true, + contentType: 'application/json', + mandatory: true, + correlationId, + ...(Buffer.isBuffer(message) + ? { headers: traceHeaders } + : { + messageId: message.job_id, + type: message.type, + headers: { 'x-attempt': message.attempt, ...traceHeaders }, + }), + }; + const { promise, resolve, reject } = Promise.withResolvers(); + let settled = false; + const fail = (): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + this.returned.delete(correlationId); + this.metrics.increment('broker.publish_failed'); + reject(new BrokerUnavailableError()); + }; + const timer = setTimeout(fail, this.publishTimeoutMs); + this.returned.set(correlationId, fail); + try { + channel.publish( + JOB_EXCHANGE, + JOB_ROUTING_KEY, + content, + options, + (error) => { + if (settled) return; + settled = true; + clearTimeout(timer); + this.returned.delete(correlationId); + if (error) { + this.metrics.increment('broker.publish_failed'); + reject(new BrokerUnavailableError()); + return; + } + this.metrics.increment('broker.published'); + resolve(); + }, + ); + } catch { + fail(); + } + return promise; + } + + consume(prefetch: number, handler: ConsumeHandler): void { + this.prefetch = prefetch; + this.handler = handler; + this.ensureConnected() + .then(() => this.subscribe()) + .catch(() => this.scheduleSubscribe()); + } + + isConsuming(): boolean { + return this.consumerTag !== undefined; + } + + async queueDepth( + queue: string, + ): Promise<{ messages: number; consumers: number }> { + const channel = await this.withTimeout( + this.ensureConnected(), + this.publishTimeoutMs, + ); + const result = await channel.checkQueue(queue); + return { + messages: result.messageCount, + consumers: result.consumerCount, + }; + } + + async stopConsuming(): Promise { + clearTimeout(this.subscribeTimer); + this.subscribeTimer = undefined; + const channel = this.consumeChannel; + const tag = this.consumerTag; + this.consumerTag = undefined; + this.consumeChannel = undefined; + this.handler = undefined; + if (channel && tag) { + try { + await channel.cancel(tag); + } catch { + // The channel is already closing; there is nothing to cancel. + } + } + if (channel) { + try { + await channel.close(); + } catch { + // Closing an already closed channel is harmless. + } + } + } + + async onModuleDestroy(): Promise { + this.closing = true; + clearTimeout(this.reconnectTimer); + clearTimeout(this.subscribeTimer); + this.reconnectTimer = undefined; + this.subscribeTimer = undefined; + for (const reject of this.returned.values()) reject(); + this.returned.clear(); + await this.stopConsuming(); + const connection = this.connection; + this.connection = undefined; + this.confirmChannel = undefined; + if (connection) { + try { + await connection.close(); + } catch { + // Shutdown is best effort; channels are already unusable. + } + } + } + + private async ensureConnected(): Promise { + if (this.closing) throw new BrokerUnavailableError(); + if (this.confirmChannel) return this.confirmChannel; + if (!this.connecting) { + this.connecting = this.connect() + .then(() => undefined) + .finally(() => { + this.connecting = undefined; + }); + } + await this.connecting; + if (!this.confirmChannel) throw new BrokerUnavailableError(); + return this.confirmChannel; + } + + private async connect(): Promise { + const connection = await amqpConnect(this.url); + connection.on('error', (error: Error) => { + this.metrics.increment('broker.error'); + this.logger.warn(`Broker connection error: ${error.message}`); + }); + connection.on('close', () => { + if (this.connection !== connection) return; + this.handleClose(); + }); + try { + const confirm = await connection.createConfirmChannel(); + confirm.on('return', (message) => { + const correlationId = message.properties?.correlationId; + if (!correlationId) return; + const reject = this.returned.get(correlationId); + if (!reject) return; + this.returned.delete(correlationId); + this.logger.warn('Broker returned an unroutable job message'); + reject(); + }); + await assertTopology(confirm, this.deliveryLimit); + confirm.on('error', (error: Error) => { + this.metrics.increment('broker.confirm_error'); + this.logger.warn(`Broker confirm channel error: ${error.message}`); + }); + confirm.on('close', () => this.handleConfirmClose(confirm)); + this.connection = connection; + this.confirmChannel = confirm; + this.reconnectDelayMs = 1000; + clearTimeout(this.reconnectTimer); + this.reconnectTimer = undefined; + this.metrics.increment('broker.connected'); + } catch (error) { + if (this.connection === connection) { + this.connection = undefined; + this.confirmChannel = undefined; + } + try { + await connection.close(); + } catch { + // The connection is already unusable. + } + throw error; + } + if (this.handler) + void this.subscribe().catch(() => this.scheduleSubscribe()); + } + + private handleConfirmClose(confirm: ConfirmChannel): void { + if (this.confirmChannel !== confirm) return; + this.metrics.increment('broker.confirm_closed'); + for (const reject of this.returned.values()) reject(); + this.returned.clear(); + this.confirmChannel = undefined; + const connection = this.connection; + if (connection) { + void connection.close().catch(() => this.handleClose()); + } else { + this.handleClose(); + } + } + + private subscribe(): Promise { + if (this.subscribing) return this.subscribing; + const connection = this.connection; + const handler = this.handler; + if (!connection || !handler || this.consumerTag) + return Promise.resolve(); + this.subscribing = this.doSubscribe(connection, handler).finally( + () => { + this.subscribing = undefined; + }, + ); + return this.subscribing; + } + + private async doSubscribe( + connection: ChannelModel, + handler: ConsumeHandler, + ): Promise { + const channel = await connection.createChannel(); + try { + channel.on('error', (error: Error) => { + this.metrics.increment('broker.consumer_error'); + this.logger.warn( + `Broker consumer channel error: ${error.message}`, + ); + this.handleConsumerClose(channel); + }); + channel.on('close', () => this.handleConsumerClose(channel)); + await channel.prefetch(this.prefetch); + await assertTopology(channel, this.deliveryLimit); + if (this.handler !== handler) { + await channel.close(); + return; + } + const consumer = await channel.consume( + JOB_QUEUE, + (message) => { + if (!message) { + // basic.cancel from the broker: the worker must not stay + // healthy while deaf. + this.handleConsumerClose(channel); + void channel.close().catch(() => undefined); + return; + } + handler(message, channel).catch((error: unknown) => { + this.metrics.increment('broker.handler_error'); + this.logger.error( + `Job handler crashed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + // Hold the message briefly instead of burning the + // quorum delivery limit in a tight nack loop. + setTimeout(() => { + try { + channel.nack(message, false, true); + } catch { + // The channel is gone; the broker redelivers after the lease. + } + }, 1000); + }); + }, + { noAck: false }, + ); + this.consumeChannel = channel; + this.consumerTag = consumer.consumerTag; + this.subscribeDelayMs = 1000; + } catch (error) { + try { + await channel.close(); + } catch { + // The channel is already unusable. + } + throw error; + } + } + + private handleConsumerClose(channel: Channel): void { + if (this.consumeChannel && this.consumeChannel !== channel) return; + this.consumeChannel = undefined; + this.consumerTag = undefined; + if (!this.closing && this.handler) this.scheduleSubscribe(); + } + + private handleClose(): void { + this.metrics.increment('broker.closed'); + clearTimeout(this.subscribeTimer); + this.subscribeTimer = undefined; + this.connection = undefined; + this.confirmChannel = undefined; + this.consumeChannel = undefined; + this.consumerTag = undefined; + for (const reject of this.returned.values()) reject(); + this.returned.clear(); + if (this.closing) return; + this.scheduleReconnect(); + } + + private scheduleReconnect(): void { + if (this.closing || this.reconnectTimer) return; + const delay = this.reconnectDelayMs; + this.reconnectDelayMs = Math.min( + this.reconnectDelayMs * 2, + MAX_RECONNECT_DELAY_MS, + ); + this.metrics.increment('broker.reconnect_scheduled'); + this.reconnectTimer = setTimeout(() => { + this.reconnectTimer = undefined; + this.ensureConnected() + .then(() => this.subscribe()) + .catch(() => this.scheduleReconnect()); + }, delay); + } + + private scheduleSubscribe(): void { + if (this.closing || !this.handler || this.subscribeTimer) return; + const delay = this.subscribeDelayMs; + this.subscribeDelayMs = Math.min( + this.subscribeDelayMs * 2, + MAX_RECONNECT_DELAY_MS, + ); + this.metrics.increment('broker.subscribe_scheduled'); + this.subscribeTimer = setTimeout(() => { + this.subscribeTimer = undefined; + this.ensureConnected() + .then(() => this.subscribe()) + .catch(() => this.scheduleSubscribe()); + }, delay); + } + + private async withTimeout(promise: Promise, ms: number): Promise { + const { promise: timeout, reject } = Promise.withResolvers(); + const timer = setTimeout(() => reject(new BrokerUnavailableError()), ms); + try { + return await Promise.race([promise, timeout]); + } finally { + clearTimeout(timer); + } + } +} diff --git a/app/src/jobs/broker.topology.ts b/app/src/jobs/broker.topology.ts new file mode 100644 index 0000000..6921d74 --- /dev/null +++ b/app/src/jobs/broker.topology.ts @@ -0,0 +1,37 @@ +import type { Channel } from 'amqplib'; + +export const JOB_EXCHANGE = 'attachments.jobs'; +export const JOB_ROUTING_KEY = 'attachment.process.v1'; +export const JOB_QUEUE = 'attachments.process'; +export const DEAD_LETTER_EXCHANGE = 'attachments.dlx'; +export const DEAD_LETTER_QUEUE = 'attachments.process.dlq'; + +/** + * Idempotent declaration used by both the producer and the consumer on every + * (re)connect: a stand started from an empty volume and a reconnect after a + * broker restart converge to the same durable topology. + */ +export async function assertTopology( + channel: Channel, + deliveryLimit: number, +): Promise { + await channel.assertExchange(DEAD_LETTER_EXCHANGE, 'fanout', { + durable: true, + }); + await channel.assertQueue(DEAD_LETTER_QUEUE, { + durable: true, + arguments: { 'x-queue-type': 'quorum' }, + }); + await channel.bindQueue(DEAD_LETTER_QUEUE, DEAD_LETTER_EXCHANGE, ''); + + await channel.assertExchange(JOB_EXCHANGE, 'direct', { durable: true }); + await channel.assertQueue(JOB_QUEUE, { + durable: true, + arguments: { + 'x-queue-type': 'quorum', + 'x-dead-letter-exchange': DEAD_LETTER_EXCHANGE, + 'x-delivery-limit': deliveryLimit, + }, + }); + await channel.bindQueue(JOB_QUEUE, JOB_EXCHANGE, JOB_ROUTING_KEY); +} diff --git a/app/src/jobs/errors.spec.ts b/app/src/jobs/errors.spec.ts new file mode 100644 index 0000000..6c37c3f --- /dev/null +++ b/app/src/jobs/errors.spec.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { ObjectStorageUnavailableError } from '../storage/object-storage.js'; +import { classifyError, JobTimeoutError } from './errors.js'; + +describe('classifyError', () => { + it('classifies unsupported sharp input as permanent invalid_image', () => { + expect( + classifyError( + new Error('Input buffer contains unsupported image format'), + ), + ).toEqual({ kind: 'permanent', code: 'invalid_image' }); + }); + + it('classifies the pixel limit as permanent image_too_large', () => { + expect( + classifyError(new Error('Input image exceeds pixel limit')), + ).toEqual({ kind: 'permanent', code: 'image_too_large' }); + }); + + it('classifies object storage outages as transient', () => { + expect(classifyError(new ObjectStorageUnavailableError())).toEqual({ + kind: 'transient', + code: 'processing_failed', + }); + }); + + it('classifies a job timeout as transient processing_timeout', () => { + expect(classifyError(new JobTimeoutError(10))).toEqual({ + kind: 'transient', + code: 'processing_timeout', + }); + }); +}); diff --git a/app/src/jobs/errors.ts b/app/src/jobs/errors.ts new file mode 100644 index 0000000..9c121e1 --- /dev/null +++ b/app/src/jobs/errors.ts @@ -0,0 +1,65 @@ +import { SERVER_FAULT } from '../attachments/image/image-decoder.js'; +import { InjectedFaultError } from './fault-injector.js'; + +export class SourceMissingError extends Error { + constructor(message = 'Source object is missing') { + super(message); + this.name = 'SourceMissingError'; + } +} + +export class SourceMismatchError extends Error { + constructor(message = 'Source object does not match its metadata') { + super(message); + this.name = 'SourceMismatchError'; + } +} + +export class UnsupportedPipelineError extends Error { + constructor(version: number) { + super(`Unsupported pipeline version: ${version}`); + this.name = 'UnsupportedPipelineError'; + } +} + +export class JobTimeoutError extends Error { + constructor(seconds: number) { + super(`Job exceeded ${seconds}s deadline`); + this.name = 'JobTimeoutError'; + } +} + +export type ErrorClass = { + kind: 'permanent' | 'transient'; + code: string; +}; + +const SHARP_INPUT = + /unsupported image format|input buffer|input file|bad seek|premature end|vipsjpeg|vippng|corrupt|truncated|invalid (?:image|pixel)|not a valid image|exceeded.*limit/iu; + +/** + * Maps a processing failure to the contract's safe error class. Permanent + * errors are never retried; transient ones are retried until max_attempts, + * after which the job is failed as `retry_exhausted`. + */ +export function classifyError(error: unknown): ErrorClass { + if (error instanceof InjectedFaultError) + return { kind: error.kind, code: 'injected_fault' }; + if (error instanceof SourceMissingError) + return { kind: 'permanent', code: 'source_missing' }; + if (error instanceof SourceMismatchError) + return { kind: 'permanent', code: 'source_mismatch' }; + if (error instanceof UnsupportedPipelineError) + return { kind: 'permanent', code: 'unsupported_pipeline' }; + if (error instanceof JobTimeoutError) + return { kind: 'transient', code: 'processing_timeout' }; + + const message = error instanceof Error ? error.message : String(error); + if (/pixel limit/iu.test(message)) + return { kind: 'permanent', code: 'image_too_large' }; + if (SERVER_FAULT.test(message)) + return { kind: 'transient', code: 'processing_failed' }; + if (SHARP_INPUT.test(message)) + return { kind: 'permanent', code: 'invalid_image' }; + return { kind: 'transient', code: 'processing_failed' }; +} diff --git a/app/src/jobs/fault-injector.ts b/app/src/jobs/fault-injector.ts new file mode 100644 index 0000000..bcc4120 --- /dev/null +++ b/app/src/jobs/fault-injector.ts @@ -0,0 +1,134 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { RedisClient } from '../redis/redis.client.js'; + +export type FaultPoint = + | 'api.after_commit_before_publish' + | 'relay.after_publish_before_mark' + | 'worker.before_side_effect' + | 'worker.after_side_effect' + | 'worker.after_commit_before_ack'; + +export type FaultTarget = { + attachmentId: string; + pipelineVersion: number; +}; + +export type FaultKind = 'permanent' | 'transient'; + +// Node timers overflow above 2^31-1 ms and fire immediately. +const MAX_TIMER_MS = 2_147_483_647; + +export class InjectedFaultError extends Error { + constructor(readonly kind: FaultKind) { + super(`Injected ${kind} fault`); + this.name = 'InjectedFaultError'; + } +} + +/** + * Active only with FAULT_INJECTION_ENABLED=1. The switch is deliberately + * checked before every Redis call so a normal stand never depends on Redis for + * job correctness. + * + * `transient` stays until the key is deleted; every other value is consumed by + * the first point that observes it. Worker points are addressed to one + * attachment and pipeline version; the untargeted key is a fallback. + */ +@Injectable() +export class FaultInjector { + private readonly logger = new Logger(FaultInjector.name); + private readonly enabled: boolean; + + constructor( + config: ConfigService, + private readonly redis: RedisClient, + private readonly metrics: MetricsService, + ) { + this.enabled = config.getOrThrow('FAULT_INJECTION_ENABLED') === 1; + } + + async point( + name: FaultPoint, + target?: FaultTarget, + signal?: AbortSignal, + ): Promise { + if (!this.enabled) return; + const keys = target + ? [ + `fault:${name}:${target.attachmentId}:${target.pipelineVersion}`, + `fault:${name}`, + ] + : [`fault:${name}`]; + for (const key of keys) { + let value: string | null; + let deleted: number; + try { + value = await this.redis.get(key); + if (value === null) continue; + if (value === 'transient') { + this.metrics.increment('faults.triggered'); + throw new InjectedFaultError('transient'); + } + deleted = await this.redis.del(key); + } catch (error) { + if (error instanceof InjectedFaultError) throw error; + this.logger.warn( + `Fault point ${name} could not read Redis: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + return; + } + if (deleted !== 1) continue; + // The action is outside the Redis try/catch: an abort or an injected + // fault must reach the job processor, not be logged as an outage. + await this.act(value, signal); + return; + } + } + + private async act(value: string, signal?: AbortSignal): Promise { + if (value === 'crash') { + this.metrics.increment('faults.triggered'); + // PID 1 in a container namespace may not be killable by SIGKILL; + // exit 137 gives the same observable crash (no graceful shutdown). + process.kill(process.pid, 'SIGKILL'); + process.exit(137); + } + if (value === 'permanent') { + this.metrics.increment('faults.triggered'); + throw new InjectedFaultError('permanent'); + } + if (value.startsWith('delay:')) { + const milliseconds = Number(value.slice('delay:'.length)); + if (!Number.isFinite(milliseconds) || milliseconds < 0) return; + this.metrics.increment('faults.triggered'); + await this.sleep(Math.min(milliseconds, MAX_TIMER_MS), signal); + } + } + + private sleep(milliseconds: number, signal?: AbortSignal): Promise { + if (signal?.aborted) + return Promise.reject( + signal.reason instanceof Error + ? signal.reason + : new Error('Aborted'), + ); + const { promise, resolve, reject } = Promise.withResolvers(); + const timer = setTimeout(() => { + signal?.removeEventListener('abort', cancel); + resolve(); + }, milliseconds); + const cancel = (): void => { + clearTimeout(timer); + reject( + signal?.reason instanceof Error + ? signal.reason + : new Error('Aborted'), + ); + }; + signal?.addEventListener('abort', cancel, { once: true }); + return promise; + } +} diff --git a/app/src/jobs/fit-inside.spec.ts b/app/src/jobs/fit-inside.spec.ts new file mode 100644 index 0000000..a2cbb07 --- /dev/null +++ b/app/src/jobs/fit-inside.spec.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest'; +import { fitInside } from './fit-inside.js'; + +describe('fitInside', () => { + it.each([ + [320, 200, 256, [256, 160]], + [1000, 335, 256, [256, 85]], + [100, 50, 256, [100, 50]], + [10000, 1, 256, [256, 1]], + [1, 10000, 256, [1, 256]], + ])('fits %ix%i into %i as %j', (width, height, box, expected) => { + expect(fitInside(width, height, box)).toEqual(expected); + }); +}); diff --git a/app/src/jobs/fit-inside.ts b/app/src/jobs/fit-inside.ts new file mode 100644 index 0000000..cff80c6 --- /dev/null +++ b/app/src/jobs/fit-inside.ts @@ -0,0 +1,15 @@ +/** + * Fits `width`x`height` into a `box`x`box` square without upscaling. + * Integer arithmetic keeps the result exact for the contract's fixtures: + * 320x200 -> 256x160, 1000x335 -> 256x85, 10000x1 -> 256x1. + */ +export function fitInside( + width: number, + height: number, + box: number, +): [number, number] { + if (width <= box && height <= box) return [width, height]; + if (width >= height) + return [box, Math.max(1, Math.floor((height * box) / width))]; + return [Math.max(1, Math.floor((width * box) / height)), box]; +} diff --git a/app/src/jobs/job-message.spec.ts b/app/src/jobs/job-message.spec.ts new file mode 100644 index 0000000..4016bd0 --- /dev/null +++ b/app/src/jobs/job-message.spec.ts @@ -0,0 +1,47 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { parseJobMessage } from './job-message.js'; + +const contract = JSON.parse( + readFileSync( + new URL('../../../contracts/jobs.schema.json', import.meta.url), + 'utf8', + ), +) as { examples: Record[] }; +const example = contract.examples[0]; + +describe('parseJobMessage', () => { + it('accepts the contract example', () => { + expect(parseJobMessage(Buffer.from(JSON.stringify(example)))).toEqual( + example, + ); + }); + + it('rejects an extra property', () => { + expect( + parseJobMessage( + Buffer.from(JSON.stringify({ ...example, extra: true })), + ), + ).toBeUndefined(); + }); + + it('rejects attempt 0', () => { + expect( + parseJobMessage( + Buffer.from(JSON.stringify({ ...example, attempt: 0 })), + ), + ).toBeUndefined(); + }); + + it('rejects a wrong type', () => { + expect( + parseJobMessage( + Buffer.from(JSON.stringify({ ...example, type: 'other' })), + ), + ).toBeUndefined(); + }); + + it('rejects non-JSON', () => { + expect(parseJobMessage(Buffer.from('not-json'))).toBeUndefined(); + }); +}); diff --git a/app/src/jobs/job-message.ts b/app/src/jobs/job-message.ts new file mode 100644 index 0000000..2e9c724 --- /dev/null +++ b/app/src/jobs/job-message.ts @@ -0,0 +1,53 @@ +import { z } from 'zod'; + +export const JOB_TYPE = 'attachment.process.v1'; + +/** + * Mirrors contracts/jobs.schema.json. The broker message carries identifiers + * and scheduling data only: no bytes, URLs, file names or credentials. + */ +export const jobMessageSchema = z.strictObject({ + schema_version: z.literal(1), + job_id: z.uuid(), + type: z.literal(JOB_TYPE), + attachment_id: z.uuid(), + pipeline_version: z.number().int().min(1), + attempt: z.number().int().min(1), + created_at: z.iso.datetime(), + traceparent: z + .string() + .regex(/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/u) + .optional(), + tracestate: z.string().max(512).optional(), +}); + +export type JobMessage = z.infer; + +export function buildJobMessage(job: { + job_id: string; + attachment_id: string; + pipeline_version: number; + attempt: number; + created_at: Date; +}): JobMessage { + return { + schema_version: 1, + job_id: job.job_id, + type: JOB_TYPE, + attachment_id: job.attachment_id, + pipeline_version: job.pipeline_version, + attempt: job.attempt, + created_at: job.created_at.toISOString(), + }; +} + +export function parseJobMessage(content: Buffer): JobMessage | undefined { + let value: unknown; + try { + value = JSON.parse(content.toString('utf8')); + } catch { + return undefined; + } + const parsed = jobMessageSchema.safeParse(value); + return parsed.success ? parsed.data : undefined; +} diff --git a/app/src/jobs/jobs.cli.ts b/app/src/jobs/jobs.cli.ts new file mode 100644 index 0000000..c931582 --- /dev/null +++ b/app/src/jobs/jobs.cli.ts @@ -0,0 +1,234 @@ +import { Module } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { AppConfigModule } from '../config/app-config.module.js'; +import { DatabaseModule } from '../database/database.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { ObjectStorage } from '../storage/object-storage.js'; +import { StorageModule } from '../storage/storage.module.js'; +import { DEAD_LETTER_QUEUE, JOB_QUEUE } from './broker.topology.js'; +import { BrokerClient } from './broker.client.js'; +import { JobsModule } from './jobs.module.js'; +import { JobsRepository } from './jobs.repository.js'; + +@Module({ + imports: [ + AppConfigModule, + DatabaseModule, + RedisModule, + MetricsModule, + StorageModule, + JobsModule, + ], +}) +class JobsCliModule {} + +const SUPPORTED_PIPELINES = [1, 2]; + +function option(args: string[], name: string): string | undefined { + const index = args.indexOf(name); + if (index === -1) return undefined; + return args[index + 1]; +} + +async function readStdin(): Promise { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + return Buffer.concat(chunks).toString('utf8'); +} + +async function s3State( + storage: ObjectStorage, + key: string, +): Promise<{ + exists: boolean; + etag: string | null; + last_modified: string | null; +}> { + const head = await storage.head(key); + return head + ? { + exists: true, + etag: head.etag ?? null, + last_modified: head.lastModified?.toISOString() ?? null, + } + : { exists: false, etag: null, last_modified: null }; +} + +async function main(): Promise { + const args = process.argv.slice(2); + const command = args[0]; + const app = await NestFactory.createApplicationContext(JobsCliModule, { + logger: false, + }); + try { + const repository = app.get(JobsRepository); + const storage = app.get(ObjectStorage); + const broker = app.get(BrokerClient); + const config = app.get(ConfigService); + + if (command === 'status') { + const attachmentId = args[1]; + if (!attachmentId) return usage(); + const status = await repository.statusOf(attachmentId); + if (!status) { + console.log(JSON.stringify({ error: 'attachment_not_found' })); + return 1; + } + const variants = []; + for (const variant of status.variants) { + variants.push({ + pipeline_version: variant.pipeline_version, + variant: variant.variant, + sha256: variant.sha256, + size_bytes: Number(variant.size_bytes), + width: variant.width, + height: variant.height, + object_key: variant.object_key, + s3: await s3State(storage, variant.object_key), + }); + } + console.log( + JSON.stringify({ + attachment: { + id: status.attachment.id, + status: status.attachment.status, + error_code: status.attachment.error_code, + ready_pipeline_version: + status.attachment.ready_pipeline_version, + staging_present: status.attachment.staging_key !== null, + }, + jobs: status.jobs.map((job) => ({ + job_id: job.job_id, + pipeline_version: job.pipeline_version, + status: job.status, + attempt: job.attempt, + max_attempts: job.max_attempts, + last_error_code: job.last_error_code, + })), + variants, + original: await s3State( + storage, + status.attachment.object_key, + ), + events: status.events.map((event) => ({ + job_id: event.job_id, + event: event.event, + attempt: event.attempt, + detail: event.detail, + created_at: event.created_at.toISOString(), + })), + outbox: status.outbox, + }), + ); + return 0; + } + + if (command === 'find-by-chat') { + const chatId = args[1]; + if (!chatId) return usage(); + console.log(JSON.stringify(await repository.findByChat(chatId))); + return 0; + } + + if (command === 'failed') { + console.log(JSON.stringify(await repository.failedJobs())); + return 0; + } + + if (command === 'replay') { + const attachmentId = args[1]; + const reason = option(args, '--reason') ?? 'operator replay'; + const operator = + option(args, '--operator') ?? process.env.USER ?? 'operator'; + if (!attachmentId) return usage(); + const candidate = await repository.replayCandidate(attachmentId); + let sourceAvailable = false; + if (candidate) { + sourceAvailable = + candidate.staging_key !== null || + (await storage.head(storage.objectKey(attachmentId))) !== null; + } + const result = await repository.replay(attachmentId, { + reason, + operator, + maxAttempts: config.getOrThrow('JOB_MAX_ATTEMPTS'), + sourceAvailable, + expectedStagingKey: candidate?.staging_key ?? null, + }); + console.log(JSON.stringify(result)); + return result.kind === 'replayed' ? 0 : 3; + } + + if (command === 'reprocess') { + const attachmentId = args[1]; + const rawVersion = option(args, '--pipeline-version'); + const version = Number(rawVersion); + if ( + !attachmentId || + rawVersion === undefined || + !SUPPORTED_PIPELINES.includes(version) + ) + return usage(); + const result = await repository.reprocess(attachmentId, version, { + reason: option(args, '--reason') ?? 'reprocess', + operator: + option(args, '--operator') ?? + process.env.USER ?? + 'operator', + maxAttempts: config.getOrThrow('JOB_MAX_ATTEMPTS'), + }); + console.log(JSON.stringify(result)); + return result.kind === 'created' ? 0 : 3; + } + + if (command === 'publish-raw') { + if (config.getOrThrow('FAULT_INJECTION_ENABLED') !== 1) { + console.log( + JSON.stringify({ refused: 'fault_injection_disabled' }), + ); + return 3; + } + const text = await readStdin(); + const lines = text.split(/\r?\n/u).filter((line) => line !== ''); + for (const line of lines) await broker.publish(Buffer.from(line)); + console.log(JSON.stringify({ published: lines.length })); + return 0; + } + + if (command === 'queues') { + console.log( + JSON.stringify({ + process: await broker.queueDepth(JOB_QUEUE), + dlq: await broker.queueDepth(DEAD_LETTER_QUEUE), + }), + ); + return 0; + } + + return usage(); + } finally { + await app.close(); + } +} + +function usage(): number { + console.error( + 'usage: jobs.cli.js status | find-by-chat | failed | replay --reason [--operator ] | reprocess --pipeline-version [--reason ] | publish-raw | queues', + ); + return 2; +} + +main() + .then((code) => process.exit(code)) + .catch((error: unknown) => { + console.log( + JSON.stringify({ + error: error instanceof Error ? error.message : 'unknown error', + }), + ); + process.exit(1); + }); diff --git a/app/src/jobs/jobs.module.ts b/app/src/jobs/jobs.module.ts new file mode 100644 index 0000000..26e251d --- /dev/null +++ b/app/src/jobs/jobs.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { BrokerClient } from './broker.client.js'; +import { FaultInjector } from './fault-injector.js'; +import { JobsRepository } from './jobs.repository.js'; + +@Module({ + imports: [DatabaseModule, RedisModule, MetricsModule], + providers: [BrokerClient, JobsRepository, FaultInjector], + exports: [BrokerClient, JobsRepository, FaultInjector], +}) +export class JobsModule {} diff --git a/app/src/jobs/jobs.repository.ts b/app/src/jobs/jobs.repository.ts new file mode 100644 index 0000000..9e0ba44 --- /dev/null +++ b/app/src/jobs/jobs.repository.ts @@ -0,0 +1,1057 @@ +import { Injectable } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; +import type { PoolClient } from 'pg'; +import type { AttachmentRow, VariantRow } from '../attachments/attachment.js'; +import { DatabaseClient } from '../database/database.client.js'; +import { buildJobMessage, type JobMessage } from './job-message.js'; +import { currentTraceFields } from '../telemetry/tracing.js'; + +/** + * Every outbox row carries the W3C trace context of the transaction that + * wrote it (optional traceparent/tracestate of contracts/jobs.schema.json), + * so causality survives restarts of the API, the broker and the worker. + * Writers without an active span (lease reaper, reconciler, CLI) produce the + * same message as before. + */ +function tracedJobMessage( + job: Parameters[0], +): JobMessage { + return { ...buildJobMessage(job), ...currentTraceFields() }; +} + +export type JobStatus = + 'queued' | 'processing' | 'succeeded' | 'failed' | 'superseded'; + +export type AttachmentJobRow = { + job_id: string; + attachment_id: string; + pipeline_version: number; + status: JobStatus; + attempt: number; + max_attempts: number; + next_attempt_at: Date; + lease_owner: string | null; + lease_token: string | null; + lease_until: Date | null; + last_error_code: string | null; + created_at: Date; + updated_at: Date; + finished_at: Date | null; +}; + +export type VariantWrite = { + name: 'thumbnail' | 'crop' | 'optimized'; + objectKey: string; + contentType: 'image/jpeg' | 'image/png' | 'image/webp'; + sizeBytes: number; + width: number; + height: number; + sha256: string; +}; + +export type ClaimResult = + | { kind: 'skip'; reason: string } + | { + kind: 'claimed'; + job: AttachmentJobRow; + attachment: AttachmentRow; + leaseToken: string; + }; + +export type CommitFailureResult = 'retry' | 'failed' | 'lease_lost'; +export type CommitSuccessResult = 'succeeded' | 'superseded' | 'lease_lost'; + +export type ReplayResult = + | { kind: 'replayed'; job_id: string; attempt: number } + | { kind: 'refused'; reason: string; job_id?: string }; + +export type ReprocessResult = + | { kind: 'created'; job_id: string } + | { kind: 'refused'; reason: string; job_id?: string }; + +@Injectable() +export class JobsRepository { + constructor(private readonly database: DatabaseClient) {} + + async acceptUpload( + attachmentId: string, + fields: { + sizeBytes: number; + sha256: string; + width: number; + height: number; + }, + pipelineVersion: number, + maxAttempts: number, + ): Promise { + return this.database.transaction('jobs.accept_upload', async (client) => { + const accepted = await client.query( + `UPDATE attachments + SET status = 'queued', size_bytes = $2, sha256 = $3, + width = $4, height = $5, expires_at = NULL, updated_at = now() + WHERE id = $1 AND status = 'pending' + RETURNING *`, + [ + attachmentId, + fields.sizeBytes, + fields.sha256, + fields.width, + fields.height, + ], + ); + const attachment = accepted.rows[0]; + if (!attachment) return undefined; + + const jobId = randomUUID(); + const created = await client.query( + `INSERT INTO attachment_jobs + (job_id, attachment_id, pipeline_version, status, attempt, + max_attempts, next_attempt_at) + VALUES ($1, $2, $3, 'queued', 1, $4, now()) + RETURNING *`, + [jobId, attachmentId, pipelineVersion, maxAttempts], + ); + const job = created.rows[0]; + await client.query( + `INSERT INTO job_outbox (job_id, payload, available_at) + VALUES ($1, $2::jsonb, now())`, + [ + job.job_id, + JSON.stringify( + tracedJobMessage({ + ...job, + created_at: job.created_at, + }), + ), + ], + ); + await this.event(client, job.job_id, 'created', 1, {}); + return attachment; + }); + } + + async claim( + message: JobMessage, + workerId: string, + leaseSeconds: number, + ): Promise { + return this.database.transaction('jobs.claim', async (client) => { + // Lock order is always job -> attachment, matching commitSuccess and + // commitFailure. A join FOR UPDATE would let the planner choose the + // opposite order under a concurrent duplicate delivery. + const foundJob = await client.query< + AttachmentJobRow & { due: boolean } + >( + `SELECT *, (next_attempt_at <= now()) AS due + FROM attachment_jobs + WHERE job_id = $1 + FOR UPDATE`, + [message.job_id], + ); + const job = foundJob.rows[0]; + if (!job) return { kind: 'skip', reason: 'unknown_job' }; + + const foundAttachment = await client.query( + `SELECT * FROM attachments WHERE id = $1 FOR UPDATE`, + [job.attachment_id], + ); + const attachment = foundAttachment.rows[0]; + + if ( + job.attachment_id !== message.attachment_id || + job.pipeline_version !== message.pipeline_version + ) + return this.skip(client, message, 'mismatch'); + + if (job.status === 'succeeded') + return this.skip(client, message, 'already_succeeded'); + if (job.status === 'failed') + return this.skip(client, message, 'already_failed'); + if (job.status === 'superseded') + return this.skip(client, message, 'superseded'); + if (job.status === 'processing') + return this.skip(client, message, 'in_progress'); + if (job.attempt !== message.attempt) + return this.skip(client, message, 'stale_attempt'); + // Both `next_attempt_at` and `now()` come from PostgreSQL; a worker + // clock skew must not turn a future retry into a lost job. + if (!job.due) + return this.skip(client, message, 'not_due'); + + if ( + attachment.ready_pipeline_version !== null && + attachment.ready_pipeline_version > job.pipeline_version + ) { + await client.query( + `UPDATE attachment_jobs + SET status = 'superseded', updated_at = now(), finished_at = now() + WHERE job_id = $1`, + [job.job_id], + ); + await this.event( + client, + job.job_id, + 'superseded', + job.attempt, + { + ready_pipeline_version: + attachment.ready_pipeline_version, + }, + ); + return this.skip(client, message, 'superseded'); + } + + const leaseToken = randomUUID(); + const claimed = await client.query( + `UPDATE attachment_jobs + SET status = 'processing', lease_owner = $2, lease_token = $3, + lease_until = now() + make_interval(secs => $4::double precision), + last_reconciled_at = NULL, + updated_at = now() + WHERE job_id = $1 + RETURNING *`, + [job.job_id, workerId, leaseToken, leaseSeconds], + ); + await client.query( + `UPDATE attachments SET status = 'processing', updated_at = now() + WHERE id = $1 AND status = 'queued'`, + [job.attachment_id], + ); + await this.event( + client, + job.job_id, + 'claimed', + claimed.rows[0].attempt, + { lease_owner: workerId }, + ); + return { + kind: 'claimed', + job: claimed.rows[0], + attachment, + leaseToken, + }; + }); + } + + async extendLease( + jobId: string, + token: string, + leaseSeconds: number, + ): Promise { + const result = await this.database.query( + 'jobs.extend_lease', + `UPDATE attachment_jobs + SET lease_until = now() + make_interval(secs => $3::double precision), + updated_at = now() + WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'`, + [jobId, token, leaseSeconds], + ); + return result.rowCount === 1; + } + + async commitSuccess( + jobId: string, + token: string, + variants: VariantWrite[], + ): Promise { + return this.database.transaction('jobs.commit_success', async (client) => { + const succeeded = await client.query( + `UPDATE attachment_jobs + SET status = 'succeeded', lease_owner = NULL, lease_token = NULL, + lease_until = NULL, updated_at = now(), finished_at = now() + WHERE job_id = $1 AND lease_token = $2 AND status = 'processing' + RETURNING *`, + [jobId, token], + ); + const job = succeeded.rows[0]; + if (!job) return 'lease_lost'; + + const attachment = await client.query( + `SELECT * FROM attachments WHERE id = $1 FOR UPDATE`, + [job.attachment_id], + ); + const row = attachment.rows[0]; + if ( + row.ready_pipeline_version !== null && + row.ready_pipeline_version > job.pipeline_version + ) { + await client.query( + `UPDATE attachment_jobs + SET status = 'superseded', updated_at = now() + WHERE job_id = $1`, + [job.job_id], + ); + await this.event( + client, + job.job_id, + 'superseded', + job.attempt, + { + ready_pipeline_version: row.ready_pipeline_version, + }, + ); + return 'superseded'; + } + + for (const variant of variants) { + await client.query( + `INSERT INTO attachment_variants + (attachment_id, pipeline_version, variant, object_key, + content_type, size_bytes, width, height, sha256, job_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (attachment_id, pipeline_version, variant) + DO UPDATE SET object_key = EXCLUDED.object_key, + content_type = EXCLUDED.content_type, + size_bytes = EXCLUDED.size_bytes, + width = EXCLUDED.width, + height = EXCLUDED.height, + sha256 = EXCLUDED.sha256, + job_id = EXCLUDED.job_id`, + [ + job.attachment_id, + job.pipeline_version, + variant.name, + variant.objectKey, + variant.contentType, + variant.sizeBytes, + variant.width, + variant.height, + variant.sha256, + job.job_id, + ], + ); + } + await client.query( + `UPDATE attachments + SET status = 'ready', ready_pipeline_version = $2, + error_code = NULL, updated_at = now() + WHERE id = $1`, + [job.attachment_id, job.pipeline_version], + ); + await this.event(client, job.job_id, 'succeeded', job.attempt, {}); + return 'succeeded'; + }); + } + + async commitFailure( + jobId: string, + token: string, + failure: { kind: 'permanent' | 'transient'; code: string }, + delayMs: number, + ): Promise { + return this.database.transaction('jobs.commit_failure', async (client) => { + const found = await client.query( + `SELECT * FROM attachment_jobs + WHERE job_id = $1 AND lease_token = $2 AND status = 'processing' + FOR UPDATE`, + [jobId, token], + ); + const job = found.rows[0]; + if (!job) return 'lease_lost'; + const finalCode = + failure.kind === 'permanent' || job.attempt >= job.max_attempts + ? failure.kind === 'transient' + ? 'retry_exhausted' + : failure.code + : failure.code; + + if ( + failure.kind === 'permanent' || + job.attempt >= job.max_attempts + ) { + await client.query( + `UPDATE attachment_jobs + SET status = 'failed', last_error_code = $2, + lease_owner = NULL, lease_token = NULL, lease_until = NULL, + updated_at = now(), finished_at = now() + WHERE job_id = $1`, + [job.job_id, finalCode], + ); + await client.query( + `UPDATE attachments + SET status = 'failed', error_code = $2, updated_at = now() + WHERE id = $1 AND status <> 'ready'`, + [job.attachment_id, finalCode], + ); + await this.event(client, job.job_id, 'failed', job.attempt, { + code: finalCode, + cause: failure.code, + }); + return 'failed'; + } + + const nextAttempt = job.attempt + 1; + await client.query( + `UPDATE attachment_jobs + SET status = 'queued', attempt = $2, + next_attempt_at = now() + make_interval(secs => $3::double precision), + lease_owner = NULL, lease_token = NULL, lease_until = NULL, + last_error_code = $4, last_reconciled_at = NULL, + updated_at = now() + WHERE job_id = $1`, + [job.job_id, nextAttempt, delayMs / 1000, failure.code], + ); + await client.query( + `UPDATE attachments SET status = 'queued', updated_at = now() + WHERE id = $1 AND status = 'processing'`, + [job.attachment_id], + ); + await client.query( + `INSERT INTO job_outbox (job_id, payload, available_at) + VALUES ($1, $2::jsonb, + now() + make_interval(secs => $3::double precision))`, + [ + job.job_id, + JSON.stringify( + tracedJobMessage({ ...job, attempt: nextAttempt }), + ), + delayMs / 1000, + ], + ); + await this.event( + client, + job.job_id, + 'retry_scheduled', + nextAttempt, + { + code: failure.code, + delay_ms: delayMs, + }, + ); + return 'retry'; + }); + } + + async reapExpiredLeases( + limit: number, + delayFor: (attempt: number) => number, + ): Promise { + return this.database.transaction('jobs.reap_expired_leases', async (client) => { + const expired = await client.query( + `SELECT * FROM attachment_jobs + WHERE status = 'processing' AND lease_until < now() + ORDER BY lease_until + LIMIT $1 + FOR UPDATE SKIP LOCKED`, + [limit], + ); + for (const job of expired.rows) { + // Keep the same lock order as claim/commit: job, then attachment. + await client.query( + `SELECT 1 FROM attachments WHERE id = $1 FOR UPDATE`, + [job.attachment_id], + ); + if (job.attempt >= job.max_attempts) { + await client.query( + `UPDATE attachment_jobs + SET status = 'failed', last_error_code = 'retry_exhausted', + lease_owner = NULL, lease_token = NULL, + lease_until = NULL, updated_at = now(), + finished_at = now() + WHERE job_id = $1`, + [job.job_id], + ); + await client.query( + `UPDATE attachments + SET status = 'failed', error_code = 'retry_exhausted', + updated_at = now() + WHERE id = $1 AND status <> 'ready'`, + [job.attachment_id], + ); + await this.event( + client, + job.job_id, + 'lease_expired', + job.attempt, + { + lease_owner: job.lease_owner, + code: 'retry_exhausted', + }, + ); + await this.event( + client, + job.job_id, + 'failed', + job.attempt, + { + code: 'retry_exhausted', + cause: 'lease_expired', + }, + ); + continue; + } + + const nextAttempt = job.attempt + 1; + const delayMs = delayFor(job.attempt); + await client.query( + `UPDATE attachment_jobs + SET status = 'queued', attempt = $2, + next_attempt_at = now() + make_interval(secs => $3::double precision), + lease_owner = NULL, lease_token = NULL, + lease_until = NULL, last_error_code = 'lease_expired', + last_reconciled_at = NULL, + updated_at = now() + WHERE job_id = $1`, + [job.job_id, nextAttempt, delayMs / 1000], + ); + await client.query( + `UPDATE attachments SET status = 'queued', updated_at = now() + WHERE id = $1 AND status = 'processing'`, + [job.attachment_id], + ); + await client.query( + `INSERT INTO job_outbox (job_id, payload, available_at) + VALUES ($1, $2::jsonb, + now() + make_interval(secs => $3::double precision))`, + [ + job.job_id, + JSON.stringify( + tracedJobMessage({ ...job, attempt: nextAttempt }), + ), + delayMs / 1000, + ], + ); + await this.event( + client, + job.job_id, + 'lease_expired', + job.attempt, + { lease_owner: job.lease_owner }, + ); + } + return expired.rows.length; + }); + } + + /** + * Backstop for a queued job whose broker message was lost or dead-lettered + * while the outbox row was already marked published. Re-emitting is safe: + * claim fences duplicates by job status and attempt. + */ + async reconcileQueuedJobs( + limit: number, + graceSeconds: number, + ): Promise { + return this.database.transaction('jobs.reconcile_queued', async (client) => { + const stuck = await client.query( + `SELECT j.* FROM attachment_jobs j + WHERE j.status = 'queued' + AND j.next_attempt_at <= now() + AND COALESCE( + (SELECT max(o.published_at) FROM job_outbox o + WHERE o.job_id = j.job_id AND o.published_at IS NOT NULL), + j.updated_at) <= now() - make_interval(secs => $2::double precision) + AND (j.last_reconciled_at IS NULL + OR j.last_reconciled_at <= now() - make_interval(secs => $2::double precision)) + AND NOT EXISTS ( + SELECT 1 FROM job_outbox o + WHERE o.job_id = j.job_id AND o.published_at IS NULL) + ORDER BY j.next_attempt_at + LIMIT $1 + FOR UPDATE SKIP LOCKED`, + [limit, graceSeconds], + ); + for (const job of stuck.rows) { + await client.query( + `UPDATE attachment_jobs SET last_reconciled_at = now(), updated_at = now() + WHERE job_id = $1`, + [job.job_id], + ); + await client.query( + `INSERT INTO job_outbox (job_id, payload, available_at) + VALUES ($1, $2::jsonb, now())`, + [job.job_id, JSON.stringify(tracedJobMessage(job))], + ); + await this.event( + client, + job.job_id, + 'reconciled', + job.attempt, + { code: 'queue_message_missing' }, + ); + } + return stuck.rows.length; + }); + } + + async publishPending( + limit: number, + publish: (message: JobMessage) => Promise, + afterPublish: () => Promise, + ): Promise { + return this.database.transaction('outbox.publish_pending', async (client) => { + const pending = await client.query<{ + id: string; + payload: JobMessage; + }>( + `SELECT id, payload FROM job_outbox + WHERE published_at IS NULL AND available_at <= now() + ORDER BY available_at, id + LIMIT $1 + FOR UPDATE SKIP LOCKED`, + [limit], + ); + const published: string[] = []; + let failure: unknown; + for (const row of pending.rows) { + try { + await publish(row.payload); + published.push(row.id); + } catch (error) { + failure = error; + break; + } + } + if (published.length === 0) { + if (failure) throw failure; + return 0; + } + await afterPublish(); + await client.query( + `UPDATE job_outbox SET published_at = now() WHERE id = ANY($1::bigint[])`, + [published], + ); + if (failure) throw failure; + return published.length; + }); + } + + async variantsFor( + attachmentId: string, + pipelineVersion: number, + ): Promise { + const result = await this.database.query( + 'jobs.variants', + `SELECT * FROM attachment_variants + WHERE attachment_id = $1 AND pipeline_version = $2 + ORDER BY array_position(ARRAY['thumbnail','crop','optimized']::text[], variant)`, + [attachmentId, pipelineVersion], + ); + return result.rows; + } + + async stagingCleanupCandidates( + retentionSeconds: number, + limit: number, + ): Promise<{ id: string; staging_key: string }[]> { + const result = await this.database.query<{ + id: string; + staging_key: string; + }>( + 'jobs.staging_candidates', + `SELECT id, staging_key FROM attachments + WHERE staging_key IS NOT NULL + AND ((status = 'ready' AND updated_at < now() - interval '1 minute') + OR (status = 'failed' AND updated_at < now() - make_interval(secs => $1::double precision))) + ORDER BY updated_at + LIMIT $2`, + [retentionSeconds, limit], + ); + return result.rows; + } + + async clearStaging( + id: string, + key: string, + removeObject: (key: string) => Promise, + ): Promise { + return this.database.transaction('attachments.clear_staging', async (client) => { + // Keep the same job -> attachment lock order as claim/replay, then + // serialize cleanup with replay on the attachment row. + await client.query( + `SELECT job_id FROM attachment_jobs + WHERE attachment_id = $1 + ORDER BY created_at DESC + LIMIT 1 + FOR UPDATE`, + [id], + ); + const locked = await client.query( + `SELECT * FROM attachments WHERE id = $1 FOR UPDATE`, + [id], + ); + const row = locked.rows[0]; + if ( + !row || + row.staging_key !== key || + !['ready', 'failed'].includes(row.status) + ) + return false; + await removeObject(key); + await client.query( + `UPDATE attachments SET staging_key = NULL, updated_at = now() + WHERE id = $1`, + [id], + ); + await client.query( + `INSERT INTO job_events (job_id, event, attempt, detail) + SELECT job_id, 'staging_deleted', attempt, $2::jsonb + FROM attachment_jobs + WHERE attachment_id = $1 + ORDER BY created_at DESC + LIMIT 1`, + [id, JSON.stringify({ staging_key: key })], + ); + return true; + }); + } + + async pruneOutbox( + retentionSeconds: number, + limit = 5000, + ): Promise { + const result = await this.database.query( + 'jobs.outbox_prune', + `DELETE FROM job_outbox + WHERE id IN ( + SELECT id FROM job_outbox + WHERE published_at IS NOT NULL + AND published_at < now() - make_interval(secs => $1::double precision) + ORDER BY published_at + LIMIT $2)`, + [retentionSeconds, limit], + ); + return result.rowCount ?? 0; + } + + async pruneEvents( + retentionSeconds: number, + limit = 5000, + ): Promise { + const result = await this.database.query( + 'jobs.events_prune', + `DELETE FROM job_events + WHERE id IN ( + SELECT id FROM job_events + WHERE created_at < now() - make_interval(secs => $1::double precision) + ORDER BY created_at + LIMIT $2)`, + [retentionSeconds, limit], + ); + return result.rowCount ?? 0; + } + + async statusOf(attachmentId: string): Promise< + | { + attachment: AttachmentRow; + jobs: AttachmentJobRow[]; + variants: VariantRow[]; + events: { + job_id: string; + event: string; + attempt: number; + detail: unknown; + created_at: Date; + }[]; + outbox: { pending: number; published: number }; + } + | undefined + > { + const attachment = await this.database.query( + 'jobs.status_attachment', + `SELECT * FROM attachments WHERE id = $1`, + [attachmentId], + ); + if (!attachment.rows[0]) return undefined; + const jobs = await this.database.query( + 'jobs.status_jobs', + `SELECT * FROM attachment_jobs WHERE attachment_id = $1 ORDER BY created_at`, + [attachmentId], + ); + const variants = await this.database.query( + 'jobs.status_variants', + `SELECT * FROM attachment_variants WHERE attachment_id = $1 + ORDER BY pipeline_version, + array_position(ARRAY['thumbnail','crop','optimized']::text[], variant)`, + [attachmentId], + ); + const events = await this.database.query<{ + job_id: string; + event: string; + attempt: number; + detail: unknown; + created_at: Date; + }>( + 'jobs.status_events', + `SELECT e.job_id, e.event, e.attempt, e.detail, e.created_at + FROM job_events e + JOIN attachment_jobs j ON j.job_id = e.job_id + WHERE j.attachment_id = $1 + ORDER BY e.id`, + [attachmentId], + ); + const outbox = await this.database.query<{ + pending: string; + published: string; + }>( + 'jobs.status_outbox', + `SELECT count(*) FILTER (WHERE o.published_at IS NULL) AS pending, + count(*) FILTER (WHERE o.published_at IS NOT NULL) AS published + FROM job_outbox o + JOIN attachment_jobs j ON j.job_id = o.job_id + WHERE j.attachment_id = $1`, + [attachmentId], + ); + return { + attachment: attachment.rows[0], + jobs: jobs.rows, + variants: variants.rows, + events: events.rows, + outbox: { + pending: Number(outbox.rows[0]?.pending ?? 0), + published: Number(outbox.rows[0]?.published ?? 0), + }, + }; + } + + async findByChat( + chatId: string, + ): Promise<{ id: string; status: string; created_at: Date }[]> { + const result = await this.database.query<{ + id: string; + status: string; + created_at: Date; + }>( + 'jobs.find_by_chat', + `SELECT id, status, created_at FROM attachments + WHERE chat_id = $1 ORDER BY created_at`, + [chatId], + ); + return result.rows; + } + + async failedJobs(): Promise< + { + attachment_id: string; + job_id: string; + pipeline_version: number; + attempt: number; + last_error_code: string | null; + updated_at: Date; + }[] + > { + const result = await this.database.query<{ + attachment_id: string; + job_id: string; + pipeline_version: number; + attempt: number; + last_error_code: string | null; + updated_at: Date; + }>( + 'jobs.failed', + `SELECT attachment_id, job_id, pipeline_version, attempt, + last_error_code, updated_at + FROM attachment_jobs WHERE status = 'failed' + ORDER BY updated_at`, + ); + return result.rows; + } + + async replayCandidate(attachmentId: string): Promise< + | { + job_id: string; + pipeline_version: number; + staging_key: string | null; + } + | undefined + > { + const result = await this.database.query<{ + job_id: string; + pipeline_version: number; + staging_key: string | null; + }>( + 'jobs.replay_candidate', + `SELECT j.job_id, j.pipeline_version, a.staging_key + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.attachment_id = $1 AND j.status = 'failed' + ORDER BY j.updated_at DESC + LIMIT 1`, + [attachmentId], + ); + return result.rows[0]; + } + + async replay( + attachmentId: string, + options: { + reason: string; + operator: string; + maxAttempts: number; + sourceAvailable: boolean; + expectedStagingKey: string | null; + }, + ): Promise { + return this.database.transaction('jobs.replay', async (client) => { + const found = await client.query( + `SELECT * FROM attachment_jobs + WHERE attachment_id = $1 AND status = 'failed' + ORDER BY updated_at DESC + LIMIT 1 + FOR UPDATE`, + [attachmentId], + ); + const job = found.rows[0]; + if (!job) return { kind: 'refused', reason: 'no_failed_job' }; + + const attachment = await client.query( + `SELECT * FROM attachments WHERE id = $1 FOR UPDATE`, + [attachmentId], + ); + const row = attachment.rows[0]; + if ( + row.status === 'ready' && + row.ready_pipeline_version !== null && + row.ready_pipeline_version >= job.pipeline_version + ) + return { + kind: 'refused', + reason: 'already_ready', + job_id: job.job_id, + }; + + const active = await client.query( + `SELECT 1 FROM attachment_jobs + WHERE attachment_id = $1 AND status IN ('queued','processing') + LIMIT 1`, + [attachmentId], + ); + if (active.rowCount !== 0) + return { + kind: 'refused', + reason: 'job_active', + job_id: job.job_id, + }; + + if (row.staging_key !== options.expectedStagingKey) + return { + kind: 'refused', + reason: 'source_changed', + job_id: job.job_id, + }; + if (row.staging_key === null && !options.sourceAvailable) + return { + kind: 'refused', + reason: 'source_expired', + job_id: job.job_id, + }; + + const attempt = job.attempt + 1; + await client.query( + `UPDATE attachment_jobs + SET status = 'queued', attempt = $2, + max_attempts = $2::integer + $3::integer - 1, + next_attempt_at = now(), lease_owner = NULL, + lease_token = NULL, lease_until = NULL, + last_reconciled_at = NULL, + updated_at = now(), finished_at = NULL + WHERE job_id = $1`, + [job.job_id, attempt, options.maxAttempts], + ); + await client.query( + `UPDATE attachments SET status = 'queued', error_code = NULL, + updated_at = now() + WHERE id = $1 AND status = 'failed'`, + [attachmentId], + ); + await client.query( + `INSERT INTO job_outbox (job_id, payload, available_at) + VALUES ($1, $2::jsonb, now())`, + [ + job.job_id, + JSON.stringify(tracedJobMessage({ ...job, attempt })), + ], + ); + await this.event(client, job.job_id, 'replayed', attempt, { + operator: options.operator, + reason: options.reason, + previous_error: job.last_error_code, + }); + return { kind: 'replayed', job_id: job.job_id, attempt }; + }); + } + + async reprocess( + attachmentId: string, + pipelineVersion: number, + options: { reason: string; operator: string; maxAttempts: number }, + ): Promise { + return this.database.transaction('jobs.reprocess', async (client) => { + const attachment = await client.query( + `SELECT * FROM attachments WHERE id = $1 FOR UPDATE`, + [attachmentId], + ); + const row = attachment.rows[0]; + if ( + !row || + !['queued', 'processing', 'ready', 'failed'].includes( + row.status, + ) + ) + return { kind: 'refused', reason: 'not_accepted' }; + + const jobId = randomUUID(); + const created = await client.query( + `INSERT INTO attachment_jobs + (job_id, attachment_id, pipeline_version, status, attempt, + max_attempts, next_attempt_at) + VALUES ($1, $2, $3, 'queued', 1, $4, now()) + ON CONFLICT (attachment_id, pipeline_version) DO NOTHING + RETURNING *`, + [jobId, attachmentId, pipelineVersion, options.maxAttempts], + ); + const job = created.rows[0]; + if (!job) { + const existing = await client.query<{ job_id: string }>( + `SELECT job_id FROM attachment_jobs + WHERE attachment_id = $1 AND pipeline_version = $2`, + [attachmentId, pipelineVersion], + ); + return { + kind: 'refused', + reason: 'job_exists', + job_id: existing.rows[0]?.job_id, + }; + } + await client.query( + `INSERT INTO job_outbox (job_id, payload, available_at) + VALUES ($1, $2::jsonb, now())`, + [job.job_id, JSON.stringify(tracedJobMessage(job))], + ); + await this.event(client, job.job_id, 'created', 1, { + reason: options.reason, + operator: options.operator, + }); + return { kind: 'created', job_id: job.job_id }; + }); + } + + private async skip( + client: PoolClient, + message: JobMessage, + reason: string, + ): Promise { + await this.event( + client, + message.job_id, + 'duplicate_skipped', + message.attempt, + { reason, message_attempt: message.attempt }, + ); + return { kind: 'skip', reason }; + } + + private async event( + client: PoolClient, + jobId: string, + event: string, + attempt: number, + detail: Record, + ): Promise { + await client.query( + `INSERT INTO job_events (job_id, event, attempt, detail) + VALUES ($1, $2, $3, $4::jsonb)`, + [jobId, event, attempt, JSON.stringify(detail)], + ); + } +} diff --git a/app/src/jobs/outbox-relay.service.ts b/app/src/jobs/outbox-relay.service.ts new file mode 100644 index 0000000..06e77cd --- /dev/null +++ b/app/src/jobs/outbox-relay.service.ts @@ -0,0 +1,119 @@ +import { + Injectable, + Logger, + OnApplicationBootstrap, + OnModuleDestroy, +} from '@nestjs/common'; +import { context, ROOT_CONTEXT } from '@opentelemetry/api'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { BrokerClient } from './broker.client.js'; +import { FaultInjector } from './fault-injector.js'; +import { JobsRepository } from './jobs.repository.js'; +import { contextFromTraceFields } from '../telemetry/tracing.js'; + +const BATCH_SIZE = 20; + +/** + * Runs in the API and worker processes. `publishPending` holds one transaction around + * the broker confirms and the `published_at` update; a crash before the mark + * rolls the transaction back and republishes the same message after restart. + * That duplicate is expected: the worker fences it on job status. + */ +@Injectable() +export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy { + private readonly logger = new Logger(OutboxRelay.name); + private timer: NodeJS.Timeout | undefined; + private running = false; + private again = false; + private current: Promise | undefined; + private failing = false; + private retryAt = 0; + private retryDelayMs = 1000; + + constructor( + private readonly config: ConfigService, + private readonly repository: JobsRepository, + private readonly broker: BrokerClient, + private readonly faults: FaultInjector, + private readonly metrics: MetricsService, + ) {} + + onApplicationBootstrap(): void { + const interval = this.config.getOrThrow('OUTBOX_POLL_INTERVAL_MS'); + this.timer = setInterval(() => this.kick(), interval); + this.timer.unref(); + this.kick(); + } + + async onModuleDestroy(): Promise { + clearInterval(this.timer); + this.timer = undefined; + await this.current; + } + + kick(): void { + if (Date.now() < this.retryAt) return; + if (this.running) { + this.again = true; + return; + } + this.running = true; + // A batch belongs to no particular request or job: each message carries + // its own trace context (see drain). + this.current = context + .with(ROOT_CONTEXT, () => this.drain()) + .catch((error: unknown) => { + this.metrics.increment('outbox.publish_failed'); + this.retryAt = Date.now() + this.retryDelayMs; + this.retryDelayMs = Math.min(this.retryDelayMs * 2, 10_000); + if (!this.failing) { + this.failing = true; + this.logger.warn( + `Outbox publish failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + }) + .finally(() => { + this.running = false; + this.current = undefined; + if (this.again) { + this.again = false; + this.kick(); + } + }); + } + + private async drain(): Promise { + const budgetMs = Math.max( + 1000, + Math.floor( + this.config.getOrThrow('DATABASE_IDLE_TX_TIMEOUT_MS') / 2, + ), + ); + const started = Date.now(); + const published = await this.repository.publishPending( + BATCH_SIZE, + async (message) => { + if (Date.now() - started > budgetMs) + throw new Error('outbox batch deadline exceeded'); + // The PRODUCER span continues the trace of the request that wrote + // the outbox row. + await context.with(contextFromTraceFields(message), () => + this.broker.publish(message), + ); + }, + () => this.faults.point('relay.after_publish_before_mark'), + ); + if (published > 0) { + this.metrics.add('outbox.published', published); + this.retryAt = 0; + this.retryDelayMs = 1000; + if (this.failing) { + this.failing = false; + this.logger.log('Outbox publishing recovered'); + } + } + } +} diff --git a/app/src/main.ts b/app/src/main.ts new file mode 100644 index 0000000..11c043d --- /dev/null +++ b/app/src/main.ts @@ -0,0 +1,110 @@ +// Must stay the first import: the OpenTelemetry SDK has to be registered +// before any module creates instruments or handles a request. +import './telemetry/api-bootstrap.js'; +import { NestFactory } from '@nestjs/core'; +import { HttpAdapterHost } from '@nestjs/core'; +import { ConfigService } from '@nestjs/config'; +import { ValidationPipe } from '@nestjs/common'; +import type { UploadRequest } from './attachments/upload-request.js'; +import { + FastifyAdapter, + NestFastifyApplication, +} from '@nestjs/platform-fastify'; +import { AppModule } from './app.module.js'; +import { HealthService } from './health/health.service.js'; +import { MetricsService } from './metrics/metrics.service.js'; +import { RequestIdInterceptor } from './common/http/request-id.interceptor.js'; +import { installHttpTelemetry } from './telemetry/http.js'; +import { appLogger } from './telemetry/logger.js'; +import { shutdownTelemetry } from './telemetry/sdk.js'; + +const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments'; +const UPLOAD_STREAM_TYPE = 'application/x-messenger-upload-stream'; + +async function bootstrap(): Promise { + const app = await NestFactory.create( + AppModule, + // Fastify's pino access log is replaced by the structured http.request + // event (telemetry/http.ts): pino logged raw URLs with identifiers. + new FastifyAdapter({ logger: false }), + { logger: appLogger }, + ); + // The upload route receives its body as an unread stream whatever the + // declared Content-Type: the service checks the type itself, after the + // auth guard (401 before 415, contracts/README.md), and bounds the body by + // its own limits, not Fastify's bodyLimit. The declared type is kept on the + // request; all other routes keep Fastify's parsers untouched. + const fastify = app.getHttpAdapter().getInstance(); + // Telemetry hooks go first, so every request is measured even if a later + // hook answers it. Routes are registered at init, after the onRoute hook, + // so their handlers run inside the request span. + installHttpTelemetry(fastify); + fastify.addHook( + 'onRequest', + (request: UploadRequest, _reply: unknown, done: () => void) => { + if ( + request.method === 'POST' && + request.routeOptions?.url === UPLOAD_ROUTE + ) { + request.uploadContentType = request.headers['content-type']; + request.headers['content-type'] = UPLOAD_STREAM_TYPE; + } + done(); + }, + ); + fastify.addContentTypeParser( + UPLOAD_STREAM_TYPE, + ( + _request: unknown, + payload: unknown, + done: (error: Error | null, body?: unknown) => void, + ) => done(null, payload), + ); + app.useGlobalInterceptors( + new RequestIdInterceptor( + app.get(HttpAdapterHost), + app.get(MetricsService), + app.get(ConfigService), + ), + ); + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + }), + ); + + const config = app.get(ConfigService); + const port = config.getOrThrow('APP_PORT'); + const host = config.getOrThrow('APP_HOST'); + await app.listen(port, host); + + // Drain before teardown. Nest's own shutdown sequence destroys providers + // (closing the database pool and Redis) before `beforeApplicationShutdown` + // runs, so relying on it would keep the replica listed in the load balancer + // while it can no longer serve: SIGTERM must first turn the replica + // not-ready for the LB probe, then wait DRAIN_DELAY_MS, and only then close + // the server and the pools. + const health = app.get(HealthService); + const drainDelayMs = config.getOrThrow('DRAIN_DELAY_MS'); + let shuttingDown = false; + const shutdown = async (): Promise => { + if (shuttingDown) return; + shuttingDown = true; + health.setDraining(); + if (drainDelayMs > 0) + await new Promise((resolve) => + setTimeout(resolve, drainDelayMs), + ); + await app.close(); + await shutdownTelemetry(); + process.exit(0); + }; + for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) + process.once(signal, () => { + void shutdown(); + }); +} + +await bootstrap(); diff --git a/app/src/messages/cache/messages-cache.metrics.spec.ts b/app/src/messages/cache/messages-cache.metrics.spec.ts new file mode 100644 index 0000000..13da19e --- /dev/null +++ b/app/src/messages/cache/messages-cache.metrics.spec.ts @@ -0,0 +1,37 @@ +import { ConfigService } from '@nestjs/config'; +import { describe, expect, it, vi } from 'vitest'; +import { MetricsService } from '../../metrics/metrics.service.js'; +import { MessagesCacheService } from './messages-cache.service.js'; + +describe('MessagesCacheService metrics', () => { + it('records a miss and a hit for a protected page fill', async () => { + const metrics = new MetricsService(); + const page = { items: [], next_cursor: null }; + const redis = { + get: vi + .fn() + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + .mockResolvedValue(JSON.stringify(page)), + setNxPx: vi.fn().mockResolvedValue(true), + set: vi.fn().mockResolvedValue('OK'), + unlock: vi.fn().mockResolvedValue(1), + }; + const config = new ConfigService({ + CACHE_MODE: 'protected', + CACHE_LOCK_TTL_MS: 1000, + CACHE_TTL_SECONDS: 30, + }); + const service = new MessagesCacheService( + redis as never, + config, + metrics, + ); + await service.getOrLoad('chat', 1n, undefined, 50, async () => page); + await service.getOrLoad('chat', 1n, undefined, 50, async () => page); + expect(metrics.snapshot().counters).toMatchObject({ + cache_miss: 1, + cache_hit: 1, + }); + }); +}); diff --git a/app/src/messages/cache/messages-cache.module.ts b/app/src/messages/cache/messages-cache.module.ts new file mode 100644 index 0000000..f1cfddf --- /dev/null +++ b/app/src/messages/cache/messages-cache.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { MessagesCacheService } from './messages-cache.service.js'; +import { MetricsModule } from '../../metrics/metrics.module.js'; +import { RedisModule } from '../../redis/redis.module.js'; + +@Module({ + imports: [RedisModule, MetricsModule], + providers: [MessagesCacheService], + exports: [MessagesCacheService], +}) +export class MessagesCacheModule {} diff --git a/app/src/messages/cache/messages-cache.service.spec.ts b/app/src/messages/cache/messages-cache.service.spec.ts new file mode 100644 index 0000000..c405349 --- /dev/null +++ b/app/src/messages/cache/messages-cache.service.spec.ts @@ -0,0 +1,72 @@ +import { ConfigService } from '@nestjs/config'; +import { describe, expect, it, vi } from 'vitest'; +import type { AppConfig } from '../../config/app-config.schema.js'; +import type { RedisClient } from '../../redis/redis.client.js'; +import { MessagesCacheService } from './messages-cache.service.js'; +import { MetricsService } from '../../metrics/metrics.service.js'; + +function serviceWithRedis(redis: Partial): MessagesCacheService { + const config = new ConfigService({ + CACHE_MODE: 'protected', + CACHE_LOCK_TTL_MS: 1000, + CACHE_TTL_SECONDS: 30, + CACHE_MISS_DELAY_MS: 0, + }); + return new MessagesCacheService( + redis as RedisClient, + config, + new MetricsService(), + ); +} + +describe('MessagesCacheService fallback', () => { + it('loads from the authoritative source when Redis read fails', async () => { + const load = vi + .fn() + .mockResolvedValue({ items: [{ id: 'db' }], next_cursor: null }); + const service = serviceWithRedis({ + get: vi.fn().mockRejectedValue(new Error('redis down')), + }); + + await expect( + service.getOrLoad('chat', 1n, undefined, 50, load), + ).resolves.toEqual({ + items: [{ id: 'db' }], + next_cursor: null, + }); + expect(load).toHaveBeenCalledOnce(); + }); + + it('falls back after bounded lock contention', async () => { + const load = vi + .fn() + .mockResolvedValue({ items: [{ id: 'db' }], next_cursor: null }); + const service = serviceWithRedis({ + get: vi.fn().mockResolvedValue(null), + setNxPx: vi.fn().mockResolvedValue(false), + }); + + await expect( + service.getOrLoad('chat', 1n, undefined, 50, load), + ).resolves.toEqual({ + items: [{ id: 'db' }], + next_cursor: null, + }); + expect(load).toHaveBeenCalledOnce(); + }); + + it('returns the authoritative page when cache write fails', async () => { + const page = { items: [{ id: 'db' }], next_cursor: null }; + const load = vi.fn().mockResolvedValue(page); + const service = serviceWithRedis({ + get: vi.fn().mockResolvedValue(null), + setNxPx: vi.fn().mockResolvedValue(true), + set: vi.fn().mockRejectedValue(new Error('redis down')), + unlock: vi.fn().mockResolvedValue(1), + }); + + await expect( + service.getOrLoad('chat', 1n, undefined, 50, load), + ).resolves.toEqual(page); + }); +}); diff --git a/app/src/messages/cache/messages-cache.service.ts b/app/src/messages/cache/messages-cache.service.ts new file mode 100644 index 0000000..565c17c --- /dev/null +++ b/app/src/messages/cache/messages-cache.service.ts @@ -0,0 +1,205 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { setTimeout as delay } from 'node:timers/promises'; +import type { AppConfig } from '../../config/app-config.schema.js'; +import { RedisClient } from '../../redis/redis.client.js'; +import type { Page } from '../../common/http/page.js'; +import { MetricsService } from '../../metrics/metrics.service.js'; + +const LOCK_RETRY_COUNT = 4; +const LOCK_RETRY_DELAY_MS = 25; + +export type CachePage = Page; + +@Injectable() +export class MessagesCacheService { + private readonly logger = new Logger(MessagesCacheService.name); + + constructor( + private readonly redis: RedisClient, + private readonly config: ConfigService, + private readonly metrics: MetricsService, + ) {} + + async getOrLoad( + chatId: string, + version: bigint, + cursor: string | undefined, + limit: number, + loader: () => Promise, + ): Promise { + const key = this.cacheKey(chatId, version, cursor, limit); + if (this.config.getOrThrow('CACHE_MODE') === 'naive') { + return this.loadNaively(key, loader); + } + + let cached: string | null; + try { + cached = await this.redis.get(key); + } catch (error) { + return this.fallbackToDatabase('read', error, loader); + } + const cachedPage = this.parsePage(cached); + if (cachedPage) { + this.metrics.increment('cache_hit'); + return cachedPage; + } + this.metrics.increment('cache_miss'); + + const lockKey = `lock:${key}`; + const owner = `${process.pid}:${Math.random().toString(36).slice(2)}`; + for (let attempt = 0; attempt < LOCK_RETRY_COUNT; attempt += 1) { + let locked: boolean; + try { + locked = await this.redis.setNxPx( + lockKey, + owner, + this.config.getOrThrow('CACHE_LOCK_TTL_MS'), + ); + } catch (error) { + return this.fallbackToDatabase('lock', error, loader); + } + if (locked) return this.fillLocked(key, lockKey, owner, loader); + + if (attempt === 0) this.metrics.increment('cache_lock_wait'); + try { + const waitedPage = this.parsePage(await this.redis.get(key)); + if (waitedPage) { + this.metrics.increment('cache_hit'); + return waitedPage; + } + } catch (error) { + return this.fallbackToDatabase('waiting read', error, loader); + } + await delay(LOCK_RETRY_DELAY_MS); + } + + // The owner did not publish the page within the bounded wait: serve the + // authoritative result instead of blocking the request further. + this.metrics.increment('cache_lock_timeout'); + return loader(); + } + + private async fillLocked( + key: string, + lockKey: string, + owner: string, + loader: () => Promise, + ): Promise { + try { + let secondCheck: string | null; + try { + secondCheck = await this.redis.get(key); + } catch (error) { + return this.fallbackToDatabase('double-check', error, loader); + } + const secondPage = this.parsePage(secondCheck); + if (secondPage) { + this.metrics.increment('cache_hit'); + return secondPage; + } + + const page = await loader(); + try { + await this.redis.set(key, JSON.stringify(page), { + EX: this.config.getOrThrow('CACHE_TTL_SECONDS'), + }); + } catch (error) { + // Redis is derived state: the page is still valid for this response, + // but the failure must stay visible in metrics and logs. + this.metrics.increment('cache_write_error'); + this.logger.warn( + `Cache fill failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + return page; + } finally { + try { + await this.redis.unlock(lockKey, owner); + } catch (error) { + // The lock has a TTL, so a stale lock expires on its own; a successful + // response must not be replaced by an unlock failure. + this.metrics.increment('cache_unlock_error'); + this.logger.warn( + `Cache unlock failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + } + } + + private cacheKey( + chatId: string, + version: bigint, + cursor: string | undefined, + limit: number, + ): string { + return `messages:${chatId}:v${version.toString()}:c${cursor ?? 'start'}:l${limit}`; + } + + private async loadNaively( + key: string, + loader: () => Promise, + ): Promise { + let cached: string | null; + try { + cached = await this.redis.get(key); + } catch (error) { + return this.fallbackToDatabase('naive read', error, loader); + } + const cachedPage = this.parsePage(cached); + if (cachedPage) { + this.metrics.increment('cache_hit'); + return cachedPage; + } + this.metrics.increment('cache_miss'); + + const cacheMissDelay = this.config.getOrThrow('CACHE_MISS_DELAY_MS'); + if (cacheMissDelay > 0) await delay(cacheMissDelay); + const page = await loader(); + try { + await this.redis.set(key, JSON.stringify(page), { + EX: this.config.getOrThrow('CACHE_TTL_SECONDS'), + }); + } catch (error) { + this.metrics.increment('cache_write_error'); + this.logger.warn( + `Cache fill failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + return page; + } + + private async fallbackToDatabase( + stage: string, + error: unknown, + loader: () => Promise, + ): Promise { + this.metrics.increment('cache_fallback'); + this.logger.warn( + `Cache ${stage} failed, serving PostgreSQL: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + return loader(); + } + + private parsePage(value: string | null): CachePage | undefined { + if (!value) return undefined; + try { + const parsed: unknown = JSON.parse(value); + if ( + typeof parsed !== 'object' || + parsed === null || + !('items' in parsed) || + !('next_cursor' in parsed) || + !Array.isArray(parsed.items) || + (parsed.next_cursor !== null && + typeof parsed.next_cursor !== 'string') + ) + return undefined; + return { items: parsed.items, next_cursor: parsed.next_cursor }; + } catch { + // A malformed entry is treated as a miss and overwritten by the owner fill. + this.metrics.increment('cache_corrupt_entry'); + return undefined; + } + } +} diff --git a/app/src/messages/dto/create-message.dto.ts b/app/src/messages/dto/create-message.dto.ts new file mode 100644 index 0000000..0a8b8d2 --- /dev/null +++ b/app/src/messages/dto/create-message.dto.ts @@ -0,0 +1,23 @@ +import { + ArrayMaxSize, + ArrayUnique, + IsArray, + IsString, + IsUUID, + ValidateIf, +} from 'class-validator'; +import { CodePointLength } from '../../common/validation/code-point-length.js'; + +export class CreateMessageDto { + @IsString() + @CodePointLength(0, 4000) + text!: string; + + // Absent means []; null is a client error. + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @ArrayMaxSize(10) + @ArrayUnique() + @IsUUID('all', { each: true }) + attachment_ids: string[] = []; +} diff --git a/app/src/messages/idempotency/idempotency-gc.cli.ts b/app/src/messages/idempotency/idempotency-gc.cli.ts new file mode 100644 index 0000000..4e473bc --- /dev/null +++ b/app/src/messages/idempotency/idempotency-gc.cli.ts @@ -0,0 +1,33 @@ +import { fileURLToPath } from 'node:url'; +import { parseDatabaseConfig } from '../../config/app-config.schema.js'; +import { DatabaseClient } from '../../database/database.client.js'; +import { MetricsService } from '../../metrics/metrics.service.js'; +import { IdempotencyRepository } from './idempotency.repository.js'; + +// Manual operator pass over the idempotency ledger: the API also purges expired +// claims in the background, but an operator must be able to reclaim space +// without waiting for traffic. It never touches unexpired claims. +// in the stand: docker compose exec api node dist/messages/idempotency/idempotency-gc.cli.js +// on the host: npm run idempotency:gc (needs a reachable DATABASE_URL) +async function main(): Promise { + const config = parseDatabaseConfig(process.env as Record); + const database = new DatabaseClient( + { + getOrThrow: (key: keyof typeof config) => config[key], + } as never, + new MetricsService(), + ); + try { + const repository = new IdempotencyRepository(database); + const purged = await repository.purgeExpired( + config.IDEMPOTENCY_TTL_SECONDS, + ); + process.stdout.write( + `Purged ${purged} idempotency key(s) older than ${config.IDEMPOTENCY_TTL_SECONDS} seconds\n`, + ); + } finally { + await database.onModuleDestroy(); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) await main(); diff --git a/app/src/messages/idempotency/idempotency.module.ts b/app/src/messages/idempotency/idempotency.module.ts new file mode 100644 index 0000000..33c8a32 --- /dev/null +++ b/app/src/messages/idempotency/idempotency.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../../database/database.module.js'; +import { IdempotencyRepository } from './idempotency.repository.js'; + +@Module({ + imports: [DatabaseModule], + providers: [IdempotencyRepository], + exports: [IdempotencyRepository], +}) +export class IdempotencyModule {} diff --git a/app/src/messages/idempotency/idempotency.repository.spec.ts b/app/src/messages/idempotency/idempotency.repository.spec.ts new file mode 100644 index 0000000..056876a --- /dev/null +++ b/app/src/messages/idempotency/idempotency.repository.spec.ts @@ -0,0 +1,24 @@ +import { describe, expect, it, vi } from 'vitest'; +import { IdempotencyRepository } from './idempotency.repository.js'; + +describe('IdempotencyRepository expired-key cleanup', () => { + it('deletes only rows older than the configured TTL', async () => { + const query = vi.fn().mockResolvedValue({ rowCount: 0, rows: [] }); + const repository = new IdempotencyRepository({ query } as never); + + await repository.forget( + 'user', + '/api/v1/chats/chat/messages', + 'key', + 86400, + ); + + expect(query).toHaveBeenCalledWith( + 'idempotency.forget', + expect.stringContaining( + 'created_at < now() - make_interval(secs => $4::double precision)', + ), + ['user', '/api/v1/chats/chat/messages', 'key', 86400], + ); + }); +}); diff --git a/app/src/messages/idempotency/idempotency.repository.ts b/app/src/messages/idempotency/idempotency.repository.ts new file mode 100644 index 0000000..badd736 --- /dev/null +++ b/app/src/messages/idempotency/idempotency.repository.ts @@ -0,0 +1,119 @@ +import { Injectable } from '@nestjs/common'; +import pg from 'pg'; +import { DatabaseClient } from '../../database/database.client.js'; +import type { Message } from '../message.js'; + +// A committed row always carries the response: the claim and the stored response +// are written by one statement, so there is no poisoned intermediate state to +// re-check at replay time. +export type IdempotencyRecord = { + request_fingerprint: string; + status_code: number; + response_body: Message; + created_at: Date | string; + expired: boolean; + is_member: boolean; +}; + +const PURGE_BATCH_LIMIT = 1000; +const PURGE_BATCHES = 10; + +@Injectable() +export class IdempotencyRepository { + constructor(private readonly database: DatabaseClient) {} + + /** + * Reads the stored result and re-checks access in the same round trip: a + * replay must still prove that the caller may read this chat. + */ + async read( + userId: string, + path: string, + key: string, + chatId: string, + ttlSeconds: number, + ): Promise { + const result = await this.database.query( + 'idempotency.read', + `SELECT k.request_fingerprint, k.status_code, k.response_body, k.created_at, + k.created_at < now() - make_interval(secs => $4::double precision) AS expired, + EXISTS ( + SELECT 1 FROM chat_members WHERE chat_id = $5 AND user_id = $1 + ) AS is_member + FROM idempotency_keys k + WHERE k.user_id = $1 AND k.method = 'POST' AND k.path = $2 AND k.key = $3`, + [userId, path, key, ttlSeconds, chatId], + ); + return result.rows[0]; + } + + async forget( + userId: string, + path: string, + key: string, + ttlSeconds: number, + ): Promise { + await this.database.query( + 'idempotency.forget', + `DELETE FROM idempotency_keys + WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3 + AND created_at < now() - make_interval(secs => $4::double precision)`, + [userId, path, key, ttlSeconds], + ); + } + + async isMember(chatId: string, userId: string): Promise { + const result = await this.database.query<{ is_member: boolean }>( + 'messages.checkMembership', + `SELECT EXISTS ( + SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2 + ) AS is_member`, + [chatId, userId], + ); + return result.rows[0]?.is_member === true; + } + + /** + * Deletes expired claims in bounded batches. The transaction-scoped advisory + * lock makes the pass single-flight across replicas without risking a lock + * leaking back into the pool with a released connection. Returns the number + * of deleted rows (0 when another replica is purging). + */ + async purgeExpired(ttlSeconds: number): Promise { + const client: pg.PoolClient = await this.database.pool.connect(); + try { + await client.query('BEGIN'); + try { + const lock = await client.query<{ locked: boolean }>( + "SELECT pg_try_advisory_xact_lock(hashtext('idempotency_gc')) AS locked", + ); + if (lock.rows[0]?.locked !== true) { + await client.query('ROLLBACK'); + return 0; + } + let purged = 0; + for (let batch = 0; batch < PURGE_BATCHES; batch += 1) { + const result = await client.query( + `DELETE FROM idempotency_keys + WHERE ctid IN ( + SELECT ctid FROM idempotency_keys + WHERE created_at < now() - make_interval(secs => $1::double precision) + LIMIT ${PURGE_BATCH_LIMIT} + )`, + [ttlSeconds], + ); + const deleted = result.rowCount ?? 0; + purged += deleted; + if (deleted < PURGE_BATCH_LIMIT) break; + } + await client.query('COMMIT'); + return purged; + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } + } finally { + client.release(); + } + } +} diff --git a/app/src/messages/idempotency/idempotency.ts b/app/src/messages/idempotency/idempotency.ts new file mode 100644 index 0000000..7c4f922 --- /dev/null +++ b/app/src/messages/idempotency/idempotency.ts @@ -0,0 +1,26 @@ +import { createHash } from 'node:crypto'; + +// Contract: ASCII [A-Za-z0-9._:-]{1,128}. Anything else (including a duplicated +// header, which Fastify joins with ", ") is rejected as a client error. +export const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/; + +export function messagesPath(chatId: string): string { + return `/api/v1/chats/${chatId}/messages`; +} + +// The fingerprint is derived from the validated payload with a fixed field +// order, so neither JSON key order nor an absent optional field can change it. +// Text-only messages keep the lab3 fingerprint; the order of attachment ids +// is significant because it is the order of attachments in the message. +export function idempotencyFingerprint( + text: string, + attachmentIds: string[], +): string { + return createHash('sha256') + .update( + attachmentIds.length === 0 + ? JSON.stringify({ text }) + : JSON.stringify({ text, attachment_ids: attachmentIds }), + ) + .digest('hex'); +} diff --git a/app/src/messages/message.ts b/app/src/messages/message.ts new file mode 100644 index 0000000..cd6c178 --- /dev/null +++ b/app/src/messages/message.ts @@ -0,0 +1,8 @@ +export type Message = { + id: string; + chat_id: string; + sender_id: string; + text: string; + created_at: string; + attachment_ids: string[]; +}; diff --git a/app/src/messages/messages.controller.ts b/app/src/messages/messages.controller.ts new file mode 100644 index 0000000..a4fcdb1 --- /dev/null +++ b/app/src/messages/messages.controller.ts @@ -0,0 +1,53 @@ +import { + BadRequestException, + Body, + Controller, + DefaultValuePipe, + Get, + Headers, + Param, + ParseIntPipe, + ParseUUIDPipe, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import { CurrentUser } from '../common/auth/current-user.decorator.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import type { User } from '../users/user.js'; +import { CreateMessageDto } from './dto/create-message.dto.js'; +import { MessagesService } from './messages.service.js'; + +@Controller('api/v1/chats/:chatId/messages') +@UseGuards(CurrentUserGuard) +export class MessagesController { + constructor(private readonly messagesService: MessagesService) {} + + @Post() + create( + @Param('chatId', new ParseUUIDPipe()) chatId: string, + @Body() body: CreateMessageDto, + @CurrentUser() currentUser: User, + @Headers('idempotency-key') idempotencyKey?: string | string[], + ) { + return this.messagesService.create( + chatId, + body, + currentUser, + idempotencyKey, + ); + } + + @Get() + list( + @Param('chatId', new ParseUUIDPipe()) chatId: string, + @CurrentUser() currentUser: User, + @Query('limit', new DefaultValuePipe(50), new ParseIntPipe()) + limit: number, + @Query('cursor') cursor?: string, + ) { + if (limit < 1 || limit > 100) + throw new BadRequestException('limit must be between 1 and 100'); + return this.messagesService.list(chatId, currentUser, limit, cursor); + } +} diff --git a/app/src/messages/messages.module.ts b/app/src/messages/messages.module.ts new file mode 100644 index 0000000..895c16b --- /dev/null +++ b/app/src/messages/messages.module.ts @@ -0,0 +1,28 @@ +import { Module } from '@nestjs/common'; +import { DatabaseModule } from '../database/database.module.js'; +import { ChatsModule } from '../chats/chats.module.js'; +import { MessagesController } from './messages.controller.js'; +import { MessagesRepository } from './messages.repository.js'; +import { MessagesService } from './messages.service.js'; +import { MessagesCacheModule } from './cache/messages-cache.module.js'; +import { IdempotencyModule } from './idempotency/idempotency.module.js'; +import { UsersModule } from '../users/users.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { AttachmentsModule } from '../attachments/attachments.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; + +@Module({ + imports: [ + ChatsModule, + MessagesCacheModule, + IdempotencyModule, + DatabaseModule, + UsersModule, + RedisModule, + MetricsModule, + AttachmentsModule, + ], + controllers: [MessagesController], + providers: [MessagesRepository, MessagesService], +}) +export class MessagesModule {} diff --git a/app/src/messages/messages.repository.spec.ts b/app/src/messages/messages.repository.spec.ts new file mode 100644 index 0000000..10fc6d3 --- /dev/null +++ b/app/src/messages/messages.repository.spec.ts @@ -0,0 +1,26 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Message } from './message.js'; +import { MessagesRepository } from './messages.repository.js'; + +const message = (id: string, created_at: string): Message => ({ + id, + chat_id: 'chat', + sender_id: 'sender', + text: id, + created_at, + attachment_ids: [], +}); + +describe('MessagesRepository', () => { + it('returns rows in response shape', async () => { + const query = vi.fn().mockResolvedValue({ + rows: [message('1', '2026-01-01T00:00:00.000Z')], + rowCount: 1, + }); + const repository = new MessagesRepository({ query } as never); + await expect(repository.findPage('chat', 1)).resolves.toEqual({ + items: [message('1', '2026-01-01T00:00:00.000Z')], + hasMore: false, + }); + }); +}); diff --git a/app/src/messages/messages.repository.ts b/app/src/messages/messages.repository.ts new file mode 100644 index 0000000..a3f17ce --- /dev/null +++ b/app/src/messages/messages.repository.ts @@ -0,0 +1,145 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { randomUUID } from 'node:crypto'; +import { DatabaseClient } from '../database/database.client.js'; +import type { Cursor } from '../common/http/cursor.js'; +import type { Message } from './message.js'; + +type MessageRow = { + id: string; + chat_id: string; + sender_id: string; + text: string; + created_at: Date | string; + attachment_ids?: string[] | null; +}; + +export type CreateOnceRequest = { + userId: string; + chatId: string; + path: string; + key: string; + fingerprint: string; + text: string; + attachmentIds: string[]; +}; + +function toMessage(row: MessageRow): Message { + return { + id: row.id, + chat_id: row.chat_id, + sender_id: row.sender_id, + text: row.text, + created_at: new Date(row.created_at).toISOString(), + attachment_ids: row.attachment_ids ?? [], + }; +} + +// Один оператор делает всё, что нужно пути записи: проверяет членство, занимает +// ключ идемпотентности, вставляет сообщение, увеличивает версию чата (якорь +// инвалидации кэша истории) и сохраняет тело ответа. Атомарность даёт сам +// оператор, поэтому явная транзакция и отдельные round trip'ы не нужны; тело +// ответа строится в SQL и служит единственным источником истины и для первого +// ответа, и для повторов. +// +// Зависимости CTE задают порядок выполнения: claim -> inserted -> bumped. +const CREATE_ONCE_SQL = ` +WITH claim AS ( + INSERT INTO idempotency_keys (user_id, method, path, key, request_fingerprint, + status_code, response_body, message_id) + SELECT $1, 'POST', $2, $3, $4, 201, + jsonb_build_object( + 'id', $5::uuid, + 'chat_id', $7::uuid, + 'sender_id', $1::uuid, + 'text', $6::text, + 'created_at', to_char(date_trunc('milliseconds', now()) AT TIME ZONE 'UTC', + 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + 'attachment_ids', to_jsonb($8::uuid[])), + $5::uuid + WHERE EXISTS ( + SELECT 1 FROM chat_members WHERE chat_id = $7::uuid AND user_id = $1 + ) + AND (SELECT count(*) FROM attachments a + WHERE a.chat_id = $7::uuid + AND a.status IN ('queued','processing','ready') + AND a.id = ANY($8::uuid[])) = cardinality($8::uuid[]) + ON CONFLICT DO NOTHING + RETURNING response_body +), inserted AS ( + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT $5::uuid, $7::uuid, $1::uuid, $6::text, date_trunc('milliseconds', now()) + FROM claim + RETURNING id +), linked AS ( + INSERT INTO message_attachments (message_id, chat_id, attachment_id, ordinal) + SELECT $5::uuid, $7::uuid, t.id, t.ord + FROM inserted, unnest($8::uuid[]) WITH ORDINALITY AS t(id, ord) +), bumped AS ( + UPDATE chats SET message_version = message_version + 1 + WHERE id = $7::uuid AND EXISTS (SELECT 1 FROM inserted) +) +SELECT response_body FROM claim`; + +@Injectable() +export class MessagesRepository { + constructor(private readonly database: DatabaseClient) {} + + /** + * Returns the created message, or undefined when the key is already taken or + * the caller is not a member of the chat (both leave no side effect). + */ + async createOnce(request: CreateOnceRequest): Promise { + const result = await this.database.query<{ response_body: Message }>( + 'messages.createIdempotent', + CREATE_ONCE_SQL, + [ + request.userId, + request.path, + request.key, + request.fingerprint, + randomUUID(), + request.text, + request.chatId, + request.attachmentIds, + ], + ); + return result.rows[0]?.response_body; + } + + async getVersion(chatId: string, userId: string): Promise { + const result = await this.database.query<{ message_version: string }>( + 'messages.version', + 'SELECT c.message_version FROM chats c WHERE c.id = $1 AND EXISTS (SELECT 1 FROM chat_members WHERE chat_id = c.id AND user_id = $2)', + [chatId, userId], + ); + if (!result.rows[0]) throw new NotFoundException(); + return BigInt(result.rows[0].message_version); + } + + async findPage( + chatId: string, + limit: number, + cursor?: Cursor, + ): Promise<{ items: Message[]; hasMore: boolean }> { + const values: unknown[] = [chatId]; + let predicate = ''; + if (cursor) { + values.push(cursor.created_at, cursor.id); + predicate = + 'AND (m.created_at, m.id) > ($2::timestamptz, $3::uuid)'; + } + values.push(limit + 1); + const result = await this.database.query( + 'messages.history', + `SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, + COALESCE((SELECT json_agg(ma.attachment_id ORDER BY ma.ordinal) + FROM message_attachments ma WHERE ma.message_id = m.id), '[]'::json) AS attachment_ids + FROM messages m WHERE m.chat_id = $1 ${predicate} ORDER BY m.created_at, m.id LIMIT $${values.length}`, + values, + ); + return { + items: result.rows.slice(0, limit).map(toMessage), + hasMore: result.rows.length > limit, + }; + } +} diff --git a/app/src/messages/messages.service.spec.ts b/app/src/messages/messages.service.spec.ts new file mode 100644 index 0000000..8618dea --- /dev/null +++ b/app/src/messages/messages.service.spec.ts @@ -0,0 +1,121 @@ +import { describe, expect, it, vi } from 'vitest'; +import { MessagesService } from './messages.service.js'; +import { idempotencyFingerprint } from './idempotency/idempotency.js'; +import type { Message } from './message.js'; + +type StoredRow = { + request_fingerprint: string; + response_body: Message; + created_at: Date; + expired: boolean; + is_member: boolean; +}; + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +describe('MessagesService idempotency expiry race', () => { + it('does not let a stale expiry decision delete a replacement claim', async () => { + const oldCreatedAt = new Date('2020-01-01T00:00:00.000Z'); + const newMessage: Message = { + id: 'message-new', + chat_id: 'chat', + sender_id: 'user', + text: 'hello', + created_at: '2026-01-01T00:00:00.000Z', + attachment_ids: [], + }; + let row: StoredRow | undefined = { + request_fingerprint: idempotencyFingerprint('hello', []), + response_body: { + ...newMessage, + id: 'message-old', + text: 'old', + }, + created_at: oldCreatedAt, + expired: true, + is_member: true, + }; + let createCalls = 0; + let readCalls = 0; + let forgetCalls = 0; + let messageWrites = 0; + const bothInitialClaims = deferred(); + const bothInitialReads = deferred(); + const replacementCreated = deferred(); + + const messagesRepository = { + createOnce: vi.fn(async () => { + createCalls += 1; + if (createCalls === 2) bothInitialClaims.resolve(); + if (createCalls <= 2) { + await bothInitialClaims.promise; + return undefined; + } + if (row) return undefined; + messageWrites += 1; + row = { + request_fingerprint: idempotencyFingerprint('hello', []), + response_body: newMessage, + created_at: new Date('2026-01-01T00:00:00.000Z'), + expired: false, + is_member: true, + }; + replacementCreated.resolve(); + return newMessage; + }), + }; + const idempotency = { + read: vi.fn(async () => { + readCalls += 1; + if (readCalls === 2) bothInitialReads.resolve(); + if (readCalls <= 2) await bothInitialReads.promise; + return row; + }), + forget: vi.fn(async (...args: unknown[]) => { + forgetCalls += 1; + if (args.length !== 4) { + row = undefined; + return; + } + if (forgetCalls === 2) await replacementCreated.promise; + if ( + !row || + row.created_at >= new Date('2026-01-01T00:00:00.000Z') + ) + return; + row = undefined; + }), + isMember: vi.fn().mockResolvedValue(true), + }; + const makeService = () => + new MessagesService( + messagesRepository as never, + {} as never, + {} as never, + idempotency as never, + { getOrThrow: vi.fn().mockReturnValue(60) } as never, + { increment: vi.fn() } as never, + {} as never, + ); + const input = { text: 'hello', attachment_ids: [] } as never; + const user = { id: 'user' } as never; + + const results = await Promise.all([ + makeService().create('chat', input, user, 'same-key'), + makeService().create('chat', input, user, 'same-key'), + ]); + + expect(results).toEqual([newMessage, newMessage]); + expect(new Set(results.map((message) => message.id))).toEqual( + new Set(['message-new']), + ); + expect(messageWrites).toBe(1); + expect(forgetCalls).toBe(2); + }); +}); diff --git a/app/src/messages/messages.service.ts b/app/src/messages/messages.service.ts new file mode 100644 index 0000000..1ab2f96 --- /dev/null +++ b/app/src/messages/messages.service.ts @@ -0,0 +1,206 @@ +import { + BadRequestException, + ConflictException, + Injectable, + Logger, + NotFoundException, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { decodeCursor, encodeCursor } from '../common/http/cursor.js'; +import type { Page } from '../common/http/page.js'; +import type { AppConfig } from '../config/app-config.schema.js'; +import type { User } from '../users/user.js'; +import { ChatsService } from '../chats/chats.service.js'; +import { AttachmentsRepository } from '../attachments/attachments.repository.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import type { CreateMessageDto } from './dto/create-message.dto.js'; +import type { Message } from './message.js'; +import { MessagesRepository } from './messages.repository.js'; +import { MessagesCacheService } from './cache/messages-cache.service.js'; +import { + IDEMPOTENCY_KEY_PATTERN, + idempotencyFingerprint, + messagesPath, +} from './idempotency/idempotency.js'; +import { IdempotencyRepository } from './idempotency/idempotency.repository.js'; + +// Один повтор нужен только для просроченного ключа: запись удаляется, и тот же +// оператор занимает ключ заново. Больше трёх кругов означает, что ключ +// перехватывают параллельные запросы, и честнее вернуть 503, чем крутиться. +const MAX_CLAIM_ATTEMPTS = 3; +const PURGE_EVERY_REQUESTS = 512; + +@Injectable() +export class MessagesService { + private readonly logger = new Logger(MessagesService.name); + private requestsSincePurge = 0; + + constructor( + private readonly messagesRepository: MessagesRepository, + private readonly chatsService: ChatsService, + private readonly cache: MessagesCacheService, + private readonly idempotency: IdempotencyRepository, + private readonly config: ConfigService, + private readonly metrics: MetricsService, + private readonly attachments: AttachmentsRepository, + ) {} + + async create( + chatId: string, + input: CreateMessageDto, + currentUser: User, + rawKey: string | string[] | undefined, + ): Promise { + // Ключ и тело проверяются до обращения к БД: клиентская ошибка не должна + // создавать заявку и не должна зависеть от состояния хранилища. + if (typeof rawKey !== 'string' || !IDEMPOTENCY_KEY_PATTERN.test(rawKey)) + throw new BadRequestException('Idempotency-Key header is required'); + const ids = input.attachment_ids.map((id) => id.toLowerCase()); + if (new Set(ids).size !== ids.length) + throw new BadRequestException('attachment_ids must be unique'); + if ( + ids.length === 0 && + [...input.text].every((character) => /\s/u.test(character)) + ) + throw new BadRequestException('Message text cannot be blank'); + + const path = messagesPath(chatId); + const fingerprint = idempotencyFingerprint(input.text, ids); + const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS'); + for (let attempt = 1; attempt <= MAX_CLAIM_ATTEMPTS; attempt += 1) { + const created = await this.messagesRepository.createOnce({ + userId: currentUser.id, + chatId, + path, + key: rawKey, + fingerprint, + text: input.text, + attachmentIds: ids, + }); + if (created) { + this.metrics.increment('idempotency.claim'); + this.metrics.increment('messages.write'); + this.scheduleExpiredPurge(); + return created; + } + + const stored = await this.idempotency.read( + currentUser.id, + path, + rawKey, + chatId, + ttl, + ); + if (!stored) { + // Заявки нет: либо запрос не имеет доступа к чату (404), либо + // чужую заявку сняли между нашими двумя запросами (503). + if (!(await this.idempotency.isMember(chatId, currentUser.id))) + throw new NotFoundException(); + // Unknown or foreign-chat ids are 404; an attachment whose + // processing failed is a conflict, not a missing object. + const linkState = + ids.length > 0 + ? await this.attachments.linkState(chatId, ids) + : 'ok'; + if (linkState === 'failed') + throw new ConflictException('Attachment processing failed'); + if (linkState === 'missing') throw new NotFoundException(); + this.metrics.increment('idempotency.claim_lost'); + throw new ServiceUnavailableException( + 'Idempotency key could not be claimed', + ); + } + if (stored.expired) { + this.metrics.increment('idempotency.released'); + await this.idempotency.forget( + currentUser.id, + path, + rawKey, + ttl, + ); + continue; + } + if (stored.request_fingerprint !== fingerprint) { + this.metrics.increment('idempotency.conflict'); + throw new ConflictException( + 'Idempotency key reused with a different body', + ); + } + if (!stored.is_member) throw new NotFoundException(); + this.metrics.increment('idempotency.replay'); + // Bodies stored before attachments existed carry no attachment_ids. + return { + ...stored.response_body, + attachment_ids: stored.response_body.attachment_ids ?? [], + }; + } + throw new ServiceUnavailableException( + 'Idempotency key could not be claimed', + ); + } + + // Expired claims are storage hygiene, not part of the request: the pass runs + // outside the request path, at most once per PURGE_EVERY_REQUESTS successful + // writes, and its failure never changes the client's result. + private scheduleExpiredPurge(): void { + this.requestsSincePurge += 1; + if (this.requestsSincePurge < PURGE_EVERY_REQUESTS) return; + this.requestsSincePurge = 0; + const ttl = this.config.getOrThrow('IDEMPOTENCY_TTL_SECONDS'); + void this.idempotency + .purgeExpired(ttl) + .then((purged) => { + if (purged > 0) this.metrics.increment('idempotency.purged'); + }) + .catch((error: unknown) => { + this.metrics.increment('idempotency.purge_error'); + this.logger.warn( + `Idempotency purge failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + }); + } + + async list( + chatId: string, + currentUser: User, + limit: number, + cursorValue?: string, + ): Promise> { + await this.chatsService.getForUser(chatId, currentUser); + const scope = `messages:${chatId}`; + const cursor = cursorValue + ? decodeCursor(cursorValue, scope) + : undefined; + const version = await this.messagesRepository.getVersion( + chatId, + currentUser.id, + ); + const page = await this.cache.getOrLoad( + chatId, + version, + cursorValue, + limit, + async () => { + const loaded = await this.messagesRepository.findPage( + chatId, + limit, + cursor, + ); + const lastLoaded = loaded.items.at(-1); + return { + items: loaded.items, + next_cursor: + loaded.hasMore && lastLoaded + ? encodeCursor({ + scope, + created_at: lastLoaded.created_at, + id: lastLoaded.id, + }) + : null, + }; + }, + ); + return page as Page; + } +} diff --git a/app/src/metrics/metrics.controller.ts b/app/src/metrics/metrics.controller.ts new file mode 100644 index 0000000..9c2100d --- /dev/null +++ b/app/src/metrics/metrics.controller.ts @@ -0,0 +1,54 @@ +import { + Controller, + Get, + Headers, + HttpCode, + HttpStatus, + Post, + UnauthorizedException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { resolveInstanceId } from '../config/instance-id.js'; +import { MetricsService } from './metrics.service.js'; + +@Controller('internal') +export class MetricsController { + private readonly instanceId: string; + private readonly buildId: string; + + constructor( + private readonly config: ConfigService, + private readonly metrics: MetricsService, + ) { + this.instanceId = resolveInstanceId(config); + this.buildId = process.env.BUILD_ID ?? 'unknown'; + } + + @Get('metrics') + get(@Headers('authorization') authorization?: string) { + this.requireToken(authorization); + return { + ...this.metrics.snapshot(), + instance_id: this.instanceId, + build_id: this.buildId, + }; + } + + @Post('metrics/reset') + @HttpCode(HttpStatus.OK) + reset(@Headers('authorization') authorization?: string): { status: 'ok' } { + this.requireToken(authorization); + this.metrics.reset(); + return { status: 'ok' }; + } + + private requireToken(authorization?: string): void { + const token = this.config.get('METRICS_TOKEN'); + if (!token || authorization !== `Bearer ${token}`) + throw new UnauthorizedException({ + message: 'Unauthorized', + challenge: 'Bearer realm="metrics"', + }); + } +} diff --git a/app/src/metrics/metrics.module.ts b/app/src/metrics/metrics.module.ts new file mode 100644 index 0000000..3e945a5 --- /dev/null +++ b/app/src/metrics/metrics.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { MetricsController } from './metrics.controller.js'; +import { MetricsService } from './metrics.service.js'; + +@Module({ + controllers: [MetricsController], + providers: [MetricsService], + exports: [MetricsService], +}) +export class MetricsModule {} diff --git a/app/src/metrics/metrics.service.spec.ts b/app/src/metrics/metrics.service.spec.ts new file mode 100644 index 0000000..0316e94 --- /dev/null +++ b/app/src/metrics/metrics.service.spec.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest'; +import { MetricsService } from './metrics.service.js'; + +describe('MetricsService', () => { + it('computes nearest-rank percentiles from observed latencies', () => { + const metrics = new MetricsService(); + metrics.increment('cache_hit'); + metrics.increment('cache_hit'); + metrics.observeLatency(30); + metrics.observeLatency(10); + metrics.observeLatency(20); + const snapshot = metrics.snapshot(); + expect(snapshot.counters).toEqual({ cache_hit: 2 }); + expect(snapshot.latency_ms).toEqual({ + count: 3, + sample_count: 3, + p50: 20, + p95: 30, + p99: 30, + max: 30, + }); + }); + + it('keeps snapshots isolated from callers and later observations', () => { + const metrics = new MetricsService(); + metrics.increment('cache_hit'); + const snapshot = metrics.snapshot(); + snapshot.counters.cache_hit = 99; + metrics.increment('cache_hit'); + expect(metrics.snapshot().counters.cache_hit).toBe(2); + expect(snapshot.latency_ms.count).toBe(0); + }); + + it('bounds retained samples but keeps cumulative count and maximum', () => { + const metrics = new MetricsService(); + metrics.observeLatency(9000); + for (let index = 0; index < 4096; index += 1) + metrics.observeLatency(10); + expect(metrics.snapshot().latency_ms).toEqual({ + count: 4097, + sample_count: 4096, + p50: 10, + p95: 10, + p99: 10, + max: 9000, + }); + }); + + it('ignores invalid latency observations', () => { + const metrics = new MetricsService(); + for (const value of [-1, NaN, Infinity]) metrics.observeLatency(value); + expect(metrics.snapshot().latency_ms).toEqual({ + count: 0, + sample_count: 0, + p50: 0, + p95: 0, + p99: 0, + max: 0, + }); + }); + + it('adds byte counters and ignores invalid amounts', () => { + const metrics = new MetricsService(); + metrics.add('bytes', 100); + metrics.add('bytes', 28); + for (const value of [-1, NaN, Infinity]) metrics.add('bytes', value); + expect(metrics.snapshot().counters.bytes).toBe(128); + }); + + it('tracks memory peaks until reset', () => { + const metrics = new MetricsService(); + const ballast = Buffer.alloc(32 * 1024 * 1024, 1); + const during = metrics.snapshot().memory_peak_bytes.array_buffers; + expect(during).toBeGreaterThanOrEqual(ballast.length); + ballast.fill(0); + }); +}); diff --git a/app/src/metrics/metrics.service.ts b/app/src/metrics/metrics.service.ts new file mode 100644 index 0000000..9087b09 --- /dev/null +++ b/app/src/metrics/metrics.service.ts @@ -0,0 +1,123 @@ +import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; + +const LATENCY_SAMPLE_CAPACITY = 4096; + +type LatencySnapshot = { + count: number; + sample_count: number; + p50: number; + p95: number; + p99: number; + max: number; +}; + +const MEMORY_SAMPLE_INTERVAL_MS = 50; + +type MemoryUsage = { + rss: number; + heap_used: number; + external: number; + array_buffers: number; +}; + +function currentMemory(): MemoryUsage { + const usage = process.memoryUsage(); + return { + rss: usage.rss, + heap_used: usage.heapUsed, + external: usage.external, + array_buffers: usage.arrayBuffers, + }; +} + +@Injectable() +export class MetricsService implements OnModuleInit, OnModuleDestroy { + private memoryPeak: MemoryUsage = currentMemory(); + private memoryTimer: NodeJS.Timeout | undefined; + private readonly counters: Record = {}; + private readonly latencies: number[] = []; + private latencyCount = 0; + private maximumLatency = 0; + private nextSample = 0; + + onModuleInit(): void { + this.memoryTimer = setInterval( + () => this.sampleMemory(), + MEMORY_SAMPLE_INTERVAL_MS, + ); + this.memoryTimer.unref(); + } + + onModuleDestroy(): void { + if (this.memoryTimer) clearInterval(this.memoryTimer); + this.memoryTimer = undefined; + } + + add(name: string, amount: number): void { + if (!Number.isFinite(amount) || amount < 0) return; + this.counters[name] = (this.counters[name] ?? 0) + amount; + } + + increment(name: string): void { + this.counters[name] = (this.counters[name] ?? 0) + 1; + } + + observeLatency(milliseconds: number): void { + if (!Number.isFinite(milliseconds) || milliseconds < 0) return; + this.latencyCount += 1; + this.maximumLatency = Math.max(this.maximumLatency, milliseconds); + this.latencies[this.nextSample] = milliseconds; + this.nextSample = (this.nextSample + 1) % LATENCY_SAMPLE_CAPACITY; + } + + snapshot(): { + counters: Record; + latency_ms: LatencySnapshot; + memory_bytes: MemoryUsage; + memory_peak_bytes: MemoryUsage; + } { + this.sampleMemory(); + const sorted = [...this.latencies].sort((left, right) => left - right); + return { + counters: { ...this.counters }, + latency_ms: { + count: this.latencyCount, + sample_count: sorted.length, + p50: this.percentile(sorted, 0.5), + p95: this.percentile(sorted, 0.95), + p99: this.percentile(sorted, 0.99), + max: this.maximumLatency, + }, + memory_bytes: currentMemory(), + memory_peak_bytes: { ...this.memoryPeak }, + }; + } + + reset(): void { + for (const name of Object.keys(this.counters)) + delete this.counters[name]; + this.latencies.length = 0; + this.latencyCount = 0; + this.maximumLatency = 0; + this.nextSample = 0; + this.memoryPeak = currentMemory(); + } + + private sampleMemory(): void { + const now = currentMemory(); + const peak = this.memoryPeak; + peak.rss = Math.max(peak.rss, now.rss); + peak.heap_used = Math.max(peak.heap_used, now.heap_used); + peak.external = Math.max(peak.external, now.external); + peak.array_buffers = Math.max(peak.array_buffers, now.array_buffers); + } + + private percentile(sorted: number[], percentile: number): number { + if (sorted.length === 0) return 0; + const index = Math.min( + sorted.length - 1, + Math.ceil(sorted.length * percentile) - 1, + ); + return sorted[index]; + } +} diff --git a/app/src/redis/redis.client.ts b/app/src/redis/redis.client.ts new file mode 100644 index 0000000..220a6fb --- /dev/null +++ b/app/src/redis/redis.client.ts @@ -0,0 +1,145 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { createClient, type RedisClientType } from 'redis'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { MetricsService } from '../metrics/metrics.service.js'; + +const UNLOCK_SCRIPT = + 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'; +type Client = RedisClientType; + +@Injectable() +export class RedisClient implements OnModuleInit, OnModuleDestroy { + readonly client: Client; + private readonly logger = new Logger(RedisClient.name); + + constructor( + private readonly config: ConfigService, + private readonly metrics: MetricsService, + ) { + this.client = createClient({ + url: this.config.getOrThrow('REDIS_URL'), + disableOfflineQueue: true, + socket: { + reconnectStrategy: (attempt) => + Math.min(1000 + attempt * 250, 5000), + connectTimeout: 5000, + }, + }) as Client; + // Reconnect failures must be visible; the readiness probe pings Redis. + this.client.on('error', (error: Error) => { + this.metrics.increment('redis.error'); + this.logger.warn(`Redis error: ${error.message}`); + }); + } + + async onModuleInit(): Promise { + await this.client.connect(); + } + + async onModuleDestroy(): Promise { + if (this.client.isOpen) await this.client.quit(); + } + + async health(): Promise { + this.metrics.increment('redis.ping'); + // AbortSignal.timeout ограничивает именно пробу: обычные GET/SET остаются + // без командного таймаута, а замороженный Redis проваливает готовность + // в бюджет, который короче timeout check балансировщика. + const timeout = AbortSignal.timeout( + this.config.getOrThrow('HEALTH_TIMEOUT_MS'), + ); + await this.client.withAbortSignal(timeout).ping(); + } + + async get(key: string): Promise { + this.metrics.increment('redis.get'); + return this.client.get(key); + } + + async set( + key: string, + value: string, + options?: { EX?: number; PX?: number; NX?: boolean }, + ): Promise { + this.metrics.increment('redis.set'); + return this.client.set(key, value, options); + } + + async setNxEx( + key: string, + value: string, + seconds: number, + ): Promise { + this.metrics.increment('redis.set'); + return ( + (await this.client.set(key, value, { NX: true, EX: seconds })) === + 'OK' + ); + } + + async setNxPx( + key: string, + value: string, + milliseconds: number, + ): Promise { + this.metrics.increment('redis.set'); + return ( + (await this.client.set(key, value, { + NX: true, + PX: milliseconds, + })) === 'OK' + ); + } + + async del(key: string): Promise { + this.metrics.increment('redis.del'); + return this.client.del(key); + } + + async incr(key: string): Promise { + this.metrics.increment('redis.incr'); + return this.client.incr(key); + } + + async expire(key: string, seconds: number): Promise { + this.metrics.increment('redis.expire'); + return (await this.client.expire(key, seconds)) === 1; + } + + async scan( + cursor: number, + pattern?: string, + count = 100, + ): Promise<{ cursor: number; keys: string[] }> { + this.metrics.increment('redis.scan'); + const result = await this.client.scan(String(cursor), { + MATCH: pattern, + COUNT: count, + }); + return { cursor: Number(result.cursor), keys: result.keys }; + } + + async unlock(key: string, owner: string): Promise { + this.metrics.increment('redis.unlock'); + return Number( + await this.client.eval(UNLOCK_SCRIPT, { + keys: [key], + arguments: [owner], + }), + ); + } + + pipeline(commands: Array<[string, ...string[]]>): Promise { + this.metrics.increment('redis.pipeline'); + const multi = this.client.multi(); + for (const [command, ...args] of commands) + multi.addCommand([command, ...args]); + return multi.exec(); + } +} diff --git a/app/src/redis/redis.module.ts b/app/src/redis/redis.module.ts new file mode 100644 index 0000000..74464f5 --- /dev/null +++ b/app/src/redis/redis.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { RedisClient } from './redis.client.js'; + +@Module({ + imports: [MetricsModule], + providers: [RedisClient], + exports: [RedisClient], +}) +export class RedisModule {} diff --git a/app/src/storage/object-storage.ts b/app/src/storage/object-storage.ts new file mode 100644 index 0000000..b9275fe --- /dev/null +++ b/app/src/storage/object-storage.ts @@ -0,0 +1,257 @@ +import { + DeleteObjectCommand, + GetObjectCommand, + HeadObjectCommand, + PutObjectCommand, + S3Client, +} from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import { NodeHttpHandler } from '@smithy/node-http-handler'; +import { SpanKind } from '@opentelemetry/api'; +import { + Injectable, + Logger, + ServiceUnavailableException, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import http from 'node:http'; +import { Readable } from 'node:stream'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { withChildSpan } from '../telemetry/tracing.js'; + +export class ObjectStorageUnavailableError extends ServiceUnavailableException { + constructor() { + super('Object storage unavailable'); + } +} + +export type PresignPutOptions = { + contentType: string; + contentLength: number; + checksumSha256Base64: string; + expiresInSeconds: number; +}; + +function isMissingKey(error: unknown): boolean { + const candidate = error as { + name?: string; + $metadata?: { httpStatusCode?: number }; + }; + return ( + candidate?.name === 'NoSuchKey' || + candidate?.name === 'NotFound' || + candidate?.$metadata?.httpStatusCode === 404 + ); +} + +@Injectable() +export class ObjectStorage { + private readonly logger = new Logger(ObjectStorage.name); + private readonly bucket: string; + private readonly internal: S3Client; + private readonly presign: S3Client; + private readonly requestTimeoutMs: number; + + constructor(config: ConfigService) { + this.bucket = config.getOrThrow('S3_BUCKET'); + this.requestTimeoutMs = config.getOrThrow('S3_REQUEST_TIMEOUT_MS'); + const common = { + region: config.getOrThrow('S3_REGION'), + forcePathStyle: true, + credentials: { + accessKeyId: config.getOrThrow('S3_ACCESS_KEY_ID'), + secretAccessKey: config.getOrThrow('S3_SECRET_ACCESS_KEY'), + }, + // Поток нельзя повторить: повтор — решение клиента API. + maxAttempts: 1, + requestChecksumCalculation: 'WHEN_REQUIRED' as const, + responseChecksumValidation: 'WHEN_REQUIRED' as const, + // requestTimeout bounds a request until its response arrives and, + // with throwOnRequestTimeout, actually fails it (otherwise smithy + // only logs a warning); socketTimeout bounds a stalled body read. + // A hung S3 therefore costs at most S3_REQUEST_TIMEOUT_MS per call. + requestHandler: new NodeHttpHandler({ + connectionTimeout: config.getOrThrow('S3_CONNECT_TIMEOUT_MS'), + requestTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'), + throwOnRequestTimeout: true, + socketTimeout: config.getOrThrow('S3_REQUEST_TIMEOUT_MS'), + httpAgent: new http.Agent({ keepAlive: true, maxSockets: 64 }), + }), + }; + this.internal = new S3Client({ + ...common, + endpoint: config.getOrThrow('S3_ENDPOINT'), + }); + // One CLIENT span per S3 call (S3.PutObject, S3.GetObject, …), only + // inside a traced request or job. Object keys contain attachment ids + // and are deliberately not recorded. + this.internal.middlewareStack.add( + (next, handlerContext) => async (args) => { + const operation = String( + handlerContext.commandName ?? 'Unknown', + ).replace(/Command$/u, ''); + return withChildSpan( + `S3.${operation}`, + SpanKind.CLIENT, + { + 'rpc.system': 'aws-api', + 'rpc.service': 'S3', + 'rpc.method': operation, + 'aws.s3.bucket': this.bucket, + }, + () => next(args), + ); + }, + { step: 'initialize', name: 'messengerTelemetry' }, + ); + // Сеть не использует: только подпись URL для клиента. + this.presign = new S3Client({ + ...common, + endpoint: config.getOrThrow('S3_PUBLIC_ENDPOINT'), + }); + } + + objectKey(attachmentId: string): string { + return `attachments/${attachmentId}/original`; + } + + stagingKey(attachmentId: string): string { + return `staging/${attachmentId}/original`; + } + + variantKey( + attachmentId: string, + pipelineVersion: number, + variant: 'thumbnail' | 'crop' | 'optimized', + extension: 'jpg' | 'webp', + attempt = 1, + ): string { + // The attempt suffix makes a stale worker's write harmless: the DB + // points at the key of the attempt that won the lease fence. + return `attachments/${attachmentId}/v${pipelineVersion}/${variant}-a${attempt}.${extension}`; + } + + async putStream( + key: string, + body: Readable, + contentLength: number, + contentType: string, + signal?: AbortSignal, + ): Promise { + try { + await this.internal.send( + new PutObjectCommand({ + Bucket: this.bucket, + Key: key, + Body: body, + ContentLength: contentLength, + ContentType: contentType, + }), + // The upload deadline (UPLOAD_TIMEOUT_MS, via `signal`) bounds the + // PUT: it lasts as long as the client sends, not S3_REQUEST_TIMEOUT_MS. + // A worker buffer has no client deadline, so it uses the SDK timeout. + signal + ? { abortSignal: signal, requestTimeout: 0 } + : { requestTimeout: this.requestTimeoutMs }, + ); + } catch (error) { + throw this.fail('put', error); + } + } + + async putBuffer( + key: string, + data: Buffer, + contentType: string, + signal?: AbortSignal, + ): Promise { + await this.putStream( + key, + Readable.from([data]), + data.length, + contentType, + signal, + ); + } + + async getStream( + key: string, + signal?: AbortSignal, + ): Promise { + try { + const result = await this.internal.send( + new GetObjectCommand({ Bucket: this.bucket, Key: key }), + { abortSignal: signal }, + ); + return result.Body as Readable; + } catch (error) { + if (isMissingKey(error)) return null; + throw this.fail('get', error); + } + } + + async head(key: string): Promise<{ + size: number; + checksumSha256?: string; + etag?: string; + lastModified?: Date; + } | null> { + try { + const result = await this.internal.send( + new HeadObjectCommand({ + Bucket: this.bucket, + Key: key, + ChecksumMode: 'ENABLED', + }), + ); + return { + size: Number(result.ContentLength ?? 0), + checksumSha256: result.ChecksumSHA256, + etag: result.ETag, + lastModified: result.LastModified, + }; + } catch (error) { + if (isMissingKey(error)) return null; + throw this.fail('head', error); + } + } + + async delete(key: string): Promise { + try { + await this.internal.send( + new DeleteObjectCommand({ Bucket: this.bucket, Key: key }), + ); + } catch (error) { + if (isMissingKey(error)) return; + throw this.fail('delete', error); + } + } + + async presignPut(key: string, options: PresignPutOptions): Promise { + return getSignedUrl( + this.presign, + new PutObjectCommand({ + Bucket: this.bucket, + Key: key, + ContentType: options.contentType, + ContentLength: options.contentLength, + ChecksumSHA256: options.checksumSha256Base64, + }), + { + expiresIn: options.expiresInSeconds, + signableHeaders: new Set([ + 'content-type', + 'content-length', + 'x-amz-checksum-sha256', + ]), + unhoistableHeaders: new Set(['x-amz-checksum-sha256']), + }, + ); + } + + private fail(operation: string, error: unknown): Error { + const name = (error as { name?: string })?.name ?? 'UnknownError'; + this.logger.warn(`S3 ${operation} failed: ${name}`); + return new ObjectStorageUnavailableError(); + } +} diff --git a/app/src/storage/storage.module.ts b/app/src/storage/storage.module.ts new file mode 100644 index 0000000..6cdffb6 --- /dev/null +++ b/app/src/storage/storage.module.ts @@ -0,0 +1,5 @@ +import { Module } from '@nestjs/common'; +import { ObjectStorage } from './object-storage.js'; + +@Module({ providers: [ObjectStorage], exports: [ObjectStorage] }) +export class StorageModule {} diff --git a/app/src/telemetry/api-bootstrap.ts b/app/src/telemetry/api-bootstrap.ts new file mode 100644 index 0000000..2671d45 --- /dev/null +++ b/app/src/telemetry/api-bootstrap.ts @@ -0,0 +1,5 @@ +// Импортируется первым в main.ts: ESM выполняет модули в порядке импорта, и +// глобальные провайдеры OTel должны быть установлены до первого запроса. +import { startTelemetry } from './sdk.js'; + +startTelemetry('messenger-api'); diff --git a/app/src/telemetry/export-counter.ts b/app/src/telemetry/export-counter.ts new file mode 100644 index 0000000..3160e90 --- /dev/null +++ b/app/src/telemetry/export-counter.ts @@ -0,0 +1,36 @@ +import { ExportResultCode, type ExportResult } from '@opentelemetry/core'; +import { instruments } from './instruments.js'; + +type BatchExporter = { + export(items: T[], resultCallback: (result: ExportResult) => void): void; + shutdown(): Promise; + forceFlush?(): Promise; +}; + +/** + * Обёртка над OTLP-экспортёром: считает, сколько span и log records ушло и + * сколько потеряно. Счётчик кумулятивный, поэтому потери во время простоя + * Collector становятся видны в Prometheus сразу после его возвращения. + * Переполнение очереди BatchProcessor (drop до экспорта) SDK пишет в diag-лог. + */ +export function countingExporter( + signal: 'traces' | 'logs', + inner: BatchExporter, +): BatchExporter { + return { + export(items: T[], resultCallback: (result: ExportResult) => void) { + inner.export(items, (result: ExportResult) => { + instruments().telemetryExport.add(items.length, { + signal, + outcome: + result.code === ExportResultCode.SUCCESS + ? 'success' + : 'failed', + }); + resultCallback(result); + }); + }, + shutdown: () => inner.shutdown(), + forceFlush: () => inner.forceFlush?.() ?? Promise.resolve(), + }; +} diff --git a/app/src/telemetry/http.spec.ts b/app/src/telemetry/http.spec.ts new file mode 100644 index 0000000..3467510 --- /dev/null +++ b/app/src/telemetry/http.spec.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { isTracedRoute, normalizeMethod, routeTemplate } from './http.js'; + +describe('routeTemplate', () => { + it('turns Fastify params into low-cardinality templates', () => { + expect(routeTemplate('/api/v1/chats/:chatId/messages')).toBe( + '/api/v1/chats/{chat_id}/messages', + ); + expect(routeTemplate('/api/v1/attachments/:attachmentId/content')).toBe( + '/api/v1/attachments/{attachment_id}/content', + ); + expect(routeTemplate('/api/v1/users/me')).toBe('/api/v1/users/me'); + }); + + it('groups requests that matched no route', () => { + expect(routeTemplate(undefined)).toBe('unmatched'); + }); +}); + +describe('normalizeMethod', () => { + it('keeps standard methods and folds the rest', () => { + expect(normalizeMethod('get')).toBe('GET'); + expect(normalizeMethod('DELETE')).toBe('DELETE'); + expect(normalizeMethod('PROPFIND')).toBe('_OTHER'); + }); +}); + +describe('isTracedRoute', () => { + it('skips probes, internal endpoints and unmatched requests', () => { + expect(isTracedRoute('/health/ready')).toBe(false); + expect(isTracedRoute('/internal/metrics')).toBe(false); + expect(isTracedRoute('unmatched')).toBe(false); + expect(isTracedRoute('/api/v1/chats/{chat_id}/messages')).toBe(true); + }); +}); diff --git a/app/src/telemetry/http.ts b/app/src/telemetry/http.ts new file mode 100644 index 0000000..d869c4f --- /dev/null +++ b/app/src/telemetry/http.ts @@ -0,0 +1,201 @@ +import { + context, + propagation, + ROOT_CONTEXT, + SpanKind, + SpanStatusCode, + trace, + type Context, + type Span, +} from '@opentelemetry/api'; +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import { instruments } from './instruments.js'; +import { appLogger } from './logger.js'; +import { tracer } from './tracing.js'; + +const STATE = Symbol('messenger.telemetry.http'); +const KNOWN_METHODS = new Set([ + 'GET', + 'HEAD', + 'POST', + 'PUT', + 'PATCH', + 'DELETE', + 'OPTIONS', +]); +// Пробы HAProxy (каждые 500 мс на реплику) и внутренние endpoint не трассируются +// и не пишут access-log: они дали бы больше половины объёма Tempo и Loki без +// диагностической ценности. В метриках они остаются. +const UNTRACED_PREFIXES = ['/health', '/internal/']; + +type HttpState = { + readonly ctx: Context; + readonly span: Span | undefined; + readonly method: string; + readonly route: string; + readonly startedAt: bigint; + finished: boolean; +}; +type InstrumentedRequest = FastifyRequest & { [STATE]?: HttpState }; +type RouteHandler = ( + this: unknown, + request: FastifyRequest, + reply: FastifyReply, +) => unknown; + +/** `/api/v1/chats/:chatId/messages` → `/api/v1/chats/{chat_id}/messages`. */ +export function routeTemplate(url: string | undefined): string { + if (!url) return 'unmatched'; + return url.replace( + /:([A-Za-z0-9_]+)/gu, + (_match, name: string) => + `{${name.replace(/([a-z0-9])([A-Z])/gu, '$1_$2').toLowerCase()}}`, + ); +} + +export function normalizeMethod(method: string): string { + const upper = method.toUpperCase(); + return KNOWN_METHODS.has(upper) ? upper : '_OTHER'; +} + +export function isTracedRoute(route: string): boolean { + return ( + route !== 'unmatched' && + !UNTRACED_PREFIXES.some((prefix) => route.startsWith(prefix)) + ); +} + +function headerValue(value: unknown): string | undefined { + if (typeof value === 'string') return value; + if (typeof value === 'number') return String(value); + if (Array.isArray(value) && typeof value[0] === 'string') return value[0]; + return undefined; +} + +/** + * HTTP-инструментация на хуках Fastify: + * - onRequest: SERVER span с родителем из входящего `traceparent`; + * - onRoute: обработчик маршрута выполняется внутри контекста span, поэтому + * span PostgreSQL/S3/RabbitMQ и логи обработчика становятся его детьми; + * - onResponse / onRequestAbort: длительность в гистограмму, access-log, end span. + * В метрики попадают только метод, route template и код статуса. + * Регистрируется до app.listen(): маршруты Nest добавляются при init. + */ +export function installHttpTelemetry(fastify: FastifyInstance): void { + fastify.addHook('onRoute', (routeOptions) => { + const original = routeOptions.handler as unknown as RouteHandler | undefined; + if (typeof original !== 'function') return; + const wrapped: RouteHandler = function ( + this: unknown, + request: FastifyRequest, + reply: FastifyReply, + ) { + const state = (request as InstrumentedRequest)[STATE]; + if (!state?.span) return original.call(this, request, reply); + return context.with(state.ctx, () => + original.call(this, request, reply), + ); + }; + (routeOptions as unknown as { handler: RouteHandler }).handler = wrapped; + }); + + fastify.addHook( + 'onRequest', + (request: FastifyRequest, _reply: FastifyReply, done: () => void) => { + const method = normalizeMethod(request.method); + const route = routeTemplate(request.routeOptions?.url); + let ctx = ROOT_CONTEXT; + let span: Span | undefined; + if (isTracedRoute(route)) { + const parent = propagation.extract(ROOT_CONTEXT, request.headers); + span = tracer().startSpan( + `${method} ${route}`, + { + kind: SpanKind.SERVER, + attributes: { + 'http.request.method': method, + 'http.route': route, + 'url.scheme': 'http', + 'network.protocol.version': request.raw.httpVersion, + }, + }, + parent, + ); + ctx = trace.setSpan(parent, span); + } + (request as InstrumentedRequest)[STATE] = { + ctx, + span, + method, + route, + startedAt: process.hrtime.bigint(), + finished: false, + }; + done(); + }, + ); + + fastify.addHook( + 'onResponse', + (request: FastifyRequest, reply: FastifyReply, done: () => void) => { + finish( + request as InstrumentedRequest, + reply.statusCode, + headerValue(reply.getHeader('x-request-id')), + false, + ); + done(); + }, + ); + + fastify.addHook( + 'onRequestAbort', + (request: FastifyRequest, done: () => void) => { + // 499 — клиент закрыл соединение до ответа (конвенция nginx); в SLO + // доступности не считается ошибкой сервиса. + finish(request as InstrumentedRequest, 499, undefined, true); + done(); + }, + ); +} + +function finish( + request: InstrumentedRequest, + status: number, + requestId: string | undefined, + aborted: boolean, +): void { + const state = request[STATE]; + if (!state || state.finished) return; + state.finished = true; + const seconds = Number(process.hrtime.bigint() - state.startedAt) / 1e9; + instruments().httpDuration.record(seconds, { + 'http.request.method': state.method, + 'http.route': state.route, + 'http.response.status_code': status, + }); + + const span = state.span; + if (!span) return; + span.setAttribute('http.response.status_code', status); + if (requestId) span.setAttribute('messenger.request_id', requestId); + if (aborted) span.setAttribute('error.type', 'request_aborted'); + if (status >= 500) + span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${status}` }); + context.with(state.ctx, () => + appLogger.event( + status >= 500 ? 'ERROR' : 'INFO', + 'http.request', + `${state.method} ${state.route} ${status}`, + { + 'http.request.method': state.method, + 'http.route': state.route, + 'http.response.status_code': status, + duration_ms: Math.round(seconds * 10_000) / 10, + request_id: requestId, + aborted: aborted || undefined, + }, + ), + ); + span.end(); +} diff --git a/app/src/telemetry/identity.ts b/app/src/telemetry/identity.ts new file mode 100644 index 0000000..3ec0de5 --- /dev/null +++ b/app/src/telemetry/identity.ts @@ -0,0 +1,35 @@ +import os from 'node:os'; + +export type ServiceIdentity = { + readonly serviceName: string; + readonly serviceVersion: string; + readonly instanceId: string; +}; + +function fromEnv(defaultServiceName: string): ServiceIdentity { + return { + serviceName: process.env.OTEL_SERVICE_NAME?.trim() || defaultServiceName, + serviceVersion: process.env.SERVICE_VERSION?.trim() || 'dev', + // В compose у реплик API нет INSTANCE_ID, но HOSTNAME — id контейнера, + // уникальный для каждой реплики: так service.instance.id различает + // api-1 и api-2 во всех трёх сигналах. + instanceId: + process.env.INSTANCE_ID?.trim() || + process.env.HOSTNAME?.trim() || + os.hostname(), + }; +} + +let current = fromEnv('messenger'); + +/** service.name / service.version / service.instance.id, общие для всех сигналов. */ +export function serviceIdentity(): ServiceIdentity { + return current; +} + +export function resolveServiceIdentity( + defaultServiceName: string, +): ServiceIdentity { + current = fromEnv(defaultServiceName); + return current; +} diff --git a/app/src/telemetry/instruments.ts b/app/src/telemetry/instruments.ts new file mode 100644 index 0000000..fff2b7e --- /dev/null +++ b/app/src/telemetry/instruments.ts @@ -0,0 +1,104 @@ +import { + metrics, + type Counter, + type Histogram, + type Meter, + type MeterProvider, +} from '@opentelemetry/api'; + +export const METER_NAME = 'messenger'; + +// Каждый SLO-порог — точная граница бакета (0.25 с для API, 30 с для +// time-to-ready): иначе good-события пришлось бы интерполировать. +export const HTTP_DURATION_BUCKETS = [ + 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.5, 0.75, 1, 2.5, 5, 10, + 30, +]; +export const JOB_DURATION_BUCKETS = [ + 0.05, 0.1, 0.25, 0.5, 1, 2, 3, 5, 7.5, 10, 15, 20, 30, 45, 60, 120, +]; +export const TIME_TO_READY_BUCKETS = [ + 0.25, 0.5, 1, 2, 3, 5, 7.5, 10, 15, 20, 30, 45, 60, 120, 300, 600, +]; +export const WAIT_BUCKETS = [ + 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, +]; +export const DB_DURATION_BUCKETS = [ + 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, +]; + +export type Instruments = { + readonly httpDuration: Histogram; + readonly jobsProcessed: Counter; + readonly jobDuration: Histogram; + readonly timeToReady: Histogram; + readonly brokerPublished: Counter; + readonly dbConnectionWait: Histogram; + readonly dbOperationDuration: Histogram; + readonly telemetryExport: Counter; +}; + +let cached: { provider: MeterProvider; instruments: Instruments } | undefined; + +export function meter(): Meter { + return metrics.getMeter(METER_NAME, '1.0.0'); +} + +/** + * Инструменты создаются лениво и пересоздаются, если сменился глобальный + * MeterProvider: созданный до старта SDK инструмент навсегда остался бы no-op. + * Атрибуты — только ограниченные множества (метод, route template, код + * статуса, outcome); id пользователей, чатов, вложений и запросов сюда не + * попадают никогда. + */ +export function instruments(): Instruments { + const provider = metrics.getMeterProvider(); + if (cached?.provider === provider) return cached.instruments; + const m = provider.getMeter(METER_NAME, '1.0.0'); + const created: Instruments = { + httpDuration: m.createHistogram('http.server.request.duration', { + unit: 's', + description: + 'HTTP server request duration by method, route template and status code', + advice: { explicitBucketBoundaries: HTTP_DURATION_BUCKETS }, + }), + jobsProcessed: m.createCounter('messenger.jobs.processed', { + unit: '{job}', + description: 'Job deliveries handled by the worker, by outcome', + }), + jobDuration: m.createHistogram('messenger.job.duration', { + unit: 's', + description: + 'Duration of one job attempt from claim to commit, by outcome', + advice: { explicitBucketBoundaries: JOB_DURATION_BUCKETS }, + }), + timeToReady: m.createHistogram('messenger.attachment.time_to_ready', { + unit: 's', + description: + 'Time from durable acceptance of an upload to the ready commit (includes queueing and retries)', + advice: { explicitBucketBoundaries: TIME_TO_READY_BUCKETS }, + }), + brokerPublished: m.createCounter('messenger.broker.published', { + unit: '{message}', + description: 'Messages published to the broker, by outcome', + }), + dbConnectionWait: m.createHistogram('db.client.connection.wait_time', { + unit: 's', + description: 'Time spent waiting for a connection from the pool', + advice: { explicitBucketBoundaries: WAIT_BUCKETS }, + }), + dbOperationDuration: m.createHistogram('db.client.operation.duration', { + unit: 's', + description: + 'PostgreSQL statement or transaction duration by query label, pool wait included', + advice: { explicitBucketBoundaries: DB_DURATION_BUCKETS }, + }), + telemetryExport: m.createCounter('messenger.telemetry.export.items', { + unit: '{item}', + description: + 'Spans and log records handed to the OTLP exporter, by outcome (failed = lost)', + }), + }; + cached = { provider, instruments: created }; + return created; +} diff --git a/app/src/telemetry/logger.spec.ts b/app/src/telemetry/logger.spec.ts new file mode 100644 index 0000000..17f2c10 --- /dev/null +++ b/app/src/telemetry/logger.spec.ts @@ -0,0 +1,99 @@ +import { context, trace } from '@opentelemetry/api'; +import { logs } from '@opentelemetry/api-logs'; +import { + InMemoryLogRecordExporter, + LoggerProvider, + SimpleLogRecordProcessor, +} from '@opentelemetry/sdk-logs'; +import { + AlwaysOffSampler, + AlwaysOnSampler, + type Sampler, +} from '@opentelemetry/sdk-trace-base'; +import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { StructuredLogger } from './logger.js'; + +type Line = Record; + +describe('StructuredLogger trace_sampled', () => { + let lines: Line[]; + let exporter: InMemoryLogRecordExporter; + let loggerProvider: LoggerProvider; + let tracerProvider: NodeTracerProvider | undefined; + + beforeEach(() => { + lines = []; + vi.spyOn(process.stdout, 'write').mockImplementation((( + chunk: string, + ) => { + lines.push(JSON.parse(chunk) as Line); + return true; + }) as typeof process.stdout.write); + exporter = new InMemoryLogRecordExporter(); + loggerProvider = new LoggerProvider({ + processors: [new SimpleLogRecordProcessor(exporter)], + }); + logs.setGlobalLoggerProvider(loggerProvider); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await tracerProvider?.shutdown(); + tracerProvider = undefined; + trace.disable(); + context.disable(); + logs.disable(); + await loggerProvider.shutdown(); + }); + + function emitInSpan(sampler: Sampler): { traceId: string; spanId: string } { + tracerProvider = new NodeTracerProvider({ sampler }); + tracerProvider.register(); + const logger = new StructuredLogger(); + let ids = { traceId: '', spanId: '' }; + trace.getTracer('test').startActiveSpan('op', (span) => { + ids = { + traceId: span.spanContext().traceId, + spanId: span.spanContext().spanId, + }; + logger.event('INFO', 'http.request', 'done'); + span.end(); + }); + return ids; + } + + it('marks a log written inside a sampled trace', () => { + const ids = emitInSpan(new AlwaysOnSampler()); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatchObject({ + trace_id: ids.traceId, + span_id: ids.spanId, + trace_sampled: true, + }); + const record = exporter.getFinishedLogRecords()[0]; + expect(record.spanContext?.traceId).toBe(ids.traceId); + expect(record.attributes.trace_sampled).toBe(true); + }); + + it('keeps IDs but reports false inside a sampled-out trace', () => { + const ids = emitInSpan(new AlwaysOffSampler()); + expect(lines[0]).toMatchObject({ + trace_id: ids.traceId, + span_id: ids.spanId, + trace_sampled: false, + }); + const record = exporter.getFinishedLogRecords()[0]; + expect(record.attributes.trace_sampled).toBe(false); + }); + + it('writes none of the three fields without a valid span context', () => { + new StructuredLogger().event('INFO', 'http.request', 'done'); + expect(lines).toHaveLength(1); + expect(lines[0]).not.toHaveProperty('trace_id'); + expect(lines[0]).not.toHaveProperty('span_id'); + expect(lines[0]).not.toHaveProperty('trace_sampled'); + const record = exporter.getFinishedLogRecords()[0]; + expect(record.attributes).not.toHaveProperty('trace_sampled'); + }); +}); diff --git a/app/src/telemetry/logger.ts b/app/src/telemetry/logger.ts new file mode 100644 index 0000000..2401bb1 --- /dev/null +++ b/app/src/telemetry/logger.ts @@ -0,0 +1,224 @@ +import type { LoggerService, LogLevel } from '@nestjs/common'; +import { context, trace, TraceFlags } from '@opentelemetry/api'; +import { + logs, + SeverityNumber, + type AnyValueMap, + type Logger as OtelLogger, + type LoggerProvider, +} from '@opentelemetry/api-logs'; +import { serviceIdentity } from './identity.js'; +import { redact } from './redact.js'; + +export type Severity = 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'FATAL'; +export type LogAttributes = Record< + string, + string | number | boolean | null | undefined +>; + +const SEVERITY_NUMBER: Record = { + TRACE: SeverityNumber.TRACE, + DEBUG: SeverityNumber.DEBUG, + INFO: SeverityNumber.INFO, + WARN: SeverityNumber.WARN, + ERROR: SeverityNumber.ERROR, + FATAL: SeverityNumber.FATAL, +}; +const RANK: Record = { + TRACE: 1, + DEBUG: 5, + INFO: 9, + WARN: 13, + ERROR: 17, + FATAL: 21, +}; +const NEST_LEVEL: Record = { + verbose: 'TRACE', + debug: 'DEBUG', + log: 'INFO', + warn: 'WARN', + error: 'ERROR', + fatal: 'FATAL', +}; +const MAX_TEXT = 4000; + +function parseSeverity(raw: string | undefined): Severity { + switch ((raw ?? '').trim().toLowerCase()) { + case 'trace': + case 'verbose': + return 'TRACE'; + case 'debug': + return 'DEBUG'; + case 'warn': + case 'warning': + return 'WARN'; + case 'error': + return 'ERROR'; + default: + return 'INFO'; + } +} + +function stringify(value: unknown): string { + if (typeof value === 'string') return value; + if (value instanceof Error) return `${value.name}: ${value.message}`; + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +} + +/** + * Структурный логгер для Nest и событий приложения. Каждая запись уходит: + * - в stdout JSON-строкой (docker logs остаются читаемыми без Loki); + * - в OTLP logs с контекстом активного span, поэтому в Loki у записи есть + * trace_id/span_id и из неё можно перейти в Tempo. + * Текст и строковые атрибуты проходят redact() и обрезаются до 4000 символов. + */ +export class StructuredLogger implements LoggerService { + private minRank = RANK[parseSeverity(process.env.LOG_LEVEL)]; + private otel: { provider: LoggerProvider; logger: OtelLogger } | undefined; + + log(message: unknown, ...optionalParams: unknown[]): void { + this.fromNest('INFO', message, optionalParams); + } + + error(message: unknown, ...optionalParams: unknown[]): void { + this.fromNest('ERROR', message, optionalParams); + } + + warn(message: unknown, ...optionalParams: unknown[]): void { + this.fromNest('WARN', message, optionalParams); + } + + debug(message: unknown, ...optionalParams: unknown[]): void { + this.fromNest('DEBUG', message, optionalParams); + } + + verbose(message: unknown, ...optionalParams: unknown[]): void { + this.fromNest('TRACE', message, optionalParams); + } + + fatal(message: unknown, ...optionalParams: unknown[]): void { + this.fromNest('FATAL', message, optionalParams); + } + + setLogLevels(levels: LogLevel[]): void { + const ranks = levels + .map((level) => NEST_LEVEL[level]) + .filter((severity): severity is Severity => severity !== undefined) + .map((severity) => RANK[severity]); + if (ranks.length > 0) this.minRank = Math.min(...ranks); + } + + /** Событие приложения: `event` — стабильное имя для запросов в Loki. */ + event( + severity: Severity, + event: string, + message: string, + attributes: LogAttributes = {}, + ): void { + this.write(severity, event, undefined, message, attributes); + } + + /** + * Конвенция Nest: контекст — последний строковый параметр, для error перед + * ним может идти stack. + */ + private fromNest( + severity: Severity, + message: unknown, + params: unknown[], + ): void { + if (RANK[severity] < this.minRank) return; + const rest = [...params]; + let contextName: string | undefined; + if (rest.length > 0 && typeof rest[rest.length - 1] === 'string') + contextName = rest.pop() as string; + let stack: string | undefined; + if (severity === 'ERROR' || severity === 'FATAL') { + const index = rest.findIndex( + (param) => typeof param === 'string' && param.includes('\n'), + ); + if (index >= 0) stack = rest.splice(index, 1)[0] as string; + if (!stack && message instanceof Error) stack = message.stack; + } + let text = stringify(message); + if (rest.length > 0) text = `${text} ${rest.map(stringify).join(' ')}`; + this.write( + severity, + 'log', + contextName, + text, + stack ? { 'exception.stacktrace': stack } : {}, + ); + } + + private write( + severity: Severity, + event: string, + contextName: string | undefined, + message: string, + attributes: LogAttributes, + ): void { + if (RANK[severity] < this.minRank) return; + const identity = serviceIdentity(); + const active = context.active(); + const spanContext = trace.getSpan(active)?.spanContext(); + let ids: + | { trace_id: string; span_id: string; trace_sampled: boolean } + | undefined; + if (spanContext && trace.isSpanContextValid(spanContext)) + ids = { + trace_id: spanContext.traceId, + span_id: spanContext.spanId, + trace_sampled: (spanContext.traceFlags & TraceFlags.SAMPLED) !== 0, + }; + + const body = redact(message).slice(0, MAX_TEXT); + const clean: Record = {}; + for (const [key, value] of Object.entries(attributes)) { + if (value === undefined || value === null) continue; + clean[key] = + typeof value === 'string' ? redact(value).slice(0, MAX_TEXT) : value; + } + + process.stdout.write( + `${JSON.stringify({ + timestamp: new Date().toISOString(), + severity, + 'service.name': identity.serviceName, + 'service.instance.id': identity.instanceId, + event, + ...(contextName ? { context: contextName } : {}), + message: body, + ...ids, + ...clean, + })}\n`, + ); + + this.otelLogger().emit({ + severityNumber: SEVERITY_NUMBER[severity], + severityText: severity, + body, + attributes: { + 'event.name': event, + ...(contextName ? { 'log.context': contextName } : {}), + ...(ids ? { trace_sampled: ids.trace_sampled } : {}), + ...clean, + } as AnyValueMap, + context: active, + }); + } + + private otelLogger(): OtelLogger { + const provider = logs.getLoggerProvider(); + if (this.otel?.provider !== provider) + this.otel = { provider, logger: provider.getLogger('messenger', '1.0.0') }; + return this.otel.logger; + } +} + +/** Единственный экземпляр: передаётся в NestFactory и используется для событий. */ +export const appLogger = new StructuredLogger(); diff --git a/app/src/telemetry/queue-stats.service.ts b/app/src/telemetry/queue-stats.service.ts new file mode 100644 index 0000000..4f37c01 --- /dev/null +++ b/app/src/telemetry/queue-stats.service.ts @@ -0,0 +1,164 @@ +import { + Injectable, + Logger, + type OnModuleDestroy, + type OnModuleInit, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { DatabaseClient } from '../database/database.client.js'; +import { JOB_QUEUE } from '../jobs/broker.topology.js'; +import { meter } from './instruments.js'; + +type QueueSnapshot = { + readonly takenAt: number; + readonly ready: number; + readonly delayed: number; + readonly processing: number; + readonly oldestAgeSeconds: number; + readonly outboxPending: number; + readonly outboxOldestAgeSeconds: number; +}; + +// Источник истины о состоянии задач — PostgreSQL, а не глубина очереди RabbitMQ: +// задача может ждать в outbox, в backoff или под истёкшим lease, не лежа в +// брокере. Возраст самой старой незавершённой задачи — то, что чувствует +// пользователь, ожидающий ready. +const JOBS_SQL = `SELECT + count(*) FILTER (WHERE status = 'queued' AND next_attempt_at <= now())::int AS ready, + count(*) FILTER (WHERE status = 'queued' AND next_attempt_at > now())::int AS delayed, + count(*) FILTER (WHERE status = 'processing')::int AS processing, + COALESCE(EXTRACT(EPOCH FROM now() - min(created_at)), 0)::float8 AS oldest_age +FROM attachment_jobs +WHERE status IN ('queued', 'processing')`; + +const OUTBOX_SQL = `SELECT + count(*)::int AS pending, + COALESCE(EXTRACT(EPOCH FROM now() - min(created_at)), 0)::float8 AS oldest_age +FROM job_outbox +WHERE published_at IS NULL AND available_at <= now()`; + +type JobsRow = { + ready: number; + delayed: number; + processing: number; + oldest_age: number; +}; +type OutboxRow = { pending: number; oldest_age: number }; + +/** + * Метрики очереди задач. Работает в API, а не в worker: в сценарии «worker + * остановлен» именно эти gauge должны продолжать расти. Обе реплики + * публикуют одинаковые значения, в PromQL берётся max(). При ошибке запроса + * старый снимок публикуется не дольше трёх интервалов, затем серия пропадает + * — лучше отсутствие данных, чем устаревший ноль. + */ +@Injectable() +export class QueueStatsService implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(QueueStatsService.name); + private readonly intervalMs: number; + private snapshot: QueueSnapshot | undefined; + private timer: NodeJS.Timeout | undefined; + private refreshing = false; + private failures = 0; + + constructor( + private readonly database: DatabaseClient, + config: ConfigService, + ) { + this.intervalMs = config.getOrThrow('QUEUE_STATS_INTERVAL_MS'); + } + + onModuleInit(): void { + const m = meter(); + const depth = m.createObservableGauge('messenger.jobs.queue.depth', { + unit: '{job}', + description: 'Unfinished attachment jobs by state (PostgreSQL)', + }); + const oldestAge = m.createObservableGauge( + 'messenger.jobs.queue.oldest_age', + { + unit: 's', + description: + 'Age of the oldest unfinished job since durable acceptance', + }, + ); + const outboxPending = m.createObservableGauge('messenger.outbox.pending', { + unit: '{message}', + description: 'Outbox rows due for publishing but not yet confirmed', + }); + const outboxAge = m.createObservableGauge('messenger.outbox.oldest_age', { + unit: 's', + description: 'Age of the oldest unpublished outbox row', + }); + m.addBatchObservableCallback( + (result) => { + const snapshot = this.freshSnapshot(); + if (!snapshot) return; + const queue = { 'messaging.destination.name': JOB_QUEUE }; + result.observe(depth, snapshot.ready, { ...queue, state: 'ready' }); + result.observe(depth, snapshot.delayed, { + ...queue, + state: 'delayed', + }); + result.observe(depth, snapshot.processing, { + ...queue, + state: 'processing', + }); + result.observe(oldestAge, snapshot.oldestAgeSeconds, queue); + result.observe(outboxPending, snapshot.outboxPending, queue); + result.observe(outboxAge, snapshot.outboxOldestAgeSeconds, queue); + }, + [depth, oldestAge, outboxPending, outboxAge], + ); + void this.refresh(); + this.timer = setInterval(() => void this.refresh(), this.intervalMs); + this.timer.unref(); + } + + onModuleDestroy(): void { + if (this.timer) clearInterval(this.timer); + } + + private freshSnapshot(): QueueSnapshot | undefined { + if (!this.snapshot) return undefined; + return Date.now() - this.snapshot.takenAt <= this.intervalMs * 3 + ? this.snapshot + : undefined; + } + + private async refresh(): Promise { + if (this.refreshing) return; + this.refreshing = true; + try { + const [jobs, outbox] = await Promise.all([ + this.database.query('telemetry.queue_stats', JOBS_SQL), + this.database.query('telemetry.outbox_stats', OUTBOX_SQL), + ]); + const j = jobs.rows[0]; + const o = outbox.rows[0]; + this.snapshot = { + takenAt: Date.now(), + ready: Number(j?.ready ?? 0), + delayed: Number(j?.delayed ?? 0), + processing: Number(j?.processing ?? 0), + oldestAgeSeconds: Number(j?.oldest_age ?? 0), + outboxPending: Number(o?.pending ?? 0), + outboxOldestAgeSeconds: Number(o?.oldest_age ?? 0), + }; + if (this.failures > 0) + this.logger.log( + `queue stats recovered after ${this.failures} failed refreshes`, + ); + this.failures = 0; + } catch (error) { + this.failures += 1; + if (this.failures === 1 || this.failures % 30 === 0) + this.logger.warn( + `queue stats refresh failed (${this.failures} in a row): ${error instanceof Error ? error.name : 'unknown error'}`, + ); + } finally { + this.refreshing = false; + } + } +} diff --git a/app/src/telemetry/redact.spec.ts b/app/src/telemetry/redact.spec.ts new file mode 100644 index 0000000..0ee534d --- /dev/null +++ b/app/src/telemetry/redact.spec.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { redact } from './redact.js'; + +describe('redact', () => { + it('masks bearer and basic credentials', () => { + const out = redact( + 'Authorization: Bearer abc.def-123 and Basic dXNlcjpwYXNz', + ); + expect(out).not.toContain('abc.def-123'); + expect(out).not.toContain('dXNlcjpwYXNz'); + }); + + it('masks credentials embedded in connection strings', () => { + expect( + redact('postgresql://messenger:s3cret@postgres:5432/messenger'), + ).toBe('postgresql://[REDACTED]@postgres:5432/messenger'); + }); + + it('masks presigned URL credentials and signatures', () => { + const out = redact( + 'https://s3.local/b/k?X-Amz-Credential=AKIAEXAMPLE%2F20260101&X-Amz-Signature=deadbeef', + ); + expect(out).not.toContain('AKIAEXAMPLE'); + expect(out).not.toContain('deadbeef'); + }); + + it('masks password-like fields', () => { + expect(redact('{"password":"hunter2"}')).not.toContain('hunter2'); + expect(redact('password=hunter2&x=1')).not.toContain('hunter2'); + }); + + it('keeps ordinary diagnostic text intact', () => { + expect(redact('job retry scheduled attempt=2 code=transient')).toBe( + 'job retry scheduled attempt=2 code=transient', + ); + }); +}); diff --git a/app/src/telemetry/redact.ts b/app/src/telemetry/redact.ts new file mode 100644 index 0000000..3e64812 --- /dev/null +++ b/app/src/telemetry/redact.ts @@ -0,0 +1,29 @@ +/** + * Последний рубеж перед stdout и OTLP: если секрет всё же попал в текст + * события (например, в сообщение ошибки драйвера), он не уйдёт в Loki. + * Основная защита — не класть такие данные в события вообще: route template + * вместо URL, коды ошибок вместо сообщений, без тел запросов. + */ +const RULES: ReadonlyArray = [ + [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/giu, '$1 [REDACTED]'], + [/([a-z][a-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/giu, '$1[REDACTED]@'], + [ + /\b(X-Amz-(?:Signature|Credential|Security-Token))=[^&\s"']+/giu, + '$1=[REDACTED]', + ], + [ + /((?:password|passwd|secret|token|authorization|cookie)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;&}]+)/giu, + '$1[REDACTED]', + ], + [ + /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gu, + '[REDACTED PRIVATE KEY]', + ], +]; + +export function redact(text: string): string { + let result = text; + for (const [pattern, replacement] of RULES) + result = result.replace(pattern, replacement); + return result; +} diff --git a/app/src/telemetry/runtime-metrics.ts b/app/src/telemetry/runtime-metrics.ts new file mode 100644 index 0000000..0fdcf2b --- /dev/null +++ b/app/src/telemetry/runtime-metrics.ts @@ -0,0 +1,55 @@ +import { monitorEventLoopDelay } from 'node:perf_hooks'; +import { meter } from './instruments.js'; + +let started = false; + +/** + * Насыщение процесса: CPU, RSS, heap и задержка event loop. Задержка event + * loop — главный признак насыщения Node.js: CPU-bound работа (sharp, argon2) + * и синхронный JSON на больших ответах растят её раньше, чем latency API. + */ +export function startRuntimeMetrics(): void { + if (started) return; + started = true; + const m = meter(); + const loop = monitorEventLoopDelay({ resolution: 20 }); + loop.enable(); + + m.createObservableCounter('process.cpu.time', { + unit: 's', + description: 'CPU time consumed by the process', + }).addCallback((result) => { + const usage = process.cpuUsage(); + result.observe(usage.user / 1e6, { 'cpu.mode': 'user' }); + result.observe(usage.system / 1e6, { 'cpu.mode': 'system' }); + }); + m.createObservableUpDownCounter('process.memory.usage', { + unit: 'By', + description: 'Resident set size of the process', + }).addCallback((result) => { + result.observe(process.memoryUsage.rss()); + }); + m.createObservableUpDownCounter('v8js.memory.heap.used', { + unit: 'By', + description: 'V8 heap in use', + }).addCallback((result) => { + result.observe(process.memoryUsage().heapUsed); + }); + + const delayP99 = m.createObservableGauge('nodejs.eventloop.delay.p99', { + unit: 's', + description: 'p99 event loop delay since the previous collection', + }); + const delayMax = m.createObservableGauge('nodejs.eventloop.delay.max', { + unit: 's', + description: 'Max event loop delay since the previous collection', + }); + m.addBatchObservableCallback( + (result) => { + result.observe(delayP99, loop.percentile(99) / 1e9); + result.observe(delayMax, loop.max / 1e9); + loop.reset(); + }, + [delayP99, delayMax], + ); +} diff --git a/app/src/telemetry/sdk.ts b/app/src/telemetry/sdk.ts new file mode 100644 index 0000000..58c948a --- /dev/null +++ b/app/src/telemetry/sdk.ts @@ -0,0 +1,295 @@ +import { + diag, + DiagLogLevel, + metrics, + type DiagLogger, +} from '@opentelemetry/api'; +import { logs } from '@opentelemetry/api-logs'; +import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'; +import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'; +import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'; +import { resourceFromAttributes } from '@opentelemetry/resources'; +import { + BatchLogRecordProcessor, + LoggerProvider, +} from '@opentelemetry/sdk-logs'; +import { + MeterProvider, + PeriodicExportingMetricReader, +} from '@opentelemetry/sdk-metrics'; +import { + BatchSpanProcessor, + ParentBasedSampler, + TraceIdRatioBasedSampler, +} from '@opentelemetry/sdk-trace-base'; +import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; +import { countingExporter } from './export-counter.js'; +import { resolveServiceIdentity } from './identity.js'; +import { redact } from './redact.js'; +import { startRuntimeMetrics } from './runtime-metrics.js'; + +type Providers = { + readonly tracer: NodeTracerProvider; + readonly meter: MeterProvider; + readonly logger: LoggerProvider; +}; + +let providers: Providers | undefined; + +function intFromEnv( + name: string, + fallback: number, + min: number, + max: number, +): number { + const raw = process.env[name]?.trim(); + if (!raw) return fallback; + const value = Number(raw); + return Number.isInteger(value) && value >= min && value <= max + ? value + : fallback; +} + +function ratioFromEnv(name: string, fallback: number): number { + const raw = process.env[name]?.trim(); + if (!raw) return fallback; + const value = Number(raw); + return Number.isFinite(value) && value >= 0 && value <= 1 ? value : fallback; +} + +/** OTEL_RESOURCE_ATTRIBUTES: `k=v,k2=v2`, значения percent-encoded. */ +export function parseResourceAttributes( + raw: string | undefined, +): Record { + const attributes: Record = {}; + if (!raw) return attributes; + for (const pair of raw.split(',')) { + const index = pair.indexOf('='); + if (index <= 0) continue; + const key = pair.slice(0, index).trim(); + const value = pair.slice(index + 1).trim(); + if (!key) continue; + try { + attributes[key] = decodeURIComponent(value); + } catch { + attributes[key] = value; + } + } + return attributes; +} + +export function telemetryEnabled(): boolean { + return (process.env.OTEL_SDK_DISABLED ?? '').trim().toLowerCase() !== 'true'; +} + +/** + * Явная настройка SDK без auto-instrumentation: приложение — ESM (авто- + * инструментации понадобился бы loader hook), а явные span дают полный + * контроль над атрибутами: SQL-текст, URL и тела не попадают в телеметрию. + * + * Экспорт асинхронный и ограниченный: очереди BatchProcessor фиксированного + * размера, таймаут экспорта 5 с. Недоступный Collector оборачивается потерей + * телеметрии (счётчик messenger.telemetry.export.items{outcome="failed"}), а не + * ростом latency или памяти API. + */ +export function startTelemetry(defaultServiceName: string): void { + if (providers) return; + const identity = resolveServiceIdentity(defaultServiceName); + if (!telemetryEnabled()) return; + + diag.setLogger( + new ThrottledDiagLogger(identity.serviceName), + DiagLogLevel.WARN, + ); + + const resource = resourceFromAttributes({ + ...parseResourceAttributes(process.env.OTEL_RESOURCE_ATTRIBUTES), + 'service.name': identity.serviceName, + 'service.version': identity.serviceVersion, + 'service.instance.id': identity.instanceId, + }); + const exportTimeout = intFromEnv( + 'OTEL_EXPORTER_OTLP_TIMEOUT', + 5000, + 100, + 60_000, + ); + + const tracer = new NodeTracerProvider({ + resource, + sampler: new ParentBasedSampler({ + root: new TraceIdRatioBasedSampler( + ratioFromEnv('OTEL_TRACES_SAMPLER_ARG', 1), + ), + }), + spanProcessors: [ + new BatchSpanProcessor( + countingExporter( + 'traces', + new OTLPTraceExporter({ timeoutMillis: exportTimeout }), + ), + { + maxQueueSize: intFromEnv('OTEL_BSP_MAX_QUEUE_SIZE', 2048, 1, 100_000), + maxExportBatchSize: intFromEnv( + 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE', + 512, + 1, + 10_000, + ), + scheduledDelayMillis: intFromEnv( + 'OTEL_BSP_SCHEDULE_DELAY', + 1000, + 1, + 60_000, + ), + exportTimeoutMillis: exportTimeout, + }, + ), + ], + }); + // Регистрирует глобальный TracerProvider, AsyncLocalStorage context manager и + // W3C TraceContext + Baggage propagator. + tracer.register(); + + const interval = intFromEnv( + 'OTEL_METRIC_EXPORT_INTERVAL', + 10_000, + 1000, + 600_000, + ); + const meter = new MeterProvider({ + resource, + readers: [ + new PeriodicExportingMetricReader({ + exporter: new OTLPMetricExporter({ timeoutMillis: exportTimeout }), + exportIntervalMillis: interval, + exportTimeoutMillis: Math.min(exportTimeout, interval), + }), + ], + }); + metrics.setGlobalMeterProvider(meter); + + const logger = new LoggerProvider({ + resource, + processors: [ + new BatchLogRecordProcessor( + countingExporter( + 'logs', + new OTLPLogExporter({ timeoutMillis: exportTimeout }), + ), + { + maxQueueSize: intFromEnv( + 'OTEL_BLRP_MAX_QUEUE_SIZE', + 2048, + 1, + 100_000, + ), + maxExportBatchSize: intFromEnv( + 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE', + 512, + 1, + 10_000, + ), + scheduledDelayMillis: intFromEnv( + 'OTEL_BLRP_SCHEDULE_DELAY', + 1000, + 1, + 60_000, + ), + exportTimeoutMillis: exportTimeout, + }, + ), + ], + }); + logs.setGlobalLoggerProvider(logger); + + providers = { tracer, meter, logger }; + startRuntimeMetrics(); +} + +/** + * Сбрасывает буферы при остановке. Ограничено по времени: недоступный + * Collector не должен задерживать graceful shutdown сервиса. + */ +export async function shutdownTelemetry(timeoutMs = 3000): Promise { + const current = providers; + if (!current) return; + providers = undefined; + let timer: NodeJS.Timeout | undefined; + await Promise.race([ + Promise.allSettled([ + current.tracer.shutdown(), + current.meter.shutdown(), + current.logger.shutdown(), + ]), + new Promise((resolve) => { + timer = setTimeout(resolve, timeoutMs); + }), + ]); + if (timer) clearTimeout(timer); +} + +/** + * Ошибки экспорта при недоступном Collector повторяются каждую секунду по + * каждому сигналу; одинаковые сообщения печатаем не чаще раза в 30 с. + */ +class ThrottledDiagLogger implements DiagLogger { + private readonly lastWritten = new Map(); + + constructor(private readonly serviceName: string) {} + + error(message: string, ...args: unknown[]): void { + this.write('ERROR', message, args); + } + + warn(message: string, ...args: unknown[]): void { + this.write('WARN', message, args); + } + + info(message: string, ...args: unknown[]): void { + this.write('INFO', message, args); + } + + debug(message: string, ...args: unknown[]): void { + this.write('DEBUG', message, args); + } + + verbose(message: string, ...args: unknown[]): void { + this.write('TRACE', message, args); + } + + private write(severity: string, message: string, args: unknown[]): void { + const key = `${severity}:${message}`; + const now = Date.now(); + const previous = this.lastWritten.get(key); + if (previous !== undefined && now - previous < 30_000) return; + if (this.lastWritten.size > 200) this.lastWritten.clear(); + this.lastWritten.set(key, now); + const detail = args + .map((arg) => + arg instanceof Error + ? `${arg.name}: ${arg.message}` + : typeof arg === 'string' + ? arg + : safeJson(arg), + ) + .join(' '); + process.stdout.write( + `${JSON.stringify({ + timestamp: new Date(now).toISOString(), + severity, + 'service.name': this.serviceName, + event: 'otel.sdk', + message: redact(`${message} ${detail}`.trim()).slice(0, 2000), + })}\n`, + ); + } +} + +function safeJson(value: unknown): string { + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +} diff --git a/app/src/telemetry/tracing.spec.ts b/app/src/telemetry/tracing.spec.ts new file mode 100644 index 0000000..2e4420e --- /dev/null +++ b/app/src/telemetry/tracing.spec.ts @@ -0,0 +1,72 @@ +import { + propagation, + ROOT_CONTEXT, + trace, + TraceFlags, +} from '@opentelemetry/api'; +import { W3CTraceContextPropagator } from '@opentelemetry/core'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { + contextFromTraceFields, + currentTraceFields, + errorType, + traceFieldsFromHeaders, +} from './tracing.js'; + +const TRACE_ID = '4bf92f3577b34da6a3ce929d0e0e4736'; +const SPAN_ID = '00f067aa0ba902b7'; +const TRACEPARENT = `00-${TRACE_ID}-${SPAN_ID}-01`; + +describe('trace context helpers', () => { + beforeAll(() => { + propagation.setGlobalPropagator(new W3CTraceContextPropagator()); + }); + + afterAll(() => { + propagation.disable(); + }); + + it('serialises the active span context as job message fields', () => { + const ctx = trace.setSpanContext(ROOT_CONTEXT, { + traceId: TRACE_ID, + spanId: SPAN_ID, + traceFlags: TraceFlags.SAMPLED, + }); + expect(currentTraceFields(ctx)).toEqual({ traceparent: TRACEPARENT }); + }); + + it('restores the remote parent from job message fields', () => { + const ctx = contextFromTraceFields({ traceparent: TRACEPARENT }); + expect(trace.getSpanContext(ctx)).toMatchObject({ + traceId: TRACE_ID, + spanId: SPAN_ID, + isRemote: true, + }); + }); + + it('reads AMQP headers delivered as buffers', () => { + expect( + traceFieldsFromHeaders({ traceparent: Buffer.from(TRACEPARENT) }), + ).toEqual({ traceparent: TRACEPARENT }); + }); + + it('ignores malformed trace context', () => { + expect(contextFromTraceFields({ traceparent: 'garbage' })).toBe( + ROOT_CONTEXT, + ); + expect(traceFieldsFromHeaders({ traceparent: 'nope' })).toEqual({}); + expect(currentTraceFields(ROOT_CONTEXT)).toEqual({}); + }); + + it('classifies errors without leaking their messages', () => { + expect( + errorType( + Object.assign(new Error('Key (username)=(alice) already exists'), { + code: '23505', + }), + ), + ).toBe('23505'); + expect(errorType(new TypeError('x'))).toBe('TypeError'); + expect(errorType('boom')).toBe('_OTHER'); + }); +}); diff --git a/app/src/telemetry/tracing.ts b/app/src/telemetry/tracing.ts new file mode 100644 index 0000000..e885a97 --- /dev/null +++ b/app/src/telemetry/tracing.ts @@ -0,0 +1,130 @@ +import { + context, + propagation, + ROOT_CONTEXT, + SpanStatusCode, + trace, + type Attributes, + type Context, + type Span, + type SpanKind, + type Tracer, +} from '@opentelemetry/api'; + +export const TRACER_NAME = 'messenger'; + +/** Совпадает с полем traceparent в contracts/jobs.schema.json. */ +const TRACEPARENT = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/u; +const MAX_TRACESTATE = 512; + +export type TraceFields = { + traceparent?: string; + tracestate?: string; +}; + +export function tracer(): Tracer { + return trace.getTracer(TRACER_NAME, '1.0.0'); +} + +/** + * W3C trace context активного span в виде полей job message. Пишется в + * outbox в той же транзакции, что и задача: причинность переживает рестарт + * API, брокера и worker, потому что хранится вместе с данными. + */ +export function currentTraceFields( + ctx: Context = context.active(), +): TraceFields { + const carrier: Record = {}; + propagation.inject(ctx, carrier); + const fields: TraceFields = {}; + if (carrier.traceparent && TRACEPARENT.test(carrier.traceparent)) + fields.traceparent = carrier.traceparent; + if ( + fields.traceparent && + carrier.tracestate && + carrier.tracestate.length <= MAX_TRACESTATE + ) + fields.tracestate = carrier.tracestate; + return fields; +} + +export function contextFromTraceFields( + fields: TraceFields | null | undefined, + base: Context = ROOT_CONTEXT, +): Context { + if (!fields?.traceparent || !TRACEPARENT.test(fields.traceparent)) + return base; + const carrier: Record = { traceparent: fields.traceparent }; + if (fields.tracestate) carrier.tracestate = fields.tracestate; + return propagation.extract(base, carrier); +} + +/** Заголовки AMQP приходят строками или Buffer — нормализуем к TraceFields. */ +export function traceFieldsFromHeaders( + headers: Record | undefined, +): TraceFields { + const read = (key: string): string | undefined => { + const value = headers?.[key]; + if (typeof value === 'string') return value; + if (Buffer.isBuffer(value)) return value.toString('utf8'); + return undefined; + }; + const traceparent = read('traceparent'); + if (!traceparent || !TRACEPARENT.test(traceparent)) return {}; + const tracestate = read('tracestate'); + return tracestate && tracestate.length <= MAX_TRACESTATE + ? { traceparent, tracestate } + : { traceparent }; +} + +/** + * Дочерний span вокруг операции зависимости. Создаётся только при активном + * родителе: опрос outbox, reaper и сбор метрик по таймеру не порождают + * тысячи одиночных корневых трасс. + */ +export async function withChildSpan( + name: string, + kind: SpanKind, + attributes: Attributes, + work: (span: Span | undefined) => Promise, +): Promise { + const parent = trace.getSpan(context.active()); + if (!parent || !parent.isRecording()) return work(undefined); + return tracer().startActiveSpan( + name, + { kind, attributes }, + async (span: Span) => { + try { + return await work(span); + } catch (error) { + markSpanError(span, error); + throw error; + } finally { + span.end(); + } + }, + ); +} + +/** + * Ошибка на span — только тип/код. Сообщения драйверов могут содержать + * значения из запроса (например, «Key (username)=(alice) already exists»), + * поэтому recordException с текстом не используется. + */ +export function markSpanError(span: Span, error: unknown): void { + const type = errorType(error); + span.setAttribute('error.type', type); + span.setStatus({ code: SpanStatusCode.ERROR, message: type }); +} + +export function errorType(error: unknown): string { + if (error && typeof error === 'object') { + const code = (error as { code?: unknown }).code; + if (typeof code === 'string' && /^[A-Za-z0-9_.-]{1,40}$/u.test(code)) + return code; + const name = (error as { name?: unknown }).name; + if (typeof name === 'string' && /^[A-Za-z0-9_.-]{1,60}$/u.test(name)) + return name; + } + return '_OTHER'; +} diff --git a/app/src/telemetry/worker-bootstrap.ts b/app/src/telemetry/worker-bootstrap.ts new file mode 100644 index 0000000..cc3c880 --- /dev/null +++ b/app/src/telemetry/worker-bootstrap.ts @@ -0,0 +1,4 @@ +// Импортируется первым в worker.main.ts (см. api-bootstrap.ts). +import { startTelemetry } from './sdk.js'; + +startTelemetry('messenger-worker'); diff --git a/app/src/types.d.ts b/app/src/types.d.ts new file mode 100644 index 0000000..6a215a6 --- /dev/null +++ b/app/src/types.d.ts @@ -0,0 +1,7 @@ +import { User } from './users/user.ts'; + +declare module 'fastify' { + interface FastifyRequest { + currentUser?: User; + } +} diff --git a/app/src/users/dto/create-user.dto.ts b/app/src/users/dto/create-user.dto.ts new file mode 100644 index 0000000..8e82f58 --- /dev/null +++ b/app/src/users/dto/create-user.dto.ts @@ -0,0 +1,22 @@ +import { IsString, Matches } from 'class-validator'; +import { CodePointLength } from '../../common/validation/code-point-length.js'; + +export class CreateUserDTO { + @IsString() + @Matches(/^[a-z0-9_]{3,32}$/) + username!: string; + + @IsString() + @CodePointLength(1, 100) + @Matches(/\S/u, { + message: 'display_name must contain a non-whitespace character', + }) + display_name!: string; + + @IsString() + @CodePointLength(12, 128) + @Matches(/\S/u, { + message: 'password must contain a non-whitespace character', + }) + password!: string; +} diff --git a/app/src/users/user.ts b/app/src/users/user.ts new file mode 100644 index 0000000..9c91d9e --- /dev/null +++ b/app/src/users/user.ts @@ -0,0 +1,6 @@ +export type User = { + id: string; + username: string; + display_name: string; + created_at: string; +}; diff --git a/app/src/users/users.controller.ts b/app/src/users/users.controller.ts new file mode 100644 index 0000000..1ab8c77 --- /dev/null +++ b/app/src/users/users.controller.ts @@ -0,0 +1,22 @@ +import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common'; +import { CurrentUser } from '../common/auth/current-user.decorator.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import type { User } from './user.js'; +import { CreateUserDTO } from './dto/create-user.dto.js'; +import { UsersService } from './users.service.js'; + +@Controller('api/v1/users') +export class UsersController { + constructor(private readonly usersService: UsersService) {} + + @Post() + create(@Body() body: CreateUserDTO) { + return this.usersService.create(body); + } + + @Get('/me') + @UseGuards(CurrentUserGuard) + getMe(@CurrentUser() currentUser: User) { + return currentUser; + } +} diff --git a/app/src/users/users.module.ts b/app/src/users/users.module.ts new file mode 100644 index 0000000..55a7328 --- /dev/null +++ b/app/src/users/users.module.ts @@ -0,0 +1,16 @@ +import { Module } from '@nestjs/common'; +import { UsersController } from './users.controller.js'; +import { UsersRepository } from './users.repository.js'; +import { UsersService } from './users.service.js'; +import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { DatabaseModule } from '../database/database.module.js'; + +@Module({ + imports: [DatabaseModule, RedisModule, MetricsModule], + controllers: [UsersController], + providers: [UsersRepository, UsersService, CurrentUserGuard], + exports: [UsersService, CurrentUserGuard, RedisModule, MetricsModule], +}) +export class UsersModule {} diff --git a/app/src/users/users.repository.ts b/app/src/users/users.repository.ts new file mode 100644 index 0000000..4fbbe86 --- /dev/null +++ b/app/src/users/users.repository.ts @@ -0,0 +1,71 @@ +import { ConflictException, Injectable } from '@nestjs/common'; +import { DatabaseClient } from '../database/database.client.js'; +import type { User } from './user.js'; + +type UserRow = { + id: string; + username: string; + display_name: string; + password_hash: string; + created_at: Date | string; +}; + +function toUser(row: UserRow): User { + return { + id: row.id, + username: row.username, + display_name: row.display_name, + created_at: new Date(row.created_at).toISOString(), + }; +} + +@Injectable() +export class UsersRepository { + constructor(private readonly database: DatabaseClient) {} + + async findById(id: string): Promise { + const result = await this.database.query( + 'users.findById', + 'SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1', + [id], + ); + const row = result.rows[0]; + return row ? toUser(row) : undefined; + } + + async findByUsername( + username: string, + ): Promise<(User & { password_hash: string }) | undefined> { + const result = await this.database.query( + 'users.findByUsername', + 'SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1', + [username], + ); + const row = result.rows[0]; + return row + ? { ...toUser(row), password_hash: row.password_hash } + : undefined; + } + + async create(user: { + id: string; + username: string; + display_name: string; + password_hash: string; + }): Promise { + try { + const result = await this.database.query( + 'users.insert', + `INSERT INTO users (id, username, display_name, password_hash) + VALUES ($1, $2, $3, $4) + RETURNING id, username, display_name, password_hash, created_at`, + [user.id, user.username, user.display_name, user.password_hash], + ); + return toUser(result.rows[0]); + } catch (error) { + if ((error as { code?: string }).code === '23505') + throw new ConflictException('Username already exists'); + throw error; + } + } +} diff --git a/app/src/users/users.service.ts b/app/src/users/users.service.ts new file mode 100644 index 0000000..e4ac35d --- /dev/null +++ b/app/src/users/users.service.ts @@ -0,0 +1,31 @@ +import { Injectable } from '@nestjs/common'; +import argon2 from 'argon2'; +import { randomUUID } from 'node:crypto'; +import { CreateUserDTO } from './dto/create-user.dto.js'; +import { User } from './user.js'; +import { UsersRepository } from './users.repository.js'; + +@Injectable() +export class UsersService { + constructor(private readonly usersRepository: UsersRepository) {} + + async create(input: CreateUserDTO): Promise { + const passwordHash = await argon2.hash(input.password, { + type: argon2.argon2id, + }); + return this.usersRepository.create({ + id: randomUUID(), + username: input.username, + display_name: input.display_name, + password_hash: passwordHash, + }); + } + + findById(id: string): Promise { + return this.usersRepository.findById(id); + } + + findByUsername(username: string) { + return this.usersRepository.findByUsername(username); + } +} diff --git a/app/src/worker.main.ts b/app/src/worker.main.ts new file mode 100644 index 0000000..085c13a --- /dev/null +++ b/app/src/worker.main.ts @@ -0,0 +1,74 @@ +// Must stay the first import (see main.ts). +import './telemetry/worker-bootstrap.js'; +import { Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import http from 'node:http'; +import type { AppConfig } from './config/app-config.schema.js'; +import { BrokerClient } from './jobs/broker.client.js'; +import { JobProcessor } from './worker/job-processor.service.js'; +import { WorkerModule } from './worker/worker.module.js'; +import { appLogger } from './telemetry/logger.js'; +import { shutdownTelemetry } from './telemetry/sdk.js'; + +const DRAIN_MS = 30_000; + +async function bootstrap(): Promise { + const app = await NestFactory.createApplicationContext(WorkerModule, { + // Verbosity comes from LOG_LEVEL (default INFO, the former + // error/warn/log set). + logger: appLogger, + }); + const config = app.get(ConfigService); + const broker = app.get(BrokerClient); + const processor = app.get(JobProcessor); + const logger = new Logger('worker'); + + const server = http.createServer((request, response) => { + if (request.method === 'GET' && request.url === '/health') { + const consuming = broker.isConsuming(); + response.writeHead(consuming ? 200 : 503, { + 'content-type': 'application/json', + }); + response.end( + JSON.stringify({ + status: consuming ? 'ok' : 'not_consuming', + }), + ); + return; + } + response.writeHead(404, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ status: 'not_found' })); + }); + await new Promise((resolve) => + server.listen( + config.getOrThrow('WORKER_HEALTH_PORT'), + '127.0.0.1', + resolve, + ), + ); + logger.log( + `worker ready: id=${process.env.INSTANCE_ID ?? process.env.HOSTNAME ?? 'worker'}`, + ); + + let shuttingDown = false; + const shutdown = async (signal: string): Promise => { + if (shuttingDown) return; + shuttingDown = true; + logger.log( + `${signal}: stopping consumption and draining in-flight jobs`, + ); + await broker.stopConsuming(); + await processor.drain(DRAIN_MS); + await new Promise((resolve) => server.close(() => resolve())); + await app.close(); + await shutdownTelemetry(); + process.exit(0); + }; + for (const signal of ['SIGTERM', 'SIGINT'] as const) + process.once(signal, () => { + void shutdown(signal); + }); +} + +await bootstrap(); diff --git a/app/src/worker/job-processor.service.spec.ts b/app/src/worker/job-processor.service.spec.ts new file mode 100644 index 0000000..a944e07 --- /dev/null +++ b/app/src/worker/job-processor.service.spec.ts @@ -0,0 +1,203 @@ +import { metrics } from '@opentelemetry/api'; +import { + AggregationTemporality, + MeterProvider, + MetricReader, + type HistogramMetricData, +} from '@opentelemetry/sdk-metrics'; +import type { Channel, ConsumeMessage } from 'amqplib'; +import { createHash, randomUUID } from 'node:crypto'; +import { Readable } from 'node:stream'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildJobMessage } from '../jobs/job-message.js'; +import { JobProcessor } from './job-processor.service.js'; + +vi.mock('./pipelines.js', () => ({ + renderVariants: () => + Promise.resolve([ + { + name: 'thumbnail', + ext: 'jpg', + contentType: 'image/jpeg', + data: Buffer.from('v'), + width: 1, + height: 1, + sha256: 'x', + }, + ]), +})); + +class TestReader extends MetricReader { + constructor() { + super({ + aggregationTemporalitySelector: () => + AggregationTemporality.CUMULATIVE, + }); + } + protected onForceFlush(): Promise { + return Promise.resolve(); + } + protected onShutdown(): Promise { + return Promise.resolve(); + } +} + +const SOURCE = Buffer.from('source-bytes'); +const T0 = Date.parse('2026-01-01T00:00:00.000Z'); + +async function readyHistogram( + reader: TestReader, +): Promise<{ count: number; sum: number }> { + const { resourceMetrics } = await reader.collect(); + for (const scope of resourceMetrics.scopeMetrics) + for (const metric of scope.metrics) + if ( + metric.descriptor.name === 'messenger.attachment.time_to_ready' + ) { + const points = (metric as HistogramMetricData).dataPoints; + return { + count: points.reduce((n, p) => n + p.value.count, 0), + sum: points.reduce((n, p) => n + (p.value.sum ?? 0), 0), + }; + } + return { count: 0, sum: 0 }; +} + +describe('JobProcessor time-to-ready boundary', () => { + let reader: TestReader; + let provider: MeterProvider; + + beforeEach(() => { + reader = new TestReader(); + provider = new MeterProvider({ readers: [reader] }); + metrics.setGlobalMeterProvider(provider); + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(T0); + }); + + afterEach(async () => { + vi.useRealTimers(); + metrics.disable(); + await provider.shutdown(); + }); + + function deliver(commitResult: 'succeeded' | 'superseded') { + const message = buildJobMessage({ + job_id: randomUUID(), + attachment_id: randomUUID(), + pipeline_version: 1, + attempt: 1, + created_at: new Date(T0), + }); + const attachment = { + id: message.attachment_id, + object_key: 'orig', + staging_key: null, + content_type: 'image/png', + size_bytes: SOURCE.length, + sha256: createHash('sha256').update(SOURCE).digest('hex'), + }; + const release = Promise.withResolvers(); + const ackPointReached = Promise.withResolvers(); + const jobs = { + claim: vi.fn(() => + Promise.resolve({ + kind: 'claimed', + job: { + job_id: message.job_id, + attachment_id: message.attachment_id, + pipeline_version: 1, + attempt: 1, + created_at: new Date(T0), + }, + attachment, + leaseToken: 'lease', + }), + ), + extendLease: vi.fn(() => Promise.resolve(true)), + commitSuccess: vi.fn(() => { + vi.setSystemTime(T0 + 2000); + return Promise.resolve(commitResult); + }), + clearStaging: vi.fn(() => Promise.resolve(false)), + }; + const faults = { + point: vi.fn((name: string) => { + if (name !== 'worker.after_commit_before_ack') + return Promise.resolve(); + ackPointReached.resolve(); + return release.promise; + }), + }; + const storage = { + head: vi.fn(() => Promise.resolve({ size: SOURCE.length })), + getStream: vi.fn(() => Promise.resolve(Readable.from([SOURCE]))), + putBuffer: vi.fn(() => Promise.resolve()), + delete: vi.fn(() => Promise.resolve()), + variantKey: vi.fn(() => 'variant'), + }; + let consumer: + ((m: ConsumeMessage, c: Channel) => Promise) | undefined; + const broker = { + consume: ( + _prefetch: number, + handler: (m: ConsumeMessage, c: Channel) => Promise, + ) => { + consumer = handler; + }, + }; + const config = { + getOrThrow: (key: string) => + ({ + MAX_IMAGE_PIXELS: 1e8, + JOB_TIMEOUT_SECONDS: 60, + JOB_LEASE_SECONDS: 60, + JOB_RETRY_BASE_MS: 1000, + JOB_RETRY_MAX_MS: 5000, + MAX_UPLOAD_BYTES: 1e7, + WORKER_CONCURRENCY: 1, + })[key], + }; + const processor = new JobProcessor( + config as never, + broker as never, + jobs as never, + { kick: vi.fn() } as never, + faults as never, + storage as never, + { increment: vi.fn() } as never, + ); + processor.onApplicationBootstrap(); + const channel = { ack: vi.fn(), nack: vi.fn() } as unknown as Channel; + const delivery = consumer!( + { + content: Buffer.from(JSON.stringify(message)), + properties: { headers: {} }, + fields: { redelivered: false }, + } as unknown as ConsumeMessage, + channel, + ); + return { delivery, release, ackPointReached }; + } + + it('records time-to-ready at the ready commit, before post-commit work', async () => { + const { delivery, release, ackPointReached } = deliver('succeeded'); + await ackPointReached.promise; + + // Post-commit fault still pending: the sample must already exist. + expect(await readyHistogram(reader)).toEqual({ count: 1, sum: 2 }); + + vi.setSystemTime(T0 + 30_000); + release.resolve(); + await delivery; + expect(await readyHistogram(reader)).toEqual({ count: 1, sum: 2 }); + }); + + it('writes no time-to-ready sample for a superseded commit', async () => { + const { delivery, release, ackPointReached } = deliver('superseded'); + await ackPointReached.promise; + release.resolve(); + await delivery; + expect((await readyHistogram(reader)).count).toBe(0); + }); +}); diff --git a/app/src/worker/job-processor.service.ts b/app/src/worker/job-processor.service.ts new file mode 100644 index 0000000..f1914eb --- /dev/null +++ b/app/src/worker/job-processor.service.ts @@ -0,0 +1,677 @@ +import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { Channel, ConsumeMessage } from 'amqplib'; +import { + ROOT_CONTEXT, + SpanKind, + SpanStatusCode, + trace, + type Span, +} from '@opentelemetry/api'; +import { createHash } from 'node:crypto'; +import os from 'node:os'; +import type { AttachmentRow } from '../attachments/attachment.js'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { ObjectStorage } from '../storage/object-storage.js'; +import { retryDelayMs } from '../jobs/backoff.js'; +import { BrokerClient } from '../jobs/broker.client.js'; +import { JOB_QUEUE } from '../jobs/broker.topology.js'; +import { + classifyError, + JobTimeoutError, + SourceMismatchError, + SourceMissingError, + type ErrorClass, +} from '../jobs/errors.js'; +import { FaultInjector } from '../jobs/fault-injector.js'; +import { + JOB_TYPE, + parseJobMessage, + type JobMessage, +} from '../jobs/job-message.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { + JobsRepository, + type ClaimResult, + type VariantWrite, +} from '../jobs/jobs.repository.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { renderVariants, type RenderedVariant } from './pipelines.js'; +import { instruments, meter } from '../telemetry/instruments.js'; +import { appLogger } from '../telemetry/logger.js'; +import { + contextFromTraceFields, + errorType, + markSpanError, + traceFieldsFromHeaders, + tracer, +} from '../telemetry/tracing.js'; + +const SHUTDOWN_DRAIN_MS = 30_000; +const VARIANT_EXTENSIONS = [ + ['thumbnail', 'jpg'], + ['crop', 'jpg'], + ['optimized', 'webp'], +] as const; + +/** Bounded outcome set: the `outcome` label of messenger.jobs.processed. */ +type JobOutcome = + | 'succeeded' + | 'superseded' + | 'lease_lost' + | 'retry' + | 'failed' + | 'commit_failed' + | 'poison' + | 'claim_failed' + | 'skipped' + | 'mismatch' + | 'crashed'; + +// Outcomes where the delivery did not do its job: WARN log, ERROR span status. +const PROBLEM_OUTCOMES: ReadonlySet = new Set([ + 'retry', + 'failed', + 'commit_failed', + 'poison', + 'claim_failed', + 'mismatch', + 'crashed', +]); + +function throwIfAborted(signal: AbortSignal): void { + if (!signal.aborted) return; + throw signal.reason instanceof Error ? signal.reason : new Error('Aborted'); +} + +function sha256(data: Buffer): string { + return createHash('sha256').update(data).digest('hex'); +} + +@Injectable() +export class JobProcessor implements OnApplicationBootstrap { + private readonly logger = new Logger(JobProcessor.name); + private readonly workerId = process.env.INSTANCE_ID ?? os.hostname(); + private readonly maxPixels: number; + private readonly timeoutSeconds: number; + private readonly leaseSeconds: number; + private readonly retryBaseMs: number; + private readonly retryMaxMs: number; + private readonly maxUploadBytes: number; + private active = 0; + private readonly idleWaiters: (() => void)[] = []; + + constructor( + private readonly config: ConfigService, + private readonly broker: BrokerClient, + private readonly jobs: JobsRepository, + private readonly relay: OutboxRelay, + private readonly faults: FaultInjector, + private readonly storage: ObjectStorage, + private readonly metrics: MetricsService, + ) { + this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS'); + this.timeoutSeconds = config.getOrThrow('JOB_TIMEOUT_SECONDS'); + this.leaseSeconds = config.getOrThrow('JOB_LEASE_SECONDS'); + this.retryBaseMs = config.getOrThrow('JOB_RETRY_BASE_MS'); + this.retryMaxMs = config.getOrThrow('JOB_RETRY_MAX_MS'); + this.maxUploadBytes = config.getOrThrow('MAX_UPLOAD_BYTES'); + } + + onApplicationBootstrap(): void { + const concurrency = this.config.getOrThrow('WORKER_CONCURRENCY'); + this.observeSaturation(concurrency); + this.broker.consume(concurrency, (message, channel) => + this.handle(message, channel), + ); + } + + /** + * Saturation of this worker: jobs in flight against WORKER_CONCURRENCY + * (= prefetch). Together with messenger.jobs.queue.* it separates «the + * worker is slow» from «the worker is full» from «the worker is gone». + */ + private observeSaturation(concurrency: number): void { + const m = meter(); + const active = m.createObservableUpDownCounter( + 'messenger.worker.jobs.active', + { unit: '{job}', description: 'Jobs this worker is processing now' }, + ); + const capacity = m.createObservableUpDownCounter( + 'messenger.worker.jobs.capacity', + { + unit: '{job}', + description: + 'Jobs this worker may process at once (WORKER_CONCURRENCY)', + }, + ); + m.addBatchObservableCallback( + (result) => { + result.observe(active, this.active); + result.observe(capacity, concurrency); + }, + [active, capacity], + ); + } + + async drain(timeoutMs = SHUTDOWN_DRAIN_MS): Promise { + if (this.active === 0) return; + const { promise, resolve } = Promise.withResolvers(); + this.idleWaiters.push(resolve); + const timer = setTimeout(resolve, timeoutMs); + await promise; + clearTimeout(timer); + } + + /** + * One CONSUMER span per delivery. Its parent is the PRODUCER span from the + * AMQP headers; messages without trace headers (published before lab6 or + * replayed raw) fall back to the trace context stored in the body. + */ + private async handle( + message: ConsumeMessage, + channel: Channel, + ): Promise { + const parsed = parseJobMessage(message.content); + const fromHeaders = traceFieldsFromHeaders( + message.properties.headers as Record | undefined, + ); + const parent = fromHeaders.traceparent + ? contextFromTraceFields(fromHeaders) + : contextFromTraceFields(parsed, ROOT_CONTEXT); + const started = process.hrtime.bigint(); + await tracer().startActiveSpan( + `process ${JOB_QUEUE}`, + { + kind: SpanKind.CONSUMER, + attributes: { + 'messaging.system': 'rabbitmq', + 'messaging.operation.type': 'process', + 'messaging.destination.name': JOB_QUEUE, + 'messaging.rabbitmq.message.redelivered': + message.fields.redelivered, + ...(parsed + ? { + 'messaging.message.id': parsed.job_id, + 'messenger.job.id': parsed.job_id, + 'messenger.attachment.id': parsed.attachment_id, + 'messenger.job.attempt': parsed.attempt, + 'messenger.pipeline.version': parsed.pipeline_version, + } + : {}), + }, + }, + parent, + async (span: Span) => { + let outcome: JobOutcome = 'crashed'; + try { + outcome = await this.dispatch(parsed, message, channel); + } catch (error) { + markSpanError(span, error); + throw error; + } finally { + this.record(span, parsed, outcome, started); + } + }, + ); + } + + private record( + span: Span, + parsed: JobMessage | undefined, + outcome: JobOutcome, + started: bigint, + ): void { + const seconds = Number(process.hrtime.bigint() - started) / 1e9; + const labels = { 'job.type': JOB_TYPE, outcome }; + instruments().jobsProcessed.add(1, labels); + instruments().jobDuration.record(seconds, labels); + // time-to-ready is recorded at the ready commit in process(). + span.setAttribute('messenger.job.outcome', outcome); + const problem = PROBLEM_OUTCOMES.has(outcome); + if (problem && outcome !== 'crashed') + span.setStatus({ code: SpanStatusCode.ERROR, message: outcome }); + appLogger.event( + problem ? 'WARN' : 'INFO', + 'job.processed', + `job ${outcome}`, + { + 'messenger.job.id': parsed?.job_id, + 'messenger.attachment.id': parsed?.attachment_id, + 'messenger.job.attempt': parsed?.attempt, + 'messenger.job.outcome': outcome, + duration_ms: Math.round(seconds * 1000), + }, + ); + span.end(); + } + + private async dispatch( + parsed: JobMessage | undefined, + message: ConsumeMessage, + channel: Channel, + ): Promise { + if (!parsed) { + this.metrics.increment('worker.messages.poison'); + this.safeNack(channel, message, false); + return 'poison'; + } + + const claim = await this.claimWithRetry(parsed); + if (!claim) { + this.metrics.increment('worker.jobs.claim_failed'); + // Do not burn the delivery limit in a tight nack loop while the + // database is briefly unavailable. + this.safeNackAfter(channel, message, true, 5000); + return 'claim_failed'; + } + if (claim.kind === 'skip') { + if (claim.reason === 'mismatch') { + this.safeNack(channel, message, false); + return 'mismatch'; + } + this.metrics.increment(`worker.jobs.skipped.${claim.reason}`); + trace + .getActiveSpan() + ?.setAttribute('messenger.job.skip_reason', claim.reason); + this.safeAck(channel, message); + return 'skipped'; + } + + this.begin(); + try { + return await this.process( + claim.job, + claim.attachment, + claim.leaseToken, + message, + channel, + ); + } finally { + this.end(); + } + } + + private async process( + job: { + job_id: string; + attachment_id: string; + pipeline_version: number; + attempt: number; + created_at: Date; + }, + attachment: AttachmentRow, + leaseToken: string, + message: ConsumeMessage, + channel: Channel, + ): Promise { + this.metrics.increment('worker.jobs.claimed'); + const controller = new AbortController(); + const target = { + attachmentId: job.attachment_id, + pipelineVersion: job.pipeline_version, + }; + const timeout = setTimeout( + () => controller.abort(new JobTimeoutError(this.timeoutSeconds)), + this.timeoutSeconds * 1000, + ); + const heartbeat = setInterval( + () => { + this.jobs + .extendLease(job.job_id, leaseToken, this.leaseSeconds) + .then((extended) => { + if (!extended && !controller.signal.aborted) + controller.abort(new Error('Lease lost')); + }) + .catch((error: unknown) => { + this.logger.warn( + `Lease heartbeat failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + }); + }, + Math.max(1000, (this.leaseSeconds * 1000) / 3), + ); + let committed = false; + let committedOutcome: JobOutcome = 'succeeded'; + + try { + await this.faults.point( + 'worker.before_side_effect', + target, + controller.signal, + ); + throwIfAborted(controller.signal); + const source = await this.ensureFinalOriginal( + attachment, + controller.signal, + ); + throwIfAborted(controller.signal); + const variants = await renderVariants( + source, + job.pipeline_version, + { + maxPixels: this.maxPixels, + timeoutSeconds: this.timeoutSeconds, + signal: controller.signal, + }, + ); + throwIfAborted(controller.signal); + for (const variant of variants) { + if ( + !(await this.jobs.extendLease( + job.job_id, + leaseToken, + this.leaseSeconds, + )) + ) + throw new Error('Lease lost'); + await this.storage.putBuffer( + this.variantKey(job, variant), + variant.data, + variant.contentType, + controller.signal, + ); + } + await this.faults.point( + 'worker.after_side_effect', + target, + controller.signal, + ); + throwIfAborted(controller.signal); + + const result = await this.jobs.commitSuccess( + job.job_id, + leaseToken, + variants.map((variant) => this.variantWrite(job, variant)), + ); + const readyCommittedAt = Date.now(); + committed = true; + committedOutcome = result; + if (result === 'succeeded') { + // Durable acceptance (job.created_at, set in the acceptance + // transaction) to the ready commit; before post-commit fault/ACK. + const ready = (readyCommittedAt - job.created_at.getTime()) / 1000; + if (Number.isFinite(ready) && ready >= 0) + instruments().timeToReady.record(ready, { 'job.type': JOB_TYPE }); + } + this.metrics.increment(`worker.jobs.${result}`); + await this.faults.point( + 'worker.after_commit_before_ack', + target, + controller.signal, + ); + this.safeAck(channel, message); + if (result === 'succeeded') { + await this.cleanupStaging(attachment); + await this.cleanupAttemptObjects(job, job.attempt); + } else if (result === 'superseded') { + await this.cleanupAttemptObjects(job, null); + } + return result; + } catch (error) { + if (committed) { + // The durable effect is already committed; a failure at the ack + // fault point or a lost reply must not turn into a retry. + this.safeAck(channel, message); + return committedOutcome; + } + // Only the error type/code reaches the span: driver messages may + // carry request values. + trace.getActiveSpan()?.setAttribute('error.type', errorType(error)); + const failure = this.classify(error, controller.signal); + const delay = retryDelayMs( + job.attempt, + this.retryBaseMs, + this.retryMaxMs, + ); + try { + const outcome = await this.jobs.commitFailure( + job.job_id, + leaseToken, + failure, + delay, + ); + this.metrics.increment(`worker.jobs.${outcome}`); + if (outcome === 'retry') this.relay.kick(); + this.safeAck(channel, message); + if (outcome === 'retry' || outcome === 'failed') + await this.cleanupAttemptObjects(job, null); + return outcome; + } catch (commitError) { + this.metrics.increment('worker.jobs.commit_failed'); + this.logger.warn( + `Failure commit failed: ${commitError instanceof Error ? commitError.message : 'unknown error'}`, + ); + setTimeout(() => this.safeNack(channel, message, true), 1000); + return 'commit_failed'; + } + } finally { + clearTimeout(timeout); + clearInterval(heartbeat); + } + } + + private classify(error: unknown, signal: AbortSignal): ErrorClass { + if (signal.aborted && signal.reason instanceof JobTimeoutError) + return classifyError(signal.reason); + return classifyError(error); + } + + private async ensureFinalOriginal( + attachment: AttachmentRow, + signal: AbortSignal, + ): Promise { + const expectedSize = Number(attachment.size_bytes); + const head = await this.storage.head(attachment.object_key); + if (head !== null && head.size === expectedSize) { + const data = await this.readObject(attachment.object_key, signal); + this.verifySource(attachment, data); + return data; + } + + const stagingKey = attachment.staging_key; + if (stagingKey === null) throw new SourceMissingError(); + const data = await this.readObject(stagingKey, signal); + this.verifySource(attachment, data); + await this.storage.putBuffer( + attachment.object_key, + data, + attachment.content_type, + signal, + ); + this.metrics.increment('worker.original.published'); + return data; + } + + private async readObject( + key: string, + signal: AbortSignal, + ): Promise { + const stream = await this.storage.getStream(key, signal); + if (stream === null) throw new SourceMissingError(); + const chunks: Buffer[] = []; + let total = 0; + const destroy = (): void => { + stream.destroy( + signal.reason instanceof Error + ? signal.reason + : new Error('Aborted'), + ); + }; + signal.addEventListener('abort', destroy, { once: true }); + try { + for await (const chunk of stream as AsyncIterable) { + total += chunk.length; + if (total > this.maxUploadBytes) + throw new SourceMismatchError( + 'Source exceeds MAX_UPLOAD_BYTES', + ); + chunks.push(chunk); + } + } catch (error) { + if (signal.aborted) + throw signal.reason instanceof Error ? signal.reason : error; + throw error; + } finally { + signal.removeEventListener('abort', destroy); + stream.destroy(); + } + return Buffer.concat(chunks, total); + } + + private verifySource(attachment: AttachmentRow, data: Buffer): void { + if ( + data.length !== Number(attachment.size_bytes) || + sha256(data) !== attachment.sha256 + ) + throw new SourceMismatchError(); + } + + private variantKey( + job: { + attachment_id: string; + pipeline_version: number; + attempt: number; + }, + variant: RenderedVariant, + ): string { + return this.storage.variantKey( + job.attachment_id, + job.pipeline_version, + variant.name, + variant.ext, + job.attempt, + ); + } + + private variantWrite( + job: { + attachment_id: string; + pipeline_version: number; + attempt: number; + }, + variant: RenderedVariant, + ): VariantWrite { + return { + name: variant.name, + objectKey: this.variantKey(job, variant), + contentType: variant.contentType, + sizeBytes: variant.data.length, + width: variant.width, + height: variant.height, + sha256: variant.sha256, + }; + } + + private async cleanupAttemptObjects( + job: { attachment_id: string; pipeline_version: number; attempt: number }, + keepAttempt: number | null, + ): Promise { + for (let attempt = 1; attempt <= job.attempt; attempt += 1) { + if (attempt === keepAttempt) continue; + for (const [name, extension] of VARIANT_EXTENSIONS) { + try { + await this.storage.delete( + this.storage.variantKey( + job.attachment_id, + job.pipeline_version, + name, + extension, + attempt, + ), + ); + } catch (error) { + this.logger.warn( + `Variant cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + } + } + } + + private async cleanupStaging(attachment: AttachmentRow): Promise { + const key = attachment.staging_key; + if (key === null) return; + try { + const cleared = await this.jobs.clearStaging( + attachment.id, + key, + (stagingKey) => this.storage.delete(stagingKey), + ); + if (cleared) this.metrics.increment('worker.staging.deleted'); + } catch (error) { + this.metrics.increment('worker.staging.error'); + this.logger.warn( + `Staging cleanup for ${attachment.id} deferred: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + } + + private async claimWithRetry( + message: JobMessage, + ): Promise { + for (let attempt = 1; attempt <= 3; attempt += 1) { + try { + return await this.jobs.claim( + message, + this.workerId, + this.leaseSeconds, + ); + } catch (error) { + if (attempt === 3) { + this.logger.warn( + `Claim failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + return undefined; + } + await this.sleep(300 * attempt); + } + } + return undefined; + } + + private sleep(milliseconds: number): Promise { + const { promise, resolve } = Promise.withResolvers(); + setTimeout(resolve, milliseconds); + return promise; + } + + private safeNackAfter( + channel: Channel, + message: ConsumeMessage, + requeue: boolean, + delayMs: number, + ): void { + setTimeout(() => this.safeNack(channel, message, requeue), delayMs); + } + + private safeAck(channel: Channel, message: ConsumeMessage): void { + try { + channel.ack(message); + } catch { + // A closed channel redelivers; the DB fence makes the duplicate a no-op. + } + } + + private safeNack( + channel: Channel, + message: ConsumeMessage, + requeue: boolean, + ): void { + try { + channel.nack(message, false, requeue); + } catch { + // The broker redelivers after the delivery limit or lease recovery. + } + } + + private begin(): void { + this.active += 1; + } + + private end(): void { + this.active -= 1; + if (this.active !== 0) return; + for (const resolve of this.idleWaiters.splice(0)) resolve(); + } +} diff --git a/app/src/worker/lease-reaper.service.ts b/app/src/worker/lease-reaper.service.ts new file mode 100644 index 0000000..5531188 --- /dev/null +++ b/app/src/worker/lease-reaper.service.ts @@ -0,0 +1,100 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { retryDelayMs } from '../jobs/backoff.js'; +import { BrokerClient } from '../jobs/broker.client.js'; +import { JOB_QUEUE } from '../jobs/broker.topology.js'; +import { JobsRepository } from '../jobs/jobs.repository.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { MetricsService } from '../metrics/metrics.service.js'; + +const REAP_BATCH = 20; + +/** + * The reaper recovers a worker killed mid-job (expired lease) and re-emits + * queued jobs whose broker message disappeared, for example after a DLQ + * dead-letter or a lost publish. Both paths only insert an outbox row; the + * claim fence absorbs duplicates. + */ +@Injectable() +export class LeaseReaper implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(LeaseReaper.name); + private timer: NodeJS.Timeout | undefined; + private running = false; + private readonly retryBaseMs: number; + private readonly retryMaxMs: number; + private readonly reconcileGraceSeconds: number; + + constructor( + private readonly config: ConfigService, + private readonly jobs: JobsRepository, + private readonly broker: BrokerClient, + private readonly relay: OutboxRelay, + private readonly metrics: MetricsService, + ) { + this.retryBaseMs = config.getOrThrow('JOB_RETRY_BASE_MS'); + this.retryMaxMs = config.getOrThrow('JOB_RETRY_MAX_MS'); + this.reconcileGraceSeconds = config.getOrThrow( + 'QUEUED_RECONCILE_GRACE_SECONDS', + ); + } + + onModuleInit(): void { + const interval = this.config.getOrThrow('LEASE_REAPER_INTERVAL_MS'); + this.timer = setInterval(() => { + if (this.running) return; + this.running = true; + this.tick() + .catch((error: unknown) => { + this.metrics.increment('worker.leases.reap_error'); + this.logger.warn( + `Lease reaper failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + }) + .finally(() => { + this.running = false; + }); + }, interval); + this.timer.unref(); + } + + onModuleDestroy(): void { + clearInterval(this.timer); + this.timer = undefined; + } + + private async tick(): Promise { + const reaped = await this.jobs.reapExpiredLeases( + REAP_BATCH, + (attempt) => + retryDelayMs(attempt, this.retryBaseMs, this.retryMaxMs), + ); + if (reaped > 0) { + this.metrics.add('worker.leases.reaped', reaped); + this.relay.kick(); + } + // A normal backlog also has queued jobs with a published outbox row. + // Re-emitting them would multiply broker messages; only reconcile when + // the queue looks empty. + let queueEmpty = false; + try { + queueEmpty = (await this.broker.queueDepth(JOB_QUEUE)).messages === 0; + } catch { + queueEmpty = false; + } + if (!queueEmpty) return; + const reconciled = await this.jobs.reconcileQueuedJobs( + REAP_BATCH, + this.reconcileGraceSeconds, + ); + if (reconciled > 0) { + this.metrics.add('worker.jobs.reconciled', reconciled); + this.relay.kick(); + } + } +} diff --git a/app/src/worker/pipelines.spec.ts b/app/src/worker/pipelines.spec.ts new file mode 100644 index 0000000..91de436 --- /dev/null +++ b/app/src/worker/pipelines.spec.ts @@ -0,0 +1,102 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import sharp from 'sharp'; +import { JobTimeoutError } from '../jobs/errors.js'; +import { renderVariants, type RenderedVariant } from './pipelines.js'; + +const sample = readFileSync( + new URL('../../../tests/fixtures/sample.png', import.meta.url), +); +const limits = { maxPixels: 40_000_000, timeoutSeconds: 30 }; + +function byName( + variants: RenderedVariant[], + name: 'thumbnail' | 'crop' | 'optimized', +): RenderedVariant { + const variant = variants.find((item) => item.name === name); + if (!variant) throw new Error(`missing ${name}`); + return variant; +} + +describe('renderVariants', () => { + it('renders the v1 contract geometry and formats', async () => { + const variants = await renderVariants(sample, 1, limits); + const thumbnail = byName(variants, 'thumbnail'); + const crop = byName(variants, 'crop'); + const optimized = byName(variants, 'optimized'); + + expect([thumbnail.width, thumbnail.height]).toEqual([256, 160]); + expect(thumbnail.contentType).toBe('image/jpeg'); + expect((await sharp(thumbnail.data).metadata()).format).toBe('jpeg'); + + expect([crop.width, crop.height]).toEqual([128, 128]); + expect((await sharp(crop.data).metadata()).format).toBe('jpeg'); + + expect([optimized.width, optimized.height]).toEqual([320, 200]); + expect(optimized.contentType).toBe('image/webp'); + expect((await sharp(optimized.data).metadata()).format).toBe('webp'); + }); + + it('applies EXIF orientation before fitting', async () => { + const oriented = await sharp({ + create: { + width: 300, + height: 200, + channels: 3, + background: { r: 20, g: 80, b: 140 }, + }, + }) + .jpeg() + .withMetadata({ orientation: 6 }) + .toBuffer(); + const variants = await renderVariants(oriented, 1, limits); + const thumbnail = byName(variants, 'thumbnail'); + expect([thumbnail.width, thumbnail.height]).toEqual([170, 256]); + }); + + it('composites transparent pixels onto white', async () => { + const transparent = await sharp({ + create: { + width: 10, + height: 10, + channels: 4, + background: { r: 0, g: 0, b: 0, alpha: 0 }, + }, + }) + .png() + .toBuffer(); + const variants = await renderVariants(transparent, 1, limits); + const thumbnail = byName(variants, 'thumbnail'); + const { data } = await sharp(thumbnail.data) + .raw() + .toBuffer({ resolveWithObject: true }); + expect([...data.subarray(0, 3)]).toEqual([255, 255, 255]); + }); + + it('is deterministic for the same input and version', async () => { + const first = await renderVariants(sample, 1, limits); + const second = await renderVariants(sample, 1, limits); + for (const name of ['thumbnail', 'crop', 'optimized'] as const) + expect(byName(first, name).sha256).toBe( + byName(second, name).sha256, + ); + }); + + it('honours an aborted job deadline before starting a render', async () => { + const controller = new AbortController(); + controller.abort(new JobTimeoutError(1)); + await expect( + renderVariants(sample, 1, { + ...limits, + signal: controller.signal, + }), + ).rejects.toBeInstanceOf(JobTimeoutError); + }); + + it('produces a different v2 thumbnail', async () => { + const v1 = byName(await renderVariants(sample, 1, limits), 'thumbnail'); + const v2 = byName(await renderVariants(sample, 2, limits), 'thumbnail'); + expect(v1.sha256).not.toBe(v2.sha256); + expect([v2.width, v2.height]).toEqual([256, 160]); + }); +}); diff --git a/app/src/worker/pipelines.ts b/app/src/worker/pipelines.ts new file mode 100644 index 0000000..0a0b80c --- /dev/null +++ b/app/src/worker/pipelines.ts @@ -0,0 +1,175 @@ +import { createHash } from 'node:crypto'; +import sharp from 'sharp'; +import { + JobTimeoutError, + UnsupportedPipelineError, +} from '../jobs/errors.js'; +import { fitInside } from '../jobs/fit-inside.js'; + +// Same policy as the API decoder: one libvips worker, no operation cache. +sharp.cache(false); +sharp.concurrency(1); + +type SharpImage = ReturnType; + +export const SUPPORTED_PIPELINE_VERSIONS = [1, 2] as const; + +export type RenderedVariant = { + name: 'thumbnail' | 'crop' | 'optimized'; + ext: 'jpg' | 'webp'; + contentType: 'image/jpeg' | 'image/webp'; + data: Buffer; + width: number; + height: number; + sha256: string; +}; + +export type RenderLimits = { + maxPixels: number; + timeoutSeconds: number; + signal?: AbortSignal; +}; + +function throwIfAborted(signal?: AbortSignal): void { + if (!signal?.aborted) return; + throw signal.reason instanceof Error + ? signal.reason + : new Error('Aborted'); +} + +function remainingSeconds(deadline: number, total: number): number { + const remaining = Math.ceil((deadline - Date.now()) / 1000); + if (remaining <= 0) throw new JobTimeoutError(total); + return Math.min(total, remaining); +} + +function input( + data: Buffer, + limits: RenderLimits, + deadline: number, +): SharpImage { + return sharp(data, { + failOn: 'warning', + limitInputPixels: limits.maxPixels, + sequentialRead: true, + }) + .timeout({ seconds: remainingSeconds(deadline, limits.timeoutSeconds) }) + .rotate(); +} + +function jpegV1(image: SharpImage): SharpImage { + return image.jpeg({ quality: 80 }); +} + +function jpegV2(image: SharpImage): SharpImage { + return image.jpeg({ quality: 90, progressive: true, mozjpeg: true }); +} + +function rendered( + name: RenderedVariant['name'], + ext: RenderedVariant['ext'], + contentType: RenderedVariant['contentType'], + data: Buffer, + width: number, + height: number, +): RenderedVariant { + return { + name, + ext, + contentType, + data, + width, + height, + sha256: createHash('sha256').update(data).digest('hex'), + }; +} + +async function output( + image: SharpImage, + name: RenderedVariant['name'], + ext: RenderedVariant['ext'], + contentType: RenderedVariant['contentType'], +): Promise { + const { data, info } = await image.toBuffer({ resolveWithObject: true }); + return rendered(name, ext, contentType, data, info.width, info.height); +} + +/** + * Renders the thumbnail, crop and optimized variants from one decoded source. + * The input dimensions are EXIF-oriented: `.rotate()` applies the orientation + * and `metadata().autoOrient` describes the result, so 300x200 orientation 6 + * becomes 200x300 before fitting. + */ +export async function renderVariants( + data: Buffer, + pipelineVersion: number, + limits: RenderLimits, +): Promise { + if ( + !(SUPPORTED_PIPELINE_VERSIONS as readonly number[]).includes( + pipelineVersion, + ) + ) + throw new UnsupportedPipelineError(pipelineVersion); + + const deadline = Date.now() + limits.timeoutSeconds * 1000; + throwIfAborted(limits.signal); + const metadata = await sharp(data, { + failOn: 'warning', + limitInputPixels: limits.maxPixels, + sequentialRead: true, + }) + .timeout({ seconds: remainingSeconds(deadline, limits.timeoutSeconds) }) + .metadata(); + throwIfAborted(limits.signal); + const width = metadata.autoOrient?.width ?? metadata.width; + const height = metadata.autoOrient?.height ?? metadata.height; + const [thumbnailWidth, thumbnailHeight] = fitInside(width, height, 256); + const [optimizedWidth, optimizedHeight] = fitInside(width, height, 1280); + const v2 = pipelineVersion >= 2; + + const thumbnail = v2 ? jpegV2 : jpegV1; + throwIfAborted(limits.signal); + remainingSeconds(deadline, limits.timeoutSeconds); + const thumbnailOutput = await output( + thumbnail( + input(data, limits, deadline) + .flatten({ background: '#ffffff' }) + .resize(thumbnailWidth, thumbnailHeight, { fit: 'fill' }), + ), + 'thumbnail', + 'jpg', + 'image/jpeg', + ); + + throwIfAborted(limits.signal); + remainingSeconds(deadline, limits.timeoutSeconds); + const cropOutput = await output( + thumbnail( + input(data, limits, deadline) + .flatten({ background: '#ffffff' }) + .resize(128, 128, { fit: 'cover', position: 'centre' }), + ), + 'crop', + 'jpg', + 'image/jpeg', + ); + + throwIfAborted(limits.signal); + remainingSeconds(deadline, limits.timeoutSeconds); + const optimizedOutput = await output( + input(data, limits, deadline) + .resize(optimizedWidth, optimizedHeight, { fit: 'fill' }) + .webp( + v2 + ? { quality: 82, effort: 5, smartSubsample: true } + : { quality: 75, effort: 4 }, + ), + 'optimized', + 'webp', + 'image/webp', + ); + + throwIfAborted(limits.signal); + return [thumbnailOutput, cropOutput, optimizedOutput]; +} diff --git a/app/src/worker/staging-cleaner.service.ts b/app/src/worker/staging-cleaner.service.ts new file mode 100644 index 0000000..49eeb8b --- /dev/null +++ b/app/src/worker/staging-cleaner.service.ts @@ -0,0 +1,92 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import type { AppConfig } from '../config/app-config.schema.js'; +import { JobsRepository } from '../jobs/jobs.repository.js'; +import { MetricsService } from '../metrics/metrics.service.js'; +import { ObjectStorage } from '../storage/object-storage.js'; + +const CLEANUP_BATCH = 100; + +/** + * Removes staging objects after the worker committed the final copy, and after + * the documented retention for failed jobs. A ready row waits one minute so a + * just-acknowledged job is never raced by the cleaner. + */ +@Injectable() +export class StagingCleaner implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(StagingCleaner.name); + private timer: NodeJS.Timeout | undefined; + private running = false; + + constructor( + private readonly config: ConfigService, + private readonly jobs: JobsRepository, + private readonly storage: ObjectStorage, + private readonly metrics: MetricsService, + ) {} + + onModuleInit(): void { + const interval = this.config.getOrThrow('STAGING_CLEANUP_INTERVAL_MS'); + if (interval <= 0) return; + this.timer = setInterval(() => { + if (this.running) return; + this.running = true; + this.cleanupOnce() + .catch((error: unknown) => { + this.metrics.increment('worker.staging.cleanup_error'); + this.logger.warn( + `Staging cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + }) + .finally(() => { + this.running = false; + }); + }, interval); + this.timer.unref(); + } + + onModuleDestroy(): void { + clearInterval(this.timer); + this.timer = undefined; + } + + async cleanupOnce(): Promise { + const candidates = await this.jobs.stagingCleanupCandidates( + this.config.getOrThrow('STAGING_RETENTION_SECONDS'), + CLEANUP_BATCH, + ); + let deleted = 0; + for (const candidate of candidates) { + try { + if ( + await this.jobs.clearStaging( + candidate.id, + candidate.staging_key, + (key) => this.storage.delete(key), + ) + ) + deleted += 1; + } catch (error) { + this.metrics.increment('worker.staging.cleanup_error'); + this.logger.warn( + `Staging cleanup of ${candidate.id} failed: ${error instanceof Error ? error.message : 'unknown error'}`, + ); + } + } + if (deleted > 0) this.metrics.add('worker.staging.deleted', deleted); + const outbox = await this.jobs.pruneOutbox( + this.config.getOrThrow('OUTBOX_RETENTION_SECONDS'), + ); + if (outbox > 0) this.metrics.add('jobs.outbox.pruned', outbox); + const events = await this.jobs.pruneEvents( + this.config.getOrThrow('JOB_EVENTS_RETENTION_SECONDS'), + ); + if (events > 0) this.metrics.add('jobs.events.pruned', events); + return deleted; + } +} diff --git a/app/src/worker/worker.module.ts b/app/src/worker/worker.module.ts new file mode 100644 index 0000000..8f409fd --- /dev/null +++ b/app/src/worker/worker.module.ts @@ -0,0 +1,26 @@ +import { Module } from '@nestjs/common'; +import { AppConfigModule } from '../config/app-config.module.js'; +import { DatabaseModule } from '../database/database.module.js'; +import { JobsModule } from '../jobs/jobs.module.js'; +import { OutboxRelay } from '../jobs/outbox-relay.service.js'; +import { MetricsModule } from '../metrics/metrics.module.js'; +import { RedisModule } from '../redis/redis.module.js'; +import { StorageModule } from '../storage/storage.module.js'; +import { JobProcessor } from './job-processor.service.js'; +import { LeaseReaper } from './lease-reaper.service.js'; +import { StagingCleaner } from './staging-cleaner.service.js'; + +@Module({ + imports: [ + AppConfigModule, + DatabaseModule, + RedisModule, + MetricsModule, + StorageModule, + JobsModule, + ], + // The worker publishes retry and lease-expiry outbox rows itself; the same + // relay also runs in the API process. SKIP LOCKED makes that safe. + providers: [JobProcessor, LeaseReaper, StagingCleaner, OutboxRelay], +}) +export class WorkerModule {} diff --git a/app/test/app.e2e-spec.ts b/app/test/app.e2e-spec.ts new file mode 100644 index 0000000..5d7cedc --- /dev/null +++ b/app/test/app.e2e-spec.ts @@ -0,0 +1,674 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { Pool } from 'pg'; +import { createClient } from 'redis'; +import type { SessionResponse } from '../src/auth/auth.service.js'; +import type { Chat } from '../src/chats/chat.js'; +import type { ApiErrorBody } from '../src/common/errors/api-error.js'; +import type { Page } from '../src/common/http/page.js'; +import type { Message } from '../src/messages/message.js'; +import type { User } from '../src/users/user.js'; + +// The suite is black-box: run it against the compiled application process. +// Vitest sets process.env.BASE_URL itself (Vite base), so the API URL uses its own name. +const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace( + /\/+$/u, + '', +); +const basicChallenge = 'Basic realm="messenger", charset="UTF-8"'; +const bearerChallenge = 'Bearer realm="messenger"'; +const password = 'integration:пароль🔐'; +const runId = randomUUID().replaceAll('-', '').slice(0, 12); +const usernames: string[] = []; +const tokens: string[] = []; +let sequence = 0; +let database: Pool; +let redis: ReturnType; + +type Actor = { user: User; password: string; token: string }; +type HttpResult = { body: T; response: Response }; + +async function http( + path: string, + init: RequestInit = {}, +): Promise> { + const response = await fetch(`${baseUrl}${path}`, init); + const text = await response.text(); + let body: unknown = undefined; + if (text) { + try { + body = JSON.parse(text); + } catch { + body = text; + } + } + return { body: body as T, response }; +} + +function json( + body: unknown, + headers: Record = {}, +): RequestInit { + return { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body: JSON.stringify(body), + }; +} + +function basic(username: string, secret: string): string { + return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`; +} + +function bearer(token: string): Record { + return { authorization: `Bearer ${token}` }; +} + +function idempotencyKey(): Record { + return { 'idempotency-key': randomUUID().replaceAll('-', '') }; +} + +function messageHeaders(token: string): Record { + return { ...bearer(token), ...idempotencyKey() }; +} + +async function register( + displayName = 'Интеграционный пользователь', + secret = password, +): Promise { + const username = `e2e_${runId}_${sequence++}`.slice(0, 32); + usernames.push(username); + const result = await http( + '/api/v1/users', + json({ username, display_name: displayName, password: secret }), + ); + expect(result.response.status).toBe(201); + return result.body; +} + +async function login(user: User, secret = password): Promise { + const result = await http('/api/v1/auth/sessions', { + method: 'POST', + headers: { authorization: basic(user.username, secret) }, + }); + expect(result.response.status).toBe(201); + tokens.push(result.body.token); + return result.body; +} + +async function actor(displayName?: string): Promise { + const user = await register(displayName); + const session = await login(user); + return { user, password, token: session.token }; +} + +function expectError( + result: HttpResult, + status: number, + code: string, +): void { + expect(result.response.status).toBe(status); + expect(result.body.error.code).toBe(code); + expect(result.body.error.request_id).toBe( + result.response.headers.get('x-request-id'), + ); +} + +describe('HTTP integration contract', () => { + beforeAll(async () => { + database = new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); + redis = createClient({ + url: process.env.REDIS_URL, + socket: { reconnectStrategy: false }, + }); + redis.on('error', () => {}); + await redis.connect(); + }); + + afterAll(async () => { + if (usernames.length) { + await database.query('BEGIN'); + try { + await database.query( + `DELETE FROM messages WHERE sender_id IN (SELECT id FROM users WHERE username = ANY($1::text[]))`, + [usernames], + ); + await database.query( + `DELETE FROM chats WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id IN (SELECT id FROM users WHERE username = ANY($1::text[])))`, + [usernames], + ); + await database.query( + 'DELETE FROM users WHERE username = ANY($1::text[])', + [usernames], + ); + await database.query('COMMIT'); + } catch (error) { + await database.query('ROLLBACK'); + throw error; + } + } + if (redis.isOpen) redis.destroy(); + await database.end(); + }); + + it('serves liveness and requires real session authentication', async () => { + const live = await http<{ status: string }>('/health/live'); + expect(live.response.status).toBe(200); + expect(live.body).toEqual({ status: 'ok' }); + const denied = await http('/api/v1/users/me'); + expectError(denied, 401, 'unauthorized'); + expect(denied.response.headers.get('www-authenticate')).toBe( + bearerChallenge, + ); + }); + + it('measures string lengths in Unicode code points', async () => { + const emoji = '🔐'; + const username = (suffix: string) => + `e2e_${runId}_${suffix}`.slice(0, 32); + const rejected = await http( + '/api/v1/users', + json({ + username: username('cp_short'), + display_name: 'Code points', + password: emoji.repeat(11), + }), + ); + expectError(rejected, 400, 'invalid_request'); + const tooLongPassword = await http( + '/api/v1/users', + json({ + username: username('cp_long'), + display_name: 'Code points', + password: emoji.repeat(129), + }), + ); + expectError(tooLongPassword, 400, 'invalid_request'); + const tooLongName = await http( + '/api/v1/users', + json({ + username: username('cp_name'), + display_name: emoji.repeat(101), + password, + }), + ); + expectError(tooLongName, 400, 'invalid_request'); + + const shortUsername = username('cp_ok'); + usernames.push(shortUsername); + const boundaryPassword = emoji.repeat(12); + const created = await http( + '/api/v1/users', + json({ + username: shortUsername, + display_name: emoji.repeat(100), + password: boundaryPassword, + }), + ); + expect(created.response.status).toBe(201); + expect([...created.body.display_name].length).toBe(100); + // The stored password keeps all 12 code points: authentication works. + const session = await http('/api/v1/auth/sessions', { + method: 'POST', + headers: { + authorization: basic(shortUsername, boundaryPassword), + }, + }); + expect(session.response.status).toBe(201); + tokens.push(session.body.token); + + const longTitleRejected = await http( + '/api/v1/chats', + json( + { title: emoji.repeat(101), member_ids: [created.body.id] }, + bearer(session.body.token), + ), + ); + expectError(longTitleRejected, 400, 'invalid_request'); + const longTitle = await http( + '/api/v1/chats', + json( + { title: emoji.repeat(100), member_ids: [created.body.id] }, + bearer(session.body.token), + ), + ); + expect(longTitle.response.status).toBe(201); + const tooLongText = await http( + `/api/v1/chats/${longTitle.body.id}/messages`, + json({ text: emoji.repeat(4001) }, messageHeaders(session.body.token)), + ); + expectError(tooLongText, 400, 'invalid_request'); + const boundaryText = await http( + `/api/v1/chats/${longTitle.body.id}/messages`, + json({ text: emoji.repeat(4000) }, messageHeaders(session.body.token)), + ); + expect(boundaryText.response.status).toBe(201); + expect([...boundaryText.body.text].length).toBe(4000); + }); + + it('rejects whitespace-only and too-short credentials', async () => { + const username = `e2e_${runId}_${sequence++}`.slice(0, 32); + usernames.push(username); + const cases = [ + { password: ' '.repeat(12), display_name: 'Пользователь' }, + { password: '\t'.repeat(16), display_name: 'Пользователь' }, + { password: 'short-pass', display_name: 'Пользователь' }, + { password, display_name: ' ' }, + ]; + for (const body of cases) { + const result = await http( + '/api/v1/users', + json({ username, ...body }), + ); + expectError(result, 400, 'invalid_request'); + } + const accepted = await http( + '/api/v1/users', + json({ username, display_name: 'Пользователь', password }), + ); + expect(accepted.response.status).toBe(201); + }); + + it('registers, logs in with Unicode/colon password, and challenges malformed Basic', async () => { + const user = await register(); + const session = await login(user); + expect(session.user.id).toBe(user.id); + expect(session.token_type).toBe('Bearer'); + const me = await http('/api/v1/users/me', { + headers: bearer(session.token), + }); + expect(me.response.status).toBe(200); + expect(me.body.id).toBe(user.id); + for (const authorization of [ + 'Basic !!!', + 'Basic YWJj', + 'Bearer nope', + ]) { + const result = await http('/api/v1/auth/sessions', { + method: 'POST', + headers: { authorization }, + }); + expectError(result, 401, 'unauthorized'); + expect(result.response.headers.get('www-authenticate')).toBe( + basicChallenge, + ); + } + const bodyResult = await http('/api/v1/auth/sessions', { + ...json({ unexpected: true }), + headers: { authorization: basic(user.username, password) }, + }); + expectError(bodyResult, 400, 'invalid_request'); + }); + + it('returns conflict for concurrent duplicate registration', async () => { + const username = `e2e_${runId}_race`.slice(0, 32); + usernames.push(username); + const results = await Promise.all([ + http( + '/api/v1/users', + json({ username, display_name: 'Race A', password }), + ), + http( + '/api/v1/users', + json({ username, display_name: 'Race B', password }), + ), + ]); + expect( + results.filter((item) => item.response.status === 201), + 'duplicate registration must create exactly one user', + ).toHaveLength(1); + expect( + results.filter((item) => item.response.status === 409), + 'loser of the race must receive 409, not 500', + ).toHaveLength(1); + // The database unique index is the race-proof guard, so verify its effect. + const persisted = await database.query<{ count: string }>( + 'SELECT count(*)::text AS count FROM users WHERE username = $1', + [username], + ); + expect(persisted.rows[0]?.count).toBe('1'); + }); + + it('uses Bearer only, ignores X-User-Id spoofing, and prevents logout replay', async () => { + const alice = await actor('Алиса'); + const bob = await actor('Боб'); + const spoof = await http('/api/v1/users/me', { + headers: { ...bearer(alice.token), 'x-user-id': bob.user.id }, + }); + expect(spoof.response.status).toBe(200); + expect((spoof.body as unknown as User).id).toBe(alice.user.id); + const basicBusiness = await http('/api/v1/users/me', { + headers: { authorization: basic(alice.user.username, password) }, + }); + expectError(basicBusiness, 401, 'unauthorized'); + expect(basicBusiness.response.headers.get('www-authenticate')).toBe( + bearerChallenge, + ); + const logout = await http('/api/v1/auth/sessions/current', { + method: 'DELETE', + headers: bearer(alice.token), + }); + expect(logout.response.status).toBe(204); + const replay = await http('/api/v1/users/me', { + headers: bearer(alice.token), + }); + expectError(replay, 401, 'unauthorized'); + }); + + it('rejects unknown and duplicate chat members and hides chats from outsiders', async () => { + const alice = await actor(); + const bob = await actor(); + const outsider = await actor(); + const unknown = await http( + '/api/v1/chats', + json( + { title: 'unknown', member_ids: [alice.user.id, randomUUID()] }, + bearer(alice.token), + ), + ); + expectError(unknown, 400, 'invalid_request'); + const leaked = await http(`/api/v1/chats?limit=100`, { + headers: bearer(alice.token), + }); + expect(leaked.response.status).toBe(200); + expect( + (leaked.body as unknown as Page).items.some( + (item) => item.title === 'unknown', + ), + ).toBe(false); + const duplicate = await http( + '/api/v1/chats', + json( + { + title: 'duplicate', + member_ids: [alice.user.id, alice.user.id], + }, + bearer(alice.token), + ), + ); + expectError(duplicate, 400, 'invalid_request'); + const created = await http( + '/api/v1/chats', + json( + { + title: `chat-${runId}`, + member_ids: [alice.user.id, bob.user.id], + }, + bearer(alice.token), + ), + ); + expect(created.response.status).toBe(201); + const hidden = await http( + `/api/v1/chats/${created.body.id}`, + { headers: bearer(outsider.token) }, + ); + expectError(hidden, 404, 'not_found'); + }); + + it('keeps sender server-owned and makes writes visible to a second session', async () => { + const alice = await actor(); + const secondSession = (await login(alice.user)).token; + const chat = await http( + '/api/v1/chats', + json( + { title: `messages-${runId}`, member_ids: [alice.user.id] }, + bearer(alice.token), + ), + ); + expect(chat.response.status).toBe(201); + const blank = await http( + `/api/v1/chats/${chat.body.id}/messages`, + json( + { text: ' \n\t', sender_id: randomUUID() }, + messageHeaders(alice.token), + ), + ); + expectError(blank, 400, 'invalid_request'); + const spoof = await http( + `/api/v1/chats/${chat.body.id}/messages`, + json( + { text: 'hello', sender_id: randomUUID() }, + messageHeaders(alice.token), + ), + ); + expectError(spoof, 400, 'invalid_request'); + await http(`/api/v1/chats/${chat.body.id}/messages?limit=50`, { + headers: bearer(secondSession), + }); + const sent = await http( + `/api/v1/chats/${chat.body.id}/messages`, + json({ text: 'hello' }, messageHeaders(alice.token)), + ); + expect(sent.response.status).toBe(201); + expect(sent.body.sender_id).toBe(alice.user.id); + const page = await http>( + `/api/v1/chats/${chat.body.id}/messages?limit=50`, + { headers: bearer(secondSession) }, + ); + expect(page.response.status).toBe(200); + expect(page.body.items.map((item) => item.id)).toContain(sent.body.id); + }); + + it('validates cursor, limits, malformed JSON, and paginates without repeats', async () => { + const alice = await actor(); + const chat = await http( + '/api/v1/chats', + json( + { title: `pages-${runId}`, member_ids: [alice.user.id] }, + bearer(alice.token), + ), + ); + for (const text of ['one', 'two', 'three']) { + const sent = await http( + `/api/v1/chats/${chat.body.id}/messages`, + json({ text }, messageHeaders(alice.token)), + ); + expect(sent.response.status).toBe(201); + } + const invalidLimit = await http( + `/api/v1/chats/${chat.body.id}/messages?limit=101`, + { headers: bearer(alice.token) }, + ); + expectError(invalidLimit, 400, 'invalid_request'); + const invalidCursor = await http( + `/api/v1/chats/${chat.body.id}/messages?cursor=not-a-cursor`, + { headers: bearer(alice.token) }, + ); + expectError(invalidCursor, 400, 'invalid_request'); + const rolledOver = http( + `/api/v1/chats/${chat.body.id}/messages?cursor=${encodeURIComponent( + Buffer.from( + JSON.stringify({ + scope: `messages:${chat.body.id}`, + created_at: '2026-02-31T00:00:00.000Z', + id: randomUUID(), + }), + 'utf8', + ).toString('base64url'), + )}`, + { headers: bearer(alice.token) }, + ); + expectError(await rolledOver, 400, 'invalid_request'); + const malformed = await http('/api/v1/users', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{', + }); + expectError(malformed, 400, 'invalid_request'); + const first = await http>( + `/api/v1/chats/${chat.body.id}/messages?limit=2`, + { headers: bearer(alice.token) }, + ); + expect(first.body.items).toHaveLength(2); + const second = await http>( + `/api/v1/chats/${chat.body.id}/messages?limit=2&cursor=${encodeURIComponent(first.body.next_cursor!)}`, + { headers: bearer(alice.token) }, + ); + expect(second.body.items).toHaveLength(1); + expect( + new Set( + [...first.body.items, ...second.body.items].map( + (item) => item.id, + ), + ).size, + ).toBe(3); + }); + + it.skipIf(process.env.SESSION_TTL_SECONDS !== '2')( + 'expires sessions with TTL=2', + async () => { + const user = await register(); + const session = await login(user); + await sleep(2300); + const expired = await http('/api/v1/users/me', { + headers: bearer(session.token), + }); + expectError(expired, 401, 'unauthorized'); + }, + ); +}); + +// lab3: the Idempotency-Key contract of POST /chats/{id}/messages. The suite is +// black-box, so these assertions hold for one replica and for a load-balanced +// fleet alike. +describe('message idempotency', () => { + async function chatFor(token: string, memberIds: string[]): Promise { + const created = await http( + '/api/v1/chats', + json({ title: `idempotency-${runId}`, member_ids: memberIds }, bearer(token)), + ); + expect(created.response.status).toBe(201); + return created.body.id; + } + + async function textsIn(chatId: string, token: string): Promise { + const page = await http>( + `/api/v1/chats/${chatId}/messages?limit=100`, + { headers: bearer(token) }, + ); + expect(page.response.status).toBe(200); + return page.body.items.map((item) => item.text); + } + + it('requires a well-formed Idempotency-Key', async () => { + const alice = await actor(); + const chatId = await chatFor(alice.token, [alice.user.id]); + const path = `/api/v1/chats/${chatId}/messages`; + const missing = await http( + path, + json({ text: 'без ключа' }, bearer(alice.token)), + ); + expectError(missing, 400, 'invalid_request'); + for (const key of ['has space', 'comma,separated', 'x'.repeat(129)]) { + const malformed = await http( + path, + json({ text: 'плохой ключ' }, { ...bearer(alice.token), 'idempotency-key': key }), + ); + expectError(malformed, 400, 'invalid_request'); + } + }); + + it('replays the stored response and conflicts on a different body', async () => { + const alice = await actor(); + const chatId = await chatFor(alice.token, [alice.user.id]); + const path = `/api/v1/chats/${chatId}/messages`; + const key = randomUUID().replaceAll('-', ''); + const headers = { ...bearer(alice.token), 'idempotency-key': key }; + const text = `повтор ${runId}`; + + const first = await http(path, json({ text }, headers)); + expect(first.response.status).toBe(201); + const replayed = await http(path, json({ text }, headers)); + expect(replayed.response.status).toBe(201); + expect(replayed.body).toEqual(first.body); + + const conflict = await http( + path, + json({ text: 'другой body' }, headers), + ); + expectError(conflict, 409, 'conflict'); + + expect(await textsIn(chatId, alice.token)).toEqual([text]); + }); + + it('creates exactly one message for concurrent requests with one key', async () => { + const alice = await actor(); + const chatId = await chatFor(alice.token, [alice.user.id]); + const path = `/api/v1/chats/${chatId}/messages`; + const headers = { ...bearer(alice.token), ...idempotencyKey() }; + const text = `конкурентный повтор ${runId}`; + + const results = await Promise.all( + Array.from({ length: 8 }, () => http(path, json({ text }, headers))), + ); + for (const result of results) expect(result.response.status).toBe(201); + const ids = new Set(results.map((result) => result.body.id)); + expect( + ids.size, + 'one key must resolve to exactly one message across replicas', + ).toBe(1); + expect(await textsIn(chatId, alice.token)).toEqual([text]); + }); + + it('replays a key created by another replica', async () => { + // lab3: повтор с тем же ключом может прийти на любую реплику, поэтому + // проверяем не только сам повтор, но и то, что его обслужила другая реплика + // (иначе тест не отличал бы общий журнал от локального состояния процесса). + const alice = await actor(); + const chatId = await chatFor(alice.token, [alice.user.id]); + const path = `/api/v1/chats/${chatId}/messages`; + const key = randomUUID().replaceAll('-', ''); + const headers = { ...bearer(alice.token), 'idempotency-key': key }; + + const first = await http(path, json({ text: 'переключение реплики' }, headers)); + expect(first.response.status).toBe(201); + const firstInstance = first.response.headers.get('x-instance-id'); + expect(firstInstance).toBeTruthy(); + + let replay = first; + let replayInstance = firstInstance; + for (let attempt = 0; attempt < 12 && replayInstance === firstInstance; attempt += 1) { + replay = await http(path, json({ text: 'переключение реплики' }, headers)); + expect(replay.response.status).toBe(201); + replayInstance = replay.response.headers.get('x-instance-id'); + } + expect( + replayInstance, + 'повтор должен был прийти на другую реплику (round-robin за LB)', + ).not.toBe(firstInstance); + expect(replay.body).toEqual(first.body); + expect(await textsIn(chatId, alice.token)).toEqual(['переключение реплики']); + }); + + it('scopes the key per user and per chat path', async () => { + const alice = await actor(); + const bob = await actor(); + const outsider = await actor(); + const chatId = await chatFor(alice.token, [alice.user.id, bob.user.id]); + const path = `/api/v1/chats/${chatId}/messages`; + const key = randomUUID().replaceAll('-', ''); + const foreignChatId = await chatFor(outsider.token, [outsider.user.id]); + + const denied = await http( + `/api/v1/chats/${foreignChatId}/messages`, + json({ text: 'чужое' }, { ...bearer(alice.token), 'idempotency-key': key }), + ); + expectError(denied, 404, 'not_found'); + + const mine = await http( + path, + json({ text: 'своё' }, { ...bearer(alice.token), 'idempotency-key': key }), + ); + expect(mine.response.status).toBe(201); + const other = await http( + path, + json({ text: 'своё' }, { ...bearer(bob.token), 'idempotency-key': key }), + ); + expect(other.response.status).toBe(201); + expect(other.body.id).not.toBe(mine.body.id); + }); +}); diff --git a/app/test/attachments.e2e-spec.ts b/app/test/attachments.e2e-spec.ts new file mode 100644 index 0000000..e7bbcf8 --- /dev/null +++ b/app/test/attachments.e2e-spec.ts @@ -0,0 +1,542 @@ +import { createHash, randomBytes, randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import net from 'node:net'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Pool } from 'pg'; +import type { ApiErrorBody } from '../src/common/errors/api-error.js'; +import type { Page } from '../src/common/http/page.js'; +import type { Message } from '../src/messages/message.js'; +import { + Actor, + actor, + baseUrl, + bearer, + createChat, + database, + download, + expectError, + http, + postMessage, + upload, + uploadRaw, + waitReady, +} from './support/e2e.js'; +import sharp from 'sharp'; +import { jpegWithMetadata, jpegWithoutScanData } from './support/jpeg.js'; +import { + maxPixelsRgba16Png, + noisePng, + padPngTo, + pixelBombPng, + pngWithGarbageIdat, +} from './support/png.js'; + +const png = readFileSync( + new URL('../../tests/fixtures/sample.png', import.meta.url), +); +const jpeg = readFileSync(new URL('./fixtures/sample.jpg', import.meta.url)); +const progressive = readFileSync( + new URL('./fixtures/sample-progressive.jpg', import.meta.url), +); +const MAX = 10_485_760; + +let db: Pool; +let alice: Actor; +let bob: Actor; +let eve: Actor; +let chatId: string; +let eveChatId: string; +let leftoverChatId: string; + +const sha256 = (data: Uint8Array) => + createHash('sha256').update(data).digest('hex'); + +async function ready(data: Buffer, type = 'image/png', chat = chatId) { + const result = await upload(alice.token, chat, data, { + contentType: type, + }); + expect(result.response.status).toBe(202); + expect(result.body.status).toBe('queued'); + return waitReady(alice.token, result.body.id); +} + +describe('attachments (proxy upload)', () => { + beforeAll(async () => { + db = database(); + alice = await actor(); + bob = await actor(); + eve = await actor(); + chatId = (await createChat(alice, [bob])).id; + eveChatId = (await createChat(eve, [])).id; + // Chat for rejected uploads: it must end up without any row. + leftoverChatId = (await createChat(alice, [])).id; + }); + + afterAll(async () => { + await db.end(); + }); + + it('stores a PNG and serves it only to chat members', async () => { + const uploaded = await upload(alice.token, chatId, png, { + filename: 'Снимок.png', + }); + expect(uploaded.response.status).toBe(202); + expect(uploaded.body).toMatchObject({ + chat_id: chatId, + owner_id: alice.user.id, + filename: 'Снимок.png', + content_type: 'image/png', + size_bytes: png.length, + sha256: sha256(png), + status: 'queued', + variants: [], + error_code: null, + }); + const id = uploaded.body.id; + + const ready = await waitReady(bob.token, id); + expect(ready).toMatchObject({ + filename: 'Снимок.png', + size_bytes: png.length, + sha256: sha256(png), + status: 'ready', + error_code: null, + }); + expect(ready.variants.map((variant) => variant.name)).toEqual([ + 'thumbnail', + 'crop', + 'optimized', + ]); + + const metadata = await http(`/api/v1/attachments/${id}`, { + headers: bearer(bob.token), + }); + expect(metadata.response.status).toBe(200); + expect(metadata.body.sha256).toBe(sha256(png)); + + const content = await download(bob.token, id); + expect(content.response.status).toBe(200); + expect(content.response.headers.get('content-type')).toBe('image/png'); + expect(content.response.headers.get('x-content-type-options')).toBe( + 'nosniff', + ); + expect(content.response.headers.get('content-length')).toBe( + String(png.length), + ); + expect(content.response.headers.get('content-disposition')).toContain( + "filename*=UTF-8''%D0%A1", + ); + expect(content.bytes.equals(png)).toBe(true); + + for (const path of [`/${id}`, `/${id}/content`]) { + expectError( + await http(`/api/v1/attachments${path}`, { + headers: bearer(eve.token), + }), + 404, + 'not_found', + ); + } + expectError( + await http(`/api/v1/attachments/${id}/content`), + 401, + 'unauthorized', + ); + expectError(await upload(eve.token, chatId, png), 404, 'not_found'); + expectError( + await http(`/api/v1/attachments/${randomUUID()}`, { + headers: bearer(bob.token), + }), + 404, + 'not_found', + ); + }); + + it.each([ + ['JPEG', jpeg], + ['progressive JPEG', progressive], + ])('accepts a %s', async (_name, data) => { + const created = await ready(data, 'image/jpeg'); + expect(created.content_type).toBe('image/jpeg'); + const content = await download(alice.token, created.id); + expect(content.bytes.equals(data)).toBe(true); + }); + + it('accepts camera-size images up to the pixel limit', async () => { + // 7728x5152 = 39.8 MP, like a 40 MP camera; decoded size far above the + // replica's 16 MiB /tmp, so libvips must not spill to a temp file. + const camera = sharp({ + create: { + width: 7728, + height: 5152, + channels: 3, + background: { r: 120, g: 80, b: 40 }, + }, + }); + const baseline = await camera.clone().jpeg({ quality: 85 }).toBuffer(); + const progressiveCamera = await camera + .clone() + .jpeg({ quality: 85, progressive: true }) + .toBuffer(); + for (const data of [baseline, progressiveCamera]) + expect((await ready(data, 'image/jpeg')).size_bytes).toBe( + data.length, + ); + const rgba16 = await maxPixelsRgba16Png(); + expect((await ready(rgba16)).size_bytes).toBe(rgba16.length); + }, 120_000); + + it('accepts a JPEG with megabytes of metadata before the frame header', async () => { + const data = jpegWithMetadata(jpeg, 20); + expect(data.length).toBeGreaterThan(1_048_576); + expect((await ready(data, 'image/jpeg')).sha256).toBe(sha256(data)); + }); + + it('authenticates before judging the content type', async () => { + const zip = await http( + `/api/v1/chats/${chatId}/attachments?filename=a.zip`, + { + method: 'POST', + headers: { 'content-type': 'application/zip' }, + body: png as unknown as BodyInit, + }, + ); + expectError(zip, 401, 'unauthorized'); + expectError( + await upload(alice.token, leftoverChatId, png, { + contentType: 'application/json', + }), + 415, + 'unsupported_media_type', + ); + }); + + it('answers 413 with the error envelope to an oversized text body on JSON routes', async () => { + const result = await http( + `/api/v1/chats/${chatId}/messages`, + { + method: 'POST', + headers: { + ...bearer(alice.token), + 'content-type': 'text/plain', + 'idempotency-key': randomUUID().replaceAll('-', ''), + }, + body: 'x'.repeat(2_100_000), + }, + ); + expectError(result, 413, 'payload_too_large'); + }); + + it('keeps one slow client from taking every upload slot', async () => { + const slow = await actor(); + const slowChat = (await createChat(slow, [])).id; + const url = new URL(baseUrl); + const sockets: net.Socket[] = []; + try { + for (let index = 0; index < 12; index += 1) { + const socket = net.connect( + Number(url.port || 80), + url.hostname, + ); + socket.on('error', () => {}); + socket.write( + `POST /api/v1/chats/${slowChat}/attachments?filename=slow.png HTTP/1.1\r\n` + + `Host: ${url.host}\r\nAuthorization: Bearer ${slow.token}\r\n` + + `Content-Type: image/png\r\nContent-Length: ${png.length}\r\n\r\n`, + ); + socket.write(png.subarray(0, 4)); + sockets.push(socket); + } + await sleep(1000); + const extra = await upload(slow.token, slowChat, png); + expectError(extra, 429, 'rate_limited'); + expect(extra.response.headers.get('retry-after')).toBe('1'); + // Another user is not affected by the slow client. + for (let index = 0; index < 4; index += 1) + expect( + (await upload(bob.token, chatId, png)).response.status, + ).toBe(202); + } finally { + for (const socket of sockets) socket.destroy(); + } + await settled(slowChat); + }); + + it('enforces the 10 MiB limit exactly', async () => { + const exact = padPngTo(png, MAX); + const created = await ready(exact); + expect(created.size_bytes).toBe(MAX); + expectError( + await upload(alice.token, leftoverChatId, padPngTo(png, MAX + 1)), + 413, + 'payload_too_large', + ); + }); + + it('rejects a pixel bomb before storing anything', async () => { + expectError( + await upload(alice.token, leftoverChatId, pixelBombPng()), + 413, + 'payload_too_large', + ); + }); + + it('rejects damaged images', async () => { + const flipped = Buffer.from(png); + flipped[Math.floor(png.length / 2)] ^= 0xff; + const cases: Buffer[] = [ + png.subarray(0, png.length - 100), + flipped, + Buffer.concat([png.subarray(0, 8), randomBytes(2048)]), + Buffer.alloc(0), + // Structure and CRCs are fine; the pixel data does not decode. + pngWithGarbageIdat(), + ]; + for (const data of cases) + expectError( + await upload(alice.token, leftoverChatId, data), + 415, + 'unsupported_media_type', + ); + }); + + it.each([ + ['baseline', jpeg], + ['progressive', progressive], + ])('rejects a %s JPEG without scan data', async (_name, data) => { + expectError( + await upload( + alice.token, + leftoverChatId, + jpegWithoutScanData(data), + { + contentType: 'image/jpeg', + }, + ), + 415, + 'unsupported_media_type', + ); + }); + + it('rejects a content type that does not match the bytes', async () => { + const gif = Buffer.from('GIF89a' + 'x'.repeat(64)); + const cases: [Buffer, string][] = [ + [png, 'image/jpeg'], + [jpeg, 'image/png'], + [gif, 'image/png'], + [png, 'text/plain'], + [png, 'application/octet-stream'], + ]; + for (const [data, type] of cases) + expectError( + await upload(alice.token, leftoverChatId, data, { + contentType: type, + }), + 415, + 'unsupported_media_type', + ); + }); + + it('validates filenames by code points and forbidden characters', async () => { + const bad = [ + '?filename=a%2Fb.png', + '?filename=a%5Cb.png', + '?filename=a%00b.png', + '?filename=a%07b.png', + '?filename=%E2%80%AEgnp.exe', + '?filename=%20', + '?filename=', + `?filename=${'a'.repeat(256)}`, + '', + '?filename=a.png&filename=b.png', + ]; + for (const query of bad) + expectError( + await uploadRaw(alice.token, leftoverChatId, query, png), + 400, + 'invalid_request', + ); + const long = '😀'.repeat(255); + const created = await upload(alice.token, chatId, png, { + filename: long, + }); + expect(created.response.status).toBe(202); + expect(created.body.filename).toBe(long); + }); + + it('links attachments to messages in the given order', async () => { + const first = await ready(png); + const second = await ready(jpeg, 'image/jpeg'); + const order = [second.id, first.id]; + const key = randomUUID().replaceAll('-', ''); + const sent = await postMessage( + alice.token, + chatId, + { text: '', attachment_ids: order }, + key, + ); + expect(sent.response.status).toBe(201); + expect(sent.body.attachment_ids).toEqual(order); + + const history = await http>( + `/api/v1/chats/${chatId}/messages?limit=100`, + { headers: bearer(bob.token) }, + ); + const stored = history.body.items.find((m) => m.id === sent.body.id); + expect(stored?.attachment_ids).toEqual(order); + + const replay = await postMessage( + alice.token, + chatId, + { text: '', attachment_ids: order }, + key, + ); + expect(replay.response.status).toBe(201); + expect(replay.body).toEqual(sent.body); + expectError( + await postMessage( + alice.token, + chatId, + { text: '', attachment_ids: [first.id] }, + key, + ), + 409, + 'conflict', + ); + + const textOnly = await postMessage(alice.token, chatId, { + text: 'hello', + }); + expect(textOnly.response.status).toBe(201); + expect(textOnly.body.attachment_ids).toEqual([]); + }); + + it('rejects invalid attachment references', async () => { + const mine = await ready(png); + const foreign = await upload(eve.token, eveChatId, png); + expect(foreign.response.status).toBe(202); + expectError( + await postMessage(alice.token, chatId, { text: '' }), + 400, + 'invalid_request', + ); + expectError( + await postMessage(alice.token, chatId, { + text: '', + attachment_ids: [foreign.body.id], + }), + 404, + 'not_found', + ); + expectError( + await postMessage(alice.token, chatId, { + text: 'x', + attachment_ids: [randomUUID()], + }), + 404, + 'not_found', + ); + for (const ids of [ + [mine.id, mine.id], + [mine.id, mine.id.toUpperCase()], + Array.from({ length: 11 }, () => randomUUID()), + null, + ['not-a-uuid'], + ]) + expectError( + await postMessage(alice.token, chatId, { + text: 'x', + attachment_ids: ids, + }), + 400, + 'invalid_request', + ); + }); + + it('serves the promised variants only after ready', async () => { + const uploaded = await upload(alice.token, chatId, png); + expect(uploaded.response.status).toBe(202); + expectError( + await http( + `/api/v1/attachments/${uploaded.body.id}/content`, + { headers: bearer(alice.token) }, + ), + 409, + 'conflict', + ); + const created = await waitReady(alice.token, uploaded.body.id); + const variant = (name: string) => + http( + `/api/v1/attachments/${created.id}/content?variant=${name}`, + { + headers: bearer(alice.token), + }, + ); + expect((await variant('original')).response.status).toBe(200); + for (const [name, type] of [ + ['thumbnail', 'image/jpeg'], + ['crop', 'image/jpeg'], + ['optimized', 'image/webp'], + ] as const) { + const response = await variant(name); + expect(response.response.status).toBe(200); + expect(response.response.headers.get('content-type')).toBe(type); + } + expectError(await variant('bogus'), 400, 'invalid_request'); + }); + + it('answers 4xx, not 500, for raw image or text bodies on JSON routes', async () => { + for (const [type, status, code] of [ + ['image/png', 415, 'unsupported_media_type'], + ['image/jpeg', 415, 'unsupported_media_type'], + ['text/plain', 400, 'invalid_request'], + ] as const) { + const result = await http('/api/v1/users', { + method: 'POST', + headers: { 'content-type': type }, + body: 'x', + }); + expectError(result, status, code); + } + }); + + it('removes the pending row when the client drops the connection', async () => { + const data = noisePng(2 * 1024 * 1024); + const url = new URL(baseUrl); + const socket = net.connect(Number(url.port || 80), url.hostname); + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('error', reject); + }); + socket.on('error', () => {}); + socket.write( + `POST /api/v1/chats/${leftoverChatId}/attachments?filename=cut.png HTTP/1.1\r\n` + + `Host: ${url.host}\r\nAuthorization: Bearer ${alice.token}\r\n` + + `Content-Type: image/png\r\nContent-Length: ${data.length}\r\n\r\n`, + ); + socket.write(data.subarray(0, 512 * 1024)); + await sleep(500); + socket.destroy(); + await settled(leftoverChatId); + }); + + it('leaves no rows behind after rejected uploads', async () => { + await settled(leftoverChatId); + }); +}); + +async function settled(chat: string): Promise { + const deadline = Date.now() + 10_000; + let count = -1; + while (Date.now() < deadline) { + const result = await db.query<{ count: string }>( + 'SELECT count(*) FROM attachments WHERE chat_id = $1', + [chat], + ); + count = Number(result.rows[0].count); + if (count === 0) return; + await sleep(250); + } + expect(count).toBe(0); +} diff --git a/app/test/dependency-failures.e2e-spec.ts b/app/test/dependency-failures.e2e-spec.ts new file mode 100644 index 0000000..9b274f5 --- /dev/null +++ b/app/test/dependency-failures.e2e-spec.ts @@ -0,0 +1,1107 @@ +import { execFile } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { readFileSync } from 'node:fs'; +import net from 'node:net'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { SessionResponse } from '../src/auth/auth.service.js'; +import type { Chat } from '../src/chats/chat.js'; +import type { ApiErrorBody } from '../src/common/errors/api-error.js'; +import type { Page } from '../src/common/http/page.js'; +import type { Message } from '../src/messages/message.js'; +import type { User } from '../src/users/user.js'; +import { noisePng } from './support/png.js'; +import { waitReady } from './support/e2e.js'; + +// Automated counterpart of the manual Redis/PostgreSQL outage checks. Four +// topologies, because the load balancer probes /health/ready (the same route as +// the container healthcheck): +// 1. Redis outage — shared dependency: every replica turns not-ready, HAProxy +// removes all backends and answers 503 itself, while the replica's own +// readiness stays a bounded API 503 with request_id. +// 2. PostgreSQL outage — same shared-dependency topology, confirmed data and +// the session survive the restart. +// 3. Per-replica PostgreSQL fault — only the selected replica loses its own +// path to the database (temporary pg_hba reject entry for its address plus +// connection termination): that slot leaves rotation, the healthy replica +// keeps serving, and the fault is always undone. +// 4. Pool saturation — a busy shared pool is overload, not a lost dependency: +// the replicas stay in rotation because the probe uses its own connection. +// +// It is opt-in because it needs control over the Docker Compose project: +// make test-dependencies +// cd app && E2E_DEPENDENCY_FAULTS=1 npm run test:dependencies +const enabled = process.env.E2E_DEPENDENCY_FAULTS === '1'; +const baseUrl = (process.env.API_BASE_URL ?? 'http://localhost:8080').replace( + /\/+$/u, + '', +); +const composeDir = + process.env.E2E_COMPOSE_DIR ?? + fileURLToPath(new URL('../..', import.meta.url)); +const composeEnvFile = process.env.E2E_COMPOSE_ENV_FILE ?? '.env'; +const redisService = process.env.E2E_REDIS_SERVICE ?? 'redis'; +const postgresService = process.env.E2E_POSTGRES_SERVICE ?? 'postgres'; +const apiService = process.env.E2E_API_SERVICE ?? 'api'; +const s3Service = process.env.E2E_S3_SERVICE ?? 's3'; +const s3Bucket = process.env.E2E_S3_BUCKET ?? 'messenger-attachments'; +const lbStatsUrl = + process.env.E2E_LB_STATS_URL ?? 'http://127.0.0.1:8404/stats;csv'; +// PostgreSQL superuser of the stand (compose.yaml, .env); psql runs over the +// container's local socket, so no password is needed here. +const postgresUser = process.env.E2E_POSTGRES_USER ?? 'messenger'; +const postgresDatabase = process.env.E2E_POSTGRES_DB ?? 'messenger'; +const pgHbaPath = + process.env.E2E_PG_HBA_PATH ?? '/var/lib/postgresql/data/pg_hba.conf'; +const pgHbaBackup = `${pgHbaPath}.lab3-partial-fault.bak`; +const password = 'outage-check:пароль🔐'; +const runId = randomUUID().replaceAll('-', '').slice(0, 12); +// A request that reaches a stopped database waits for the pool connection +// timeout, so every outage step costs up to DATABASE_CONNECTION_TIMEOUT_MS. +const outagedRequestBudgetMs = 180_000; +const slotBudgetMs = 20_000; +const readyReads = 16; +const saturatingWrites = 60; // больше, чем replicas × DATABASE_POOL_MAX (2 × 10) + +const execFileAsync = promisify(execFile); + +type Result = { body: T; text: string; response: Response }; +type ReplicaProbe = { + instanceId: string | null; + requestId: string | null; + status: number; + text: string; +}; +type LbSlot = { addr: string; check: string; name: string; status: string }; + +async function compose(...args: string[]): Promise { + const result = await execFileAsync( + 'docker', + ['compose', '--env-file', composeEnvFile, ...args], + { cwd: composeDir, timeout: 120_000 }, + ); + return result.stdout.trim(); +} + +async function docker(...args: string[]): Promise { + const result = await execFileAsync('docker', args, { + cwd: composeDir, + timeout: 60_000, + }); + return result.stdout.trim(); +} + +async function request( + path: string, + init: RequestInit = {}, +): Promise> { + const response = await fetch(`${baseUrl}${path}`, init); + const text = await response.text(); + // With every backend out of rotation the answer is the LB's own HTML 503, + // so a body is not guaranteed to be JSON (it always is for API answers). + let body: T | undefined; + try { + body = text ? (JSON.parse(text) as T) : undefined; + } catch { + body = undefined; + } + return { body: body as T, text, response }; +} + +function json( + body: unknown, + headers: Record = {}, +): RequestInit { + return { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body: JSON.stringify(body), + }; +} + +function bearer(token: string): Record { + return { authorization: `Bearer ${token}` }; +} + +// POST messages needs a unique Idempotency-Key in lab3+; outage checks only +// need the write path, not replay semantics. +function messageHeaders(token: string): Record { + return { + ...bearer(token), + 'idempotency-key': randomUUID().replaceAll('-', ''), + }; +} + +function basic(username: string, secret: string): string { + return `Basic ${Buffer.from(`${username}:${secret}`, 'utf8').toString('base64')}`; +} + +// The dependencies recover asynchronously, so readiness is polled instead of +// asserted right after docker compose returns. +async function waitForReadiness( + expected: number, + timeoutMs = 90_000, +): Promise { + const deadline = Date.now() + timeoutMs; + let last: number | string = 'no response'; + for (;;) { + try { + const probe = await request('/health/ready'); + last = probe.response.status; + if (probe.response.status === expected) return; + } catch (error) { + last = error instanceof Error ? error.message : 'request failed'; + } + if (Date.now() > deadline) + throw new Error( + `readiness never became ${expected} within ${timeoutMs}ms (last: ${String(last)})`, + ); + await sleep(250); + } +} + +async function waitFor( + condition: () => Promise, + describe: () => Promise, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + if (await condition()) return; + if (Date.now() > deadline) + throw new Error( + `condition not reached within ${timeoutMs}ms: ${await describe()}`, + ); + await sleep(250); + } +} + +function expectBoundedError( + status: number, + text: string, + requestId: string | null, +): void { + expect(status).toBe(503); + const body = JSON.parse(text) as ApiErrorBody; + expect(body.error.code).toBe('unavailable'); + expect(body.error.message).toBe('Service unavailable'); + expect(body.error.request_id).toBe(requestId); + // A bounded error must not leak driver details, SQL text or a stack trace. + expect(text).not.toMatch( + /ECONNREFUSED|ECONNRESET|Connection terminated|pg\.|node_modules|at .*\(.+:\d+:\d+\)/u, + ); +} + +function expectBoundedOutage(result: Result): void { + expectBoundedError( + result.response.status, + result.text, + result.response.headers.get('x-request-id'), + ); +} + +// With every backend out of rotation the last hop is the load balancer itself: +// it answers with its own 503 page, so there is no API error body and no +// X-Instance-Id — the request never reached a replica. +function expectLbOutage(result: Result): void { + expect(result.response.status).toBe(503); + expect(result.response.headers.get('x-instance-id')).toBeNull(); +} + +// What a client sees while a shared dependency is down: either the bounded 503 +// of a replica that is still in rotation (identified by X-Instance-Id), or the +// LB's own 503 once every replica has left rotation. Never a success. +function expectUnavailableThroughLb(result: Result): void { + expect(result.response.status).toBe(503); + if (result.response.headers.get('x-instance-id') === null) return; + expectBoundedOutage(result); +} + +async function historyOf( + chatId: string, + token: string, +): Promise>> { + return request>( + `/api/v1/chats/${chatId}/messages?limit=100`, + { + headers: bearer(token), + }, + ); +} + +async function apiContainers(): Promise { + const stdout = await compose('ps', '-q', apiService); + return stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0) + .sort(); +} + +async function containerIp(container: string): Promise { + return docker( + 'inspect', + '-f', + '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}', + container, + ); +} + +// The replicas publish no ports, so a single replica is probed from inside its +// own network namespace (loopback). +const probeScript = ` +const params = JSON.parse(process.env.LAB3_PROBE); +const port = process.env.APP_PORT || 8080; +const response = await fetch('http://127.0.0.1:' + port + params.path, { + method: params.method || 'GET', + headers: params.headers || {}, + body: params.body, +}); +const text = await response.text(); +console.log(JSON.stringify({ + status: response.status, + text, + instanceId: response.headers.get('x-instance-id'), + requestId: response.headers.get('x-request-id'), +})); +`; + +type ProbeInit = { + body?: string; + headers?: Record; + method?: string; +}; + +async function probeReplica( + container: string, + path: string, + init: ProbeInit = {}, +): Promise { + const stdout = await docker( + 'exec', + '-e', + `LAB3_PROBE=${JSON.stringify({ path, ...init })}`, + container, + 'node', + '--input-type=module', + '-e', + probeScript, + ); + return JSON.parse(stdout) as ReplicaProbe; +} + +async function waitForReplicaReadiness( + container: string, + expected: number, + timeoutMs: number, +): Promise { + let last = 'no probe'; + await waitFor( + async () => { + try { + const probe = await probeReplica(container, '/health/ready'); + last = `${probe.status} ${probe.text}`; + return probe.status === expected; + } catch (error) { + last = error instanceof Error ? error.message : 'probe failed'; + return false; + } + }, + async () => last, + timeoutMs, + ); +} + +function parseCsvLine(line: string): string[] { + const values: string[] = []; + let current = ''; + let quoted = false; + for (const character of line) { + if (character === '"') quoted = !quoted; + else if (character === ',' && !quoted) { + values.push(current); + current = ''; + } else current += character; + } + values.push(current.replace(/\r$/u, '')); + return values; +} + +// Resolved backend slots of the api backend: the unused slots of the +// server-template have no address and are ignored. +async function lbSlots(): Promise { + const response = await fetch(lbStatsUrl); + const lines = (await response.text()).trim().split('\n'); + const header = parseCsvLine(lines[0].replace(/^#\s*/u, '')).map((name) => + name.trim(), + ); + const column = (name: string): number => header.indexOf(name); + return lines + .slice(1) + .map(parseCsvLine) + .filter( + (columns) => + columns[column('pxname')] === 'api' && + /^api\d+$/u.test(columns[column('svname')] ?? '') && + (columns[column('addr')] ?? '').length > 0, + ) + .map((columns) => ({ + addr: columns[column('addr')], + check: columns[column('check_status')], + name: columns[column('svname')], + status: columns[column('status')], + })); +} + +async function waitForSlot( + predicate: (slots: LbSlot[]) => boolean, + describe: string, + timeoutMs = slotBudgetMs, +): Promise { + let last = 'no stats'; + await waitFor( + async () => { + try { + const slots = await lbSlots(); + last = slots + .map( + (slot) => + `${slot.name}@${slot.addr} ${slot.status}/${slot.check}`, + ) + .join(', '); + return slots.length > 0 && predicate(slots); + } catch (error) { + last = error instanceof Error ? error.message : 'stats failed'; + return false; + } + }, + async () => `${describe} (last: ${last})`, + timeoutMs, + ); + return lbSlots(); +} + +function upSlots(slots: LbSlot[]): LbSlot[] { + return slots.filter((slot) => slot.status === 'UP'); +} + +async function psql(query: string): Promise { + return dockerExecService( + postgresService, + 'psql', + '-U', + postgresUser, + '-d', + postgresDatabase, + '-tA', + '-c', + query, + ); +} + +// docker exec needs a container, while the suite is configured with Compose +// service names, so the container of the service is resolved first. +async function dockerExecService( + service: string, + ...args: string[] +): Promise { + const container = (await compose('ps', '-q', service)) + .split('\n')[0] + ?.trim(); + if (!container) throw new Error(`no container for service ${service}`); + return docker('exec', container, ...args); +} + +// Takes away the replica's own path to PostgreSQL without touching the shared +// database: a reject entry for the replica's address becomes the first matching +// line of pg_hba.conf, so its new connections fail while the server stays up +// for everyone else. The file is rewritten through the existing inode (`cat > +// file`) to preserve the owner and mode the server needs to reload it. +async function applyReplicaDatabaseReject(address: string): Promise { + const script = [ + `test -f ${pgHbaBackup} || cat ${pgHbaPath} > ${pgHbaBackup}`, + `printf 'host all all ${address}/32 reject\\n' > /tmp/lab3-pg-hba`, + `cat ${pgHbaPath} >> /tmp/lab3-pg-hba`, + `cat /tmp/lab3-pg-hba > ${pgHbaPath}`, + 'rm -f /tmp/lab3-pg-hba', + ].join('; '); + await dockerExecService(postgresService, 'sh', '-c', script); + await psql('select pg_reload_conf()'); + await psql( + `select count(pg_terminate_backend(pid)) from pg_stat_activity where client_addr = '${address}'`, + ); +} + +// Idempotent restore: also runs from afterAll, so an assertion that failed +// mid-fault cannot leave the stand rejecting one replica. +async function restoreDatabaseAccess(): Promise { + await dockerExecService( + postgresService, + 'sh', + '-c', + `if [ -f ${pgHbaBackup} ]; then cat ${pgHbaBackup} > ${pgHbaPath}; rm -f ${pgHbaBackup}; fi`, + ); + await psql('select pg_reload_conf()'); +} + +const samplePng = readFileSync( + new URL('../../tests/fixtures/sample.png', import.meta.url), +); + +function secretFile(name: string): string { + return readFileSync(`${composeDir}/secrets/${name}`, 'utf8').trim(); +} + +// Root credentials stay inside the local process and the container's exec +// environment; they are never printed. +async function objectExists(key: string): Promise { + const host = `http://${secretFile('minio_root_user')}:${secretFile('minio_root_password')}@127.0.0.1:9000`; + try { + await dockerExecService( + s3Service, + 'env', + `MC_HOST_stand=${host}`, + 'mc', + 'stat', + `stand/${s3Bucket}/${key}`, + ); + return true; + } catch { + return false; + } +} + +async function waitForS3Healthy(): Promise { + const container = (await compose('ps', '-q', s3Service)).split('\n')[0]; + await waitFor( + async () => + (await docker( + 'inspect', + '-f', + '{{.State.Health.Status}}', + container, + ).catch(() => '')) === 'healthy', + async () => 's3 is not healthy', + 60_000, + ); +} + +function uploadPath(chatId: string, filename: string): string { + return `/api/v1/chats/${chatId}/attachments?filename=${encodeURIComponent(filename)}`; +} + +async function sweepNow(): Promise { + await compose( + 'exec', + '-T', + '-e', + 'ATTACHMENT_SWEEP_GRACE_SECONDS=0', + apiService, + 'node', + 'dist/attachments/attachments-sweep.cli.js', + ); +} + +async function waitUntilExpired(filter: string): Promise { + await waitFor( + async () => + Number( + await psql( + `select count(*) from attachments where ${filter} and expires_at < now()`, + ), + ) > 0, + async () => 'pending row did not expire', + 60_000, + ); +} + +async function rawUpload( + data: Buffer, + chatId: string, + filename: string, + token: string, + splitAt: number, + between: () => Promise, +): Promise { + const url = new URL(baseUrl); + const socket = net.connect(Number(url.port || 80), url.hostname); + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('error', reject); + }); + const chunks: Buffer[] = []; + socket.on('data', (chunk: Buffer) => chunks.push(chunk)); + const closed = new Promise((resolve) => socket.on('close', resolve)); + socket.write( + `POST ${uploadPath(chatId, filename)} HTTP/1.1\r\nHost: ${url.host}\r\n` + + `Authorization: Bearer ${token}\r\nContent-Type: image/png\r\n` + + `Content-Length: ${data.length}\r\nConnection: close\r\n\r\n`, + ); + socket.write(data.subarray(0, splitAt)); + await between(); + socket.write(data.subarray(splitAt)); + await closed; + return Buffer.concat(chunks).toString('latin1'); +} + +describe.skipIf(!enabled)('dependency outages', () => { + let user: User; + let token: string; + let chat: Chat; + let message: Message; + let replicas: string[]; + + beforeAll(async () => { + await compose('up', '-d'); + await waitForReadiness(200); + const username = `outage_${runId}`; + const registered = await request( + '/api/v1/users', + json({ username, display_name: 'Отказ зависимости', password }), + ); + expect(registered.response.status).toBe(201); + user = registered.body; + const session = await request( + '/api/v1/auth/sessions', + { + method: 'POST', + headers: { authorization: basic(username, password) }, + }, + ); + expect(session.response.status).toBe(201); + token = session.body.token; + const created = await request( + '/api/v1/chats', + json( + { title: `outage-${runId}`, member_ids: [user.id] }, + bearer(token), + ), + ); + expect(created.response.status).toBe(201); + chat = created.body; + const sent = await request( + `/api/v1/chats/${chat.id}/messages`, + json({ text: 'Сообщение до отказа' }, messageHeaders(token)), + ); + expect(sent.response.status).toBe(201); + message = sent.body; + replicas = await apiContainers(); + expect(replicas.length).toBeGreaterThanOrEqual(2); + await waitForSlot( + (slots) => upSlots(slots).length === replicas.length, + 'not every replica is UP', + 30_000, + ); + }, outagedRequestBudgetMs); + + afterAll(async () => { + // Always restore the stand, even when an assertion failed mid-outage: + // first the services (pg_hba is only reachable in a running container), + // then the temporary per-replica rule, then rotation. + await compose('start', redisService); + await compose('start', postgresService); + await compose('start', s3Service); + const s3Container = (await compose('ps', '-q', s3Service)).split( + '\n', + )[0]; + await docker('unpause', s3Container).catch(() => undefined); + await waitForReadiness(200); + await restoreDatabaseAccess(); + const expected = (await apiContainers()).length; + await waitForSlot( + (slots) => upSlots(slots).length === expected, + 'backends did not return to rotation', + 30_000, + ); + }, outagedRequestBudgetMs); + + it( + 'keeps every replica in rotation while the database pool is saturated', + async () => { + // A row lock on the chat parks every write in the shared pool; the + // readiness probe uses its own connection and must keep answering. + const lock = psql( + `begin; select id from chats where id = '${chat.id}' for update; select pg_sleep(4); commit;`, + ); + await sleep(300); + const statuses = new Set(); + let sampling = true; + const sampler = (async () => { + while (sampling) { + for (const slot of await lbSlots()) + statuses.add(slot.status); + await sleep(200); + } + })(); + const writes = await Promise.all( + Array.from({ length: saturatingWrites }, () => + request( + `/api/v1/chats/${chat.id}/messages`, + json({ text: 'saturation' }, messageHeaders(token)), + ), + ), + ); + await lock; + await sleep(1000); + sampling = false; + await sampler; + expect([...statuses]).toEqual(['UP']); + expect( + writes + .map((write) => write.response.status) + .filter((status) => status !== 201), + ).toEqual([]); + }, + outagedRequestBudgetMs, + ); + + it( + 'serves bounded 503 for the Redis outage and recovers the session', + async () => { + await compose('stop', redisService); + const replica = replicas[0]; + + expect((await probeReplica(replica, '/health/live')).status).toBe( + 200, + ); + await waitForReplicaReadiness(replica, 503, 30_000); + const readiness = await probeReplica(replica, '/health/ready'); + expectBoundedError( + readiness.status, + readiness.text, + readiness.requestId, + ); + + const me = await probeReplica(replica, '/api/v1/users/me', { + headers: bearer(token), + }); + expectBoundedError(me.status, me.text, me.requestId); + + // A request without a session must stay unauthorized during an outage: + // the outage may not turn an anonymous caller into a trusted one. + const anonymous = await probeReplica(replica, '/api/v1/chats', { + headers: { 'x-user-id': user.id }, + }); + expect(anonymous.status).toBe(401); + expect( + (JSON.parse(anonymous.text) as ApiErrorBody).error.code, + ).toBe('unauthorized'); + + expectUnavailableThroughLb( + await request('/api/v1/users/me', { + headers: bearer(token), + }), + ); + await waitForSlot( + // 'UP 1/2' is still in rotation: wait for DOWN itself. + (slots) => slots.every((slot) => slot.status === 'DOWN'), + 'not every slot left rotation', + ); + expectLbOutage( + await request('/api/v1/users/me', { headers: bearer(token) }), + ); + + await compose('start', redisService); + await waitForReadiness(200); + await waitForSlot( + (slots) => upSlots(slots).length === replicas.length, + 'backends did not return to rotation', + 30_000, + ); + + // Sessions live in Redis with persistence, so the old token still works. + const recovered = await request('/api/v1/users/me', { + headers: bearer(token), + }); + expect(recovered.response.status).toBe(200); + expect(recovered.body.id).toBe(user.id); + + const history = await historyOf(chat.id, token); + expect(history.response.status).toBe(200); + expect(history.body.items.map((item) => item.id)).toContain( + message.id, + ); + }, + outagedRequestBudgetMs, + ); + + it( + 'serves bounded 503 for the PostgreSQL outage and keeps confirmed data', + async () => { + await compose('stop', postgresService); + const replica = replicas[0]; + + expect((await probeReplica(replica, '/health/live')).status).toBe( + 200, + ); + await waitForReplicaReadiness(replica, 503, 30_000); + const readiness = await probeReplica(replica, '/health/ready'); + expectBoundedError( + readiness.status, + readiness.text, + readiness.requestId, + ); + + // Redis still answers, so these requests reach the database layer and + // must fail with the bounded 503, not an unhandled 500. + const me = await probeReplica(replica, '/api/v1/users/me', { + headers: bearer(token), + }); + expectBoundedError(me.status, me.text, me.requestId); + + const chats = await probeReplica(replica, '/api/v1/chats', { + headers: bearer(token), + }); + expectBoundedError(chats.status, chats.text, chats.requestId); + + const history = await probeReplica( + replica, + `/api/v1/chats/${chat.id}/messages?limit=100`, + { headers: bearer(token) }, + ); + expectBoundedError(history.status, history.text, history.requestId); + + const registration = await probeReplica(replica, '/api/v1/users', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + username: `outage_${runId}_late`, + display_name: 'Отказ зависимости', + password, + }), + }); + expectBoundedError( + registration.status, + registration.text, + registration.requestId, + ); + + expectUnavailableThroughLb( + await request('/api/v1/users/me', { + headers: bearer(token), + }), + ); + await waitForSlot( + // 'UP 1/2' is still in rotation: wait for DOWN itself. + (slots) => slots.every((slot) => slot.status === 'DOWN'), + 'not every slot left rotation', + ); + expectLbOutage( + await request('/api/v1/users/me', { headers: bearer(token) }), + ); + + await compose('start', postgresService); + await waitForReadiness(200); + await waitForSlot( + (slots) => upSlots(slots).length === replicas.length, + 'backends did not return to rotation', + 30_000, + ); + + const recovered = await request('/api/v1/users/me', { + headers: bearer(token), + }); + expect(recovered.response.status).toBe(200); + expect(recovered.body.id).toBe(user.id); + + const after = await historyOf(chat.id, token); + expect(after.response.status).toBe(200); + expect(after.body.items.map((item) => item.id)).toContain( + message.id, + ); + + const sent = await request( + `/api/v1/chats/${chat.id}/messages`, + json({ text: 'Сообщение после отказа' }, messageHeaders(token)), + ); + expect(sent.response.status).toBe(201); + }, + outagedRequestBudgetMs, + ); + + it( + 'excludes only the replica that lost its own database path', + async () => { + const selected = replicas[0]; + const healthy = replicas[1]; + const selectedIp = await containerIp(selected); + const selectedAddress = `${selectedIp}:8080`; + const selectedInstance = ( + await probeReplica(selected, '/health/live') + ).instanceId; + expect(selectedInstance).not.toBeNull(); + const healthyInstance = ( + await probeReplica(healthy, '/health/live') + ).instanceId; + + try { + await applyReplicaDatabaseReject(selectedIp); + const faultAt = Date.now(); + + await waitForReplicaReadiness(selected, 503, 30_000); + expect( + (await probeReplica(healthy, '/health/ready')).status, + ).toBe(200); + + // Only the affected slot leaves rotation. While `fall 2` counts the + // failed checks the slot passes through "UP 1/2 (L7STS)", so the + // wait is for DOWN itself, not for "no longer plain UP". + const slots = await waitForSlot( + (candidates) => + upSlots(candidates).length === replicas.length - 1 && + candidates.some( + (slot) => + slot.addr === selectedAddress && + slot.status === 'DOWN', + ), + `selected slot ${selectedAddress} did not go down`, + 30_000, + ); + // inter 500 ms × fall 2 + timeout check 500 ms + polling step 250 ms. + expect(Date.now() - faultAt).toBeLessThan(3_000); + expect( + slots.find((slot) => slot.addr === selectedAddress)?.status, + ).toBe('DOWN'); + + const served = new Set(); + for (let index = 0; index < readyReads; index += 1) { + const read = await historyOf(chat.id, token); + expect(read.response.status).toBe(200); + served.add( + read.response.headers.get('x-instance-id') ?? 'unknown', + ); + } + expect(served.has(selectedInstance as string)).toBe(false); + expect(served.has(healthyInstance as string)).toBe(true); + } finally { + await restoreDatabaseAccess(); + } + + await waitForReplicaReadiness(selected, 200, 30_000); + await waitForSlot( + (slots) => + upSlots(slots).length === replicas.length && + slots.some( + (slot) => + slot.addr === selectedAddress && + slot.status === 'UP', + ), + 'restored replica did not return to rotation', + 30_000, + ); + + let servedAgain = false; + for ( + let index = 0; + index < readyReads * 2 && !servedAgain; + index += 1 + ) { + const read = await historyOf(chat.id, token); + expect(read.response.status).toBe(200); + servedAgain = + read.response.headers.get('x-instance-id') === + selectedInstance; + } + expect(servedAgain).toBe(true); + }, + outagedRequestBudgetMs, + ); + + it( + 'degrades attachments while S3 is down and sweeps the failed upload afterwards', + async () => { + const upload = (data: Buffer, name: string) => + request( + uploadPath(chat.id, name), + { + method: 'POST', + headers: { + ...bearer(token), + 'content-type': 'image/png', + }, + body: data as unknown as BodyInit, + }, + ); + const before = await upload(samplePng, `s3before-${runId}.png`); + expect(before.response.status).toBe(202); + await waitReady(token, before.body.id); + + await compose('stop', s3Service); + try { + const failed = await upload(samplePng, `s3down-${runId}.png`); + expectBoundedOutage(failed); + const metadata = await request( + `/api/v1/attachments/${before.body.id}`, + { headers: bearer(token) }, + ); + expect(metadata.response.status).toBe(200); + const content = await request( + `/api/v1/attachments/${before.body.id}/content`, + { headers: bearer(token) }, + ); + expectBoundedOutage(content); + const text = await request( + `/api/v1/chats/${chat.id}/messages`, + json({ text: 'S3 down' }, messageHeaders(token)), + ); + expect(text.response.status).toBe(201); + expect((await request('/health/ready')).response.status).toBe( + 200, + ); + // Compensation claimed the row but could not delete the object: + // the row stays in `deleting`, tracked for the sweeper. + expect( + await psql( + `select status from attachments where chat_id = '${chat.id}' and filename = 's3down-${runId}.png'`, + ), + ).toBe('deleting'); + } finally { + await compose('start', s3Service); + } + await waitForS3Healthy(); + + const bytes = await fetch( + `${baseUrl}/api/v1/attachments/${before.body.id}/content`, + { headers: bearer(token) }, + ); + expect(bytes.status).toBe(200); + expect( + Buffer.from(await bytes.arrayBuffer()).equals(samplePng), + ).toBe(true); + const after = await upload(samplePng, `s3after-${runId}.png`); + expect(after.response.status).toBe(202); + await waitReady(token, after.body.id); + + // A `deleting` row is re-claimed one minute after its last change + // (an in-flight compensation is never raced), then swept. + const filter = `chat_id = '${chat.id}' and filename = 's3down-${runId}.png'`; + await waitFor( + async () => { + await sweepNow(); + return ( + (await psql( + `select count(*) from attachments where ${filter}`, + )) === '0' + ); + }, + async () => 'deleting row was not swept', + 90_000, + ); + }, + outagedRequestBudgetMs, + ); + + it( + 'bounds requests by S3_REQUEST_TIMEOUT_MS when S3 hangs instead of refusing', + async () => { + const created = await request<{ id: string }>( + uploadPath(chat.id, `hang-${runId}.png`), + { + method: 'POST', + headers: { ...bearer(token), 'content-type': 'image/png' }, + body: samplePng as unknown as BodyInit, + }, + ); + expect(created.response.status).toBe(202); + await waitReady(token, created.body.id); + // A paused container keeps its TCP port open but never answers: the + // failure mode a stopped container (connection refused) does not show. + const container = (await compose('ps', '-q', s3Service)).split( + '\n', + )[0]; + await docker('pause', container); + try { + const started = Date.now(); + const content = await request( + `/api/v1/attachments/${created.body.id}/content`, + { headers: bearer(token) }, + ); + const elapsed = Date.now() - started; + expectBoundedOutage(content); + // S3_REQUEST_TIMEOUT_MS is 15 s in the stand; HAProxy gives up at 30 s. + expect(elapsed).toBeLessThan(20_000); + expect( + ( + await request( + `/api/v1/attachments/${created.body.id}`, + { + headers: bearer(token), + }, + ) + ).response.status, + ).toBe(200); + expect((await request('/health/ready')).response.status).toBe( + 200, + ); + } finally { + await docker('unpause', container); + } + const bytes = await fetch( + `${baseUrl}/api/v1/attachments/${created.body.id}/content`, + { headers: bearer(token) }, + ); + expect(bytes.status).toBe(200); + expect( + Buffer.from(await bytes.arrayBuffer()).equals(samplePng), + ).toBe(true); + }, + outagedRequestBudgetMs, + ); + + it( + 'keeps the object while PostgreSQL is down before ready and sweeps it afterwards', + async () => { + const data = noisePng(1024 * 1024); + const filename = `pgfault-${runId}.png`; + const filter = `chat_id = '${chat.id}' and status = 'pending' and filename = '${filename}'`; + let restarted = false; + let reply = ''; + try { + reply = await rawUpload( + data, + chat.id, + filename, + token, + 64 * 1024, + async () => { + await waitFor( + async () => + Number( + await psql( + `select count(*) from attachments where ${filter}`, + ), + ) === 1, + async () => 'pending row did not appear', + 10_000, + ); + await compose('stop', postgresService); + }, + ); + } finally { + await compose('start', postgresService); + restarted = true; + } + expect(restarted).toBe(true); + expect(reply.startsWith('HTTP/1.1 503')).toBe(true); + await waitForReadiness(200); + + const key = await psql( + `select staging_key from attachments where ${filter}`, + ); + expect(key).toMatch(/^staging\/[0-9a-f-]{36}\/original$/u); + // Without PostgreSQL the API cannot tell a lost commit from a failed + // one, so it deletes nothing; the pending row keeps the object tracked. + expect(await objectExists(key)).toBe(true); + + await waitUntilExpired(filter); + await sweepNow(); + expect( + await psql(`select count(*) from attachments where ${filter}`), + ).toBe('0'); + expect(await objectExists(key)).toBe(false); + }, + outagedRequestBudgetMs, + ); +}); diff --git a/app/test/direct-upload.e2e-spec.ts b/app/test/direct-upload.e2e-spec.ts new file mode 100644 index 0000000..04149a4 --- /dev/null +++ b/app/test/direct-upload.e2e-spec.ts @@ -0,0 +1,348 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { setTimeout as sleep } from 'node:timers/promises'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import type { Pool } from 'pg'; +import type { Attachment } from '../src/attachments/attachment.js'; +import type { DirectUpload } from '../src/attachments/direct-uploads.service.js'; +import type { ApiErrorBody } from '../src/common/errors/api-error.js'; +import { + Actor, + actor, + bearer, + createChat, + database, + download, + expectError, + http, + json, + postMessage, + waitReady, +} from './support/e2e.js'; +import { noisePng, pixelBombPng } from './support/png.js'; + +const png = readFileSync( + new URL('../../tests/fixtures/sample.png', import.meta.url), +); +const jpeg = readFileSync(new URL('./fixtures/sample.jpg', import.meta.url)); +const MAX = 10_485_760; +const shortTtl = process.env.E2E_DIRECT_TTL_SHORT === '1'; + +let db: Pool; +let alice: Actor; +let bob: Actor; +let eve: Actor; +let chatId: string; + +const sha256 = (data: Uint8Array) => + createHash('sha256').update(data).digest('hex'); + +function init(token: string, chat: string, body: Record) { + return http( + `/api/v1/chats/${chat}/attachments/direct-uploads`, + json(body, bearer(token)), + ); +} + +function declaration(data: Buffer, contentType = 'image/png') { + return { + filename: 'direct.png', + content_type: contentType, + size_bytes: data.length, + sha256: sha256(data), + }; +} + +async function initOk(data: Buffer, contentType = 'image/png') { + const result = await init( + alice.token, + chatId, + declaration(data, contentType), + ); + expect(result.response.status).toBe(201); + return result.body; +} + +// The PUT goes straight to the public S3 endpoint, not through the API. +async function put(ticket: DirectUpload, data: Buffer): Promise { + return fetch(ticket.url, { + method: ticket.method, + headers: ticket.headers, + body: data as unknown as BodyInit, + }); +} + +function complete(token: string, id: string) { + return http( + `/api/v1/attachments/${id}/complete`, + { + method: 'POST', + headers: bearer(token), + }, + ); +} + +describe('direct upload (presigned PUT)', () => { + beforeAll(async () => { + db = database(); + alice = await actor(); + bob = await actor(); + eve = await actor(); + chatId = (await createChat(alice, [bob])).id; + }); + + afterAll(async () => { + await db.end(); + }); + + it('uploads around the API and exposes the attachment after complete', async () => { + const ticket = await initOk(png); + expect(ticket.method).toBe('PUT'); + expect(ticket.headers['x-amz-checksum-sha256']).toBe( + Buffer.from(sha256(png), 'hex').toString('base64'), + ); + expect(Date.parse(ticket.expires_at)).toBeGreaterThan(Date.now()); + expect(new URL(ticket.url).pathname).toBe( + `/messenger-attachments/staging/${ticket.attachment_id}/original`, + ); + + const hidden = await http( + `/api/v1/attachments/${ticket.attachment_id}`, + { headers: bearer(bob.token) }, + ); + expectError(hidden, 404, 'not_found'); + expectError( + await postMessage(alice.token, chatId, { + text: '', + attachment_ids: [ticket.attachment_id], + }), + 404, + 'not_found', + ); + expectError( + await complete(alice.token, ticket.attachment_id), + 409, + 'conflict', + ); + + expect((await put(ticket, png)).status).toBe(200); + expectError( + await complete(bob.token, ticket.attachment_id), + 404, + 'not_found', + ); + expectError( + await complete(eve.token, ticket.attachment_id), + 404, + 'not_found', + ); + const done = await complete(alice.token, ticket.attachment_id); + expect(done.response.status).toBe(200); + expect(done.body).toMatchObject({ + id: ticket.attachment_id, + owner_id: alice.user.id, + content_type: 'image/png', + size_bytes: png.length, + sha256: sha256(png), + status: 'queued', + }); + const ready = await waitReady(alice.token, ticket.attachment_id); + expect(ready.status).toBe('ready'); + expect(ready.variants).toHaveLength(3); + const again = await complete(alice.token, ticket.attachment_id); + expect(again.response.status).toBe(200); + expect(again.body.status).toBe('ready'); + + const content = await download(bob.token, ticket.attachment_id); + expect(content.response.status).toBe(200); + expect(content.bytes.equals(png)).toBe(true); + const sent = await postMessage(alice.token, chatId, { + text: '', + attachment_ids: [ticket.attachment_id], + }); + expect(sent.response.status).toBe(201); + expect(sent.body.attachment_ids).toEqual([ticket.attachment_id]); + }); + + it('answers 200 to every parallel complete of one upload', async () => { + const ticket = await initOk(png); + expect((await put(ticket, png)).status).toBe(200); + const results = await Promise.all( + Array.from({ length: 4 }, () => + complete(alice.token, ticket.attachment_id), + ), + ); + expect(results.map((result) => result.response.status)).toEqual([ + 200, 200, 200, 200, + ]); + for (const result of results) + expect(result.body.id).toBe(ticket.attachment_id); + }); + + it('rejects invalid declarations', async () => { + const base = declaration(png); + expectError(await init(eve.token, chatId, base), 404, 'not_found'); + expectError( + await init(alice.token, chatId, { ...base, size_bytes: MAX + 1 }), + 413, + 'payload_too_large', + ); + expectError( + await init(alice.token, chatId, { + ...base, + content_type: 'image/gif', + }), + 415, + 'unsupported_media_type', + ); + for (const bad of [ + { ...base, extra: true }, + { ...base, sha256: 'ABC' }, + { ...base, size_bytes: 0 }, + { ...base, filename: 'a/b.png' }, + ]) + expectError( + await init(alice.token, chatId, bad), + 400, + 'invalid_request', + ); + }); + + it('lets the storage refuse bytes that differ from the declaration', async () => { + const ticket = await initOk(png); + const tampered = Buffer.from(png); + tampered[1000] ^= 1; + const refused = await put(ticket, tampered); + expect(refused.status).toBe(400); + expect(await refused.text()).toContain('XAmzContentChecksumMismatch'); + // No object was created, so the upload can still be finished. + expectError( + await complete(alice.token, ticket.attachment_id), + 409, + 'conflict', + ); + expect((await put(ticket, png)).status).toBe(200); + expect( + (await complete(alice.token, ticket.attachment_id)).response.status, + ).toBe(200); + + const longer = await initOk(png); + const wrongLength = await put( + longer, + Buffer.concat([png, Buffer.from('x')]), + ); + expect(wrongLength.status).toBe(403); + }); + + it('rejects a declared PNG that is really a JPEG, then forgets the claim', async () => { + const ticket = await initOk(jpeg, 'image/png'); + expect((await put(ticket, jpeg)).status).toBe(200); + expectError( + await complete(alice.token, ticket.attachment_id), + 415, + 'unsupported_media_type', + ); + expectError( + await complete(alice.token, ticket.attachment_id), + 404, + 'not_found', + ); + // The URL is still valid: a re-PUT must stay tracked so the sweeper + // removes the new object too. + expect((await put(ticket, jpeg)).status).toBe(200); + const row = await db.query<{ status: string }>( + 'SELECT status FROM attachments WHERE id = $1', + [ticket.attachment_id], + ); + expect(row.rows[0]?.status).toBe('rejected'); + expectError( + await complete(alice.token, ticket.attachment_id), + 404, + 'not_found', + ); + }); + + it.each([ + ['truncated PNG', () => png.subarray(0, png.length - 100)], + [ + 'PNG damaged after the first 64 KiB', + () => { + const data = noisePng(1_048_576); + data[700_000] ^= 0xff; + return data; + }, + ], + ])('rejects a %s even with a matching checksum', async (_name, make) => { + // The declaration and the signed checksum match the bytes exactly: + // only a check of the whole image can tell they are not an image. + const data = make(); + const ticket = await initOk(data); + expect((await put(ticket, data)).status).toBe(200); + expectError( + await complete(alice.token, ticket.attachment_id), + 415, + 'unsupported_media_type', + ); + expectError( + await complete(alice.token, ticket.attachment_id), + 404, + 'not_found', + ); + }); + + it('rejects a pixel bomb on complete', async () => { + const bomb = pixelBombPng(); + const ticket = await initOk(bomb); + expect((await put(ticket, bomb)).status).toBe(200); + expectError( + await complete(alice.token, ticket.attachment_id), + 413, + 'payload_too_large', + ); + expectError( + await complete(alice.token, ticket.attachment_id), + 404, + 'not_found', + ); + }); + + it('limits unfinished direct uploads per user', async () => { + const spammer = await actor(); + const chat = (await createChat(spammer, [])).id; + for (let index = 0; index < 10; index += 1) { + const ok = await init(spammer.token, chat, declaration(png)); + expect(ok.response.status).toBe(201); + } + const limited = await init(spammer.token, chat, declaration(png)); + expectError(limited, 429, 'rate_limited'); + expect( + Number(limited.response.headers.get('retry-after')), + ).toBeGreaterThan(0); + }); + + it.runIf(shortTtl)( + 'refuses an expired URL and removes the claim', + async () => { + const ticket = await initOk(png); + const expiresAt = Date.parse(ticket.expires_at); + await sleep(Math.max(0, expiresAt - Date.now()) + 2000); + expect((await put(ticket, png)).status).toBe(403); + const deadline = Date.now() + 15_000; + for (;;) { + const rows = await db.query( + 'SELECT 1 FROM attachments WHERE id = $1', + [ticket.attachment_id], + ); + if (rows.rowCount === 0) break; + expect(Date.now()).toBeLessThan(deadline); + await sleep(250); + } + expectError( + await complete(alice.token, ticket.attachment_id), + 404, + 'not_found', + ); + }, + 60_000, + ); +}); diff --git a/app/test/fixtures/sample-progressive.jpg b/app/test/fixtures/sample-progressive.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eed80152996e3a0dca2a2178deb7e430065cd816 GIT binary patch literal 4891 zcmbVP3n0|l8lUl+sVU8bX&UmFbR!Kt4CB$25k;3w8S*wOkMSJBhT1L}B;=85CuwI0 zJ2g^5Atf!ci#(c4Elct$ZA`mLTe;^yUU9cw?fIYi&-Z=jobUX;*Eutjos&H{!QkM5O+JB{!K5Xnq@*OJ!An|NS_ZKUi2!W{3bkYzX2r^tm=zd|99C(SoIG9u zgTblc@N3qnsHn)TBB&FT)s>W0lp!T>uoNMKkVPV8mE|$=%3s_j@4_%hSOa{!B%A<~ zz`!Lj@X32HJb)^0u$d+Smz09ZAi$U+93~+N24_ZK5Gy4k4MR*mhAoo>qi9Jqu=733 zNVv-y6=v;QrA6u175H^CI6>vRxiMkfZYzObX9X4FMr~>%wa;t~aMdWc6C`c5HapaQ z^Bi55*hAi}KEdYUdGAx`F<>#QWjumFeMXjGMXM zXLO0pzjsug{=JiNlN)quf6&)OoS(~!YOR_xbsal{8|+JuDkyM**ZFS^u;)~CX(vgy zotWBqqrTm*Cu$6d&uj()<3{wwC{Tym9WO=ZvnmAF-M}imKPkYTbz7eQ;INaHIp42x zYtlorNSce*Iy>#JX~J;_+VX)?CV#hWY1b9M&`N4B$${lfGjH;bcDwIyUe(yGP{_xY z@?P3#*%9BO+TF*BqT9`@ul=l>g6)e6M7-`kCo9qu<^||0Jh=I4z;&r2#=dDU=Y}?` z<>;0n+gE$}?2Be0xAb#9Mz_t|}~Gke1`QuZGPl z3c{Fj-0s~Me|oaYiuiEKlX(BF!MYv#I|ND6zRq>*pPn?4mcRW$JM-y7E8?Z_R_*W# z?CZjt5yo8XL{P=L=5or&Mwd$L56jEBzoAgA<~Q8kTu&UKm;L4zLyyuZm)6m4+FR?_ z6^1$=#JUZS*z;DP@3q{%n-le9`Cw%?DLZH!f9A^G!?);FFZ}CDl7wb{qUWdFDBWJy z`h+zBEZ#)8&!YzCmI#+8T6wx}i9qC}=5P6R zl^>IM0s++dkdVmr}0y$h-;$zzftzGUrh-!f-UrO8P^*A+DBbwEZq=@3wA}Q$G zH9Fik?FBZOu}qsKHH#qX2iz4tXsE`@Y)+0vs(RuY7Lt_FvNBd_o*L4Lf=w%9^&fsT z=#Kr|yP6g*9 zbW&o(E(QKJfs^nl7P-{I4!`+CURYvkdKz|uk>j@mX#J-a+YiSguWtXJ(g^zK!tb z?1C--#Xs=ya#9M0%JmaiJ2e!xD&YT0luNnpYk%C*QBzA-%Yx;5Dk~$S;DlSo1=Ka2?G)MysU?bfo}ON2UKT$E2vcUKko!_U=_eM-6Dt)SAz#(L!hExS-#o{_a3KakRjwYaI7OP39Ng(5p1au4# zsqTAShFt zCvFD;1?XZxxLsHcpyTe;$!yvzCS78Zmw9+f;ubaVMZsJ!`R@Yvry-sf&G|+y%;h<^ zPAAb=Lb5TvPnj|GtiT1GzF<&ldn^bnP>Ml9(NzV61QfTJ*#WfaOnyNS z!Sq?!puQ5pY;j(IU_gT)5TL+Jt{_txKJhnr zy!GU+TcUIo!`1qDCm>gxm3sYaZ5j zPeKw>Iz1!nbHX3}0*M~z2VU!8q}0RBDCw3Tu)rBU-i{U$Pb;B zkYK`(2U?P5S>VFYNW4m1`g1c;-pRcx6lfBUf4W)lqmRE=N$EA=V_`tKbAeJK$zcjPPg5=i7lq|{DCEk z)0WI#w!o6~)-g`+>^+P2cM_EHr(cgY_Ma~)3vFKg#K=cXGMgPCvKL6_&D-ht@t6U5 zk7!A&;AmmX=#r17CJ%hxB~QZ8+1cygB@ewYAlul;4RU2y1?)L6g3`Bp*7q7;xH$gJ8R3_ZGvGs~z)zVZwxfTZ`a2)S51Je~f8O{) z`m@1znnp z(&_KD60&M*VpzwHp-_?tt(cf&r)q0i#}XuM7)=HR#M3`|l`N7fZxH9x+>6WOae3_& zw)}&9R`%t7A1#A@|A3hgHqO9hqY`;PZvTE9 znOV&2@$l%WY4q@*gHHG8seS8!5Iv-Uy+EVV9O~S*jGalY>K$A`j;#F$Og*S~bA>77 z%+a3SJGHejF)UV0LW1N9tpwok6*4l)N=js$i9`?GgWhvz88MC;!c(ez&x}Uk}8q@(RIL U;KSoBC2*5A6n@7`Iyx!*AA%PG5dZ)H literal 0 HcmV?d00001 diff --git a/app/test/fixtures/sample.jpg b/app/test/fixtures/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..708a5aeef83f6f6e4dc9df6944d19622739dabf0 GIT binary patch literal 4726 zcmb7I4LH>479U2~TTIgwF_;WH*{!tAPgd#!|A|3+|VPOH*Nx6Pfrg&0X`;7n4oVk$lMfOA3WTGNsy5t!yo?I1OK(bCCVYi3S&6h~0DWoO`+PmmPY~828JTZO-wjP{Ru}R@M zx;0^B>trg|kIEh1x>_K?wj$If>EwmxiTnRUW9^`^G8eig?gN4Z%s7m?Z3GpcEmwqK zP+!~RD6~|_xWf=RnFP1zVg8CgfEEC#p_~;!W07GiUze%KKaH!~ExqYzH8Xv}!F+cI z(V-m)(z4dpH2lU!9xTOmtXY^LS2Gno3~^1`!0#7=`7yQgvzm9mpLclqo#RbC^x3ao z6-F@LJ-HS)Af~V#KIvyjTDj5r@!%}qZWJ$=`78HLyiJfrrW;3i78wwZNRvzV?3m{g4+|B8V&hEf3(hn{wqq|{TJdn%& zxL7PR-!~w|!m0u9Vx`W-PFkPq(Ru2GY}!J zR(h-=fK-Hw@3(SK3?X#|Q+bvnsJ4BxHK>cvNOmp*8V1DSiKwbWGr7@_Z6zQwJlxt+ z{kmLZr&rEwzBkMzg)nYv#il0{>9dIRIcwCNtGHCA;yhCkS69t-vE>{n<_H2VG;b1-8vQ*nW*$Z-m~%$}gV|hjI{3Y$dd`|qALLNUj@@ihx%ZHGfwk< z#vzbw&q}WQD1J1%F?p;N-|YD9$(X?KCD{mAdK7Ww66yALTH6qcIFQj5v|!!Zh3^@gQ4Uo879RTc?s=#$J-I`;)N#~TVMsrRFPZS7p;nNR z66H^0DrAV1U-x+BY%F>nBH0RJa-!>paCf5@XG{C(SV)?*`IOP^o}jcPR|oT#ZAQw2 z5E{g5)kg(t<(bKLuU00;o^`tYdbfXRQ^4|loCJ%k&5gWS^}8=n+|IptPy3N& zD4nYGyWGk6>9woRjTpa*Zijy)LS&hdfv-6&W%cq6gxu#bRw98*@u)El(PUq(J6Oy) zfWV~Xy~k!nRfY8P1+u}ZRIaa!|AS(Lihq^6x5#^iymX8jjdRN%B+4m>g)9=d6Ic8% zVup_wjfLcKUc@Y)?2bvKv=skUL|3Nb)Q-Z_f;0&H%HH0rl$KNvl@@Uo(n&a0(=}-1 zB_ookEk~z+@Le#k_pAZRSeYzfS@@{&_+IzgAKSM%+V-)$K0|1uY5a7YG&)gQ211+U z;qRe}T(0Gnglo^EL7-1^GZ8B2*=B7`(c_4}(%vF6akZic?kVifn`{G>4_2mbE0tL* zoCmQgG#{%%sHR<;f}MB=;)+7V}^`30+V29z_B*6eA9nhLh~4EO^)TAH60VN)~SwW*=N${1F$ zP#GhXCWVznxD;6y3nZHfsgK`w7ZHRu0|_q&q8LXyA1{Govn8VF{(!l-%O-QMhXFrf zaQjbe?0z3xbbm=*77agY_PH^4`RPZ4WYK}HZve6qKuAd$reE~`q8!3~*>O?a6{|H* z`P?Eh3}e%m4Wus<{$8yV{$6ukAc>qSeDGWE5N@eW!1cq%qjq**p?i8*_cq5_clM2F z8;fiMYL#JS;Z&}tmM+9Yku(YrNf;M6Eiz1FXUhK0VGaW#(* zEx}_+Qpr)0j&wG7WBD|-*UB3O{=1sT0MC488!a`tE&Dc@$NpIP?p}RMl}P5=KQE1c zigmH&samQk%E5!R6pVIolUrq-wyVD?EqA8KDb`}9vs@bj`M=-H`(3K zFW)?Vu`~2CZflo`2Bk;IADk?@9rNksjH-h~^aAFAiLt<`_nT<)`svlY^iK_Y=yNS( zA&oph&QB?C{e97GSs8jeJAsC_Lv${IGV5G}k+ao*TC26UAZfN3n6-YuM#Nf!V z_Qx@hz6!f4cMcE5R1YQvBvv*Yy|IU{O-(oCj^x6wDXBpTG`6Im^E{I3VXd8TDABnr zaGwLMC+dPV^#W^M*T^o_(?=WP{h2h>nr0U0YZ~f|$qUI?Lyfv*)cQh~3}63m>kADz z*7{;pSU;@=UHI2QF9urcBGpXe(k5%gcuM1&PBu2wN>hYU{+ppATRI>Ny!Bzw{qubX zkSW9zJ~m0{GrqM}cib4lu`^~^+OI#_C%ykd{Zx30sW`TmR>XVFpTw?kIsIh{k57xd zwkxXfH@IA!Zf)t!%KBBV4)*HY)>c_jQjj$trU2i5<0`?2LCbwY1Rd-@r(sVfv^WFt zfyIL#MP7>*tSea9$v9b&Q=ml;=`GT?2}-*SrXmuy8VNProwOl0mT$zappU?uU@FdT zQ0#JD{Hej*TiI zt|N6Yz4lpkXwGN5uk3so1Q|+&hV-OHWzsE{5TaqsHFWFX0qmkT8;4#Wc%qvOe*g0dX(rCz>}tB_73XgS!u;l2K)nd)*X_v>W_ z+2M@1_H}F8z&GcL5`T}0znV?O2v)6uh5BRFKnE4!ryAdTo2}JmD^j-P0K0Kl@7xL`Jxbl+d zJNZJCKaOxI;L{+72^QSeK_m96O;qkz9!9UEkgvN9g=w)VIo)e*;eF(js~BKEY^8Ls zsH=-^-3n2(C`gcgc~;LlM|t^X*-&4O1<==!2yZ` zG$O`}%8)lWFA%kif3K5?*g6$EUL)7WVIJ9{7E4`G=%(x zgg)0l$5Fl2C{ZAZ?l#JnpW0~%`@gmc?IN3%!D3vVgVAC5&w%KjR7c=Ui=g(jIsySy g64*8iZ6j$-0nRU3Z4Wm+nv;=@q@iuT9z*K?0+^xq^#A|> literal 0 HcmV?d00001 diff --git a/app/test/support/e2e.ts b/app/test/support/e2e.ts new file mode 100644 index 0000000..7f0338a --- /dev/null +++ b/app/test/support/e2e.ts @@ -0,0 +1,187 @@ +import { randomUUID } from 'node:crypto'; +import { Pool } from 'pg'; +import { expect } from 'vitest'; +import type { Chat } from '../../src/chats/chat.js'; +import type { ApiErrorBody } from '../../src/common/errors/api-error.js'; +import type { Message } from '../../src/messages/message.js'; +import type { Attachment } from '../../src/attachments/attachment.js'; +import type { User } from '../../src/users/user.js'; + +export const baseUrl = ( + process.env.API_BASE_URL ?? 'http://localhost:8080' +).replace(/\/+$/u, ''); +export const password = 'integration:пароль🔐'; +const runId = randomUUID().replaceAll('-', '').slice(0, 10); +let sequence = 0; + +export type Actor = { user: User; token: string }; +export type HttpResult = { body: T; response: Response }; + +export function database(): Pool { + return new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); +} + +export async function http( + path: string, + init: RequestInit = {}, +): Promise> { + const response = await fetch(`${baseUrl}${path}`, init); + const text = await response.text(); + let body: unknown = undefined; + if (text) { + try { + body = JSON.parse(text); + } catch { + body = text; + } + } + return { body: body as T, response }; +} + +export function json( + body: unknown, + headers: Record = {}, +): RequestInit { + return { + method: 'POST', + headers: { 'content-type': 'application/json', ...headers }, + body: JSON.stringify(body), + }; +} + +export function bearer(token: string): Record { + return { authorization: `Bearer ${token}` }; +} + +export function expectError( + result: HttpResult, + status: number, + code: string, +): void { + expect(result.response.status).toBe(status); + expect(result.body.error.code).toBe(code); + expect(result.body.error.request_id).toBe( + result.response.headers.get('x-request-id'), + ); +} + +export async function actor(): Promise { + const username = `e2e_${runId}_${sequence++}`.slice(0, 32); + const created = await http( + '/api/v1/users', + json({ username, display_name: 'Attachments e2e', password }), + ); + expect(created.response.status).toBe(201); + const basic = Buffer.from(`${username}:${password}`, 'utf8').toString( + 'base64', + ); + const session = await http<{ token: string }>('/api/v1/auth/sessions', { + method: 'POST', + headers: { authorization: `Basic ${basic}` }, + }); + expect(session.response.status).toBe(201); + return { user: created.body, token: session.body.token }; +} + +export async function createChat( + owner: Actor, + members: Actor[], +): Promise { + const result = await http( + '/api/v1/chats', + json( + { + title: 'attachments', + member_ids: [owner.user.id, ...members.map((m) => m.user.id)], + }, + bearer(owner.token), + ), + ); + expect(result.response.status).toBe(201); + return result.body; +} + +/** `query` is sent verbatim so tests can craft malformed filename parameters. */ +export function uploadRaw( + token: string, + chatId: string, + query: string, + body: Buffer | undefined, + contentType = 'image/png', +): Promise> { + return http(`/api/v1/chats/${chatId}/attachments${query}`, { + method: 'POST', + headers: { ...bearer(token), 'content-type': contentType }, + body: body as BodyInit | undefined, + }); +} + +export function upload( + token: string, + chatId: string, + body: Buffer | undefined, + options: { filename?: string; contentType?: string } = {}, +) { + return uploadRaw( + token, + chatId, + `?filename=${encodeURIComponent(options.filename ?? 'picture.png')}`, + body, + options.contentType ?? 'image/png', + ); +} + +/** + * Lab5 uploads answer 202 before the worker runs. Poll metadata until ready; + * a failed attachment is a test failure, never a silent timeout. + */ +export async function waitReady( + token: string, + attachmentId: string, + timeoutMs = 60_000, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const result = await http( + `/api/v1/attachments/${attachmentId}`, + { headers: bearer(token) }, + ); + expect(result.response.status).toBe(200); + if (result.body.status === 'failed') + throw new Error( + `attachment ${attachmentId} failed: ${result.body.error_code ?? 'unknown'}`, + ); + if (result.body.status === 'ready') return result.body; + if (Date.now() >= deadline) + throw new Error( + `attachment ${attachmentId} did not become ready within ${timeoutMs}ms`, + ); + await new Promise((resolve) => setTimeout(resolve, 200)); + } +} + +export async function download( + token: string, + attachmentId: string, +): Promise<{ response: Response; bytes: Buffer }> { + const response = await fetch( + `${baseUrl}/api/v1/attachments/${attachmentId}/content`, + { headers: bearer(token) }, + ); + return { response, bytes: Buffer.from(await response.arrayBuffer()) }; +} + +export function postMessage( + token: string, + chatId: string, + body: unknown, + key = randomUUID().replaceAll('-', ''), +) { + return http( + `/api/v1/chats/${chatId}/messages`, + json(body, { ...bearer(token), 'idempotency-key': key }), + ); +} diff --git a/app/test/support/jpeg.ts b/app/test/support/jpeg.ts new file mode 100644 index 0000000..b2d1ef9 --- /dev/null +++ b/app/test/support/jpeg.ts @@ -0,0 +1,24 @@ +/** Keeps every segment through the SOS header and drops the scan data. */ +export function jpegWithoutScanData(jpeg: Buffer): Buffer { + let offset = 2; + for (;;) { + const marker = jpeg[offset + 1]; + offset += 2 + jpeg.readUInt16BE(offset + 2); + if (marker === 0xda) break; + } + return Buffer.concat([jpeg.subarray(0, offset), Buffer.from([0xff, 0xd9])]); +} + +/** Inserts `count` APP13 segments of ~64 KiB right after SOI (Photoshop-style metadata). */ +export function jpegWithMetadata(jpeg: Buffer, count: number): Buffer { + const payload = Buffer.alloc(65_533, 0x20); + const segment = Buffer.concat([ + Buffer.from([0xff, 0xed, 0xff, 0xff]), + payload, + ]); + return Buffer.concat([ + jpeg.subarray(0, 2), + ...Array.from({ length: count }, () => segment), + jpeg.subarray(2), + ]); +} diff --git a/app/test/support/png.ts b/app/test/support/png.ts new file mode 100644 index 0000000..0605b82 --- /dev/null +++ b/app/test/support/png.ts @@ -0,0 +1,140 @@ +import { randomBytes } from 'node:crypto'; +import { once } from 'node:events'; +import { crc32, createDeflate, deflateSync } from 'node:zlib'; + +const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +function chunk(type: string, data: Buffer): Buffer { + const head = Buffer.alloc(8); + head.writeUInt32BE(data.length, 0); + head.write(type, 4, 'latin1'); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0); + return Buffer.concat([head, data, crc]); +} + +export function buildPng(options: { + width: number; + height: number; + colorType: number; + bitDepth: number; + idat: Buffer; +}): Buffer { + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(options.width, 0); + ihdr.writeUInt32BE(options.height, 4); + ihdr[8] = options.bitDepth; + ihdr[9] = options.colorType; + return Buffer.concat([ + SIGNATURE, + chunk('IHDR', ihdr), + chunk('IDAT', options.idat), + chunk('IEND', Buffer.alloc(0)), + ]); +} + +/** Inserts a private ancillary chunk before IEND to reach exactly `size` bytes. */ +export function padPngTo(png: Buffer, size: number): Buffer { + const extra = size - png.length; + if (extra === 0) return png; + if (extra < 12) throw new Error('PNG padding needs at least 12 bytes'); + const iend = png.length - 12; + return Buffer.concat([ + png.subarray(0, iend), + chunk('prVt', Buffer.alloc(extra - 12)), + png.subarray(iend), + ]); +} + +/** 8000x5001 grayscale 1-bit, all-zero rows: tiny file, 40 008 000 pixels. */ +export function pixelBombPng(): Buffer { + const width = 8000; + const height = 5001; + const row = Buffer.alloc(1 + Math.ceil(width / 8)); + const raw = Buffer.alloc(row.length * height); + return buildPng({ + width, + height, + colorType: 0, + bitDepth: 1, + idat: deflateSync(raw, { level: 9 }), + }); +} + +const NOISE_WIDTH = 1024; +const NOISE_ROW = 1 + NOISE_WIDTH * 3; + +function noiseOfHeight(height: number): Buffer { + const raw = randomBytes(NOISE_ROW * height); + for (let row = 0; row < height; row += 1) raw[row * NOISE_ROW] = 0; + return buildPng({ + width: NOISE_WIDTH, + height, + colorType: 2, + bitDepth: 8, + idat: deflateSync(raw, { level: 0 }), + }); +} + +/** Incompressible, structurally valid PNG of exactly `size` bytes. */ +export function noisePng(size: number): Buffer { + let height = Math.max(1, Math.floor(size / NOISE_ROW)); + for (;;) { + const png = noiseOfHeight(height); + if (png.length > size) { + height -= 1; + if (height < 1) throw new Error('size is too small for noisePng'); + continue; + } + const extra = size - png.length; + if (extra > 0 && extra < 12) { + height -= 1; + continue; + } + return padPngTo(png, size); + } +} + +/** Valid signature, IHDR, CRCs and IEND around a zlib stream of random bytes. */ +export function pngWithGarbageIdat(): Buffer { + return buildPng({ + width: 320, + height: 200, + colorType: 2, + bitDepth: 8, + idat: randomBytes(5000), + }); +} + +/** + * 8000x5000 RGBA 16-bit (8 bytes/pixel, 40 000 000 px — the pixel limit): + * the heaviest decode a valid upload can ask for. Rows are streamed into the + * compressor, so the 320 MB raw image is never allocated here. + */ +export async function maxPixelsRgba16Png(): Promise { + const width = 8000; + const height = 5000; + // First row: a gradient; every next row uses filter "Up" with zero + // deltas, i.e. repeats it — a valid image that compresses well. + const first = Buffer.alloc(1 + width * 8); + for (let x = 0; x < width; x += 1) + first.writeUInt16BE((x * 8) & 0xffff, 1 + x * 8); + const repeat = Buffer.alloc(1 + width * 8); + repeat[0] = 2; + const deflate = createDeflate({ level: 1 }); + const chunks: Buffer[] = []; + deflate.on('data', (chunk: Buffer) => chunks.push(chunk)); + const ended = once(deflate, 'end'); + for (let y = 0; y < height; y += 1) + if (!deflate.write(y === 0 ? first : repeat)) + await once(deflate, 'drain'); + deflate.end(); + await ended; + return buildPng({ + width, + height, + colorType: 6, + bitDepth: 16, + idat: Buffer.concat(chunks), + }); +} diff --git a/app/tsconfig.build.json b/app/tsconfig.build.json new file mode 100644 index 0000000..2eafee0 --- /dev/null +++ b/app/tsconfig.build.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"], + "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] +} diff --git a/app/tsconfig.json b/app/tsconfig.json new file mode 100644 index 0000000..6aa3ca7 --- /dev/null +++ b/app/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "nodenext", + "moduleResolution": "nodenext", + "resolvePackageJsonExports": true, + "esModuleInterop": true, + "isolatedModules": true, + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "target": "ES2024", + "sourceMap": true, + "outDir": "./dist", + "incremental": true, + "skipLibCheck": true, + "strict": true, + "strictPropertyInitialization": false, + "types": ["vitest/globals", "node"] + } +} diff --git a/app/vitest.config.e2e.ts b/app/vitest.config.e2e.ts new file mode 100644 index 0000000..a7d6317 --- /dev/null +++ b/app/vitest.config.e2e.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vitest/config'; +import tsconfigPaths from 'vite-tsconfig-paths'; + +export default defineConfig({ + plugins: [tsconfigPaths()], + test: { + globals: true, + root: './', + include: ['test/*.e2e-spec.ts'], + testTimeout: 30_000, + hookTimeout: 30_000, + sequence: { concurrent: false }, + }, +}); diff --git a/app/vitest.config.ts b/app/vitest.config.ts new file mode 100644 index 0000000..9384f47 --- /dev/null +++ b/app/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; +import tsconfigPaths from 'vite-tsconfig-paths'; + +export default defineConfig({ + // Resolves the path aliases declared in tsconfig.json, including the ones + // added by `nest g library`. + plugins: [tsconfigPaths()], + test: { + globals: true, + root: './', + include: ['**/*.spec.ts'], + }, +}); diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..cc71cd4 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,531 @@ +# Стенд lab7 (база lab6): клиент -> HAProxy -> API x N -> PostgreSQL + Redis + MinIO +# + RabbitMQ; отдельный worker читает задания из quorum-очереди и публикует +# оригинал и варианты в конечный S3-prefix. API отвечает 202 после COMMIT +# (staging-объект + attachment + job + outbox), поэтому брокер не входит в +# /health/ready и его недоступность не останавливает приём загрузок. +# Одна команда запуска: make stand-up (docker compose --env-file .env up -d --build --wait) +# +# Проект запинен именем, чтобы имена контейнеров и labels были предсказуемы для +# scripts/stop-one.sh; container_name нигде не задан, иначе масштабирование +# одного Compose-service стало бы невозможным. +name: mtusi-lab7 + +services: + postgres: + image: postgres:16.4-alpine + # pg_stat_statements включён для трека 1 (агрегаты SQL по репликам); + # max_connections поднят под N x DATABASE_POOL_MAX. + command: + [ + 'postgres', + '-c', + 'shared_preload_libraries=pg_stat_statements', + '-c', + 'max_connections=120', + '-c', + 'shared_buffers=128MB', + '-c', + 'effective_cache_size=384MB', + ] + environment: + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} + # Только loopback: операторские проверки (host-side npm run test:e2e, + # psql в evidence). API-реплики портов не публикуют вовсе. + ports: + - '127.0.0.1:${POSTGRES_PUBLISHED_PORT:-5432}:5432' + volumes: + - postgres-data:/var/lib/postgresql/data + deploy: + resources: + limits: + cpus: '${PG_CPUS:-1.5}' + memory: ${PG_MEMORY:-512m} + healthcheck: + test: + [ + 'CMD-SHELL', + 'pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}', + ] + interval: 5s + timeout: 3s + retries: 20 + + redis: + image: redis:7.4.2-alpine + # appendonly: сессии и кэш переживают рестарт контейнера (проверка + # сохранности с неизменным токеном). volatile-lru вытесняет только + # ключи с TTL; в стенде у них ограниченный набор и объём. + command: + [ + 'redis-server', + '--appendonly', + 'yes', + '--appendfsync', + 'everysec', + '--maxmemory', + '96mb', + '--maxmemory-policy', + 'volatile-lru', + ] + ports: + - '127.0.0.1:${REDIS_PUBLISHED_PORT:-6379}:6379' + volumes: + - redis-data:/data + deploy: + resources: + limits: + cpus: '${REDIS_CPUS:-0.25}' + memory: ${REDIS_MEMORY:-128m} + healthcheck: + test: ['CMD', 'redis-cli', 'ping'] + interval: 5s + timeout: 3s + retries: 20 + + broker: + image: rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e + # Имя узла rabbit@broker должно оставаться стабильным: при смене + # hostname данные в broker-data превращаются в сирот. + hostname: broker + secrets: + - source: rabbitmq_conf + target: /etc/rabbitmq/conf.d/20-credentials.conf + volumes: + - broker-data:/var/lib/rabbitmq + # rabbitmq_prometheus: агрегированные метрики на 15692 (наружу не публикуется). + - ./infra/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro + # Портов нет: брокер доступен только сервисам compose-сети. + deploy: + resources: + limits: + cpus: '${BROKER_CPUS:-0.5}' + memory: ${BROKER_MEMORY:-512m} + healthcheck: + test: ['CMD', 'rabbitmq-diagnostics', '-q', 'check_port_connectivity'] + interval: 5s + timeout: 5s + retries: 30 + start_period: 20s + stop_grace_period: 30s + restart: unless-stopped + + # One-shot: creates the worker identity and tightens the API identity. + # rabbitmqctl talks to rabbit@broker using the shared Erlang cookie, so the + # data volume is mounted read-only. + broker-init: + image: rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e + entrypoint: ['/bin/sh', '/bootstrap/init-worker.sh'] + volumes: + - broker-data:/var/lib/rabbitmq:ro + - ./infra/rabbitmq:/bootstrap:ro + secrets: [broker_worker_password] + depends_on: + broker: { condition: service_healthy } + restart: 'no' + deploy: + resources: + limits: + cpus: '0.25' + memory: 128m + + s3: + image: minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e + command: ['server', '/data', '--address', ':9000'] + environment: + MINIO_ROOT_USER_FILE: minio_root_user + MINIO_ROOT_PASSWORD_FILE: minio_root_password + MINIO_BROWSER: 'off' + secrets: [minio_root_user, minio_root_password] + # Консольный порт 9001 не публикуется, консоль отключена (MINIO_BROWSER=off). + ports: + - '${S3_PUBLIC_BIND:-127.0.0.1}:${S3_PUBLIC_PORT:-9000}:9000' + volumes: + - s3-data:/data + deploy: + resources: + limits: + cpus: '${S3_CPUS:-1.0}' + memory: ${S3_MEMORY:-512m} + healthcheck: + test: ['CMD', 'mc', 'ready', 'local'] + interval: 5s + timeout: 3s + retries: 20 + + # Идемпотентный bootstrap: bucket, политика, пользователь API. + # Лимит 256m: mc admin policy attach на 128m получал OOM-kill (exit 137). + s3-init: + image: minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727 + entrypoint: ['/bin/sh', '/bootstrap/bootstrap.sh'] + environment: + S3_BUCKET: '${S3_BUCKET:-messenger-attachments}' + volumes: + - ./infra/minio:/bootstrap:ro + secrets: + - minio_root_user + - minio_root_password + - s3_api_access_key_id + - s3_api_secret_access_key + - s3_worker_access_key_id + - s3_worker_secret_access_key + depends_on: + s3: { condition: service_healthy } + restart: 'no' + deploy: + resources: + limits: + cpus: '0.25' + memory: 256m + + # Миграции выполняются один раз отдельным сервисом, а не гонкой реплик: + # api стартует только после его успешного завершения. + migrate: + build: + context: . + dockerfile: Dockerfile + image: ${API_IMAGE:-mtusi-messenger:lab7} + command: ['node', 'dist/database/migration.runner.js'] + env_file: [.env] + deploy: + resources: + limits: + cpus: '0.5' + memory: 192m + depends_on: + postgres: { condition: service_healthy } + redis: { condition: service_healthy } + restart: 'no' + + api: + build: + context: . + dockerfile: Dockerfile + args: + BUILD_ID: ${BUILD_ID:-unknown} + image: ${API_IMAGE:-mtusi-messenger:lab7} + # Портов нет намеренно: единственная точка входа — HAProxy. + env_file: [.env] + environment: + DATABASE_POOL_MAX: ${DATABASE_POOL_MAX:-10} + CACHE_MODE: ${CACHE_MODE:-protected} + CACHE_MISS_DELAY_MS: ${CACHE_MISS_DELAY_MS:-0} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + # Бюджет пробы готовности; LB проверяет ту же ручку с timeout check 500 ms. + HEALTH_TIMEOUT_MS: ${HEALTH_TIMEOUT_MS:-400} + # Дрейн длиннее обнаружения отказа LB (500 ms x fall 2 ≈ 1 s). + DRAIN_DELAY_MS: ${DRAIN_DELAY_MS:-3000} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_access_key + UPLOAD_TIMEOUT_MS: ${UPLOAD_TIMEOUT_MS:-25000} + DIRECT_UPLOAD_URL_TTL_SECONDS: ${DIRECT_UPLOAD_URL_TTL_SECONDS:-300} + ATTACHMENT_SWEEP_GRACE_SECONDS: ${ATTACHMENT_SWEEP_GRACE_SECONDS:-900} + ATTACHMENT_SWEEP_INTERVAL_MS: ${ATTACHMENT_SWEEP_INTERVAL_MS:-60000} + # libvips держит декодируемое изображение в памяти, а не во временном + # файле: /tmp — tmpfs 16 MiB, и изображение ~40 Мп туда не помещается. + VIPS_DISC_THRESHOLD: ${VIPS_DISC_THRESHOLD:-1g} + FAULT_INJECTION_ENABLED: ${FAULT_INJECTION_ENABLED:-0} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_RETRY_BASE_MS: ${JOB_RETRY_BASE_MS:-1000} + JOB_RETRY_MAX_MS: ${JOB_RETRY_MAX_MS:-30000} + BROKER_PUBLISH_TIMEOUT_MS: ${BROKER_PUBLISH_TIMEOUT_MS:-5000} + # lab6: телеметрия. Collector НЕ в depends_on: приложение обязано + # стартовать и работать без телеметрии. + OTEL_SERVICE_NAME: messenger-api + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_SDK_DISABLED: '${OTEL_SDK_DISABLED:-false}' + OTEL_TRACES_SAMPLER_ARG: '${OTEL_TRACES_SAMPLER_ARG:-1}' + OTEL_METRIC_EXPORT_INTERVAL: '${OTEL_METRIC_EXPORT_INTERVAL:-10000}' + SERVICE_VERSION: ${BUILD_ID:-local} + OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} + LOG_LEVEL: ${LOG_LEVEL:-INFO} + OTEL_EXPORTER_OTLP_TIMEOUT: '${OTEL_EXPORTER_OTLP_TIMEOUT:-5000}' + OTEL_BSP_MAX_QUEUE_SIZE: '${OTEL_BSP_MAX_QUEUE_SIZE:-2048}' + OTEL_BSP_MAX_EXPORT_BATCH_SIZE: '${OTEL_BSP_MAX_EXPORT_BATCH_SIZE:-512}' + OTEL_BSP_SCHEDULE_DELAY: '${OTEL_BSP_SCHEDULE_DELAY:-1000}' + OTEL_BLRP_MAX_QUEUE_SIZE: '${OTEL_BLRP_MAX_QUEUE_SIZE:-2048}' + OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: '${OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:-512}' + OTEL_BLRP_SCHEDULE_DELAY: '${OTEL_BLRP_SCHEDULE_DELAY:-1000}' + # Недоступный otel-collector: getaddrinfo по неизвестному имени в сети + # Docker занимает поток libuv на секунды и без запаса голодают DNS- + # запросы к postgres/s3 (проверено: 5-7 с на ENOTFOUND). + UV_THREADPOOL_SIZE: '32' + dns_opt: ['timeout:1', 'attempts:1'] + # Outbox закрывает недоступность брокера: API принимает загрузку и + # отвечает 202 без публикации, relay доставит задание после восстановления. + secrets: + - s3_api_access_key_id + - s3_api_secret_access_key + - broker_url + # Корневая ФС только для чтения: локального файла оригинала на API нет. + read_only: true + tmpfs: ['/tmp:size=16m'] + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: '${API_CPUS_PER_REPLICA:-1.5}' + memory: ${API_MEMORY_PER_REPLICA:-1024m} + stop_grace_period: 20s + restart: unless-stopped + depends_on: + migrate: { condition: service_completed_successfully } + postgres: { condition: service_healthy } + redis: { condition: service_healthy } + s3-init: { condition: service_completed_successfully } + healthcheck: + test: + [ + 'CMD', + 'node', + '-e', + "fetch('http://127.0.0.1:'+ (process.env.APP_PORT||8080) + '/health/ready').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))", + ] + interval: 5s + timeout: 3s + retries: 20 + + # Worker — отдельный процесс без HTTP API. Он читает задания из quorum- + # очереди, держит lease с heartbeat, пишет варианты и коммитит результат в + # PostgreSQL. Остановка worker не блокирует приём загрузок API. + worker: + build: + context: . + dockerfile: Dockerfile + args: + BUILD_ID: ${BUILD_ID:-unknown} + image: ${API_IMAGE:-mtusi-messenger:lab7} + command: ['node', 'dist/worker.main.js'] + env_file: [.env] + environment: + BROKER_URL_FILE: /run/secrets/broker_worker_url + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_worker_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_worker_secret_access_key + VIPS_DISC_THRESHOLD: ${VIPS_DISC_THRESHOLD:-1g} + FAULT_INJECTION_ENABLED: ${FAULT_INJECTION_ENABLED:-0} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-30} + JOB_RETRY_BASE_MS: ${JOB_RETRY_BASE_MS:-1000} + JOB_RETRY_MAX_MS: ${JOB_RETRY_MAX_MS:-30000} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + WORKER_HEALTH_PORT: ${WORKER_HEALTH_PORT:-8081} + BROKER_PUBLISH_TIMEOUT_MS: ${BROKER_PUBLISH_TIMEOUT_MS:-5000} + QUEUED_RECONCILE_GRACE_SECONDS: ${QUEUED_RECONCILE_GRACE_SECONDS:-15} + OUTBOX_RETENTION_SECONDS: ${OUTBOX_RETENTION_SECONDS:-86400} + JOB_EVENTS_RETENTION_SECONDS: ${JOB_EVENTS_RETENTION_SECONDS:-2592000} + # lab6: телеметрия. Collector НЕ в depends_on: приложение обязано + # стартовать и работать без телеметрии. + OTEL_SERVICE_NAME: messenger-worker + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_SDK_DISABLED: '${OTEL_SDK_DISABLED:-false}' + OTEL_TRACES_SAMPLER_ARG: '${OTEL_TRACES_SAMPLER_ARG:-1}' + OTEL_METRIC_EXPORT_INTERVAL: '${OTEL_METRIC_EXPORT_INTERVAL:-10000}' + SERVICE_VERSION: ${BUILD_ID:-local} + OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} + LOG_LEVEL: ${LOG_LEVEL:-INFO} + OTEL_EXPORTER_OTLP_TIMEOUT: '${OTEL_EXPORTER_OTLP_TIMEOUT:-5000}' + OTEL_BSP_MAX_QUEUE_SIZE: '${OTEL_BSP_MAX_QUEUE_SIZE:-2048}' + OTEL_BSP_MAX_EXPORT_BATCH_SIZE: '${OTEL_BSP_MAX_EXPORT_BATCH_SIZE:-512}' + OTEL_BSP_SCHEDULE_DELAY: '${OTEL_BSP_SCHEDULE_DELAY:-1000}' + OTEL_BLRP_MAX_QUEUE_SIZE: '${OTEL_BLRP_MAX_QUEUE_SIZE:-2048}' + OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: '${OTEL_BLRP_MAX_EXPORT_BATCH_SIZE:-512}' + OTEL_BLRP_SCHEDULE_DELAY: '${OTEL_BLRP_SCHEDULE_DELAY:-1000}' + # Недоступный otel-collector: getaddrinfo по неизвестному имени в сети + # Docker занимает поток libuv на секунды и без запаса голодают DNS- + # запросы к postgres/s3 (проверено: 5-7 с на ENOTFOUND). + UV_THREADPOOL_SIZE: '32' + dns_opt: ['timeout:1', 'attempts:1'] + secrets: + - s3_worker_access_key_id + - s3_worker_secret_access_key + - broker_worker_url + read_only: true + tmpfs: ['/tmp:size=16m'] + deploy: + replicas: ${WORKER_REPLICAS:-1} + resources: + limits: + cpus: '${WORKER_CPUS:-1.5}' + memory: ${WORKER_MEMORY:-1280m} + stop_grace_period: 40s + restart: unless-stopped + depends_on: + migrate: { condition: service_completed_successfully } + postgres: { condition: service_healthy } + redis: { condition: service_healthy } + broker: { condition: service_healthy } + broker-init: { condition: service_completed_successfully } + s3-init: { condition: service_completed_successfully } + healthcheck: + test: + [ + 'CMD', + 'node', + '-e', + "fetch('http://127.0.0.1:'+ (process.env.WORKER_HEALTH_PORT||8081) + '/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))", + ] + interval: 5s + timeout: 3s + retries: 20 + start_period: 20s + + haproxy: + # PROMEX (USE_PROMEX=1) проверен `haproxy -vv`; digest закреплён. + image: haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 + ports: + - '${APP_PUBLIC_PORT:-8080}:8080' + # Страница статистики — интерфейс LB, публикуется только на loopback. + - '127.0.0.1:${LB_STATS_PORT:-8404}:8404' + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + deploy: + resources: + limits: + cpus: '${LB_CPUS:-0.25}' + memory: ${LB_MEMORY:-128m} + depends_on: + api: { condition: service_healthy } + + # --- lab6: наблюдаемость. Приложение от этих сервисов не зависит. --- + + # One-shot: владельцы томов Loki/Tempo (UID 10001) без предположений о + # наличии shell/chown в их образах. Использует уже собранный образ приложения. + obs-volumes-init: + image: ${API_IMAGE:-mtusi-messenger:lab7} + pull_policy: never + user: '0:0' + entrypoint: ['node'] + command: + [ + '-e', + "const fs=require('node:fs');for(const p of ['/var/tempo','/loki']){fs.mkdirSync(p,{recursive:true});fs.chownSync(p,10001,10001)}", + ] + volumes: + - tempo-data:/var/tempo + - loki-data:/loki + restart: 'no' + deploy: + resources: + limits: + cpus: '0.25' + memory: 128m + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.128.0@sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7 + command: ['--config=/etc/otelcol-contrib/config.yaml'] + volumes: + - ./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro + deploy: + resources: + limits: + cpus: '${OTELCOL_CPUS:-0.5}' + memory: ${OTELCOL_MEMORY:-256m} + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.4.1@sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d + command: + [ + '--config.file=/etc/prometheus/prometheus.yml', + '--storage.tsdb.path=/prometheus', + '--storage.tsdb.retention.time=7d', + '--web.enable-otlp-receiver', + ] + ports: + - '127.0.0.1:${PROMETHEUS_PORT:-9090}:9090' + volumes: + - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/rules:/etc/prometheus/rules:ro + - prometheus-data:/prometheus + deploy: + resources: + limits: + cpus: '${PROMETHEUS_CPUS:-0.5}' + memory: ${PROMETHEUS_MEMORY:-768m} + restart: unless-stopped + + loki: + image: grafana/loki:3.5.1@sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745 + command: ['-config.file=/etc/loki/loki.yaml'] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro + - loki-data:/loki + depends_on: + obs-volumes-init: { condition: service_completed_successfully } + deploy: + resources: + limits: + cpus: '${LOKI_CPUS:-0.5}' + memory: ${LOKI_MEMORY:-512m} + restart: unless-stopped + + tempo: + image: grafana/tempo:2.8.1@sha256:bc9245fe3da4e63dc4c6862d9c2dad9bcd8be13d0ba4f7705fa6acda4c904d0e + command: ['-config.file=/etc/tempo/tempo.yaml'] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro + - tempo-data:/var/tempo + depends_on: + obs-volumes-init: { condition: service_completed_successfully } + deploy: + resources: + limits: + cpus: '${TEMPO_CPUS:-0.5}' + memory: ${TEMPO_MEMORY:-512m} + restart: unless-stopped + + grafana: + image: grafana/grafana:12.0.2@sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_AUTH_ANONYMOUS_ENABLED: 'false' + GF_USERS_ALLOW_SIGN_UP: 'false' + GF_ANALYTICS_REPORTING_ENABLED: 'false' + GF_ANALYTICS_CHECK_FOR_UPDATES: 'false' + GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: 'false' + secrets: [grafana_admin_password] + ports: + - '127.0.0.1:${GRAFANA_PORT:-3000}:3000' + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/etc/grafana/dashboards:ro + - grafana-data:/var/lib/grafana + depends_on: + - prometheus + - loki + - tempo + deploy: + resources: + limits: + cpus: '${GRAFANA_CPUS:-0.5}' + memory: ${GRAFANA_MEMORY:-384m} + restart: unless-stopped + +secrets: + minio_root_user: { file: ./secrets/minio_root_user } + minio_root_password: { file: ./secrets/minio_root_password } + s3_api_access_key_id: { file: ./secrets/s3_api_access_key_id } + s3_api_secret_access_key: { file: ./secrets/s3_api_secret_access_key } + s3_worker_access_key_id: { file: ./secrets/s3_worker_access_key_id } + s3_worker_secret_access_key: { file: ./secrets/s3_worker_secret_access_key } + broker_url: { file: ./secrets/broker_url } + broker_worker_url: { file: ./secrets/broker_worker_url } + broker_worker_password: { file: ./secrets/broker_worker_password } + rabbitmq_conf: { file: ./secrets/rabbitmq.conf } + grafana_admin_password: { file: ./secrets/grafana_admin_password } + +volumes: + postgres-data: + redis-data: + s3-data: + broker-data: + prometheus-data: + loki-data: + tempo-data: + grafana-data: diff --git a/contracts/extensions.openapi.json b/contracts/extensions.openapi.json new file mode 100644 index 0000000..8dded17 --- /dev/null +++ b/contracts/extensions.openapi.json @@ -0,0 +1,618 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "MTUSI Messenger — расширение lab4: прямая загрузка", + "version": "1.4.0-ext.2", + "description": "Трек 1. Не меняет обязательный контракт openapi.json: POST /api/v1/chats/{chat_id}/attachments остаётся основным путём. Клиент получает presigned PUT URL и отправляет байты прямо в приватный bucket MinIO, минуя API. Подписаны заголовки content-type, content-length и x-amz-checksum-sha256: хранилище само отвергает тело с другим размером (403 SignatureDoesNotMatch) или другим SHA-256 (400 XAmzContentChecksumMismatch), объект при этом не создаётся. TTL URL — DIRECT_UPLOAD_URL_TTL_SECONDS (300 с по умолчанию). Ключ объекта attachments//original раскрывает только UUID вложения; bucket приватный, анонимный доступ запрещён. Незавершённые и отклонённые заявки и их объекты убирает уборщик через ATTACHMENT_SWEEP_GRACE_SECONDS после истечения. Вложение видно участникам чата только после успешного complete (status=ready)." + }, + "servers": [ + { + "url": "http://localhost:8080", + "description": "Локальный учебный стенд" + } + ], + "security": [ + { + "bearerAuth": [] + } + ], + "paths": { + "/api/v1/chats/{chat_id}/attachments/direct-uploads": { + "post": { + "operationId": "initDirectUpload", + "summary": "Заявка на прямую загрузку: вернуть presigned PUT URL", + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateDirectUpload" + } + } + } + }, + "responses": { + "201": { + "description": "Заявка создана; вложение pending и не видно никому, кроме загрузки", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DirectUpload" + } + } + } + }, + "400": { + "description": "Некорректное тело, filename или sha256", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет или неверен токен", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Чат недоступен", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "size_bytes больше 10 MiB", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "415": { + "description": "content_type не image/png и не image/jpeg", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Слишком много незавершённых прямых загрузок пользователя; Retry-After — секунды до освобождения слота (TTL URL).", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Секунды до повтора.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/v1/attachments/{attachment_id}/complete": { + "post": { + "operationId": "completeDirectUpload", + "summary": "Подтвердить прямую загрузку: HEAD объекта, полное чтение и декод изображения", + "description": "Только владелец заявки. Сверяет размер и подписанный SHA-256 объекта (HEAD), затем читает объект целиком: структурная проверка PNG/JPEG и полный декод (повреждённые и усечённые изображения отвергаются, даже если checksum совпадает). При несоответствии объект удаляется, а заявка получает внутренний статус rejected до истечения URL и grace-периода уборщика (повторный PUT по ещё действующему URL не оставит неучтённый объект); повторный complete отклонённой заявки — 404. Если объект ещё не загружен — 409, заявка не меняется. Повторный и параллельный complete готового вложения идемпотентен (200).", + "parameters": [ + { + "name": "attachment_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Вложение готово; тело идентично Attachment из openapi.json", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Attachment" + } + } + } + }, + "400": { + "description": "Некорректный attachment_id", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет или неверен токен", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Заявка не найдена, не принадлежит пользователю или уже удалена", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Объект не получен или не совпадает с заявленным размером/SHA-256", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Слишком много пикселей", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "415": { + "description": "Содержимое не PNG/JPEG или не совпадает с content_type", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Хранилище недоступно или не ответило за S3_REQUEST_TIMEOUT_MS / UPLOAD_TIMEOUT_MS", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Реплика проверяет слишком много изображений одновременно (UPLOAD_MAX_IN_FLIGHT) или у пользователя слишком много одновременных проверок (UPLOAD_MAX_IN_FLIGHT_PER_USER); Retry-After — секунды до повтора.", + "headers": { + "X-Request-Id": { + "description": "Идентификатор запроса.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор реплики.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Секунды до повтора.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "openapi.json#/components/schemas/Error" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "opaque session token" + } + }, + "schemas": { + "CreateDirectUpload": { + "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}$" + } + } + }, + "DirectUpload": { + "type": "object", + "additionalProperties": false, + "required": [ + "attachment_id", + "method", + "url", + "headers", + "expires_at" + ], + "properties": { + "attachment_id": { + "type": "string", + "format": "uuid" + }, + "method": { + "type": "string", + "enum": [ + "PUT" + ] + }, + "url": { + "type": "string", + "format": "uri", + "description": "Presigned URL; содержит подпись, не логировать." + }, + "headers": { + "type": "object", + "description": "Заголовки, которые клиент обязан отправить как есть. Content-Length клиент ставит сам; тело должно быть ровно size_bytes.", + "properties": { + "Content-Type": { + "type": "string" + }, + "x-amz-checksum-sha256": { + "type": "string" + } + }, + "required": [ + "Content-Type", + "x-amz-checksum-sha256" + ] + }, + "expires_at": { + "type": "string", + "format": "date-time" + } + } + } + } + } +} diff --git a/docs/runbooks/MessengerApiHighErrorRate.md b/docs/runbooks/MessengerApiHighErrorRate.md new file mode 100644 index 0000000..6717793 --- /dev/null +++ b/docs/runbooks/MessengerApiHighErrorRate.md @@ -0,0 +1,20 @@ +# MessengerApiHighErrorRate + +**Условие:** `messenger:api_errors:rate1m / messenger:api_requests:rate1m > 0.05` при `messenger:api_requests:rate1m > 0.1`, держится 30 с (warning). +SLI: 5xx / все бизнес-запросы API (маршруты `/health*`, `/internal/*` исключены, 4xx не ошибка). Локальная цель: availability ≥ 99.5% за 5m (`messenger:api_availability:ratio5m`). + +## Источник сигнала +Histogram `http_server_request_duration_seconds_count{job="messenger-api"}` (OTLP, обе реплики); правила — `infra/prometheus/rules/recording.yml`. + +## Диагностика (Grafana: «Messenger: API и worker») +1. **Какие маршруты и коды.** Панель «RPS по маршруту и классу статуса»: 5xx на одном маршруте или на всех. +2. **Балансировщик или приложение.** `sum(rate(haproxy_backend_http_responses_total{proxy="api",code="5xx"}[1m]))` против 5xx API. 503 от HAProxy без 5xx API — нет готовых реплик (`haproxy_backend_active_servers{proxy="api"}`, `/health/ready`). +3. **БД.** `histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket[1m])))`, пул: `db_client_connection_count` (used/idle), `db_client_connection_pending_requests`, wait p95. Рост длительности операций с `error_type` и 5xx — БД (блокировка, недоступность). Откройте трассу 5xx-запроса (Loki: `{service_name="messenger-api"} |= "5"` → поле TraceID): время ушло в CLIENT-span БД. +4. **Handler.** Если SERVER-span длиннее суммы DB-span, а операции БД быстрые — задержка в коде handler (разрыв между дочерними span-ами). +5. **S3/Redis/брокер.** Логи `ObjectStorage`, `OutboxRelay` (WARN) и span-ы ошибок; `rabbitmq_queue_messages_unacked`. + +## Действие +Устранить причину: снять блокировку/вернуть БД (`pg_stat_activity`, `pg_locks`), вернуть недоступную реплику (`scripts/start-replica.sh`), восстановить S3/Redis. Перезапуск реплик — только после выяснения причины. + +## Критерий восстановления +`messenger:api_errors:rate1m` близок к 0 и alert перешёл в resolved; `messenger:api_availability:ratio5m` возвращается ≥ 0.995 (окно 5m даёт запаздывание); очередь задач разобрана (`messenger_jobs_queue_depth` → 0). diff --git a/docs/runbooks/MessengerJobsQueueLagGrowing.md b/docs/runbooks/MessengerJobsQueueLagGrowing.md new file mode 100644 index 0000000..67ed17f --- /dev/null +++ b/docs/runbooks/MessengerJobsQueueLagGrowing.md @@ -0,0 +1,20 @@ +# MessengerJobsQueueLagGrowing + +**Условие:** `max(messenger_jobs_queue_oldest_age_seconds) > 30` и `max(messenger_jobs_queue_depth{state=~"ready|delayed"}) > 0`, держится 30 с (warning). +Это возраст самой старой необработанной задачи (backlog), а не время обработки: рост ряда означает, что задачи не успевают или не обрабатываются. + +## Источник сигнала +Gauge публикуют обе API-реплики из одного snapshot PostgreSQL (`attachment_jobs`), поэтому `max`, не `sum`. Источник истины — БД, не глубина очереди RabbitMQ: задача может ждать в outbox, backoff или под истёкшим lease. + +## Диагностика +1. **Worker жив?** `messenger_worker_jobs_active`, `messenger_worker_jobs_capacity`; `docker compose ps worker`; логи worker. Нет серии — worker остановлен; `active = capacity` — перегружен. +2. **Outbox не публикуется.** `max(messenger_outbox_pending)` и `messenger_outbox_oldest_age_seconds` растут при пустой очереди брокера — проблема в relay/брокере (`rabbitmq_queue_messages_ready`, health брокера). +3. **Брокер.** `rabbitmq_queue_messages_ready` растёт, consumers нет — worker отключён от брокера; `unacked` растёт — задачи зависли в работе. +4. **S3/БД.** Задачи падают в `retry`: `sum by (outcome)(rate(messenger_jobs_processed_total[1m]))`, длительность попытки `messenger_job_duration_seconds`; логи `job.processed` WARN и трассы consumer-span-ов (S3 PUT/DB). +5. **Backoff.** Состояние `delayed` > 0 при `retry` — ожидание повторной попытки, смотрите причину ретраев. + +## Действие +Вернуть остановленный worker (`docker compose --env-file .env up -d worker`), восстановить S3/БД/брокер; для зависших задач — `jobs.cli status ` / `replay` по документации lab5. Не очищайте очередь вручную. + +## Критерий восстановления +`messenger_jobs_queue_oldest_age_seconds` падает ниже 30 с и далее к 0, `messenger_jobs_queue_depth{state=~"ready|delayed|processing"}` → 0, `messenger_outbox_pending` → 0, alert resolved; принятые вложения стали `ready`. diff --git a/infra/README.md b/infra/README.md index 5a39e86..f8008ac 100644 --- a/infra/README.md +++ b/infra/README.md @@ -4,4 +4,39 @@ В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. +## Роли (база lab6) + +| Роль | Service | Образ | Готовность | Volume | Credentials | +| --- | --- | --- | --- | --- | --- | +| API | `api` | сборка `mtusi-messenger:lab7` | `/health/ready` (PostgreSQL, Redis, S3) | — | `secrets/s3_api_*`, `secrets/broker_url` | +| Worker | `worker` | та же сборка, `dist/worker.main.js` | `127.0.0.1:8081/health` (consumer активен) | — | `secrets/s3_worker_*`, `secrets/broker_worker_url` | +| Broker | `broker` | `rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e` | `rabbitmq-diagnostics check_port_connectivity` | `broker-data` | `rabbitmq.conf`; `broker-init` — `broker_worker_password` | +| PostgreSQL | `postgres` | `postgres:16.4-alpine` | `pg_isready` | `postgres-data` | пароль в `.env` / `DATABASE_URL` | +| Redis | `redis` | `redis:7.4.2-alpine` | `redis-cli ping` | `redis-data` | без пароля, только compose-сеть | +| Object storage | `s3` | `minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e` | `mc ready local` | `s3-data` | root — `secrets/minio_root_*` | +| S3 bootstrap | `s3-init` | `minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727` | завершается 0 | — | root + identities API/worker | +| Broker bootstrap | `broker-init` | `rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e` | завершается 0 | `broker-data` (ro, cookie) | `broker_worker_password` | +| Load balancer | `haproxy` | `haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122` | зависит от `api` healthy | — | — | +| OTel Collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.128.0@sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7` | внутренний OTLP 4318 | — | — | +| Prometheus | `prometheus` | `prom/prometheus:v3.4.1@sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d` | loopback `:9090` | `prometheus-data` | — | +| Loki | `loki` | `grafana/loki:3.5.1@sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745` | внутренний `:3100` | `loki-data` | — | +| Tempo | `tempo` | `grafana/tempo:2.8.1@sha256:bc9245fe3da4e63dc4c6862d9c2dad9bcd8be13d0ba4f7705fa6acda4c904d0e` | внутренний `:3200` | `tempo-data` | — | +| Grafana | `grafana` | `grafana/grafana:12.0.2@sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa` | loopback `:3000` | `grafana-data` | `secrets/grafana_admin_password` | +| Obs volumes init | `obs-volumes-init` | сборка `mtusi-messenger:lab7` | завершается 0 | `tempo-data`, `loki-data` | — | + +Политики MinIO разделены: API пишет/удаляет только `staging/*`, читает +`attachments/*` и удаляет только legacy `attachments/*/original`; worker +читает/удаляет `staging/*` и читает/пишет `attachments/*` (без удаления). +Обе роли получают `s3:ListBucket`. Пароль брокера генерируется один раз в +`scripts/init-env.sh` и попадает и в `secrets/broker_url` (amqplib), и в +`secrets/rabbitmq.conf` (сам брокер), поэтому URL и конфигурация не расходятся. + +Bootstrap идемпотентен: `scripts/init-env.sh` создаёт `.env` и секреты, `migrate` +применяет SQL-миграции, `s3-init` создаёт bucket/политики/пользователей, а +producer и consumer объявляют обменники и quorum-очереди при каждом подключении. +Одноразовый `broker-init` (образ RabbitMQ, data volume только для cookie) +создаёт `messenger-worker` и сужает права `messenger`: API публикует и объявляет +топологию, но не читает основную очередь, worker потребляет её. Так схема +сходится и на существующем volume, где `default_permissions` уже не применяются. + Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. diff --git a/infra/grafana/dashboards/messenger-overview.json b/infra/grafana/dashboards/messenger-overview.json new file mode 100644 index 0000000..6a3c37b --- /dev/null +++ b/infra/grafana/dashboards/messenger-overview.json @@ -0,0 +1,1294 @@ +{ + "uid": "messenger-overview", + "title": "Messenger: API и worker", + "schemaVersion": 39, + "version": 1, + "editable": false, + "refresh": "10s", + "time": { + "from": "now-15m", + "to": "now" + }, + "timezone": "utc", + "tags": [ + "messenger", + "lab6" + ], + "templating": { + "list": [] + }, + "annotations": { + "list": [] + }, + "panels": [ + { + "type": "row", + "title": "API (бизнес-запросы; /health* и /internal/* исключены)", + "collapsed": false, + "id": 1, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + } + }, + { + "type": "timeseries", + "title": "RPS по маршруту и классу статуса", + "id": 2, + "description": "rate(http_server_request_duration_seconds_count[1m]) по http_route и классу кода; число запросов — _count гистограммы.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (http_route, status_class)(label_replace(rate(http_server_request_duration_seconds_count{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m]), \"status_class\", \"${1}xx\", \"http_response_status_code\", \"(.)..\"))", + "legendFormat": "{{http_route}} {{status_class}}" + } + ] + }, + { + "type": "timeseries", + "title": "Доля 5xx (1m)", + "id": 3, + "description": "Recording rules: 5xx rate / все бизнес-запросы за 1m; 4xx — не ошибка сервиса. Пусто без трафика (N/A).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + }, + "min": 0, + "max": 1 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger:api_errors:rate1m / messenger:api_requests:rate1m", + "legendFormat": "5xx / бизнес-запросы" + } + ] + }, + { + "type": "stat", + "title": "Availability (5m), цель ≥ 99.5%", + "id": 4, + "description": "1 - 5xx/все бизнес-запросы за 5m (recording rule messenger:api_availability:ratio5m). N/A без трафика.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 4, + "w": 6, + "x": 0, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "messenger:api_availability:ratio5m", + "legendFormat": "" + } + ] + }, + { + "type": "stat", + "title": "Свежие реплики API", + "id": 5, + "description": "Число API-реплик, чей target_info обновлялся за последние 30 с (OTLP-метрики).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 4, + "w": 6, + "x": 6, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "count((time() - timestamp(target_info{job=\"messenger-api\"})) < 30) or vector(0)", + "legendFormat": "" + } + ] + }, + { + "type": "stat", + "title": "HAProxy 5xx, rps", + "id": 6, + "description": "HAProxy backend api: ответы 5xx (включая 503 балансировщика, когда нет готовых узлов).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 4, + "w": 6, + "x": 12, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(haproxy_backend_http_responses_total{proxy=\"api\",code=\"5xx\"}[1m])) or vector(0)", + "legendFormat": "" + } + ] + }, + { + "type": "stat", + "title": "HAProxy: активные серверы", + "id": 7, + "description": "Активные серверы backend api по данным HAProxy PROMEX.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 4, + "w": 6, + "x": 18, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ] + }, + "colorMode": "value" + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "haproxy_backend_active_servers{proxy=\"api\"}", + "legendFormat": "" + } + ] + }, + { + "type": "timeseries", + "title": "Задержка HTTP: общая p50/p95/p99", + "id": 8, + "description": "histogram_quantile по суммированным бакетам всех реплик; перцентили реплик не усредняются.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 13 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by(le)(rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by(le)(rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by(le)(rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m])))", + "legendFormat": "p99" + } + ] + }, + { + "type": "timeseries", + "title": "Задержка HTTP по маршруту p50/p95/p99", + "id": 9, + "description": "То же, с разбивкой по route template.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 13 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by(le,http_route)(rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m])))", + "legendFormat": "p50 {{http_route}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by(le,http_route)(rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m])))", + "legendFormat": "p95 {{http_route}}" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by(le,http_route)(rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\",http_route!~\"/health.*|/internal/.*\"}[1m])))", + "legendFormat": "p99 {{http_route}}" + } + ] + }, + { + "type": "row", + "title": "Worker и задачи", + "collapsed": false, + "id": 10, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 21 + } + }, + { + "type": "timeseries", + "title": "Задачи по outcome", + "id": 11, + "description": "messenger_jobs_processed_total по фактическому outcome (succeeded, retry, failed, ...), задач/с.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 22 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (outcome)(rate(messenger_jobs_processed_total[1m]))", + "legendFormat": "{{outcome}}" + } + ] + }, + { + "type": "timeseries", + "title": "Длительность попытки задачи p50/p95/p99", + "id": 12, + "description": "От claim до commit одной попытки; не включает ожидание в очереди.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 22 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by(le)(rate(messenger_job_duration_seconds_bucket[1m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by(le)(rate(messenger_job_duration_seconds_bucket[1m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by(le)(rate(messenger_job_duration_seconds_bucket[1m])))", + "legendFormat": "p99" + } + ] + }, + { + "type": "timeseries", + "title": "Time-to-ready p50/p95/p99", + "id": 13, + "description": "От durable acceptance (created_at задачи) до commit ready; включает очередь, ретраи и backoff. Измеряется на commit, до ACK и cleanup.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 30 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by(le)(rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by(le)(rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by(le)(rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))", + "legendFormat": "p99" + } + ] + }, + { + "type": "timeseries", + "title": "Worker: занято / ёмкость", + "id": 14, + "description": "Задач в работе против WORKER_CONCURRENCY; показатели не суммируются.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 30 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(messenger_worker_jobs_active)", + "legendFormat": "active" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_worker_jobs_capacity)", + "legendFormat": "capacity (WORKER_CONCURRENCY)" + } + ] + }, + { + "type": "row", + "title": "Очередь и outbox (snapshot PostgreSQL, max по репликам)", + "collapsed": false, + "id": 15, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 38 + } + }, + { + "type": "timeseries", + "title": "Глубина очереди по состоянию", + "id": 16, + "description": "Незавершённые задачи по state; обе реплики публикуют одно значение, поэтому max, а не sum.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 39 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (state)(messenger_jobs_queue_depth)", + "legendFormat": "{{state}}" + } + ] + }, + { + "type": "timeseries", + "title": "Возраст самой старой задачи", + "id": 17, + "description": "Возраст ожидания backlog (alert MessengerJobsQueueLagGrowing: > 30 с), не время обработки.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 39 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_jobs_queue_oldest_age_seconds)", + "legendFormat": "oldest job age" + } + ] + }, + { + "type": "timeseries", + "title": "Outbox: ожидающие и возраст", + "id": 18, + "description": "Неопубликованные записи outbox (доступные к публикации) и возраст старейшей.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 47 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_outbox_pending)", + "legendFormat": "pending (шт.)" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(messenger_outbox_oldest_age_seconds)", + "legendFormat": "oldest age (с)" + } + ] + }, + { + "type": "timeseries", + "title": "RabbitMQ: ready / unacked", + "id": 19, + "description": "Агрегат по очередям, rabbitmq_prometheus (порт 15692, внутри сети).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 47 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rabbitmq_queue_messages_ready)", + "legendFormat": "ready" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rabbitmq_queue_messages_unacked)", + "legendFormat": "unacked" + } + ] + }, + { + "type": "row", + "title": "PostgreSQL и процессы", + "collapsed": false, + "id": 20, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 55 + } + }, + { + "type": "timeseries", + "title": "Пул БД: used / idle / max", + "id": 21, + "description": "Соединения основного пула по репликам.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 56 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (db_client_connection_state, instance)(db_client_connection_count{job=~\"messenger-.*\",db_client_connection_pool_name=\"main\"})", + "legendFormat": "{{db_client_connection_state}} {{instance}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (instance)(db_client_connection_max{job=~\"messenger-.*\",db_client_connection_pool_name=\"main\"})", + "legendFormat": "max {{instance}}" + } + ] + }, + { + "type": "timeseries", + "title": "Пул БД: ожидающие запросы и wait p95", + "id": 22, + "description": "Очередь на получение соединения и p95 ожидания (секунды).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 56 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (instance)(db_client_connection_pending_requests{job=~\"messenger-.*\"})", + "legendFormat": "pending {{instance}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le)(rate(db_client_connection_wait_time_seconds_bucket{job=~\"messenger-.*\"}[1m])))", + "legendFormat": "wait p95 (с)" + } + ] + }, + { + "type": "timeseries", + "title": "Операция БД p95 по db_operation_name", + "id": 23, + "description": "p95 длительности операций БД по типу операции.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 64 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket{job=~\"messenger-.*\"}[1m])))", + "legendFormat": "{{db_operation_name}}" + } + ] + }, + { + "type": "timeseries", + "title": "CPU процессов (ядра)", + "id": 24, + "description": "rate(process_cpu_time_seconds_total): 1.0 = одно логическое ядро.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 64 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (job, instance)(rate(process_cpu_time_seconds_total{job=~\"messenger-.*\"}[1m]))", + "legendFormat": "{{job}} {{instance}}" + } + ] + }, + { + "type": "timeseries", + "title": "RAM процессов", + "id": 25, + "description": "Resident memory процесса и использованная куча V8.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 72 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "process_memory_usage_bytes{job=~\"messenger-.*\"}", + "legendFormat": "{{job}} {{instance}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "v8js_memory_heap_used_bytes{job=~\"messenger-.*\"}", + "legendFormat": "heap {{job}} {{instance}}" + } + ] + }, + { + "type": "timeseries", + "title": "Event loop delay p99", + "id": 26, + "description": "Задержка event loop (p99 окна, секунды).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 72 + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "nodejs_eventloop_delay_p99_seconds{job=~\"messenger-.*\"}", + "legendFormat": "{{job}} {{instance}}" + } + ] + }, + { + "type": "row", + "title": "Логи (переход в трассу по TraceID)", + "collapsed": false, + "id": 27, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 80 + } + }, + { + "type": "logs", + "title": "Логи API", + "id": 28, + "description": "Структурные логи; trace_id — structured metadata, поле TraceID ведёт в Tempo.", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "h": 10, + "w": 12, + "x": 0, + "y": 81 + }, + "options": { + "showTime": true, + "wrapLogMessage": true, + "sortOrder": "Descending", + "enableLogDetails": true + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{service_name=\"messenger-api\"}", + "queryType": "range" + } + ] + }, + { + "type": "logs", + "title": "Логи worker", + "id": 29, + "description": "Структурные логи worker; trace_id ведёт в Tempo.", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "h": 10, + "w": 12, + "x": 12, + "y": 81 + }, + "options": { + "showTime": true, + "wrapLogMessage": true, + "sortOrder": "Descending", + "enableLogDetails": true + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "expr": "{service_name=\"messenger-worker\"}", + "queryType": "range" + } + ] + } + ] +} diff --git a/infra/grafana/dashboards/messenger-telemetry.json b/infra/grafana/dashboards/messenger-telemetry.json new file mode 100644 index 0000000..eb31d58 --- /dev/null +++ b/infra/grafana/dashboards/messenger-telemetry.json @@ -0,0 +1,632 @@ +{ + "uid": "messenger-telemetry", + "title": "Messenger: telemetry pipeline", + "schemaVersion": 39, + "version": 1, + "editable": false, + "refresh": "10s", + "time": { + "from": "now-15m", + "to": "now" + }, + "timezone": "utc", + "tags": [ + "messenger", + "lab6" + ], + "templating": { + "list": [] + }, + "annotations": { + "list": [] + }, + "panels": [ + { + "type": "row", + "title": "Collector", + "collapsed": false, + "id": 1, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + } + }, + { + "type": "timeseries", + "title": "Collector: принято", + "id": 2, + "description": "Элементов, принятых OTLP-receiver, в секунду (не байты).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "suffix:items/s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_accepted_spans[1m]))", + "legendFormat": "spans" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_accepted_log_records[1m]))", + "legendFormat": "log records" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_receiver_accepted_metric_points[1m]))", + "legendFormat": "metric points" + } + ] + }, + { + "type": "timeseries", + "title": "Collector: отправлено", + "id": 3, + "description": "Элементов, успешно отправленных exporter-ами в backend.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "suffix:items/s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_sent_spans[1m]))", + "legendFormat": "spans" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_sent_log_records[1m]))", + "legendFormat": "log records" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(otelcol_exporter_sent_metric_points[1m]))", + "legendFormat": "metric points" + } + ] + }, + { + "type": "timeseries", + "title": "Collector: ошибки отправки и постановки в очередь", + "id": 4, + "description": "Потери на выходе Collector. Нулевые серии могут отсутствовать до первой ошибки.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "suffix:items/s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (exporter)(rate(otelcol_exporter_send_failed_spans[1m]))", + "legendFormat": "send_failed spans {{exporter}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (exporter)(rate(otelcol_exporter_send_failed_log_records[1m]))", + "legendFormat": "send_failed logs {{exporter}}" + }, + { + "refId": "C", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (exporter)(rate(otelcol_exporter_send_failed_metric_points[1m]))", + "legendFormat": "send_failed metrics {{exporter}}" + }, + { + "refId": "D", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (exporter)(rate(otelcol_exporter_enqueue_failed_spans[1m]))", + "legendFormat": "enqueue_failed spans {{exporter}}" + }, + { + "refId": "E", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (exporter)(rate(otelcol_exporter_enqueue_failed_log_records[1m]))", + "legendFormat": "enqueue_failed logs {{exporter}}" + }, + { + "refId": "F", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (exporter)(rate(otelcol_exporter_enqueue_failed_metric_points[1m]))", + "legendFormat": "enqueue_failed metrics {{exporter}}" + } + ] + }, + { + "type": "timeseries", + "title": "Collector: очередь / ёмкость", + "id": 5, + "description": "Очередь sending_queue в запросах (batch), не в spans.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 9 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (exporter)(otelcol_exporter_queue_size)", + "legendFormat": "size {{exporter}}" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (exporter)(otelcol_exporter_queue_capacity)", + "legendFormat": "capacity {{exporter}}" + } + ] + }, + { + "type": "timeseries", + "title": "Collector: RSS", + "id": 6, + "description": "Resident set size процесса Collector; лимит контейнера 256 MiB, memory_limiter 204 MiB.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 17 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "otelcol_process_memory_rss", + "legendFormat": "RSS" + } + ] + }, + { + "type": "timeseries", + "title": "Приложение: экспорт телеметрии (items)", + "id": 7, + "description": "Элементов, дошедших до OTLP-exporter приложения (traces/logs). Не учёт метрик и не все pre-export drops.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 17 + }, + "fieldConfig": { + "defaults": { + "unit": "suffix:items/s", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (signal, outcome)(rate(messenger_telemetry_export_items_total[1m]))", + "legendFormat": "{{signal}} {{outcome}}" + } + ] + }, + { + "type": "row", + "title": "Backend-хранилища", + "collapsed": false, + "id": 8, + "panels": [], + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 25 + } + }, + { + "type": "timeseries", + "title": "Loki / Tempo: up", + "id": 9, + "description": "1 — scrape успешен.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 26 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "up{job=~\"loki|tempo\"}", + "legendFormat": "{{job}}" + } + ] + }, + { + "type": "timeseries", + "title": "Loki / Tempo: ingest", + "id": 10, + "description": "Байт, принятых distributor-ами, в секунду.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 26 + }, + "fieldConfig": { + "defaults": { + "unit": "Bps", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(loki_distributor_bytes_received_total[1m]))", + "legendFormat": "loki" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(tempo_distributor_bytes_received_total[1m]))", + "legendFormat": "tempo" + } + ] + }, + { + "type": "timeseries", + "title": "Prometheus: размер TSDB", + "id": 11, + "description": "Блоки и WAL локального TSDB (retention 7d).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 34 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 1, + "fillOpacity": 8, + "showPoints": "never" + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "prometheus_tsdb_storage_blocks_bytes", + "legendFormat": "blocks" + }, + { + "refId": "B", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "prometheus_tsdb_wal_storage_size_bytes", + "legendFormat": "wal" + } + ] + }, + { + "type": "table", + "title": "Состояние правил (ALERTS)", + "id": 12, + "description": "Pending/firing alerts из метрики ALERTS. Отсутствие строк означает, что нет pending/firing при загруженных rules (правила проверяются через /api/v1/rules).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 34 + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "options": { + "showHeader": true + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "ALERTS{alertname=~\"Messenger.*\"}", + "instant": true, + "format": "table" + } + ], + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "job": true, + "Value": true + } + } + } + ] + } + ] +} diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..6b69675 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,12 @@ +apiVersion: 1 + +providers: + - name: messenger-lab7 + orgId: 1 + folder: Messenger lab7 + type: file + allowUiUpdates: false + disableDeletion: true + updateIntervalSeconds: 30 + options: + path: /etc/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..b03143f --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,48 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + jsonData: + manageAlerts: false + timeInterval: 10s + + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + derivedFields: + # trace_id — structured metadata записи (не текст строки). + - name: TraceID + matcherType: label + matcherRegex: trace_id + datasourceUid: tempo + url: '$${__value.raw}' + + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + tags: + - { key: service.name, value: service_name } + spanStartTimeShift: '-2m' + spanEndTimeShift: '2m' + filterByTraceID: false + filterBySpanID: false + customQuery: true + query: '{$${__tags}} | trace_id="$${__span.traceId}"' + nodeGraph: + enabled: true diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 0000000..08fe064 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,63 @@ +# HAProxy — единственная точка входа lab4. +# +# Проверка готовности backend: GET /health/ready — та же ручка, что у +# healthcheck контейнера. Реплика, потерявшая обязательную зависимость (свой +# путь к общей БД или Redis), исключается из ротации, и трафик уходит на +# здоровые; при отказе общей зависимости неготовыми становятся все реплики, и +# клиент получает 503 от балансировщика — это честный признак того, что +# готовых узлов нет. +# Проба с зависимостями ограничена на стороне API: бюджет пробы 400 ms (общий +# дедлайн /health/ready, проверка БД — по отдельному соединению, не из общего +# пула) меньше timeout check 500 ms, который равен интервалу inter. Обнаружение +# отказа (inter 500 ms × fall 2 ≈ 1 s) короче окна дреина API +# (DRAIN_DELAY_MS=3000): узел уходит из ротации раньше, чем перестаёт +# обслуживать. +# +# Реплики не перечислены статически: server-template + DNS Docker обновляет +# список адресов при масштабировании (init-addr none — стартовать без адресов +# и дождаться DNS, а не падать при пустом ответе). + +global + maxconn 8192 + log stdout format raw local0 + +defaults + mode http + option httplog + timeout connect 500ms + timeout client 35s + timeout server 30s + timeout queue 2s + retries 3 + option redispatch + retry-on conn-failure + +resolvers docker + nameserver dns1 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 500ms + hold nx 500ms + hold other 1s + +frontend http + bind *:8080 + default_backend api + +backend api + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + timeout check 500ms + default-server check inter 500ms fastinter 250ms downinter 1s fall 2 rise 2 maxconn 200 + server-template api 1-8 api:8080 resolvers docker init-addr none + +listen stats + bind *:8404 + stats enable + stats uri /stats + stats refresh 1s + stats show-legends + # Prometheus-экспортёр HAProxy (PROMEX); scrape: haproxy:8404/metrics. + http-request use-service prometheus-exporter if { path /metrics } diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 0000000..21f5e48 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,48 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + +common: + path_prefix: /loki + replication_factor: 1 + ring: + kvstore: + store: inmemory + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + +schema_config: + configs: + - from: 2025-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +ingester: + wal: + dir: /loki/wal + +limits_config: + allow_structured_metadata: true + retention_period: 168h + +distributor: + otlp_config: + default_resource_attributes_as_index_labels: + - service.name + - deployment.environment.name + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + +analytics: + reporting_enabled: false diff --git a/infra/minio/bootstrap.sh b/infra/minio/bootstrap.sh new file mode 100755 index 0000000..27e5024 --- /dev/null +++ b/infra/minio/bootstrap.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# Идемпотентная инициализация MinIO: приватный bucket, ограниченная политика и +# отдельный пользователь API. Выполняется в контейнере minio/mc. +set -eu + +IFS= read -r root_user < /run/secrets/minio_root_user || [ -n "$root_user" ] +IFS= read -r root_password < /run/secrets/minio_root_password || [ -n "$root_password" ] +IFS= read -r api_key < /run/secrets/s3_api_access_key_id || [ -n "$api_key" ] +IFS= read -r api_secret < /run/secrets/s3_api_secret_access_key || [ -n "$api_secret" ] +IFS= read -r worker_key < /run/secrets/s3_worker_access_key_id || [ -n "$worker_key" ] +IFS= read -r worker_secret < /run/secrets/s3_worker_secret_access_key || [ -n "$worker_secret" ] +bucket="${S3_BUCKET:?}" + +export MC_CONFIG_DIR=/tmp/.mc +export MC_HOST_stand="http://${root_user}:${root_password}@s3:9000" + +mc mb --ignore-existing "stand/$bucket" +mc anonymous set none "stand/$bucket" + +# The API owns the staging prefix only: it writes the accepted upload there and +# can remove it after the worker commits the result. The final prefix is read +# for variant/original downloads and legacy lab4 originals, but never written. +printf '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/attachments/*"]},{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/attachments/*/original"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::%s"],"Condition":{"StringLike":{"s3:prefix":["staging/*","attachments/*"]}}}]}' "$bucket" "$bucket" "$bucket" "$bucket" > /tmp/messenger-api-policy.json + +# The worker reads staging, writes the final original and variants, and removes +# staging after a safe commit. It never deletes the final prefix. +printf '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":["arn:aws:s3:::%s/attachments/*"]},{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/attachments/*/v*/*"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::%s"],"Condition":{"StringLike":{"s3:prefix":["staging/*","attachments/*"]}}}]}' "$bucket" "$bucket" "$bucket" "$bucket" > /tmp/messenger-worker-policy.json + +ensure_user() { + name=$1 + secret=$2 + if ! mc admin user info stand "$name" >/dev/null 2>&1; then + mc admin user add stand "$name" "$secret" + fi +} + +# `mc admin policy create` does not overwrite and a policy attached to a user +# cannot be removed. Detach, remove and recreate makes the script converge on +# the current policy even when the stand volume predates lab5. +install_policy() { + name=$1 + file=$2 + user=$3 + if mc admin policy info stand "$name" >/dev/null 2>&1; then + mc admin policy detach stand "$name" --user "$user" >/dev/null 2>&1 || true + mc admin policy remove stand "$name" >/dev/null 2>&1 || true + fi + mc admin policy create stand "$name" "$file" + mc admin policy attach stand "$name" --user "$user" +} + +ensure_user "$api_key" "$api_secret" +ensure_user "$worker_key" "$worker_secret" + +install_policy messenger-api /tmp/messenger-api-policy.json "$api_key" +install_policy messenger-worker /tmp/messenger-worker-policy.json "$worker_key" + +echo "bootstrap ok: bucket=$bucket policies=messenger-api,messenger-worker" diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..c7ccd64 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,109 @@ +# OpenTelemetry Collector (contrib 0.128.0): единственная OTLP-точка входа. +# traces -> Tempo, metrics -> Prometheus OTLP receiver, logs -> Loki OTLP. +# Порт 4318 доступен только внутри compose-сети (наружу не публикуется). +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + # Бэкпрешер: при приближении к лимиту отказывает приёмнику (SDK ретраит/теряет). + # Для контейнера 256 MiB: limit_mib=floor(256*0.8), spike=floor(limit*0.2). + memory_limiter: + check_interval: 1s + limit_mib: 204 + spike_limit_mib: 40 + # Второй рубеж: секретные атрибуты. Тело лога защищает redaction приложения. + attributes/scrub: + actions: + - { key: authorization, action: delete } + - { key: Authorization, action: delete } + - { key: http.request.header.authorization, action: delete } + - { key: cookie, action: delete } + - { key: Cookie, action: delete } + - { key: http.request.header.cookie, action: delete } + - { key: password, action: delete } + - { key: token, action: delete } + - { key: session_token, action: delete } + - { key: http.request.body, action: delete } + - { key: http.response.body, action: delete } + - { key: url.full, action: delete } + - { key: http.url, action: delete } + batch: + timeout: 1s + send_batch_size: 512 + send_batch_max_size: 1024 + +exporters: + otlp/tempo: + endpoint: tempo:4317 + tls: + insecure: true + timeout: 5s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 128 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s + otlphttp/loki: + endpoint: http://loki:3100/otlp + timeout: 5s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 128 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s + otlphttp/prometheus: + # Prometheus сам обслуживает /api/v1/otlp/v1/metrics. + endpoint: http://prometheus:9090/api/v1/otlp + timeout: 5s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 128 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 30s + +service: + extensions: [health_check] + telemetry: + metrics: + level: detailed + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + without_scope_info: true + without_units: true + without_type_suffix: true + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, batch] + exporters: [otlp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, batch] + exporters: [otlphttp/prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, attributes/scrub, batch] + exporters: [otlphttp/loki] diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 0000000..cce8b65 --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,34 @@ +global: + scrape_interval: 10s + evaluation_interval: 10s + scrape_timeout: 5s + +rule_files: + - /etc/prometheus/rules/*.yml + +# Метрики API/worker приходят только по OTLP (--web.enable-otlp-receiver); +# /internal/metrics — legacy JSON, не exposition-формат, и не скрейпится. +otlp: + translation_strategy: UnderscoreEscapingWithSuffixes + promote_resource_attributes: + - service.version + - deployment.environment.name + +storage: + tsdb: + out_of_order_time_window: 10m + +scrape_configs: + - job_name: prometheus + static_configs: [{ targets: ['localhost:9090'] }] + - job_name: otel-collector + static_configs: [{ targets: ['otel-collector:8888'] }] + - job_name: haproxy + metrics_path: /metrics + static_configs: [{ targets: ['haproxy:8404'] }] + - job_name: rabbitmq + static_configs: [{ targets: ['broker:15692'] }] + - job_name: loki + static_configs: [{ targets: ['loki:3100'] }] + - job_name: tempo + static_configs: [{ targets: ['tempo:3200'] }] diff --git a/infra/prometheus/rules/alerts.yml b/infra/prometheus/rules/alerts.yml new file mode 100644 index 0000000..86b27a5 --- /dev/null +++ b/infra/prometheus/rules/alerts.yml @@ -0,0 +1,21 @@ +groups: + - name: messenger-alerts + rules: + - alert: MessengerApiHighErrorRate + expr: messenger:api_errors:rate1m / messenger:api_requests:rate1m > 0.05 and messenger:api_requests:rate1m > 0.1 + for: 30s + labels: + severity: warning + annotations: + summary: Доля 5xx бизнес-запросов API выше 5% дольше 30 с + description: Серверные ошибки (5xx, без 4xx и без /health*, /internal/*) превышают 5% от бизнес-запросов при трафике выше 0.1 rps. Различите БД, балансировщик и handler по трассам и db_client_operation_duration_seconds. + runbook_url: docs/runbooks/MessengerApiHighErrorRate.md + - alert: MessengerJobsQueueLagGrowing + expr: max(messenger_jobs_queue_oldest_age_seconds) > 30 and max(messenger_jobs_queue_depth{state=~"ready|delayed"}) > 0 + for: 30s + labels: + severity: warning + annotations: + summary: Самая старая необработанная задача ждёт дольше 30 с, очередь не пуста + description: Backlog задач вложений устойчиво стареет. Это возраст ожидания, а не время обработки; проверьте worker, брокер, outbox, S3 и БД. + runbook_url: docs/runbooks/MessengerJobsQueueLagGrowing.md diff --git a/infra/prometheus/rules/recording.yml b/infra/prometheus/rules/recording.yml new file mode 100644 index 0000000..5a4ab7f --- /dev/null +++ b/infra/prometheus/rules/recording.yml @@ -0,0 +1,18 @@ +# SLI доступности API: good = любой бизнес-запрос, кроме 5xx; знаменатель — все +# бизнес-запросы (маршруты /health* и /internal/* исключены). 4xx — good. +# Учебная цель стенда: availability >= 99.5% в скользящем окне 5m. +# Без трафика отношение отсутствует (N/A), а не искусственные 100%. +groups: + - name: messenger-sli + interval: 10s + rules: + - record: messenger:api_requests:rate1m + expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*"}[1m])) + - record: messenger:api_errors:rate1m + expr: (sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*",http_response_status_code=~"5.."}[1m])) or vector(0)) + - record: messenger:api_requests:rate5m + expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*"}[5m])) + - record: messenger:api_errors:rate5m + expr: (sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*",http_response_status_code=~"5.."}[5m])) or vector(0)) + - record: messenger:api_availability:ratio5m + expr: 1 - (messenger:api_errors:rate5m / (messenger:api_requests:rate5m > 0)) diff --git a/infra/prometheus/tests/alerts.test.yml b/infra/prometheus/tests/alerts.test.yml new file mode 100644 index 0000000..abc05eb --- /dev/null +++ b/infra/prometheus/tests/alerts.test.yml @@ -0,0 +1,100 @@ +rule_files: + - ../rules/recording.yml + - ../rules/alerts.yml + +evaluation_interval: 10s + +tests: + # Нормальная нагрузка с 4xx (клиентские ошибки) не поднимает error alert. + - interval: 10s + input_series: + - series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="201"}' + values: '0+100x60' + - series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="404"}' + values: '0+30x60' + alert_rule_test: + - eval_time: 3m + alertname: MessengerApiHighErrorRate + exp_alerts: [] + - eval_time: 9m + alertname: MessengerApiHighErrorRate + exp_alerts: [] + promql_expr_test: + - expr: messenger:api_availability:ratio5m + eval_time: 9m + exp_samples: + - labels: 'messenger:api_availability:ratio5m' + value: 1 + + # Устойчивые 5xx: pending -> firing -> восстановление снимает alert. + - interval: 10s + input_series: + - series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="201"}' + values: '0+100x60' + - series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="500"}' + values: '0x12 0+30x18 540x30' + # health-пробы с 5xx не считаются. + - series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/health/ready",http_response_status_code="503"}' + values: '0+100x60' + alert_rule_test: + - eval_time: 90s + alertname: MessengerApiHighErrorRate + exp_alerts: [] + - eval_time: 2m20s + alertname: MessengerApiHighErrorRate + exp_alerts: [] + - eval_time: 3m + alertname: MessengerApiHighErrorRate + exp_alerts: + - exp_labels: + severity: warning + exp_annotations: + summary: Доля 5xx бизнес-запросов API выше 5% дольше 30 с + description: Серверные ошибки (5xx, без 4xx и без /health*, /internal/*) превышают 5% от бизнес-запросов при трафике выше 0.1 rps. Различите БД, балансировщик и handler по трассам и db_client_operation_duration_seconds. + runbook_url: docs/runbooks/MessengerApiHighErrorRate.md + - eval_time: 9m + alertname: MessengerApiHighErrorRate + exp_alerts: [] + + # Две реплики публикуют одинаковый snapshot: max(), а не sum(), иначе 2x20=40>30. + - interval: 10s + input_series: + - series: 'messenger_jobs_queue_oldest_age_seconds{job="messenger-api",instance="a"}' + values: '20x30' + - series: 'messenger_jobs_queue_oldest_age_seconds{job="messenger-api",instance="b"}' + values: '20x30' + - series: 'messenger_jobs_queue_depth{job="messenger-api",instance="a",state="ready"}' + values: '5x30' + - series: 'messenger_jobs_queue_depth{job="messenger-api",instance="b",state="ready"}' + values: '5x30' + alert_rule_test: + - eval_time: 4m + alertname: MessengerJobsQueueLagGrowing + exp_alerts: [] + + # Краткий всплеск возраста короче for не даёт firing; устойчивый — даёт и снимается. + - interval: 10s + input_series: + - series: 'messenger_jobs_queue_oldest_age_seconds{job="messenger-api",instance="a"}' + values: '5x6 40 40 5x12 40x12 5x30' + - series: 'messenger_jobs_queue_depth{job="messenger-api",instance="a",state="ready"}' + values: '3x60' + alert_rule_test: + - eval_time: 1m20s + alertname: MessengerJobsQueueLagGrowing + exp_alerts: [] + - eval_time: 3m + alertname: MessengerJobsQueueLagGrowing + exp_alerts: [] + - eval_time: 4m30s + alertname: MessengerJobsQueueLagGrowing + exp_alerts: + - exp_labels: + severity: warning + exp_annotations: + summary: Самая старая необработанная задача ждёт дольше 30 с, очередь не пуста + description: Backlog задач вложений устойчиво стареет. Это возраст ожидания, а не время обработки; проверьте worker, брокер, outbox, S3 и БД. + runbook_url: docs/runbooks/MessengerJobsQueueLagGrowing.md + - eval_time: 7m + alertname: MessengerJobsQueueLagGrowing + exp_alerts: [] diff --git a/infra/rabbitmq/enabled_plugins b/infra/rabbitmq/enabled_plugins new file mode 100644 index 0000000..7124839 --- /dev/null +++ b/infra/rabbitmq/enabled_plugins @@ -0,0 +1 @@ +[rabbitmq_prometheus]. diff --git a/infra/rabbitmq/init-worker.sh b/infra/rabbitmq/init-worker.sh new file mode 100755 index 0000000..fc50bba --- /dev/null +++ b/infra/rabbitmq/init-worker.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Runs as a one-shot sidecar against rabbit@broker. The broker data volume is +# mounted read-only only to share the Erlang cookie; no queue data is modified. +set -eu + +password=$(cat /run/secrets/broker_worker_password) +configure='^(attachments\.jobs|attachments\.process|attachments\.dlx|attachments\.process\.dlq)$' +write='^attachments\.(jobs|process|dlx|process\.dlq)$' +all_read='^attachments\.(jobs|process|dlx|process\.dlq)$' +api_read='^attachments\.(jobs|dlx)$' + +if ! rabbitmqctl -n rabbit@broker -p messenger add_user messenger-worker "$password" 2>/dev/null; then + rabbitmqctl -n rabbit@broker -q -p messenger change_password messenger-worker "$password" +fi +rabbitmqctl -n rabbit@broker -q -p messenger set_permissions messenger-worker \ + "$configure" "$write" "$all_read" +# The API may publish and declare the topology, but must not consume the job +# queue. The worker identity is used by the worker process. +rabbitmqctl -n rabbit@broker -q -p messenger set_permissions messenger \ + "$configure" "$write" "$api_read" +echo "broker init ok: publisher and consumer identities separated" diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 0000000..c570d71 --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,24 @@ +server: + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + +compactor: + compaction: + block_retention: 168h + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + +usage_report: + reporting_enabled: false diff --git a/scripts/app-e2e.sh b/scripts/app-e2e.sh new file mode 100755 index 0000000..3931d1c --- /dev/null +++ b/scripts/app-e2e.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Black-box набор приложения (app/test/*.e2e-spec.ts) против поднятого стенда. +# Требует loopback-портов PostgreSQL, Redis и MinIO из compose.yaml. +set -eu + +env_file="${COMPOSE_ENV_FILE:-.env}" +compose_dir="$(pwd)" +# shellcheck disable=SC1090 +set -a +. "./$env_file" +set +a + +export API_BASE_URL="${API_BASE_URL:-http://127.0.0.1:${APP_PUBLIC_PORT:-8080}}" +export DATABASE_URL="postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in $env_file}@127.0.0.1:${POSTGRES_PUBLISHED_PORT:-5432}/${POSTGRES_DB:-messenger}" +export REDIS_URL="redis://127.0.0.1:${REDIS_PUBLISHED_PORT:-6379}" +export E2E_S3_PUBLIC_ENDPOINT="${S3_PUBLIC_ENDPOINT:-http://localhost:9000}" +export E2E_S3_BUCKET="${S3_BUCKET:-messenger-attachments}" +export E2E_COMPOSE_DIR="$compose_dir" +export E2E_COMPOSE_ENV_FILE="$env_file" + +cd "$(dirname "$0")/../app" +exec npm run test:e2e -- "$@" diff --git a/scripts/init-env.sh b/scripts/init-env.sh new file mode 100755 index 0000000..1656054 --- /dev/null +++ b/scripts/init-env.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# Идемпотентно создаёт .env и secrets/* для локального стенда. Значения не печатает. +set -eu +cd "$(dirname "$0")/.." + +if [ ! -f .env ]; then + ( + umask 077 + pg=$(openssl rand -hex 24) + mt=$(openssl rand -hex 16) + sed \ + -e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${pg}|" \ + -e "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:${pg}@postgres:5432/messenger|" \ + -e "s|^METRICS_TOKEN=.*|METRICS_TOKEN=${mt}|" \ + .env.example > .env + ) + echo "created .env" +else + echo "kept .env" +fi + +mkdir -p secrets +chmod 700 secrets + +write_secret() { + name=$1 + value=$2 + if [ -s "secrets/$name" ]; then + echo "kept secrets/$name" + return + fi + (umask 133; printf '%s' "$value" > "secrets/$name") + chmod 0644 "secrets/$name" + echo "created secrets/$name" +} + +write_secret minio_root_user "root-$(openssl rand -hex 6)" +write_secret minio_root_password "$(openssl rand -hex 24)" +write_secret s3_api_access_key_id "api-$(openssl rand -hex 8)" +write_secret s3_api_secret_access_key "$(openssl rand -hex 24)" +write_secret s3_worker_access_key_id "worker-$(openssl rand -hex 8)" +write_secret s3_worker_secret_access_key "$(openssl rand -hex 24)" +write_secret grafana_admin_password "$(openssl rand -hex 24)" + +if [ -s secrets/broker_worker_password ] && [ -s secrets/broker_worker_url ]; then + echo "kept secrets/broker_worker_password secrets/broker_worker_url" +else + wp=$(openssl rand -hex 24) + (umask 133; printf '%s' "$wp" > secrets/broker_worker_password) + chmod 0644 secrets/broker_worker_password + (umask 133; printf '%s' "amqp://messenger-worker:${wp}@broker:5672/messenger" > secrets/broker_worker_url) + chmod 0644 secrets/broker_worker_url + echo "created secrets/broker_worker_password secrets/broker_worker_url" +fi + +# Broker password lives in one place and is rendered into both files, so the +# URL used by the app and the RabbitMQ config cannot drift apart. +if [ -s secrets/broker_url ] && [ -s secrets/rabbitmq.conf ]; then + echo "kept secrets/broker_url secrets/rabbitmq.conf" +else + bp=$(openssl rand -hex 24) + (umask 133; printf '%s' "amqp://messenger:${bp}@broker:5672/messenger" > secrets/broker_url) + chmod 0644 secrets/broker_url + ( + umask 133 + { + printf 'default_vhost = messenger\n' + printf 'default_user = messenger\n' + printf 'default_pass = %s\n' "$bp" + printf 'default_permissions.configure = ^(attachments\\.jobs|attachments\\.process|attachments\\.dlx|attachments\\.process\\.dlq)$\n' + printf 'default_permissions.read = ^attachments\\.(jobs|process|dlx|process\\.dlq)$\n' + printf 'default_permissions.write = ^attachments\\.(jobs|process|dlx|process\\.dlq)$\n' + } > secrets/rabbitmq.conf + ) + chmod 0644 secrets/rabbitmq.conf + echo "created secrets/broker_url secrets/rabbitmq.conf" +fi diff --git a/scripts/lab4/attachments_bench.py b/scripts/lab4/attachments_bench.py new file mode 100755 index 0000000..9e5151d --- /dev/null +++ b/scripts/lab4/attachments_bench.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""Upload benchmark: API traffic and peak RSS per upload for proxy vs direct mode. + + attachments_bench.py run --mode proxy --size-bytes 1048576 --concurrency 10 \ + --uploads-per-worker 5 --repeat 3 --output evidence/lab4/bench/proxy-1048576-c10.json + attachments_bench.py summarize evidence/lab4/bench/*.json > evidence/lab4/summary.md + +Run from the repository root with the stand up. Tokens, signed URLs and secrets +are never written to the output. +""" +import argparse +import base64 +import hashlib +import http.client +import json +import os +import statistics +import subprocess +import sys +import threading +import time +import urllib.parse +import uuid +from datetime import datetime, timezone + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pngkit import noise_png # noqa: E402 + + +def sh(*args, check=True): + return subprocess.run(args, check=check, capture_output=True, text=True).stdout.strip() + + +def read_env(path=".env"): + values = {} + with open(path) as handle: + for line in handle: + line = line.strip() + if line and not line.startswith("#") and "=" in line: + key, _, value = line.partition("=") + values[key] = value + return values + + +def request(host, port, method, path, headers=None, body=None): + connection = http.client.HTTPConnection(host, port, timeout=120) + try: + connection.request(method, path, body=body, headers=headers or {}) + response = connection.getresponse() + payload = response.read() + return response.status, payload + finally: + connection.close() + + +def api_json(env, method, path, token=None, body=None, basic=None): + headers = {} + data = None + if body is not None: + headers["content-type"] = "application/json" + data = json.dumps(body).encode() + if token: + headers["authorization"] = f"Bearer {token}" + if basic: + headers["authorization"] = "Basic " + base64.b64encode(basic.encode()).decode() + port = int(env.get("APP_PUBLIC_PORT", "8080")) + status, payload = request("127.0.0.1", port, method, path, headers, data) + return status, json.loads(payload) if payload else None + + +def containers(): + ids = sh("docker", "compose", "--env-file", ".env", "ps", "-q", "api").split() + return sorted(ids) + + +NODE_METRICS = ( + "fetch('http://127.0.0.1:'+(process.env.APP_PORT||8080)+'/internal/metrics'+process.argv[1]," + "{method:process.argv[1]?'POST':'GET',headers:{authorization:'Bearer '+process.env.METRICS_TOKEN}})" + ".then(r=>r.text()).then(console.log)" +) + + +def metrics(container): + return json.loads(sh("docker", "exec", container, "node", "-e", NODE_METRICS, "")) + + +def reset_metrics(container): + sh("docker", "exec", container, "node", "-e", NODE_METRICS, "/reset") + + +def net_bytes(container): + for line in sh("docker", "exec", container, "cat", "/proc/net/dev").splitlines(): + if line.strip().startswith("eth0:"): + fields = line.split(":", 1)[1].split() + return int(fields[0]), int(fields[8]) + raise RuntimeError("eth0 not found") + + +def percentile(values, fraction): + ordered = sorted(values) + if not ordered: + return 0.0 + return ordered[min(len(ordered) - 1, max(0, int(round(fraction * len(ordered) + 0.5)) - 1))] + + +def one_upload(env, mode, token, chat_id, data, seed): + """Returns (ok, elapsed_ms, outcome); outcome names the failing step and status, e.g. "complete:429".""" + digest = hashlib.sha256(data).hexdigest() + filename = f"bench-{seed}.png" + port = int(env.get("APP_PUBLIC_PORT", "8080")) + started = time.perf_counter() + outcome, attachment = "ok", None + try: + if mode == "proxy": + status, body = request( + "127.0.0.1", port, "POST", + f"/api/v1/chats/{chat_id}/attachments?filename={urllib.parse.quote(filename)}", + {"authorization": f"Bearer {token}", "content-type": "image/png"}, data, + ) + if status == 201: + attachment = json.loads(body) + else: + outcome = f"upload:{status}" + else: + headers = {"authorization": f"Bearer {token}", "content-type": "application/json"} + status, body = request( + "127.0.0.1", port, "POST", f"/api/v1/chats/{chat_id}/attachments/direct-uploads", headers, + json.dumps({"filename": filename, "content_type": "image/png", + "size_bytes": len(data), "sha256": digest}).encode(), + ) + if status != 201: + outcome = f"init:{status}" + else: + ticket = json.loads(body) + target = urllib.parse.urlsplit(ticket["url"]) + put_status, _ = request( + target.hostname, target.port, "PUT", target.path + "?" + target.query, + {**ticket["headers"]}, data, + ) + if put_status != 200: + outcome = f"put:{put_status}" + else: + status, body = request( + "127.0.0.1", port, "POST", f"/api/v1/attachments/{ticket['attachment_id']}/complete", + {"authorization": f"Bearer {token}"}, + ) + if status == 200: + attachment = json.loads(body) + else: + outcome = f"complete:{status}" + except (OSError, http.client.HTTPException, ValueError) as error: + outcome = f"error:{type(error).__name__}" + elapsed_ms = (time.perf_counter() - started) * 1000 + if outcome == "ok" and (attachment is None or attachment["sha256"] != digest): + outcome = "checksum_mismatch" + return outcome == "ok", elapsed_ms, outcome + + +def payload(args, seed): + if args.image: + with open(args.image, "rb") as handle: + return handle.read() + return noise_png(args.size_bytes, seed) + + +def run_once(env, args, actors, ids): + for container in ids: + reset_metrics(container) + time.sleep(0.2) + baseline = {c: metrics(c) for c in ids} + net_before = {c: net_bytes(c) for c in ids} + latencies, failures = [], [] + outcomes = {} + lock = threading.Lock() + + def worker(index): + for step in range(args.uploads_per_worker): + seed = index * 1000 + step + data = payload(args, seed) + token, chat_id = actors[index % len(actors)] + ok, elapsed, outcome = one_upload(env, args.mode, token, chat_id, data, seed) + with lock: + (latencies if ok else failures).append(elapsed) + outcomes[outcome] = outcomes.get(outcome, 0) + 1 + + started = time.perf_counter() + threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + duration = time.perf_counter() - started + time.sleep(0.2) + after = {c: metrics(c) for c in ids} + net_after = {c: net_bytes(c) for c in ids} + + replicas = [] + for c in ids: + base_rss = baseline[c]["memory_bytes"]["rss"] + peak = after[c]["memory_peak_bytes"] + replicas.append({ + "instance_id": after[c]["instance_id"], + "delta_rx_bytes": net_after[c][0] - net_before[c][0], + "delta_tx_bytes": net_after[c][1] - net_before[c][1], + "baseline_rss_bytes": base_rss, + "peak_memory_bytes": peak, + "delta_rss_bytes": peak["rss"] - base_rss, + "counters": {k: v for k, v in after[c]["counters"].items() if k.startswith("attachments.")}, + }) + total = args.concurrency * args.uploads_per_worker + return { + "uploads": total, + "succeeded": len(latencies), + "failed": len(failures), + "outcomes": outcomes, + "duration_s": round(duration, 3), + "latency_ms": { + "p50": round(percentile(latencies, 0.50), 1), + "p95": round(percentile(latencies, 0.95), 1), + "p99": round(percentile(latencies, 0.99), 1), + }, + "replicas": replicas, + "total_delta_rx_bytes": sum(r["delta_rx_bytes"] for r in replicas), + "total_delta_tx_bytes": sum(r["delta_tx_bytes"] for r in replicas), + "rx_bytes_per_upload": round(sum(r["delta_rx_bytes"] for r in replicas) / total), + "tx_bytes_per_upload": round(sum(r["delta_tx_bytes"] for r in replicas) / total), + "max_delta_rss_bytes": max(r["delta_rss_bytes"] for r in replicas), + } + + +def command_run(args): + if args.image: + args.size_bytes = os.path.getsize(args.image) + if args.size_bytes <= 0: + sys.exit("--size-bytes or --image is required") + env = read_env() + ids = containers() + if not ids: + sys.exit("no api containers found") + # One user per worker: the API caps concurrent uploads per user + # (UPLOAD_MAX_IN_FLIGHT_PER_USER), and real traffic comes from many users. + actors = [] + for _ in range(args.concurrency): + name = f"bench_{uuid.uuid4().hex[:10]}" + password = "bench:" + uuid.uuid4().hex + status, user = api_json(env, "POST", "/api/v1/users", + body={"username": name, "display_name": "bench", "password": password}) + assert status == 201, status + status, session = api_json(env, "POST", "/api/v1/auth/sessions", basic=f"{name}:{password}") + assert status == 201, status + token = session["token"] + status, chat = api_json(env, "POST", "/api/v1/chats", token, {"title": "bench", "member_ids": [user["id"]]}) + assert status == 201, status + actors.append((token, chat["id"])) + + # Warm-up: two uploads per replica, not measured. + for seed in range(len(ids) * 2): + token, chat_id = actors[seed % len(actors)] + one_upload(env, args.mode, token, chat_id, payload(args, 900000 + seed), seed) + + limits = [] + for c in ids: + limits.append(sh("docker", "inspect", "-f", "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}", c)) + repeats = [run_once(env, args, actors, ids) for _ in range(args.repeat)] + mem_total = next(int(l.split()[1]) * 1024 for l in open("/proc/meminfo") if l.startswith("MemTotal")) + result = { + "date": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "git": sh("git", "rev-parse", "--short", "HEAD", check=False), + "params": { + "mode": args.mode, "size_bytes": args.size_bytes, "concurrency": args.concurrency, + "uploads_per_worker": args.uploads_per_worker, "repeat": args.repeat, + "users": args.concurrency, "image": os.path.basename(args.image) if args.image else None, + }, + "host": {"nproc": os.cpu_count(), "mem_total_bytes": mem_total}, + "api_container_limits_nanocpus_memory": limits, + "repeats": repeats, + } + os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) + with open(args.output, "w") as handle: + json.dump(result, handle, indent=2) + handle.write("\n") + for index, item in enumerate(repeats): + print(f"repeat {index + 1}: ok={item['succeeded']}/{item['uploads']} " + f"rx/upload={item['rx_bytes_per_upload']} tx/upload={item['tx_bytes_per_upload']} " + f"maxΔrss={item['max_delta_rss_bytes']} p50={item['latency_ms']['p50']}ms " + f"outcomes={item['outcomes']}") + + +def mib(value): + return f"{value / 1048576:.2f}" + + +def command_summarize(args): + rows = [] + for path in args.paths: + with open(path) as handle: + data = json.load(handle) + p = data["params"] + reps = data["repeats"] + med = lambda key: statistics.median(r[key] for r in reps) # noqa: E731 + label = p["mode"] + (f" ({p['image']})" if p.get("image") else "") + rows.append((label, p["size_bytes"], p["concurrency"], reps, med, data)) + rows.sort(key=lambda r: (r[0].count("("), r[1], r[0], r[2])) + print("| mode | size, MiB | C | ok | failures | API rx/upload, MiB | API tx/upload, MiB | max Δrss, MiB | peak RSS, MiB | p50, ms | p95, ms |") + print("|---|---|---|---|---|---|---|---|---|---|---|") + for mode, size, conc, reps, med, _data in rows: + peak = max(x["peak_memory_bytes"]["rss"] for r in reps for x in r["replicas"]) + failed = {} + for rep in reps: + for name, count in rep.get("outcomes", {}).items(): + if name != "ok": + failed[name] = failed.get(name, 0) + count + failures = ", ".join(f"{name}×{count}" for name, count in sorted(failed.items())) or "—" + ok = sum(r["succeeded"] for r in reps) + total = sum(r["uploads"] for r in reps) + p50 = statistics.median(r["latency_ms"]["p50"] for r in reps) + p95 = statistics.median(r["latency_ms"]["p95"] for r in reps) + print(f"| {mode} | {mib(size)} | {conc} | {ok}/{total} | {failures} | {mib(med('rx_bytes_per_upload'))} | " + f"{mib(med('tx_bytes_per_upload'))} | {mib(med('max_delta_rss_bytes'))} | {mib(peak)} | {p50:.0f} | {p95:.0f} |") + + +def main(): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="command", required=True) + run = sub.add_parser("run") + run.add_argument("--mode", choices=["proxy", "direct"], required=True) + run.add_argument("--size-bytes", type=int, default=0) + run.add_argument("--image", help="upload this file instead of generated noise PNGs") + run.add_argument("--concurrency", type=int, default=10) + run.add_argument("--uploads-per-worker", type=int, default=5) + run.add_argument("--repeat", type=int, default=3) + run.add_argument("--output", required=True) + summarize = sub.add_parser("summarize") + summarize.add_argument("paths", nargs="+") + args = parser.parse_args() + {"run": command_run, "summarize": command_summarize}[args.command](args) + + +if __name__ == "__main__": + main() diff --git a/scripts/lab4/check_s3_security.sh b/scripts/lab4/check_s3_security.sh new file mode 100755 index 0000000..497c5ba --- /dev/null +++ b/scripts/lab4/check_s3_security.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# Проверка приватности S3 вне API: анонимный доступ, права отдельных credentials +# API, закрытая консоль. Секреты не печатаются. +set -u +cd "$(dirname "$0")/../.." +env_file="${COMPOSE_ENV_FILE:-.env}" +# shellcheck disable=SC1090 +set -a; . "./$env_file"; set +a +endpoint="${S3_PUBLIC_ENDPOINT:-http://localhost:9000}" +bucket="${S3_BUCKET:-messenger-attachments}" +compose="docker compose --env-file $env_file" +fail=0 + +report() { # status name + if [ "$1" = ok ]; then echo "PASS $2"; else echo "FAIL $2"; fail=1; fi +} + +key=$($compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -At \ + -c "SELECT object_key FROM attachments WHERE status = 'ready' ORDER BY created_at DESC LIMIT 1") +if [ -z "$key" ]; then + echo "FAIL no ready attachment to check; upload one first (make test)" + exit 1 +fi + +code=$(curl -s -o /dev/null -w '%{http_code}' "$endpoint/$bucket/$key") +[ "$code" = 403 ] && report ok "anonymous GET of a ready object -> 403" || report fail "anonymous GET of a ready object -> $code (want 403)" + +code=$(curl -s -o /dev/null -w '%{http_code}' "$endpoint/$bucket/") +[ "$code" = 403 ] && report ok "anonymous list of the bucket -> 403" || report fail "anonymous list of the bucket -> $code (want 403)" + +code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT --data-binary x "$endpoint/$bucket/attachments/anonymous-write") +[ "$code" = 403 ] && report ok "anonymous PUT -> 403" || report fail "anonymous PUT -> $code (want 403)" + +# The API credentials only, inside a one-off container (secrets come from files). +api_mc() { + $compose run --rm --no-deps -T --entrypoint /bin/sh s3-init -c ' + IFS= read -r k < /run/secrets/s3_api_access_key_id + IFS= read -r s < /run/secrets/s3_api_secret_access_key + export MC_CONFIG_DIR=/tmp/.mc MC_HOST_api="http://$k:$s@s3:9000" + exec mc "$@"' sh "$@" >/dev/null 2>&1 +} + +api_mc mb api/forbidden-bucket && report fail "API credentials can create buckets" || report ok "API credentials cannot create buckets" +api_mc admin info api && report fail "API credentials can use admin API" || report ok "API credentials cannot use admin API" +api_mc stat "api/$bucket/$key" && report ok "API credentials can read attachments/*" || report fail "API credentials cannot read attachments/*" +api_mc stat "api/$bucket/outside-prefix" ; rc=$? +api_mc cp /etc/hostname "api/$bucket/outside-prefix" && report fail "API credentials can write outside attachments/" || report ok "API credentials cannot write outside attachments/" +: "$rc" + +port=$($compose port s3 9001 2>/dev/null || true) +[ -z "$port" ] && report ok "console port 9001 is not published" || report fail "console port 9001 is published ($port)" +if curl -s -o /dev/null --max-time 3 http://localhost:9001; then report fail "console reachable on localhost:9001"; else report ok "console not reachable on localhost:9001"; fi + +exit "$fail" diff --git a/scripts/lab4/consistency_check.sh b/scripts/lab4/consistency_check.sh new file mode 100755 index 0000000..fd97eb7 --- /dev/null +++ b/scripts/lab4/consistency_check.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Сверка bucket и БД (только чтение): orphans — объект без строки, missing — +# ready-строка без объекта. Код выхода 1, если что-то найдено. +set -eu +cd "$(dirname "$0")/../.." +env_file="${COMPOSE_ENV_FILE:-.env}" +# shellcheck disable=SC1090 +set -a; . "./$env_file"; set +a +bucket="${S3_BUCKET:-messenger-attachments}" +compose="docker compose --env-file $env_file" + +objects=$(mktemp) +rows=$(mktemp) +trap 'rm -f "$objects" "$rows"' EXIT + +$compose run --rm --no-deps -T --entrypoint /bin/sh s3-init -c ' + IFS= read -r u < /run/secrets/minio_root_user + IFS= read -r p < /run/secrets/minio_root_password + export MC_CONFIG_DIR=/tmp/.mc MC_HOST_stand="http://$u:$p@s3:9000" + exec mc ls --recursive "stand/$S3_BUCKET"' 2>/dev/null \ + | sed -n 's/.* \(attachments\/.*\)$/\1/p' | sort > "$objects" +$compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -At \ + -c "SELECT object_key, status FROM attachments" | sort > "$rows" + +echo "bucket: $bucket" +echo "objects: $(wc -l < "$objects" | tr -d ' ')" +echo "rows by status:" +cut -d'|' -f2 "$rows" | sort | uniq -c | sed 's/^ */ /' +orphans=$(cut -d'|' -f1 "$rows" | sort | comm -13 - "$objects") +missing=$(grep '|ready$' "$rows" | cut -d'|' -f1 | sort | comm -23 - "$objects") +echo "orphans: $(printf '%s' "$orphans" | grep -c . || true)" +[ -z "$orphans" ] || printf '%s\n' "$orphans" | sed 's/^/ orphan /' +echo "missing: $(printf '%s' "$missing" | grep -c . || true)" +[ -z "$missing" ] || printf '%s\n' "$missing" | sed 's/^/ missing /' +[ -z "$orphans$missing" ] diff --git a/scripts/lab4/decode_memory.mjs b/scripts/lab4/decode_memory.mjs new file mode 100644 index 0000000..65bd84b --- /dev/null +++ b/scripts/lab4/decode_memory.mjs @@ -0,0 +1,33 @@ +// Peak RSS of one full decode check with the same sharp pipeline as +// app/src/attachments/image/image-decoder.ts, on worst-case inputs near +// MAX_IMAGE_PIXELS. Runs where the API runs (same libvips, VIPS_DISC_THRESHOLD): +// docker compose exec -T api node - < scripts/lab4/decode_memory.mjs # reads files from IMAGES (paths in the container) +// or on the host from app/: IMAGES="a.png b.jpg" node ../scripts/lab4/decode_memory.mjs +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; + +const sharp = createRequire(`${process.cwd()}/`)('sharp'); +sharp.cache(false); +sharp.concurrency(1); +for (const file of (process.env.IMAGES ?? '').split(/\s+/u).filter(Boolean)) { + const data = readFileSync(file); + const meta = await sharp(data).metadata(); + const base = process.memoryUsage().rss; + let peak = base; + const timer = setInterval(() => { + peak = Math.max(peak, process.memoryUsage().rss); + }, 5); + const started = Date.now(); + let verdict = 'ok'; + try { + await sharp(data, { failOn: 'warning', sequentialRead: true, limitInputPixels: 40_000_000 }) + .resize(64, 64, { fit: 'inside' }) + .toBuffer(); + } catch (error) { + verdict = `rejected: ${String(error.message).split('\n')[0]}`; + } + clearInterval(timer); + console.log( + `${meta.format} ${meta.width}x${meta.height} ${meta.channels}ch ${meta.depth}${meta.isProgressive ? ' progressive' : ''}${meta.isPalette ? ' palette' : ''} bytes=${data.length} decode_ms=${Date.now() - started} peak_delta_rss_mib=${((peak - base) / 1048576).toFixed(1)} ${verdict}`, + ); +} diff --git a/scripts/lab4/pngkit.py b/scripts/lab4/pngkit.py new file mode 100644 index 0000000..1ec0b8d --- /dev/null +++ b/scripts/lab4/pngkit.py @@ -0,0 +1,78 @@ +"""Synthetic PNG helpers (stdlib only); same semantics as app/test/support/png.ts.""" +import random +import struct +import zlib + +SIGNATURE = b"\x89PNG\r\n\x1a\n" +NOISE_WIDTH = 1024 +NOISE_ROW = 1 + NOISE_WIDTH * 3 + + +def chunk(kind: bytes, data: bytes) -> bytes: + crc = zlib.crc32(kind + data) & 0xFFFFFFFF + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", crc) + + +def build_png(width: int, height: int, idat: bytes) -> bytes: + ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) + return SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"") + + +def pad_png(data: bytes, size: int) -> bytes: + """Insert a private ancillary chunk before IEND to reach exactly `size` bytes.""" + extra = size - len(data) + if extra == 0: + return data + if extra < 12: + raise ValueError("padding needs at least 12 bytes") + return data[:-12] + chunk(b"prVt", bytes(extra - 12)) + data[-12:] + + +def _noise_of_height(height: int, rng: random.Random) -> bytes: + raw = bytearray(rng.randbytes(NOISE_ROW * height)) + for row in range(height): + raw[row * NOISE_ROW] = 0 # filter type "none" + compressor = zlib.compressobj(0) + return build_png(NOISE_WIDTH, height, compressor.compress(bytes(raw)) + compressor.flush()) + + +def noise_png(size: int, seed: int = 0) -> bytes: + """Incompressible, structurally valid PNG of exactly `size` bytes.""" + rng = random.Random(seed) + height = max(1, size // NOISE_ROW) + while True: + png = _noise_of_height(height, rng) + if len(png) > size or 0 < size - len(png) < 12: + height -= 1 + if height < 1: + raise ValueError("size is too small") + continue + return pad_png(png, size) + + +ADAM7 = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)] + + +def worst_decode_png(size: int = 10_485_760, width: int = 8000, height: int = 5000) -> bytes: + """The heaviest valid upload to decode: 40 MP RGBA 16-bit, Adam7-interlaced + (the decoder must hold the whole image), padded to exactly `size` bytes.""" + compressor = zlib.compressobj(1) + parts = [] + for x0, y0, dx, dy in ADAM7: + pass_width = (width - x0 + dx - 1) // dx if width > x0 else 0 + pass_height = (height - y0 + dy - 1) // dy if height > y0 else 0 + if pass_width == 0 or pass_height == 0: + continue + row = bytes(1 + pass_width * 8) + for _ in range(pass_height): + parts.append(compressor.compress(row)) + parts.append(compressor.flush()) + ihdr = struct.pack(">IIBBBBB", width, height, 16, 6, 0, 0, 1) + png = SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", b"".join(parts)) + chunk(b"IEND", b"") + return pad_png(png, size) + + +if __name__ == "__main__": + import sys + + sys.stdout.buffer.write(worst_decode_png()) diff --git a/scripts/lab4/run_matrix.sh b/scripts/lab4/run_matrix.sh new file mode 100755 index 0000000..2c6578c --- /dev/null +++ b/scripts/lab4/run_matrix.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Experiment matrix: sizes x {proxy,direct} at C=10, plus proxy 9.5 MiB at C=20. +# Needs a running stand (make stand-up) and `make init-env` credentials. +set -eu +cd "$(dirname "$0")/../.." +out=evidence/lab4/bench +mkdir -p "$out" +bench() { + mode=$1 size=$2 conc=$3 + python3 scripts/lab4/attachments_bench.py run --mode "$mode" --size-bytes "$size" \ + --concurrency "$conc" --uploads-per-worker 5 --repeat 3 \ + --output "$out/$mode-$size-c$conc.json" +} +for size in 131072 1048576 9961472; do + for mode in proxy direct; do + echo "== $mode size=$size c=10" + bench "$mode" "$size" 10 + done +done +echo "== proxy size=9961472 c=20" +bench proxy 9961472 20 +# Worst case for memory: every request carries the heaviest valid image +# (40 MP RGBA16 Adam7 PNG padded to 10 MiB, ~340 MiB per decode) and C=32 +# saturates UPLOAD_MAX_IN_FLIGHT (16) on both replicas. +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +worst="$tmp/worst-40mp-rgba16-adam7.png" +python3 scripts/lab4/pngkit.py > "$worst" +for mode in proxy direct; do + echo "== $mode worst-case image c=32" + python3 scripts/lab4/attachments_bench.py run --mode "$mode" --image "$worst" \ + --concurrency 32 --uploads-per-worker 2 --repeat 3 \ + --output "$out/$mode-worst-c32.json" +done +python3 scripts/lab4/attachments_bench.py summarize "$out"/*.json > evidence/lab4/summary.md +cat evidence/lab4/summary.md diff --git a/scripts/lab5/fault_suite.py b/scripts/lab5/fault_suite.py new file mode 100755 index 0000000..ae02145 --- /dev/null +++ b/scripts/lab5/fault_suite.py @@ -0,0 +1,749 @@ +#!/usr/bin/env python3 +"""Automated fault injection for lab5 levels 4 and 5 (track 2).""" +import argparse +import json +import re +import sys +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'lab4')) + +from stand import ( # noqa: E402 + ROOT, + Failure, + check, + clear_fault, + clear_faults, + cli, + compose, + docker, + new_client, + rabbit_queues, + sample_bytes, + set_fault, + sha256, + upload, + variant_sha, + wait_for, + wait_ready, + worker_env, + worker_start_count, +) +from pngkit import worst_decode_png # noqa: E402 + +HINT = ('FAULT_INJECTION_ENABLED=1 JOB_TIMEOUT_SECONDS=10 ' + 'JOB_LEASE_SECONDS=8 JOB_RETRY_BASE_MS=500 JOB_RETRY_MAX_MS=4000 ' + 'make stand-up') + +LEVEL4 = [ + 'crash_after_commit_before_publish', + 'crash_after_side_effect', + 'crash_after_commit_before_ack', + 'retry_and_replay', + 'hung_worker', + 'poison', + 'big_image', +] +TRACK2 = [ + 'duplicate', + 'reorder', + 'crash_before_side_effect', + 'crash_after_side_effect', + 'crash_after_commit_before_ack', + 'relay_crash_after_publish', + 'stale_version', +] + + +class Tracker(threading.Thread): + """Polls metadata while a scenario runs to prove readiness never regresses.""" + + def __init__(self, base_url, actor, ca_file=None): + super().__init__(daemon=True) + self.client = new_client(base_url, ca_file) + self.actor = actor + self.ids = [] + self.records = {} + self.stop_event = threading.Event() + + def track(self, attachment_id): + if attachment_id not in self.records: + self.ids.append(attachment_id) + self.records[attachment_id] = [] + + def run(self): + while not self.stop_event.is_set(): + for attachment_id in list(self.ids): + try: + meta = self.client.call( + 'GET', '/api/v1/attachments/' + attachment_id, + actor=self.actor, schema='Attachment', + )['json'] + self.records[attachment_id].append( + (time.monotonic(), meta['status'], + meta.get('ready_pipeline_version')) + ) + except Exception: + pass + self.stop_event.wait(0.2) + + def stop(self): + self.stop_event.set() + self.join(timeout=5) + + +def build_message(status, job, attempt=None): + created = next( + event for event in status['events'] + if event['job_id'] == job['job_id'] and event['event'] == 'created' + ) + return { + 'schema_version': 1, + 'job_id': job['job_id'], + 'type': 'attachment.process.v1', + 'attachment_id': status['attachment']['id'], + 'pipeline_version': job['pipeline_version'], + 'attempt': attempt if attempt is not None else job['attempt'], + 'created_at': created['created_at'], + } + + +def publish_raw(messages): + text = ''.join(json.dumps(message, separators=(',', ':')) + '\n' + for message in messages) + code, payload = cli('publish-raw', stdin=text) + check(code == 0, 'publish-raw failed: ' + str(payload)) + return payload + + +def status_of(attachment_id): + code, payload = cli('status', attachment_id) + check(code == 0, 'status failed: ' + str(payload)) + return payload + + +def flush_outbox(attachment_id): + wait_for(lambda: status_of(attachment_id)['outbox']['pending'] == 0, + 30, 'outbox publish', 1.0) + + +def new_attachment_id(chat_id, before): + rows = cli('find-by-chat', chat_id)[1] + for row in reversed(rows): + if row['id'] not in before: + return row['id'] + return None + + +def evaluate(tracker, attachment_id, baseline, expect_failed=False, + compare_baseline=True): + if attachment_id is None: + return {'I1': True, 'I2': True, 'I3': True, + 'I4': True, 'I5': True, 'I6': True} + status = status_of(attachment_id) + attachment = status['attachment'] + jobs = status['jobs'] + variants = status['variants'] + ready_version = attachment['ready_pipeline_version'] + + records = tracker.records.get(attachment_id, []) + reached = any(record[1] == ('failed' if expect_failed else 'ready') + for record in records) + if not records: + reached = attachment['status'] == ('failed' if expect_failed else 'ready') + i1 = reached or attachment['status'] in ('ready', 'failed') + + ready_variants = [v for v in variants + if v['pipeline_version'] == ready_version] + succeeded_ids = {job['job_id'] for job in jobs + if job['status'] == 'succeeded'} + succeeded_events = {} + for event in status['events']: + if event['event'] == 'succeeded': + succeeded_events[event['job_id']] = ( + succeeded_events.get(event['job_id'], 0) + 1 + ) + i2 = (len(ready_variants) == 3 + and all(succeeded_events.get(job_id) == 1 + for job_id in succeeded_ids)) + + i3 = True + seen_ready = False + last_version = 0 + for _at, state, version in records: + if seen_ready and state != 'ready': + i3 = False + if state == 'ready': + seen_ready = True + if version is not None: + if version < last_version: + i3 = False + last_version = version + + i4 = bool(succeeded_ids) or expect_failed or attachment['status'] == 'ready' + keys = {(variant['pipeline_version'], variant['variant']) + for variant in variants} + i5 = len(keys) == len(variants) + + if compare_baseline and ready_version == 1 and ready_variants: + observed = {variant['variant']: variant['sha256'] + for variant in ready_variants} + i6 = all(observed.get(name) == digest + for name, digest in baseline.items()) + else: + i6 = True + + return {'I1': i1, 'I2': i2, 'I3': i3, 'I4': i4, + 'I5': i5, 'I6': i6} + + +# --- scenarios ----------------------------------------------------------- + + +def scenario_duplicate(ctx): + attachment = upload(ctx['client'], ctx['alice'], ctx['chat'], + sample_bytes(), 'duplicate.png') + ctx['attachment_id'] = attachment['id'] + ctx['tracker'].track(attachment['id']) + wait_ready(ctx['client'], ctx['alice'], attachment['id']) + status = status_of(attachment['id']) + before = {variant['variant']: variant['s3'] + for variant in status['variants']} + message = build_message(status, status['jobs'][0]) + publish_raw([message] * 5) + wait_for( + lambda: len([event for event in status_of(attachment['id'])['events'] + if event['event'] == 'duplicate_skipped' + and event['detail'].get('reason') == 'already_succeeded']) == 5, + 20, 'five duplicate_skipped events', 1.0, + ) + after_status = status_of(attachment['id']) + after = {variant['variant']: variant['s3'] + for variant in after_status['variants']} + check(before == after, 'duplicate delivery rewrote variant objects') + return {'attachment_id': attachment['id'], + 'job_attempts': [job['attempt'] for job in after_status['jobs']], + 'notes': '5 duplicate deliveries were absorbed by the DB fence'} + + +def scenario_reorder(ctx): + compose('stop', 'worker') + try: + attachment = upload(ctx['client'], ctx['alice'], ctx['chat'], + sample_bytes(), 'reorder.png') + ctx['attachment_id'] = attachment['id'] + ctx['tracker'].track(attachment['id']) + flush_outbox(attachment['id']) + status = status_of(attachment['id']) + message = build_message(status, status['jobs'][0]) + stale = dict(message, attempt=99) + publish_raw([stale, message]) + compose('start', 'worker') + wait_ready(ctx['client'], ctx['alice'], attachment['id']) + finally: + compose('start', 'worker') + after_status = status_of(attachment['id']) + skipped = [event for event in after_status['events'] + if event['event'] == 'duplicate_skipped'] + check(len(skipped) == 2, 'expected exactly two skipped out-of-order messages') + check(len([event for event in after_status['events'] + if event['event'] == 'succeeded']) == 1, + 'expected exactly one successful effect') + return {'attachment_id': attachment['id'], + 'job_attempts': [job['attempt'] for job in after_status['jobs']], + 'notes': 'attempt 99 and a duplicate attempt 1 were acked as skips'} + + +def crash_scenario(ctx, point, filename, expected_attempt, + expect_lease_expired=False, expect_duplicate=False): + compose('stop', 'worker') + try: + attachment = upload(ctx['client'], ctx['alice'], ctx['chat'], + sample_bytes(), filename) + ctx['attachment_id'] = attachment['id'] + ctx['tracker'].track(attachment['id']) + starts = worker_start_count() + set_fault('fault:' + point + ':' + attachment['id'] + ':1', 'crash') + compose('start', 'worker') + wait_ready(ctx['client'], ctx['alice'], attachment['id'], 90) + finally: + compose('start', 'worker') + status = status_of(attachment['id']) + job = status['jobs'][0] + check(job['attempt'] == expected_attempt, + 'expected attempt ' + str(expected_attempt) + + ', got ' + str(job['attempt'])) + check(worker_start_count() >= starts + 2, + 'worker process did not restart after the injected crash') + if expect_lease_expired: + check(any(event['event'] == 'lease_expired' + for event in status['events']), + 'missing lease_expired event') + if expect_duplicate: + check(any(event['event'] == 'duplicate_skipped' + and event['detail'].get('reason') == 'already_succeeded' + for event in status['events']), + 'missing already_succeeded duplicate after redelivery') + return {'attachment_id': attachment['id'], + 'job_attempts': [job['attempt']], + 'notes': 'crashed at ' + point} + + +def scenario_crash_before_side_effect(ctx): + return crash_scenario(ctx, 'worker.before_side_effect', + 'crash-before.png', 2, expect_lease_expired=True) + + +def scenario_crash_after_side_effect(ctx): + return crash_scenario(ctx, 'worker.after_side_effect', + 'crash-after.png', 2, expect_lease_expired=True) + + +def scenario_crash_after_commit_before_ack(ctx): + return crash_scenario(ctx, 'worker.after_commit_before_ack', + 'crash-ack.png', 1, expect_duplicate=True) + + +def scenario_crash_after_commit_before_publish(ctx): + before = {row['id'] for row in cli('find-by-chat', ctx['chat']['id'])[1]} + set_fault('fault:api.after_commit_before_publish', 'crash') + try: + try: + ctx['client'].call( + 'POST', + '/api/v1/chats/' + ctx['chat']['id'] + + '/attachments?filename=crash-publish.png', + (202, 502, 503, 504), + actor=ctx['alice'], + raw=sample_bytes(), + headers={'Content-Type': 'image/png'}, + ) + except Failure: + # A killed replica may close the connection instead of answering. + pass + finally: + clear_fault('fault:api.after_commit_before_publish') + attachment_id = wait_for( + lambda: new_attachment_id(ctx['chat']['id'], before), 30, + 'attachment row after API crash', 1.0, + ) + ctx['attachment_id'] = attachment_id + ctx['tracker'].track(attachment_id) + wait_ready(ctx['client'], ctx['alice'], attachment_id, 90) + status = status_of(attachment_id) + check(len([event for event in status['events'] + if event['event'] == 'created']) == 1, + 'expected exactly one created event') + return {'attachment_id': attachment_id, + 'job_attempts': [job['attempt'] for job in status['jobs']], + 'notes': 'outbox relay published the committed job after API restart'} + + +def scenario_relay_crash_after_publish(ctx): + compose('stop', 'worker') + before = {row['id'] for row in cli('find-by-chat', ctx['chat']['id'])[1]} + try: + set_fault('fault:relay.after_publish_before_mark', 'crash') + try: + ctx['client'].call( + 'POST', + '/api/v1/chats/' + ctx['chat']['id'] + + '/attachments?filename=relay-crash.png', + (202, 502, 503, 504), + actor=ctx['alice'], + raw=sample_bytes(), + headers={'Content-Type': 'image/png'}, + ) + except Failure: + # The relay may crash the handling replica before the reply flushes. + pass + clear_fault('fault:relay.after_publish_before_mark') + attachment_id = wait_for( + lambda: new_attachment_id(ctx['chat']['id'], before), 30, + 'attachment row after relay crash', 1.0, + ) + ctx['attachment_id'] = attachment_id + ctx['tracker'].track(attachment_id) + wait_for(lambda: status_of(attachment_id)['outbox']['pending'] == 0, + 60, 'outbox published after relay crash', 1.0) + queue_depth = rabbit_queues().get('attachments.process', {}).get( + 'messages', 0) + compose('start', 'worker') + wait_ready(ctx['client'], ctx['alice'], attachment_id, 90) + finally: + clear_fault('fault:relay.after_publish_before_mark') + compose('start', 'worker') + status = status_of(attachment_id) + check(len([event for event in status['events'] + if event['event'] == 'succeeded']) == 1, + 'expected exactly one succeeded event') + duplicated = any(event['event'] == 'duplicate_skipped' + for event in status['events']) + note = ('relay republished the same message; duplicate absorbed' + if duplicated else + 'relay published once in this run; I1/I2 still hold') + if queue_depth >= 2: + check(duplicated, 'two queued copies but no duplicate_skipped event') + return {'attachment_id': attachment_id, + 'job_attempts': [job['attempt'] for job in status['jobs']], + 'notes': note} + + +def scenario_stale_version(ctx): + check(int(worker_env('WORKER_CONCURRENCY') or '1') >= 2, + 'stale_version needs WORKER_CONCURRENCY>=2') + compose('stop', 'worker') + try: + attachment = upload(ctx['client'], ctx['alice'], ctx['chat'], + sample_bytes(), 'stale.png') + attachment_id = attachment['id'] + ctx['attachment_id'] = attachment_id + ctx['tracker'].track(attachment_id) + flush_outbox(attachment_id) + code, payload = cli('reprocess', attachment_id, + '--pipeline-version', '2', '--reason', 'suite') + check(code == 0, 'reprocess v2 failed: ' + str(payload)) + set_fault('fault:worker.after_side_effect:' + attachment_id + ':1', + 'delay:8000') + compose('start', 'worker') + v2_etags = None + + def both_terminal(): + nonlocal v2_etags + status = status_of(attachment_id) + jobs = {(job['pipeline_version']): job for job in status['jobs']} + if '2' in jobs or 2 in jobs: + v2_job = jobs.get(2) + if v2_job and v2_job['status'] == 'succeeded' and v2_etags is None: + v2_etags = {variant['variant']: variant['s3'] + for variant in status['variants'] + if variant['pipeline_version'] == 2} + v1_job = jobs.get(1) + v2_job = jobs.get(2) + return (v1_job and v2_job + and v1_job['status'] == 'superseded' + and v2_job['status'] == 'succeeded') + + wait_for(both_terminal, 90, 'v2 ready and v1 superseded', 1.0) + status = status_of(attachment_id) + check(status['attachment']['ready_pipeline_version'] == 2, + 'ready pipeline version is not 2') + check(all(variant['pipeline_version'] == 2 + for variant in status['variants']), + 'variant rows from v1 survived') + after_etags = {variant['variant']: variant['s3'] + for variant in status['variants'] + if variant['pipeline_version'] == 2} + check(v2_etags == after_etags, 'v1 overwrote v2 variant objects') + + served = ctx['client'].call( + 'GET', + '/api/v1/attachments/' + attachment_id + + '/content?variant=thumbnail', + actor=ctx['alice'], + ) + v2_thumbnail = next(variant for variant in status['variants'] + if variant['variant'] == 'thumbnail') + check(sha256(served['bytes']) == v2_thumbnail['sha256'], + 'served thumbnail is not the v2 object') + check(sha256(served['bytes']) != ctx['baseline']['thumbnail'], + 'served thumbnail equals the v1 baseline') + + v1_job = next(job for job in status['jobs'] + if job['pipeline_version'] == 1) + publish_raw([build_message(status, v1_job)]) + wait_for( + lambda: any(event['event'] == 'duplicate_skipped' + and event['detail'].get('reason') == 'superseded' + for event in status_of(attachment_id)['events']), + 20, 'superseded duplicate skip', 1.0, + ) + finally: + clear_fault('fault:worker.after_side_effect:' + + (attachment['id'] if 'attachment' in locals() else '')) + compose('start', 'worker') + return {'attachment_id': attachment_id, + 'job_attempts': [job['attempt'] for job in status['jobs']], + 'notes': 'v1 finished after v2 and was recorded as superseded'} + + +def scenario_poison(ctx): + before = rabbit_queues().get('attachments.process.dlq', {}).get( + 'messages', 0) + publish_raw(['not-json', '{"schema_version":1}']) + wait_for( + lambda: rabbit_queues().get('attachments.process.dlq', {}).get( + 'messages', 0) >= before + 2, + 15, 'two poison messages in DLQ', 0.5, + ) + return {'attachment_id': None, 'job_attempts': [], + 'notes': 'malformed messages moved to the DLQ without touching jobs'} + + +def scenario_retry_and_replay(ctx): + max_attempts = int(worker_env('JOB_MAX_ATTEMPTS') or '5') + base = int(worker_env('JOB_RETRY_BASE_MS') or '500') + cap = int(worker_env('JOB_RETRY_MAX_MS') or '4000') + compose('stop', 'worker') + try: + attachment = upload(ctx['client'], ctx['alice'], ctx['chat'], + sample_bytes(), 'retry.png') + attachment_id = attachment['id'] + ctx['attachment_id'] = attachment_id + ctx['tracker'].track(attachment_id) + set_fault('fault:worker.before_side_effect:' + attachment_id + ':1', + 'transient') + compose('start', 'worker') + failed = wait_ready(ctx['client'], ctx['alice'], attachment_id, + 90, allow_failed=True) + finally: + compose('start', 'worker') + check(failed['status'] == 'failed', 'transient fault was not exhausted') + check(failed['error_code'] == 'retry_exhausted', + 'expected retry_exhausted, got ' + str(failed['error_code'])) + status = status_of(attachment_id) + retries = [event for event in status['events'] + if event['event'] == 'retry_scheduled'] + check(len(retries) == max_attempts - 1, + 'expected ' + str(max_attempts - 1) + ' retries, got ' + + str(len(retries))) + for index, event in enumerate(retries): + limit = min(cap, base * 2 ** index) + check(0 <= event['detail'].get('delay_ms', cap + 1) <= limit, + 'retry delay exceeds its jitter cap') + ctx['client'].call( + 'GET', '/api/v1/attachments/' + attachment_id + '/content', + 409, actor=ctx['alice'], + ) + code, payload = cli('replay', ctx['reference_id'], '--reason', 'suite') + check(code == 3 and payload.get('reason') in ('no_failed_job', + 'already_ready'), + 'replay of a ready attachment was not refused') + + clear_fault('fault:worker.before_side_effect:' + attachment_id + ':1') + code, payload = cli('replay', attachment_id, '--reason', 'suite') + check(code == 0, 'operator replay failed: ' + str(payload)) + wait_ready(ctx['client'], ctx['alice'], attachment_id, 60) + status = status_of(attachment_id) + replayed = [event for event in status['events'] + if event['event'] == 'replayed'] + check(len(replayed) == 1 and replayed[0]['detail'].get('operator'), + 'missing replayed event or operator audit') + return {'attachment_id': attachment_id, + 'job_attempts': [job['attempt'] for job in status['jobs']], + 'notes': 'transient injected fault exhausted retries; replay recovered'} + + +def scenario_hung_worker(ctx): + timeout_seconds = int(worker_env('JOB_TIMEOUT_SECONDS') or '10') + compose('stop', 'worker') + try: + attachment = upload(ctx['client'], ctx['alice'], ctx['chat'], + sample_bytes(), 'hung.png') + attachment_id = attachment['id'] + ctx['attachment_id'] = attachment_id + ctx['tracker'].track(attachment_id) + set_fault('fault:worker.after_side_effect:' + attachment_id + ':1', + 'delay:' + str((timeout_seconds + 5) * 1000)) + compose('start', 'worker') + wait_ready(ctx['client'], ctx['alice'], attachment_id, 90) + finally: + compose('start', 'worker') + status = status_of(attachment_id) + check(any(event['event'] == 'retry_scheduled' + and event['detail'].get('code') == 'processing_timeout' + for event in status['events']), + 'missing processing_timeout retry') + return {'attachment_id': attachment_id, + 'job_attempts': [job['attempt'] for job in status['jobs']], + 'notes': 'hard timeout aborted the hung render and retried'} + + +def scenario_big_image(ctx): + ctx['compare_baseline'] = False + data = worst_decode_png() + containers = compose('ps', '-q', 'worker').stdout.split() + stop = threading.Event() + peak = {'mb': 0.0} + + def sample(): + while not stop.is_set(): + if containers: + result = docker( + 'stats', '--no-stream', '--format', + '{{.Name}} {{.MemUsage}}', *containers, + check_result=False, + ) + for line in result.stdout.splitlines(): + parts = line.split() + if len(parts) < 2: + continue + match = re.match(r'([\d.]+)(KiB|MiB|GiB)', parts[1]) + if not match: + continue + value = float(match.group(1)) + if match.group(2) == 'GiB': + value *= 1024 + elif match.group(2) == 'KiB': + value /= 1024 + peak['mb'] = max(peak['mb'], value) + stop.wait(0.3) + + sampler = threading.Thread(target=sample, daemon=True) + sampler.start() + try: + def do_upload(index): + client = new_client(ctx['base_url']) + return upload(client, ctx['alice'], ctx['chat'], data, + 'big-' + str(index) + '.png') + + with ThreadPoolExecutor(max_workers=2) as pool: + attachments = list(pool.map(do_upload, (1, 2))) + ctx['attachment_id'] = attachments[0]['id'] + for attachment in attachments: + ctx['tracker'].track(attachment['id']) + results = [wait_ready(ctx['client'], ctx['alice'], + attachment['id'], 120, allow_failed=True) + for attachment in attachments] + finally: + stop.set() + sampler.join(timeout=5) + for meta in results: + check(meta['status'] in ('ready', 'failed'), 'big image stuck') + if meta['status'] == 'failed': + check(meta['error_code'] in ('image_too_large', 'invalid_image'), + 'unexpected big-image error code') + for container in containers: + result = docker('inspect', '-f', '{{.State.OOMKilled}}', container, + check_result=False) + check(result.stdout.strip() == 'false', 'worker was OOM-killed') + return {'attachment_id': attachments[0]['id'], + 'job_attempts': [], + 'notes': 'peak worker memory: %.1f MiB / 1280 MiB' % peak['mb']} + + +SCENARIOS = { + 'duplicate': scenario_duplicate, + 'reorder': scenario_reorder, + 'crash_before_side_effect': scenario_crash_before_side_effect, + 'crash_after_side_effect': scenario_crash_after_side_effect, + 'crash_after_commit_before_ack': scenario_crash_after_commit_before_ack, + 'crash_after_commit_before_publish': scenario_crash_after_commit_before_publish, + 'relay_crash_after_publish': scenario_relay_crash_after_publish, + 'stale_version': scenario_stale_version, + 'poison': scenario_poison, + 'retry_and_replay': scenario_retry_and_replay, + 'hung_worker': scenario_hung_worker, + 'big_image': scenario_big_image, +} + + +def select(name): + if name == 'all': + return LEVEL4 + [item for item in TRACK2 if item not in LEVEL4] + if name == 'level4': + return LEVEL4 + if name == 'track2': + return TRACK2 + if name in SCENARIOS: + return [name] + raise SystemExit('unknown scenario: ' + name) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--base-url', default=None) + parser.add_argument('--ca-file', default=None) + parser.add_argument('--scenario', default='level4') + parser.add_argument('--repeat', type=int, default=1) + parser.add_argument('--output', default=None) + args = parser.parse_args() + + if worker_env('FAULT_INJECTION_ENABLED') != '1': + print('fault injection is disabled; restart the stand with:\n ' + HINT, + file=sys.stderr) + raise SystemExit(2) + + client = new_client(args.base_url, args.ca_file) + alice, _bob, _eve, chat = client.bootstrap() + clear_faults() + reference = upload(client, alice, chat, sample_bytes(), 'reference.png') + ready = wait_ready(client, alice, reference['id'], 60) + baseline = variant_sha(ready) + + selected = select(args.scenario) + results = [] + failed = 0 + for name in selected: + for repeat in range(1, args.repeat + 1): + clear_faults() + tracker = Tracker(args.base_url or 'http://localhost:8080', alice, + args.ca_file) + tracker.start() + started = time.monotonic() + ctx = { + 'client': client, + 'base_url': args.base_url or 'http://localhost:8080', + 'alice': alice, + 'chat': chat, + 'tracker': tracker, + 'baseline': baseline, + 'reference_id': reference['id'], + 'ca_file': args.ca_file, + } + scenario = {'attachment_id': None, 'job_attempts': [], + 'notes': ''} + passed = True + try: + scenario.update(SCENARIOS[name](ctx)) + except Exception as error: # noqa: BLE001 - scenario boundary + passed = False + scenario['notes'] = type(error).__name__ + ': ' + str(error) + finally: + tracker.stop() + clear_faults() + compose('start', 'worker', check_result=False) + attachment_id = scenario['attachment_id'] or ctx.get('attachment_id') + try: + invariants = evaluate( + tracker, attachment_id, baseline, + compare_baseline=ctx.get('compare_baseline', True), + ) + except Exception: # noqa: BLE001 + invariants = {key: False for key in + ('I1', 'I2', 'I3', 'I4', 'I5', 'I6')} + passed = passed and all(invariants.values()) + if not passed: + failed += 1 + result = { + 'name': name, + 'repeat': repeat, + 'passed': passed, + 'duration_s': round(time.monotonic() - started, 3), + 'attachment_id': attachment_id, + 'job_attempts': scenario['job_attempts'], + 'events_summary': scenario.get('events_summary', {}), + 'invariants': invariants, + 'notes': scenario['notes'], + } + results.append(result) + print(('PASS ' if passed else 'FAIL ') + name + ' #' + str(repeat) + + ' ' + str(result['duration_s']) + 's ' + + json.dumps(invariants) + ' ' + result['notes'], + flush=True) + + if args.output: + path = Path(args.output) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(results, indent=2, ensure_ascii=False) + '\n') + print(str(len(results) - failed) + '/' + str(len(results)) + ' scenarios passed') + raise SystemExit(1 if failed else 0) + + +if __name__ == '__main__': + main() diff --git a/scripts/lab5/stand.py b/scripts/lab5/stand.py new file mode 100644 index 0000000..387ddff --- /dev/null +++ b/scripts/lab5/stand.py @@ -0,0 +1,180 @@ +"""Shared stdlib-only helpers for the lab5 demo and fault suite.""" +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, Failure, check # noqa: E402 + +ENV_FILE = '.env' +COMPOSE = ['docker', 'compose', '--env-file', ENV_FILE] + + +def compose(*args, stdin=None, check_result=True): + result = subprocess.run( + COMPOSE + list(args), + cwd=ROOT, + input=stdin, + text=True, + capture_output=True, + ) + if check_result and result.returncode != 0: + detail = (result.stderr or result.stdout).strip().splitlines() + raise Failure('compose ' + ' '.join(args) + ' failed: ' + + (detail[-1] if detail else 'unknown error')) + return result + + +def docker(*args, check_result=True): + result = subprocess.run( + ['docker'] + list(args), cwd=ROOT, text=True, capture_output=True, + ) + if check_result and result.returncode != 0: + detail = (result.stderr or result.stdout).strip().splitlines() + raise Failure('docker ' + ' '.join(args) + ' failed: ' + + (detail[-1] if detail else 'unknown error')) + return result + + +def cli(*args, stdin=None): + """Run jobs.cli in the API container; returns (exit_code, parsed_json).""" + for _ in range(5): + result = compose( + 'exec', '-T', 'api', 'node', 'dist/jobs/jobs.cli.js', *args, + stdin=stdin, check_result=False, + ) + text = result.stdout.strip() + if text: + try: + return result.returncode, json.loads(text) + except ValueError: + pass + time.sleep(1) + raise Failure('jobs.cli did not return JSON for ' + ' '.join(args)) + + +def set_fault(key, value): + compose('exec', '-T', 'redis', 'redis-cli', 'SET', key, value) + + +def clear_fault(key): + compose('exec', '-T', 'redis', 'redis-cli', 'DEL', key) + + +def clear_faults(): + script = ( + "local keys=redis.call('keys',ARGV[1]) " + "for i=1,#keys do redis.call('del',keys[i]) end return #keys" + ) + compose('exec', '-T', 'redis', 'redis-cli', 'EVAL', script, '0', 'fault:*') + + +def rabbit_queues(): + result = compose('exec', '-T', 'broker', 'rabbitmqctl', '-q', + '-p', 'messenger', 'list_queues', + 'name', 'messages', 'type') + queues = {} + for line in result.stdout.splitlines(): + parts = line.split() + if len(parts) >= 2 and parts[0] not in ('name', 'Timeout:'): + try: + queues[parts[0]] = {'messages': int(parts[1]), + 'type': parts[2] if len(parts) > 2 else ''} + except ValueError: + continue + return queues + + +def wait_for(predicate, timeout, description='condition', interval=0.5): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + last = predicate() + if last: + return last + time.sleep(interval) + raise Failure('timed out waiting for ' + description) + + +def upload(client, actor, chat, data, filename='sample.png', + content_type='image/png'): + result = client.call( + 'POST', + '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename, + 202, + actor=actor, + raw=data, + headers={'Content-Type': content_type}, + schema='Attachment', + ) + check(result['json']['status'] == 'queued', 'upload did not answer queued') + return result['json'] + + +def metadata(client, actor, attachment_id): + return client.call('GET', '/api/v1/attachments/' + attachment_id, + actor=actor, schema='Attachment')['json'] + + +def wait_ready(client, actor, attachment_id, timeout=60, + allow_failed=False): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + meta = metadata(client, actor, attachment_id) + if meta['status'] == 'failed': + if allow_failed: + return meta + raise Failure('attachment failed: ' + + str(meta.get('error_code'))) + if meta['status'] == 'ready': + return meta + time.sleep(0.2) + raise Failure('attachment did not become ready in ' + str(timeout) + 's') + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def variant_sha(meta): + return {item['name']: item['sha256'] for item in meta['variants']} + + +def sample_bytes(): + return (ROOT / 'tests/fixtures/sample.png').read_bytes() + + +def worker_env(name): + result = compose('exec', '-T', 'worker', 'printenv', name, + check_result=False) + return result.stdout.strip() + + +def worker_start_count(): + result = compose('logs', '--no-color', 'worker', check_result=False) + return result.stdout.count('worker ready:') + + +def worker_memory_peak(containers): + names = [line for line in containers.splitlines() if line.strip()] + if not names: + return 'n/a' + result = subprocess.run( + ['docker', 'stats', '--no-stream', '--format', + '{{.Name}} {{.MemUsage}}'] + names, + text=True, capture_output=True, + ) + return result.stdout.strip() + + +def print_step(number, text): + print('[' + str(number) + '] ' + text, flush=True) + + +def new_client(base_url, ca_file=None): + return Client(base_url, ca_file) diff --git a/scripts/lab5/worker_down_demo.py b/scripts/lab5/worker_down_demo.py new file mode 100755 index 0000000..ab4beea --- /dev/null +++ b/scripts/lab5/worker_down_demo.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Level-3 demo: work accepted while the worker is down survives restarts.""" +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from stand import ( # noqa: E402 + Failure, + check, + cli, + compose, + new_client, + print_step, + rabbit_queues, + sample_bytes, + sha256, + upload, + wait_for, + wait_ready, +) +from client import arguments, run # noqa: E402 +from image_probe import jpeg_size # noqa: E402 + + +def main(): + args = arguments('lab5 worker-down durability demo') + client = new_client(args.base_url, args.ca_file) + alice, _bob, _eve, chat = client.bootstrap() + data = sample_bytes() + + print_step(1, 'compose ps') + print(compose('ps', '--format', + 'table {{.Service}}\t{{.Status}}').stdout.strip()) + + print_step(2, 'stop worker') + compose('stop', 'worker') + + print_step(3, 'upload while worker is down (expect 202 queued)') + attachment = upload(client, alice, chat, data, 'durability.png') + attachment_id = attachment['id'] + print('attachment=' + attachment_id + ' status=' + attachment['status']) + + print_step(4, 'content and thumbnail must answer 409 before ready') + for query in ('', '?variant=thumbnail'): + result = client.call( + 'GET', + '/api/v1/attachments/' + attachment_id + '/content' + query, + 409, + actor=alice, + ) + check(result['status'] == 409, 'content was served before ready') + + print_step(5, 'link the queued attachment to messages') + with_attachment = client.message( + alice, chat, '', attachments=[attachment_id], + )['json'] + plain = client.message(alice, chat, 'plain while worker is down')['json'] + check(with_attachment['attachment_ids'] == [attachment_id], + 'message lost the queued attachment') + check(plain['attachment_ids'] == [], 'plain message gained an attachment') + print('message=' + with_attachment['id']) + + print_step(6, 'wait for outbox publish and a message in the queue') + def published(): + _code, status = cli('status', attachment_id) + queues = rabbit_queues() + return ( + status['outbox']['pending'] == 0 + and queues.get('attachments.process', {}).get('messages', 0) >= 1 + ) + wait_for(published, 30, 'outbox publish and queue depth >= 1') + queues = rabbit_queues() + print('queue=' + str(queues.get('attachments.process'))) + + print_step(7, 'restart broker and API with volumes') + compose('restart', 'broker', 'api') + compose('up', '-d', '--no-recreate', '--no-deps', '--wait', 'broker', 'api') + + print_step(8, 'the quorum message survived the broker restart') + def survived(): + depth = rabbit_queues().get('attachments.process', {}).get('messages', 0) + return depth >= 1 + wait_for(survived, 60, 'queue depth >= 1 after broker restart') + print('queue=' + str(rabbit_queues().get('attachments.process'))) + + print_step(9, 'start worker') + compose('start', 'worker') + + print_step(10, 'wait ready and verify the thumbnail') + ready = wait_ready(client, alice, attachment_id, 60) + thumbnail = [v for v in ready['variants'] if v['name'] == 'thumbnail'][0] + content = client.call( + 'GET', + '/api/v1/attachments/' + attachment_id + '/content?variant=thumbnail', + actor=alice, + ) + check(jpeg_size(content['bytes']) == (256, 160), + 'thumbnail is not 256x160 JPEG') + check(len(content['bytes']) == thumbnail['size_bytes'], + 'thumbnail size differs from metadata') + check(sha256(content['bytes']) == thumbnail['sha256'], + 'thumbnail checksum differs from metadata') + history = client.call( + 'GET', + '/api/v1/chats/' + chat['id'] + '/messages?limit=100', + actor=alice, + schema='MessagePage', + )['json'] + check( + any(attachment_id in item['attachment_ids'] + for item in history['items']), + 'message history lost the attachment', + ) + print('ready attachment=' + attachment_id + + ' thumbnail=256x160 sha256=' + thumbnail['sha256'][:16] + '...') + + print_step(11, 'compose ps') + print(compose('ps', '--format', + 'table {{.Service}}\t{{.Status}}').stdout.strip()) + print('PASS: worker-down durability demo') + + +if __name__ == '__main__': + run(main) diff --git a/scripts/lab6/gen_dashboards.py b/scripts/lab6/gen_dashboards.py new file mode 100755 index 0000000..2ee0f5a --- /dev/null +++ b/scripts/lab6/gen_dashboards.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Generates the two provisioned Grafana dashboards (stdlib only). + +Output: infra/grafana/dashboards/messenger-overview.json and +messenger-telemetry.json. Metric names were verified against the live +Prometheus (verify.py inventory). Percentiles are computed from summed buckets, +never averaged across replicas; queue/outbox snapshots use max() because every +API replica publishes the same PostgreSQL snapshot. +""" +import json +from pathlib import Path + +OUT = Path(__file__).resolve().parents[2] / 'infra/grafana/dashboards' +PROM = {'type': 'prometheus', 'uid': 'prometheus'} +LOKI = {'type': 'loki', 'uid': 'loki'} +BIZ = 'job="messenger-api",http_route!~"/health.*|/internal/.*"' + + +class Board: + def __init__(self, uid, title): + self.uid, self.title = uid, title + self.panels = [] + self.y = 0 + self.x = 0 + self.row_h = 0 + self.next_id = 1 + + def row(self, title): + if self.x: + self.y += self.row_h + self.x = 0 + self.panels.append({'type': 'row', 'title': title, 'collapsed': False, + 'id': self._id(), 'panels': [], + 'gridPos': {'h': 1, 'w': 24, 'x': 0, 'y': self.y}}) + self.y += 1 + self.row_h = 0 + + def _id(self): + self.next_id += 1 + return self.next_id - 1 + + def _place(self, w, h): + if self.x + w > 24: + self.y += self.row_h + self.x, self.row_h = 0, 0 + pos = {'h': h, 'w': w, 'x': self.x, 'y': self.y} + self.x += w + self.row_h = max(self.row_h, h) + return pos + + def ts(self, title, queries, unit, description, w=12, h=8, vmin=None, vmax=None): + self.panels.append({ + 'type': 'timeseries', 'title': title, 'id': self._id(), + 'description': description, 'datasource': PROM, + 'gridPos': self._place(w, h), + 'fieldConfig': {'defaults': {**{'unit': unit, 'custom': { + 'lineWidth': 1, 'fillOpacity': 8, 'showPoints': 'never'}}, + **({'min': vmin} if vmin is not None else {}), + **({'max': vmax} if vmax is not None else {})}, + 'overrides': []}, + 'options': {'legend': {'displayMode': 'list', 'placement': 'bottom'}, + 'tooltip': {'mode': 'multi'}}, + 'targets': [{'refId': chr(65 + i), 'datasource': PROM, 'expr': expr, + 'legendFormat': legend} + for i, (expr, legend) in enumerate(queries)]}) + + def stat(self, title, expr, unit, description, w=6, h=4, legend=''): + self.panels.append({ + 'type': 'stat', 'title': title, 'id': self._id(), + 'description': description, 'datasource': PROM, + 'gridPos': self._place(w, h), + 'fieldConfig': {'defaults': {'unit': unit}, 'overrides': []}, + 'options': {'reduceOptions': {'calcs': ['lastNotNull']}, + 'colorMode': 'value'}, + 'targets': [{'refId': 'A', 'datasource': PROM, 'expr': expr, + 'legendFormat': legend}]}) + + def table(self, title, expr, description, w=12, h=8): + self.panels.append({ + 'type': 'table', 'title': title, 'id': self._id(), + 'description': description, 'datasource': PROM, + 'gridPos': self._place(w, h), + 'fieldConfig': {'defaults': {'unit': 'short'}, 'overrides': []}, + 'options': {'showHeader': True}, + 'targets': [{'refId': 'A', 'datasource': PROM, 'expr': expr, + 'instant': True, 'format': 'table'}], + 'transformations': [{'id': 'organize', 'options': { + 'excludeByName': {'Time': True, '__name__': True, + 'job': True, 'Value': True}}}]}) + + def logs(self, title, expr, description, w=12, h=10): + self.panels.append({ + 'type': 'logs', 'title': title, 'id': self._id(), + 'description': description, 'datasource': LOKI, + 'gridPos': self._place(w, h), + 'options': {'showTime': True, 'wrapLogMessage': True, + 'sortOrder': 'Descending', 'enableLogDetails': True}, + 'targets': [{'refId': 'A', 'datasource': LOKI, 'expr': expr, + 'queryType': 'range'}]}) + + def render(self): + return { + 'uid': self.uid, 'title': self.title, 'schemaVersion': 39, + 'version': 1, 'editable': False, 'refresh': '10s', + 'time': {'from': 'now-15m', 'to': 'now'}, 'timezone': 'utc', + 'tags': ['messenger', 'lab6'], 'templating': {'list': []}, + 'annotations': {'list': []}, 'panels': self.panels} + + +def quantiles(metric, by='', selector='', window='1m'): + group = 'le' + (',' + by if by else '') + legend = ' {{' + by + '}}' if by else '' + return [('histogram_quantile(%s, sum by(%s)(rate(%s_bucket%s[%s])))' + % (q, group, metric, selector, window), 'p%d%s' % (round(q * 100), legend)) + for q in (0.5, 0.95, 0.99)] + + +def overview(): + b = Board('messenger-overview', 'Messenger: API и worker') + b.row('API (бизнес-запросы; /health* и /internal/* исключены)') + b.ts('RPS по маршруту и классу статуса', [( + 'sum by (http_route, status_class)(label_replace(rate(http_server_request_duration_seconds_count{%s}[1m]), "status_class", "${1}xx", "http_response_status_code", "(.).."))' % BIZ, + '{{http_route}} {{status_class}}')], 'reqps', + 'rate(http_server_request_duration_seconds_count[1m]) по http_route и классу кода; число запросов — _count гистограммы.') + b.ts('Доля 5xx (1m)', [('messenger:api_errors:rate1m / messenger:api_requests:rate1m', '5xx / бизнес-запросы')], + 'percentunit', 'Recording rules: 5xx rate / все бизнес-запросы за 1m; 4xx — не ошибка сервиса. Пусто без трафика (N/A).', vmin=0, vmax=1) + b.stat('Availability (5m), цель ≥ 99.5%', 'messenger:api_availability:ratio5m', + 'percentunit', '1 - 5xx/все бизнес-запросы за 5m (recording rule messenger:api_availability:ratio5m). N/A без трафика.') + b.stat('Свежие реплики API', 'count((time() - timestamp(target_info{job="messenger-api"})) < 30) or vector(0)', + 'short', 'Число API-реплик, чей target_info обновлялся за последние 30 с (OTLP-метрики).') + b.stat('HAProxy 5xx, rps', 'sum(rate(haproxy_backend_http_responses_total{proxy="api",code="5xx"}[1m])) or vector(0)', + 'reqps', 'HAProxy backend api: ответы 5xx (включая 503 балансировщика, когда нет готовых узлов).') + b.stat('HAProxy: активные серверы', 'haproxy_backend_active_servers{proxy="api"}', 'short', + 'Активные серверы backend api по данным HAProxy PROMEX.') + b.ts('Задержка HTTP: общая p50/p95/p99', quantiles('http_server_request_duration_seconds', selector='{%s}' % BIZ), + 's', 'histogram_quantile по суммированным бакетам всех реплик; перцентили реплик не усредняются.') + b.ts('Задержка HTTP по маршруту p50/p95/p99', quantiles('http_server_request_duration_seconds', by='http_route', selector='{%s}' % BIZ), + 's', 'То же, с разбивкой по route template.') + b.row('Worker и задачи') + b.ts('Задачи по outcome', [('sum by (outcome)(rate(messenger_jobs_processed_total[1m]))', '{{outcome}}')], 'ops', + 'messenger_jobs_processed_total по фактическому outcome (succeeded, retry, failed, ...), задач/с.') + b.ts('Длительность попытки задачи p50/p95/p99', quantiles('messenger_job_duration_seconds'), 's', + 'От claim до commit одной попытки; не включает ожидание в очереди.') + b.ts('Time-to-ready p50/p95/p99', quantiles('messenger_attachment_time_to_ready_seconds'), 's', + 'От durable acceptance (created_at задачи) до commit ready; включает очередь, ретраи и backoff. Измеряется на commit, до ACK и cleanup.') + b.ts('Worker: занято / ёмкость', [('sum(messenger_worker_jobs_active)', 'active'), + ('max(messenger_worker_jobs_capacity)', 'capacity (WORKER_CONCURRENCY)')], + 'short', 'Задач в работе против WORKER_CONCURRENCY; показатели не суммируются.') + b.row('Очередь и outbox (snapshot PostgreSQL, max по репликам)') + b.ts('Глубина очереди по состоянию', [('max by (state)(messenger_jobs_queue_depth)', '{{state}}')], 'short', + 'Незавершённые задачи по state; обе реплики публикуют одно значение, поэтому max, а не sum.') + b.ts('Возраст самой старой задачи', [('max(messenger_jobs_queue_oldest_age_seconds)', 'oldest job age')], 's', + 'Возраст ожидания backlog (alert MessengerJobsQueueLagGrowing: > 30 с), не время обработки.') + b.ts('Outbox: ожидающие и возраст', [('max(messenger_outbox_pending)', 'pending (шт.)'), + ('max(messenger_outbox_oldest_age_seconds)', 'oldest age (с)')], + 'short', 'Неопубликованные записи outbox (доступные к публикации) и возраст старейшей.') + b.ts('RabbitMQ: ready / unacked', [('sum(rabbitmq_queue_messages_ready)', 'ready'), + ('sum(rabbitmq_queue_messages_unacked)', 'unacked')], 'short', + 'Агрегат по очередям, rabbitmq_prometheus (порт 15692, внутри сети).') + b.row('PostgreSQL и процессы') + b.ts('Пул БД: used / idle / max', [ + ('sum by (db_client_connection_state, instance)(db_client_connection_count{job=~"messenger-.*",db_client_connection_pool_name="main"})', '{{db_client_connection_state}} {{instance}}'), + ('max by (instance)(db_client_connection_max{job=~"messenger-.*",db_client_connection_pool_name="main"})', 'max {{instance}}')], + 'short', 'Соединения основного пула по репликам.') + b.ts('Пул БД: ожидающие запросы и wait p95', [ + ('sum by (instance)(db_client_connection_pending_requests{job=~"messenger-.*"})', 'pending {{instance}}'), + ('histogram_quantile(0.95, sum by (le)(rate(db_client_connection_wait_time_seconds_bucket{job=~"messenger-.*"}[1m])))', 'wait p95 (с)')], + 'short', 'Очередь на получение соединения и p95 ожидания (секунды).') + b.ts('Операция БД p95 по db_operation_name', [( + 'histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket{job=~"messenger-.*"}[1m])))', + '{{db_operation_name}}')], 's', 'p95 длительности операций БД по типу операции.') + b.ts('CPU процессов (ядра)', [('sum by (job, instance)(rate(process_cpu_time_seconds_total{job=~"messenger-.*"}[1m]))', '{{job}} {{instance}}')], + 'short', 'rate(process_cpu_time_seconds_total): 1.0 = одно логическое ядро.') + b.ts('RAM процессов', [('process_memory_usage_bytes{job=~"messenger-.*"}', '{{job}} {{instance}}'), + ('v8js_memory_heap_used_bytes{job=~"messenger-.*"}', 'heap {{job}} {{instance}}')], + 'bytes', 'Resident memory процесса и использованная куча V8.') + b.ts('Event loop delay p99', [('nodejs_eventloop_delay_p99_seconds{job=~"messenger-.*"}', '{{job}} {{instance}}')], 's', + 'Задержка event loop (p99 окна, секунды).') + b.row('Логи (переход в трассу по TraceID)') + b.logs('Логи API', '{service_name="messenger-api"}', 'Структурные логи; trace_id — structured metadata, поле TraceID ведёт в Tempo.') + b.logs('Логи worker', '{service_name="messenger-worker"}', 'Структурные логи worker; trace_id ведёт в Tempo.') + return b.render() + + +def telemetry(): + b = Board('messenger-telemetry', 'Messenger: telemetry pipeline') + b.row('Collector') + b.ts('Collector: принято', [ + ('sum(rate(otelcol_receiver_accepted_spans[1m]))', 'spans'), + ('sum(rate(otelcol_receiver_accepted_log_records[1m]))', 'log records'), + ('sum(rate(otelcol_receiver_accepted_metric_points[1m]))', 'metric points')], + 'suffix:items/s', 'Элементов, принятых OTLP-receiver, в секунду (не байты).') + b.ts('Collector: отправлено', [ + ('sum(rate(otelcol_exporter_sent_spans[1m]))', 'spans'), + ('sum(rate(otelcol_exporter_sent_log_records[1m]))', 'log records'), + ('sum(rate(otelcol_exporter_sent_metric_points[1m]))', 'metric points')], + 'suffix:items/s', 'Элементов, успешно отправленных exporter-ами в backend.') + b.ts('Collector: ошибки отправки и постановки в очередь', [ + ('sum by (exporter)(rate(otelcol_exporter_send_failed_spans[1m]))', 'send_failed spans {{exporter}}'), + ('sum by (exporter)(rate(otelcol_exporter_send_failed_log_records[1m]))', 'send_failed logs {{exporter}}'), + ('sum by (exporter)(rate(otelcol_exporter_send_failed_metric_points[1m]))', 'send_failed metrics {{exporter}}'), + ('sum by (exporter)(rate(otelcol_exporter_enqueue_failed_spans[1m]))', 'enqueue_failed spans {{exporter}}'), + ('sum by (exporter)(rate(otelcol_exporter_enqueue_failed_log_records[1m]))', 'enqueue_failed logs {{exporter}}'), + ('sum by (exporter)(rate(otelcol_exporter_enqueue_failed_metric_points[1m]))', 'enqueue_failed metrics {{exporter}}')], + 'suffix:items/s', 'Потери на выходе Collector. Нулевые серии могут отсутствовать до первой ошибки.') + b.ts('Collector: очередь / ёмкость', [ + ('max by (exporter)(otelcol_exporter_queue_size)', 'size {{exporter}}'), + ('max by (exporter)(otelcol_exporter_queue_capacity)', 'capacity {{exporter}}')], + 'short', 'Очередь sending_queue в запросах (batch), не в spans.') + b.ts('Collector: RSS', [('otelcol_process_memory_rss', 'RSS')], 'bytes', + 'Resident set size процесса Collector; лимит контейнера 256 MiB, memory_limiter 204 MiB.') + b.ts('Приложение: экспорт телеметрии (items)', [ + ('sum by (signal, outcome)(rate(messenger_telemetry_export_items_total[1m]))', '{{signal}} {{outcome}}')], + 'suffix:items/s', 'Элементов, дошедших до OTLP-exporter приложения (traces/logs). Не учёт метрик и не все pre-export drops.') + b.row('Backend-хранилища') + b.ts('Loki / Tempo: up', [('up{job=~"loki|tempo"}', '{{job}}')], 'short', '1 — scrape успешен.') + b.ts('Loki / Tempo: ingest', [('sum(rate(loki_distributor_bytes_received_total[1m]))', 'loki'), + ('sum(rate(tempo_distributor_bytes_received_total[1m]))', 'tempo')], + 'Bps', 'Байт, принятых distributor-ами, в секунду.') + b.ts('Prometheus: размер TSDB', [('prometheus_tsdb_storage_blocks_bytes', 'blocks'), + ('prometheus_tsdb_wal_storage_size_bytes', 'wal')], 'bytes', + 'Блоки и WAL локального TSDB (retention 7d).') + b.table('Состояние правил (ALERTS)', 'ALERTS{alertname=~"Messenger.*"}', + 'Pending/firing alerts из метрики ALERTS. Отсутствие строк означает, что нет pending/firing при загруженных rules (правила проверяются через /api/v1/rules).') + return b.render() + + +def main(): + OUT.mkdir(parents=True, exist_ok=True) + for name, board in (('messenger-overview', overview()), + ('messenger-telemetry', telemetry())): + (OUT / (name + '.json')).write_text( + json.dumps(board, indent=2, ensure_ascii=False) + '\n') + print('wrote', OUT / (name + '.json')) + + +if __name__ == '__main__': + main() diff --git a/scripts/lab6/incidents.py b/scripts/lab6/incidents.py new file mode 100755 index 0000000..c5e6a0a --- /dev/null +++ b/scripts/lab6/incidents.py @@ -0,0 +1,676 @@ +#!/usr/bin/env python3 +"""lab6 controlled incidents: worker | db | telemetry. Stdlib only. + +Every scenario runs inside obs.app_environment (SDK on, sampling 1, +FAULT_INJECTION_ENABLED=1) and always undoes its own faults/locks/stopped +services in `finally`. Times are UTC + monotonic offsets; an unobserved +transition is null with a reason, never a guess.""" +import argparse +import calendar +import subprocess +import sys +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measurement # noqa: E402 +import obs # noqa: E402 +import reconcile # noqa: E402 +import resources # noqa: E402 +import verify # noqa: E402 +import workload # noqa: E402 +from obs import Failure, stand, utc_now # noqa: E402 + +ROOT = obs.ROOT + + +def utc_epoch(text): + return calendar.timegm(time.strptime(text[:19], '%Y-%m-%dT%H:%M:%S')) +ALERTS = ('MessengerApiHighErrorRate', 'MessengerJobsQueueLagGrowing') +ENV = {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER_ARG': '1', + 'FAULT_INJECTION_ENABLED': '1', 'LOG_LEVEL': 'INFO'} + + +class Ctx: + def __init__(self, args): + self.args = args + self.obs = verify.make_obs(args) + self.out = Path(args.output_dir) + self.t0 = time.monotonic() + + def mono(self): + return round(time.monotonic() - self.t0, 2) + + def mark(self, timeline, key, extra=None): + timeline[key] = {'utc': utc_now(), 'mono_s': self.mono()} + if extra: + timeline[key].update(extra) + print('[%s] %s' % (timeline[key]['utc'], key), flush=True) + + def actor_chat(self): + c = stand.new_client(self.args.base_url, self.args.ca_file) + alice, _, _, chat = c.bootstrap() + return alice, chat + + +def alert_state(ctx, name): + result = ctx.obs.prom_query('ALERTS{alertname="%s"}' % name) + states = {r['metric'].get('alertstate') for r in result} + if 'firing' in states: + return 'firing' + return 'pending' if 'pending' in states else None + + +def wait_state(ctx, name, want, timeout, timeline, polls): + """want: 'firing' or None (resolved). Returns True when reached.""" + end = time.monotonic() + timeout + while time.monotonic() < end: + state = alert_state(ctx, name) + polls.append({'utc': utc_now(), 'mono_s': ctx.mono(), 'alert': name, 'state': state}) + if state == 'pending' and 'pending' not in timeline: + ctx.mark(timeline, 'pending') + if state == want: + return True + time.sleep(5) + return False + + +class BackgroundLoad: + def __init__(self, ctx, actor, chat, rate, upload_every, phase): + self.stop_event = threading.Event() + self.result = None + self.error = None + + def body(): + try: + self.result = workload.run_window( + ctx.args.base_url, ctx.args.ca_file, actor, chat, rate, 1800, + phase, upload_every=upload_every, stop_event=self.stop_event, + settle=False) + except Exception as exc: # reported by stop() + self.error = exc + self.thread = threading.Thread(target=body, daemon=True) + self.thread.start() + + def stop(self): + self.stop_event.set() + self.thread.join(timeout=120) + if self.error: + raise self.error + if self.result is None: + raise Failure('background load did not finish') + return self.result + + +def baseline(ctx, actor, chat, rate, upload_every): + ctx.obs.require_no_foreign_faults() + for name in ALERTS: + if alert_state(ctx, name) is not None: + raise Failure('alert already active before baseline: ' + name) + result = workload.run_window(ctx.args.base_url, ctx.args.ca_file, actor, chat, + rate, 60, 'baseline', upload_every=upload_every, + settle=False) + drain = obs.wait_drained(result['uploads'], obs=ctx.obs) + for name in ALERTS: + if alert_state(ctx, name) is not None: + raise Failure('alert active at the end of baseline: ' + name) + if not drain['drained']: + raise Failure('baseline jobs did not drain') + return {'load': result['load'], 'drain': drain, 'uploads': result['uploads']} + + +def series(ctx, expr, start, end, step=10): + out = [] + for item in ctx.obs.prom_range(expr, start, end, step): + out.append({'labels': item['metric'], + 'points': [[float(t), v] for t, v in item['values']]}) + return out + + +def peak(rows): + values = [float(v) for r in rows for _, v in r['points'] if v != 'NaN'] + return max(values) if values else None + + +def ready_seconds(ids): + """max/median finished_at - created_at of the jobs of these attachments.""" + if not ids: + return {'n': 0, 'max': None, 'median': None} + values = [] + for i in range(0, len(ids), 200): + chunk = ids[i:i + 200] + arr = "ARRAY[" + ",".join("'" + x + "'" for x in chunk) + "]::uuid[]" + out = obs.psql( + "SELECT COALESCE(string_agg(extract(epoch from (finished_at - created_at))::text, ';'),'') " + "FROM attachment_jobs WHERE status='succeeded' AND attachment_id = ANY(" + arr + ")") + values += [float(x) for x in out.split(';') if x] + return {'n': len(values), 'max': max(values) if values else None, + 'median': measurement.median(values)} + + +def finish(ctx, name, result): + result['passed'] = not result['problems'] + verify.write_json(ctx.out, name, result) + if result['problems']: + raise Failure(name + ': ' + '; '.join(result['problems'])) + print('PASS: ' + name) + + +# ------------------------------------------------------------------- worker + +def scenario_worker(ctx, label=''): + alice, chat = ctx.actor_chat() + result = {'scenario': 'worker', 'profile': {'rate': 20, 'upload_every': 20}, + 'timeline': {}, 'problems': [], 'polls': []} + tl = result['timeline'] + base = baseline(ctx, alice, chat, 20, 20) + result['baseline'] = {'load': base['load'], 'ready_seconds': ready_seconds(base['uploads'])} + load = None + worker_stopped = False + try: + load = BackgroundLoad(ctx, alice, chat, 20, 20, 'incident') + time.sleep(10) + ctx.mark(tl, 'inject') + stand.compose('stop', 'worker') + worker_stopped = True + fired = wait_state(ctx, 'MessengerJobsQueueLagGrowing', 'firing', 150, tl, result['polls']) + if fired: + ctx.mark(tl, 'firing') + else: + tl['firing'] = None + result['problems'].append('queue-lag alert did not fire within 150 s') + # Capture the evidence while the backlog exists. + t_now = time.time() + result['queue_at_firing'] = { + 'oldest_age_max': ctx.obs.prom_scalar('max(messenger_jobs_queue_oldest_age_seconds)'), + 'depth_ready_max': ctx.obs.prom_scalar('max(messenger_jobs_queue_depth{state="ready"})'), + 'depth_ready_sum_over_replicas': ctx.obs.prom_scalar('sum(messenger_jobs_queue_depth{state="ready"})'), + 'depth_ready_per_replica': { + r['metric']['instance']: float(r['value'][1]) + for r in ctx.obs.prom_query('messenger_jobs_queue_depth{state="ready"}')}, + 'outbox_pending_max': ctx.obs.prom_scalar('max(messenger_outbox_pending)'), + } + q = result['queue_at_firing'] + per = list(q['depth_ready_per_replica'].values()) + if len(per) >= 2 and q['depth_ready_max'] != max(per): + result['problems'].append('max() does not equal the per-replica snapshot') + if len(per) >= 2 and q['depth_ready_sum_over_replicas'] == q['depth_ready_max'] and per[0] > 0: + result['problems'].append('replicas not both reporting (cannot show non-doubling)') + finally: + ctx.mark(tl, 'recover_start') + if worker_stopped: + stand.compose('up', '-d', '--no-deps', '--wait', 'worker') + ctx.mark(tl, 'worker_back') + incident_load = load.stop() if load else None + ctx.mark(tl, 'load_stopped') + ids = incident_load['uploads'] + result['incident_load'] = incident_load['load'] + drain = obs.wait_drained(ids + base['uploads'], obs=ctx.obs, timeout=180) + result['drain'] = drain + ctx.mark(tl, 'backlog_drained' if drain['drained'] else 'drain_deadline') + if not drain['drained']: + tl['backlog_drained'] = None + result['problems'].append('backlog not drained within 180 s') + elif any(s != 'ready' for s in drain['states'].values()): + result['problems'].append('some accepted attachments are not ready') + resolved = wait_state(ctx, 'MessengerJobsQueueLagGrowing', None, 180, tl, result['polls']) + if resolved: + ctx.mark(tl, 'resolved') + else: + tl['resolved'] = None + result['problems'].append('queue-lag alert not resolved within 180 s') + end = time.time() + t_inject = utc_epoch(tl['inject']['utc']) + window = (t_inject - 60, end) + result['queries'] = { + 'oldest_age': 'max(messenger_jobs_queue_oldest_age_seconds)', + 'depth': 'max by (state)(messenger_jobs_queue_depth)', + 'outbox': 'max(messenger_outbox_pending)', + 'worker_active': 'sum(messenger_worker_jobs_active)'} + result['series'] = {k: series(ctx, v, *window) for k, v in result['queries'].items()} + peak_age = peak(result['series']['oldest_age']) + result['peak_oldest_age_s'] = peak_age + if peak_age is None or peak_age < 30: + result['problems'].append('queue age did not grow past 30 s') + result['incident_ready_seconds'] = ready_seconds(ids) + if (result['incident_ready_seconds']['max'] or 0) <= (result['baseline']['ready_seconds']['max'] or 0): + result['problems'].append('time-to-ready did not exceed the baseline') + http_ok = result['incident_load']['http_5xx'] == 0 and \ + sum(result['incident_load']['transport_failures'].values()) == 0 + result['http_acceptance_continued'] = http_ok + if not http_ok: + result['problems'].append('HTTP acceptance degraded during worker outage') + finish(ctx, 'incident-worker.json', result) + + +# ----------------------------------------------------------------------- db + +def trace_gap(spans, server): + """Server duration minus the union of its direct child intervals (ms).""" + children = sorted((s['start_ns'], s['end_ns']) for s in spans + if s['parent_span_id'] == server['span_id']) + # Descendants of the transaction span are covered by their ancestor. + covered, last = 0, None + for start, end in children: + if last is None or start > last: + covered += end - start + last = end + elif end > last: + covered += end - last + last = end + return ((server['end_ns'] - server['start_ns']) - covered) / 1e6 + + +def db_time_ms(spans, server): + return sum((s['end_ns'] - s['start_ns']) for s in spans + if s['kind'] == 'CLIENT' and 'db.operation.name' in s['attributes'] + and s['parent_span_id'] == server['span_id']) / 1e6 + + +def sequential_uploads(ctx, actor, chat, count, delay): + c = stand.new_client(ctx.args.base_url, ctx.args.ca_file) + c.timeout = 30 + key = 'fault:api.after_commit_before_publish' + rows = [] + for _ in range(count): + if delay: + stand.set_fault(key, 'delay:%d' % delay) + started = time.monotonic() + r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', + range(200, 600), actor=actor, raw=stand.sample_bytes(), + headers={'Content-Type': 'image/png'}, schema='Attachment') + elapsed = (time.monotonic() - started) * 1000 + consumed = True + if delay: + out = stand.compose('exec', '-T', 'redis', 'redis-cli', 'GET', key).stdout.strip() + consumed = out == '' + rows.append({'request_id': r['headers']['X-Request-Id'], 'status': r['status'], + 'elapsed_ms': elapsed, 'consumed': consumed, + 'attachment_id': r['json']['id'] if r['status'] == 202 else None}) + return rows + + +def server_view(ctx, request_id): + log = verify.http_log(ctx.obs, request_id) + tid, sid = log['labels']['trace_id'], log['labels']['span_id'] + spans = verify.trace_with(ctx.obs, tid, lambda sp: any( + s['span_id'] == sid for s in sp), description='server trace') + server = next(s for s in spans if s['span_id'] == sid) + return spans, server + + +def scenario_db(ctx, label=''): + alice, chat = ctx.actor_chat() + result = {'scenario': 'db', 'profile': {'rate': 2, 'upload_every': 1}, + 'timeline': {}, 'problems': [], 'polls': []} + tl = result['timeline'] + base = baseline(ctx, alice, chat, 2, 1) + result['baseline'] = {'load': base['load']} + load = None + lock_released = False + try: + load = BackgroundLoad(ctx, alice, chat, 2, 1, 'incident') + time.sleep(10) + # Own client: 30 s timeout is set inside workload (REQUEST_TIMEOUT). + with obs.hold_table_lock('attachments') as pid: + ctx.mark(tl, 'inject', {'lock_backend_pid': pid}) + fired = wait_state(ctx, 'MessengerApiHighErrorRate', 'firing', 120, tl, result['polls']) + if fired: + ctx.mark(tl, 'firing') + else: + tl['firing'] = None + result['problems'].append('error-rate alert did not fire within 120 s') + result['at_firing'] = { + 'api_5xx_rate_1m': ctx.obs.prom_scalar('messenger:api_errors:rate1m'), + 'api_request_rate_1m': ctx.obs.prom_scalar('messenger:api_requests:rate1m'), + 'haproxy_5xx_rate_1m': ctx.obs.prom_scalar( + 'sum(rate(haproxy_backend_http_responses_total{proxy="api",code="5xx"}[1m]))', 0.0), + 'db_insert_attachments_p95_s': ctx.obs.prom_scalar( + 'histogram_quantile(0.95, sum by (le)(rate(db_client_operation_duration_seconds_bucket{db_operation_name="INSERT"}[1m])))'), + 'pool_pending': ctx.obs.prom_scalar('sum(db_client_connection_pending_requests)'), + 'pool_used': ctx.obs.prom_scalar('sum(db_client_connection_count{db_client_connection_state="used"})'), + } + lock_released = True + ctx.mark(tl, 'lock_released') + finally: + if not lock_released: + ctx.mark(tl, 'lock_released_in_finally') + incident_load = load.stop() if load else None + ctx.mark(tl, 'load_stopped') + result['incident_load'] = incident_load['load'] + if incident_load['load']['http_5xx'] == 0: + result['problems'].append('no real server 5xx observed in the load') + ids = incident_load['uploads'] + drain = obs.wait_drained(ids + base['uploads'], obs=ctx.obs, timeout=180) + result['drain'] = drain + if drain['drained']: + ctx.mark(tl, 'backlog_drained') + else: + tl['backlog_drained'] = None + result['problems'].append('jobs did not drain after recovery') + if wait_state(ctx, 'MessengerApiHighErrorRate', None, 120, tl, result['polls']): + ctx.mark(tl, 'resolved') + else: + tl['resolved'] = None + result['problems'].append('error-rate alert not resolved within 120 s') + # -- localisation: a 5xx trace where the time went to the DB. + inject_ns = int(utc_epoch(tl['inject']['utc']) - 5) * 10 ** 9 + rows = verify.wait_rows( + ctx.obs, '{service_name="messenger-api"} | event_name="http.request" ' + '| http_response_status_code=~"5.."', timeout=60, back=900) + rows = [r for r in rows if r['ts'] >= inject_ns] + if rows: + row = rows[0] + spans = verify.trace_with(ctx.obs, row['labels']['trace_id'], lambda sp: any( + s['span_id'] == row['labels']['span_id'] for s in sp), description='5xx trace') + server = next(s for s in spans if s['span_id'] == row['labels']['span_id']) + dur = (server['end_ns'] - server['start_ns']) / 1e6 + db_ms = db_time_ms(spans, server) + result['trace_5xx'] = { + 'request_id': row['labels'].get('request_id'), 'trace_id': row['labels']['trace_id'], + 'status': row['labels'].get('http_response_status_code'), + 'server_ms': dur, 'db_children_ms': db_ms, + 'handler_gap_ms': trace_gap(spans, server), + 'db_children': [verify.safe_span(s) | {'duration_ms': (s['end_ns'] - s['start_ns']) / 1e6} + for s in spans if s['kind'] == 'CLIENT' and 'db.operation.name' in s['attributes'] + and s['parent_span_id'] == server['span_id']][:6]} + if db_ms < 0.5 * dur: + result['problems'].append('5xx trace is not dominated by DB spans') + else: + result['problems'].append('no 5xx http.request log found in Loki') + # -- control: handler delay (not DB) shows up as a gap, not as DB time. + ctx.obs.require_no_foreign_faults() + ctrl_chat = ctx.actor_chat() + base_rows = sequential_uploads(ctx, ctrl_chat[0], ctrl_chat[1], 20, 0) + delay_rows = sequential_uploads(ctx, ctrl_chat[0], ctrl_chat[1], 20, 500) + stand.clear_fault('fault:api.after_commit_before_publish') + + def gaps(rows_): + out = [] + for r in rows_: + spans, server = server_view(ctx, r['request_id']) + out.append({'request_id': r['request_id'], + 'server_ms': (server['end_ns'] - server['start_ns']) / 1e6, + 'db_children_ms': db_time_ms(spans, server), + 'handler_gap_ms': trace_gap(spans, server)}) + return out + base_g, delay_g = gaps(base_rows), gaps(delay_rows) + med = measurement.median + shift = med([g['handler_gap_ms'] for g in delay_g]) - med([g['handler_gap_ms'] for g in base_g]) + result['control'] = { + 'baseline_uploads': base_g, 'delayed_uploads': delay_g, + 'handler_gap_shift_ms_median': shift, + 'db_children_ms_median_baseline': med([g['db_children_ms'] for g in base_g]), + 'db_children_ms_median_delayed': med([g['db_children_ms'] for g in delay_g]), + 'all_keys_consumed': all(r['consumed'] for r in delay_rows), + 'all_http_202': all(r['status'] == 202 for r in base_rows + delay_rows), + 'note': 'timer/scheduling noise is part of the shift; the check is ~500 ms +/- 250 ms'} + if not result['control']['all_keys_consumed']: + result['problems'].append('delay fault key was not consumed') + if not result['control']['all_http_202']: + result['problems'].append('control uploads were not all 202') + if not (250 <= shift <= 750): + result['problems'].append('handler gap shift %.0f ms is not ~500 ms' % shift) + cdb = result['control'] + if abs(cdb['db_children_ms_median_delayed'] - cdb['db_children_ms_median_baseline']) > 100: + result['problems'].append('DB time changed in the handler-delay control') + stand.wait_for(lambda: obs.wait_drained( + [r['attachment_id'] for r in base_rows + delay_rows], obs=None, timeout=60, + flush_telemetry=False)['drained'], 90, 'control uploads ready') + end = time.time() + t_inject = utc_epoch(tl['inject']['utc']) + window = (t_inject - 60, t_inject + 240) + result['queries'] = { + 'db_operation_p95_by_op': 'histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket[1m])))', + 'pool_by_state': 'sum by (db_client_connection_state)(db_client_connection_count{db_client_connection_pool_name="main"})', + 'pool_pending': 'sum(db_client_connection_pending_requests)', + 'api_5xx_ratio': 'messenger:api_errors:rate1m / messenger:api_requests:rate1m'} + result['series'] = {k: series(ctx, v, *window) for k, v in result['queries'].items()} + finish(ctx, 'incident-db.json', result) + + +# ---------------------------------------------------------------- telemetry + +def regression_slope(points): + n = len(points) + if n < 3: + return None + mx = sum(x for x, _ in points) / n + my = sum(y for _, y in points) / n + den = sum((x - mx) ** 2 for x, _ in points) + return sum((x - mx) * (y - my) for x, y in points) / den if den else None + + +def rss_trend(samples, service, after_s, start_mono): + pts = [(s['mono'] - start_mono, s['rss_bytes']) for s in samples + if s['service'] == service and s.get('rss_bytes') is not None + and s['mono'] - start_mono >= after_s] + by_tick = {} + for t, v in pts: + by_tick.setdefault(round(t / 5), []).append((t, v)) + summed = [(sum(t for t, _ in g) / len(g), sum(v for _, v in g)) for g in by_tick.values()] + values = [v for _, v in summed] + return {'points': len(summed), 'min': min(values) if values else None, + 'max': max(values) if values else None, + 'slope_bytes_per_s': regression_slope(summed), + 'first': values[0] if values else None, 'last': values[-1] if values else None} + + +def sdk_overflow_logs(since_utc): + result = subprocess.run( + ['docker', 'compose', '--env-file', stand.ENV_FILE, 'logs', '--no-color', + '--no-log-prefix', '--since', since_utc, 'api', 'worker'], + cwd=ROOT, text=True, capture_output=True, timeout=180) + count = 0 + for line in result.stdout.splitlines(): + if '"event":"otel.sdk"' in line and ('queue' in line.lower() or 'dropped' in line.lower()): + count += 1 + return count + + +def resume_probe(ctx, actor, chat, count): + """After recovery: fresh requests must reach Loki (logs) and Tempo (traces).""" + c = stand.new_client(ctx.args.base_url, ctx.args.ca_file) + since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 1)) + start_ns = time.time_ns() - 5 * 10 ** 9 + requests = [] + for i in range(count): + r = c.message(actor, chat, 'lab6-resume-%d' % i) + requests.append({'request_id': r['headers']['X-Request-Id'], 'status': r['status']}) + _, summary = reconcile.reconcile(ctx.obs, 'full', requests, since, start_ns, + time.time_ns() + 60 * 10 ** 9) + return summary + + +def telemetry_outage(ctx, service, alice, chat, repeat): + out = {'service': service, 'timeline': {}, 'problems': []} + tl = out['timeline'] + ctx.obs.require_no_foreign_faults() + base = baseline(ctx, alice, chat, 20, 20) + out['baseline'] = {'load': base['load']} + state_before = ctx.obs.app_state() + ids = resources.container_map() + sampler = resources.ResourceSampler(ids, interval=5.0) + sampler.start() + sampler_start = time.monotonic() + since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 1)) + pre_failed = ctx.obs.prom_scalar('sum(messenger_telemetry_export_items_total{outcome="failed"})', 0.0) + load = BackgroundLoad(ctx, alice, chat, 20, 20, service + '-outage') + stopped = False + t_smoke = None + try: + time.sleep(10) + ctx.mark(tl, 'inject') + t_inject = time.time() + stand.compose('stop', service) + stopped = True + t_start = time.monotonic() + smoke = subprocess.run(['make', 'test', 'BASE_URL=' + ctx.args.base_url], cwd=ROOT, + capture_output=True, text=True, timeout=80) + t_smoke = time.monotonic() - t_start + out['smoke_during_outage'] = {'returncode': smoke.returncode, + 'seconds': round(t_smoke, 1), + 'tail': smoke.stdout.strip().splitlines()[-1:] if smoke.stdout else []} + if smoke.returncode != 0: + out['problems'].append('make test failed during the outage') + remaining = 90 - (time.monotonic() - t_start) + if remaining > 0: + time.sleep(remaining) + if service == 'tempo': + out['collector_during_outage'] = { + 'queue_size_max': ctx.obs.prom_scalar('max(max_over_time(otelcol_exporter_queue_size{exporter="otlp/tempo"}[90s]))'), + 'queue_capacity': ctx.obs.prom_scalar('max(otelcol_exporter_queue_capacity{exporter="otlp/tempo"})'), + 'send_failed_spans_increase': ctx.obs.prom_scalar('sum(increase(otelcol_exporter_send_failed_spans[90s]))', 0.0), + 'enqueue_failed_spans_increase': ctx.obs.prom_scalar('sum(increase(otelcol_exporter_enqueue_failed_spans[90s]))', 0.0), + 'logs_sent_increase': ctx.obs.prom_scalar('sum(increase(otelcol_exporter_sent_log_records[90s]))', 0.0), + 'metrics_sent_increase': ctx.obs.prom_scalar('sum(increase(otelcol_exporter_sent_metric_points[90s]))', 0.0), + 'collector_rss_bytes': ctx.obs.prom_scalar('otelcol_process_memory_rss'), + 'loki_up': ctx.obs.prom_scalar('up{job="loki"}'), 'prometheus_ready': True} + ctx.mark(tl, 'outage_end') + finally: + if stopped: + stand.compose('start', service) + ctx.mark(tl, 'recover') + try: + incident_load = load.stop() + finally: + ctx.mark(tl, 'load_stopped') + t_restore = time.time() + ctx.obs.wait_ready(timeout=180, app_telemetry=True, provisioning=True) + ctx.mark(tl, 'backends_ready') + drain = obs.wait_drained(incident_load['uploads'] + base['uploads'], obs=ctx.obs, timeout=180) + out['drain'] = drain + if drain['drained']: + ctx.mark(tl, 'backlog_drained') + else: + out['problems'].append('jobs did not drain') + sampler.stop() + out['resume_probe'] = resume_probe(ctx, alice, chat, 10) + probe = out['resume_probe'] + if probe.get('sampled_present') != 10 or probe.get('log_exported') != 10: + out['problems'].append('traces/logs did not resume after recovery: %s' % probe) + out['incident_load'] = incident_load['load'] + if incident_load['load']['http_5xx'] or sum(incident_load['load']['transport_failures'].values()): + out['problems'].append('business traffic degraded during telemetry outage') + # -- no restarts/OOM, same instances. + state_after = ctx.obs.app_state() + for svc in ('api', 'worker'): + if set(state_before[svc]) != set(state_after[svc]): + out['problems'].append('instance IDs changed for ' + svc) + for cid, info in state_after[svc].items(): + if info['restarts'] != state_before[svc].get(cid, info)['restarts'] or info['oom_killed']: + out['problems'].append('restart/OOM in ' + svc) + summary = resources.summarize(sampler.samples) + out['resources'] = {k: v for k, v in summary.items() if k != 'sample_errors'} + out['sample_errors'] = summary['sample_errors'] + out['memory_vs_limit'] = { + svc: (v['container_memory_bytes']['max'] / v['mem_limit_bytes']) + for svc, v in summary.items() if svc != 'sample_errors' + and v['mem_limit_bytes'] and v['container_memory_bytes']['max'] is not None} + for svc, ratio in out['memory_vs_limit'].items(): + if ratio >= 1.0: + out['problems'].append(svc + ' memory at/over limit') + out['rss_trend_after_first_minute'] = { + svc: rss_trend(sampler.samples, svc, 60, sampler_start) + for svc in (('otel-collector', 'api', 'worker') if service == 'collector' or service == 'otel-collector' + else ('otel-collector',))} + out['sdk_queue_diagnostic_messages'] = sdk_overflow_logs(since) + # -- stdout vs backends for requests accepted during the outage. + inject_unix = utc_epoch(tl['inject']['utc']) + during = [s for s in incident_load['slots'] if s.get('outcome') == 'http' + and s.get('request_id') and s['kind'] == 'message'] + stdout = reconcile.stdout_http_logs(since) + # slots are relative to the load t0; classify by stdout timestamp instead. + in_window = [] + for s in during: + row = stdout.get(s['request_id']) + if row is None: + continue + ts = utc_epoch(row['timestamp']) + if inject_unix <= ts <= inject_unix + 90: + in_window.append((s, row)) + sampled_window = [(s, r) for s, r in in_window if r.get('trace_sampled') is True] + step = max(1, len(sampled_window) // 100) + probe = sampled_window[::step][:100] + targets = {s['request_id']: (r['trace_id'], r['span_id']) for s, r in probe} + found = reconcile.tempo_server_spans(ctx.obs, targets, deadline_s=60) + out['stdout_vs_tempo'] = { + 'requests_in_outage_window_with_stdout': len(in_window), + 'sampled_in_window_per_stdout': len(sampled_window), + 'tempo_probe_size': len(probe), + 'tempo_probe_missing_server_spans': sum(1 for v in found.values() if not v), + 'note': 'loss is measured for SERVER root spans only, on a systematic probe ' + 'sample; it does not count lost child spans'} + if not in_window: + out['problems'].append('no stdout http.request lines in the outage window') + if any(not r.get('trace_id') or r.get('trace_sampled') is not True for _, r in sampled_window): + out['problems'].append('stdout trace fields missing') + if service == 'tempo': + c = out['collector_during_outage'] + if (c['queue_size_max'] or 0) > (c['queue_capacity'] or 128): + out['problems'].append('Collector queue exceeded capacity') + if not (c['send_failed_spans_increase'] or 0) > 0: + out['problems'].append('Collector did not count failed span exports') + if not (c['logs_sent_increase'] or 0) > 0 or not (c['metrics_sent_increase'] or 0) > 0: + out['problems'].append('Loki/Prometheus paths stopped during the Tempo outage') + else: + post_failed = ctx.obs.prom_scalar('sum(messenger_telemetry_export_items_total{outcome="failed"})', 0.0) + out['app_export_failed_items'] = {'before': pre_failed, 'after': post_failed, + 'delta': post_failed - pre_failed if post_failed >= pre_failed else None, + 'reason': None if post_failed >= pre_failed else 'counter_reset'} + if not (out['app_export_failed_items']['delta'] or 0) > 0: + out['problems'].append('app failed-export counter did not grow') + resumed = {name: ctx.obs.prom_scalar(expr, 0.0) for name, expr in ( + ('spans_sent_300s', 'sum(increase(otelcol_exporter_sent_spans[300s]))'), + ('logs_sent_300s', 'sum(increase(otelcol_exporter_sent_log_records[300s]))'), + ('metrics_sent_300s', 'sum(increase(otelcol_exporter_sent_metric_points[300s]))'))} + out['signals_resumed'] = resumed + if not all(v > 0 for v in resumed.values()): + out['problems'].append('not all three signals resumed') + return out + + +def scenario_telemetry(ctx, label=''): + alice, chat = ctx.actor_chat() + result = {'scenario': 'telemetry', 'repeat': label, 'problems': [], 'outages': []} + for service in ('tempo', 'otel-collector'): + outage = telemetry_outage(ctx, service, alice, chat, label) + result['outages'].append(outage) + result['problems'] += [service + ': ' + p for p in outage['problems']] + name = 'incident-telemetry-%s.json' % label + finish(ctx, name, result) + + +SCENARIOS = {'worker': scenario_worker, 'db': scenario_db, 'telemetry': scenario_telemetry} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--scenario', required=True, choices=sorted(SCENARIOS)) + parser.add_argument('--repeat', type=int, default=1) + parser.add_argument('--base-url', default='http://localhost:8080') + parser.add_argument('--ca-file') + parser.add_argument('--prometheus-url', default='http://localhost:9090') + parser.add_argument('--grafana-url', default='http://localhost:3000') + parser.add_argument('--output-dir', default='evidence/lab6') + args = parser.parse_args(argv) + ctx = Ctx(args) + failed = False + try: + with ctx.obs.app_environment(ENV): + for repeat in range(1, args.repeat + 1): + try: + SCENARIOS[args.scenario](ctx, str(repeat)) + except Failure as error: + failed = True + print('FAIL: ' + str(error), file=sys.stderr) + break + except Failure as error: + print('FAIL: ' + str(error), file=sys.stderr) + return 1 + return 1 if failed else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/lab6/measurement.py b/scripts/lab6/measurement.py new file mode 100644 index 0000000..418a651 --- /dev/null +++ b/scripts/lab6/measurement.py @@ -0,0 +1,337 @@ +"""Pure measurement logic for lab6 track 1 (no I/O): statistics, counter +deltas, cohort classification, run validity and the p25/full selection rules. +Everything here is unit-tested in test_measurement.py.""" +import math + +MODES = { + 'off': {'OTEL_SDK_DISABLED': 'true', 'OTEL_TRACES_SAMPLER_ARG': '1'}, + 'full': {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER_ARG': '1'}, + 'p25': {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER_ARG': '0.25'}, + 'p10': {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER_ARG': '0.1'}, +} +SAMPLER_RATIO = {'off': None, 'full': 1.0, 'p25': 0.25, 'p10': 0.1} +ORDERS = (('off', 'full', 'p25', 'p10'), ('p25', 'off', 'p10', 'full'), + ('p10', 'p25', 'full', 'off')) +START_LAG_LIMIT_MS = 50.0 +COMPLETION_LIMIT = 0.99 +SPAN_RATIO_LIMIT = 0.5 +LATENCY_RATIO_LIMIT = 1.10 + + +# ----------------------------------------------------------------- statistics + +def nearest_rank(values, q): + """Nearest-rank quantile: sorted[ceil(n*q)-1] (same as tests/load.py).""" + if not values: + return None + ordered = sorted(values) + return ordered[max(0, math.ceil(len(ordered) * q) - 1)] + + +def median(values): + values = [v for v in values if v is not None] + if not values: + return None + ordered = sorted(values) + n = len(ordered) + mid = n // 2 + return ordered[mid] if n % 2 else (ordered[mid - 1] + ordered[mid]) / 2 + + +def spread(values): + values = [v for v in values if v is not None] + if not values: + return {'min': None, 'median': None, 'max': None, 'n': 0} + return {'min': min(values), 'median': median(values), 'max': max(values), + 'n': len(values)} + + +def relative(value, reference): + if value is None or reference in (None, 0): + return None + return value / reference - 1.0 + + +def miss_all_probability(ratio, n): + """(1-r)^N: chance that independent root sampling keeps none of N events. + A model assumption, not a measurement.""" + return (1.0 - ratio) ** n + + +# ---------------------------------------------------------------------- load + +ERROR_OUTCOMES = ('timeout', 'transport_error', 'protocol_error') + + +def slot_completed(slot): + return slot['outcome'] == 'http' + + +def summarize_load(slots, rate): + """slots: one record per *planned* slot, including client_dropped ones. + + Dropped and late slots stay in the denominator; p95 includes error + responses (it is not a latency of successes only).""" + scheduled = len(slots) + done = [s for s in slots if slot_completed(s)] + dropped = sum(1 for s in slots if s['outcome'] == 'client_dropped') + failures = {k: sum(1 for s in slots if s['outcome'] == k) + for k in ERROR_OUTCOMES} + http_5xx = sum(1 for s in done if s['status'] >= 500) + http_4xx = sum(1 for s in done if 400 <= s['status'] < 500) + successes = [s for s in done if 200 <= s['status'] < 300] + started = [s for s in slots if s.get('start_lag_ms') is not None] + lag = [s['start_lag_ms'] for s in started] + sched_all = [s['scheduled_ms'] for s in done] + service_all = [s['service_ms'] for s in done] + return { + 'rate_rps': rate, + 'scheduled': scheduled, + 'completed': len(done), + 'completed_ratio': (len(done) / scheduled) if scheduled else None, + 'client_dropped': dropped, + 'transport_failures': failures, + 'http_5xx': http_5xx, + 'http_4xx': http_4xx, + 'http_2xx': len(successes), + 'start_lag_ms_p95': nearest_rank(lag, 0.95), + 'start_lag_ms_max': max(lag) if lag else None, + 'scheduled_ms': {q: nearest_rank(sched_all, v) for q, v in + (('p50', .5), ('p95', .95), ('p99', .99))}, + 'service_ms': {q: nearest_rank(service_all, v) for q, v in + (('p50', .5), ('p95', .95), ('p99', .99))}, + 'success_scheduled_ms': {q: nearest_rank( + [s['scheduled_ms'] for s in successes], v) for q, v in + (('p50', .5), ('p95', .95), ('p99', .99))}, + 'success_service_ms': {q: nearest_rank( + [s['service_ms'] for s in successes], v) for q, v in + (('p50', .5), ('p95', .95), ('p99', .99))}, + } + + +def load_errors(load): + """HTTP/protocol errors among delivered healthy traffic.""" + return (load['http_5xx'] + sum(load['transport_failures'].values())) + + +def delivered_stream(load): + """Generator delivered the planned stream (protocol validity).""" + reasons = [] + if load['client_dropped']: + reasons.append('client_dropped=%d' % load['client_dropped']) + lag = load['start_lag_ms_p95'] + if lag is None or lag > START_LAG_LIMIT_MS: + reasons.append('start_lag_p95=%s' % lag) + return reasons + + +# ------------------------------------------------------------------ counters + +def counter_delta(start, end, failure_only=False): + """-> (delta, reason). Never turns a missing positive series into zero and + never reports a reset as a negative loss.""" + if start is None and end is None: + if failure_only: + return 0.0, 'absent_until_first_error' + return None, 'missing_series' + if start is None: + if failure_only: + return end, 'series_created_in_window' + return None, 'missing_start' + if end is None: + return None, 'missing_end' + if end < start: + return None, 'counter_reset' + return end - start, None + + +# ------------------------------------------------------------------- cohorts + +def classify_record(mode, record): + """Classify one cohort request. + + record: {'stdout': None | {'trace_id','span_id','trace_sampled'} (the keys + are absent when the SDK is off or no span context), 'loki': True/False/None + (None: backend observation incomplete), 'span': True/False/None}. + Returns (trace_class, log_class).""" + stdout = record.get('stdout') + if stdout is None: + return 'unmatched_stdout', 'incomplete_observation' + if mode == 'off': + if any(k in stdout for k in ('trace_id', 'span_id', 'trace_sampled')): + return 'ids_present_with_sdk_off', 'not_applicable' + return 'not_applicable', 'not_applicable' + sampled = stdout.get('trace_sampled') + if not stdout.get('trace_id') or not stdout.get('span_id') or \ + not isinstance(sampled, bool): + return 'unmatched_stdout', 'incomplete_observation' + if record.get('loki') is None: + log_class = 'incomplete_observation' + elif record['loki']: + log_class = 'exported' + else: + log_class = 'missing_exported_logs' + if sampled is False: + return 'intentional_unsampled', log_class + if record.get('span') is None: + return 'incomplete_observation', log_class + return ('sampled_present' if record['span'] else 'sampled_missing'), log_class + + +def summarize_cohort(mode, records): + counts = {'n': len(records)} + for record in records: + trace_class, log_class = classify_record(mode, record) + counts[trace_class] = counts.get(trace_class, 0) + 1 + counts['log_' + log_class] = counts.get('log_' + log_class, 0) + 1 + counts['retained_traces'] = counts.get('sampled_present', 0) + return counts + + +def export_loss(items_failed_delta, send_failed, enqueue_failed): + """Telemetry export losses; a false trace_sampled flag is NOT a loss.""" + parts = {'app_export_failed_items': items_failed_delta, + 'collector_send_failed': send_failed, + 'collector_enqueue_failed': enqueue_failed} + known = [v for v in parts.values() if isinstance(v, (int, float))] + return {'parts': parts, 'total_known': sum(known), + 'loss': sum(known) > 0} + + +# ------------------------------------------------------------------ validity + +def evaluate_run(summary): + """-> (valid, invalid_reasons, configuration_failures). + + Invalid = the protocol was not executed as specified; configuration + failures are valid adverse outcomes and stay in the matrix.""" + invalid = list(summary.get('measurement_defects', [])) + failures = [] + load = summary['load'] + invalid += delivered_stream(load) + if load['completed_ratio'] is None or load['completed_ratio'] < COMPLETION_LIMIT: + invalid.append('completed_ratio=%s' % load['completed_ratio']) + if summary.get('effective_mode_ok') is False: + invalid.append('effective_env_mismatch') + if summary.get('image_ids_ok') is False: + invalid.append('image_changed') + if summary.get('foreign_faults'): + invalid.append('foreign_faults') + for name, cohort in (summary.get('cohorts') or {}).items(): + if cohort.get('invalid'): + invalid.append('cohort_invalid:%s' % name) + # Counter resets are only explained by an observed restart/OOM. + for name, item in (summary.get('ingest') or {}).items(): + if isinstance(item, dict) and item.get('reason') == 'counter_reset' \ + and not summary.get('restarts'): + invalid.append('unexplained_counter_reset:%s' % name) + # --- adverse outcomes of the configuration (valid) + if load_errors(load): + failures.append('healthy_errors=%d' % load_errors(load)) + if summary.get('not_ready_at_deadline'): + failures.append('not_ready_at_deadline=%d' % summary['not_ready_at_deadline']) + if summary.get('integrity_errors'): + failures.append('healthy_errors_integrity=%d' % summary['integrity_errors']) + if summary.get('restarts'): + failures.append('restart_or_oom') + loss = summary.get('export_failures') or {} + if loss.get('loss'): + failures.append('export_loss') + for name, cohort in (summary.get('cohorts') or {}).items(): + if cohort.get('sampled_missing'): + failures.append('sampled_missing:%s=%d' % (name, cohort['sampled_missing'])) + if cohort.get('log_missing_exported_logs'): + failures.append('missing_exported_logs:%s=%d' % ( + name, cohort['log_missing_exported_logs'])) + return (not invalid), invalid, failures + + +def matrix_entry(summary): + """Every protocol-run stays in the matrix, valid-adverse included.""" + return { + 'mode': summary['mode'], 'repeat': summary.get('repeat'), + 'attempt': summary.get('attempt', 1), 'valid': summary['valid'], + 'invalid_reasons': summary['invalid_reasons'], + 'configuration_failures': summary['configuration_failures'], + 'spans_per_operation': summary.get('spans_per_operation'), + 'scheduled_p95_ms': (summary['load']['scheduled_ms'] or {}).get('p95'), + 'dir': summary.get('dir'), + } + + +# ---------------------------------------------------------------- selection + +def _clean(run): + return (run['valid'] and not any( + f.startswith(('healthy_errors', 'not_ready', 'restart', 'export_loss')) + for f in run['configuration_failures'])) + + +def _retained(run, name): + return (run['cohorts'].get(name) or {}).get('retained_traces', 0) + + +def _no_missing(run): + for cohort in run['cohorts'].values(): + if cohort.get('sampled_missing') or cohort.get('log_missing_exported_logs') \ + or cohort.get('log_incomplete_observation') \ + or cohort.get('unmatched_stdout') or cohort.get('incomplete_observation'): + return False + return True + + +def full_reference(full_runs): + """Frozen reference: medians of the three full runs; None if any datum is + unmeasurable (then p25 cannot be declared a winner).""" + spans = [r.get('spans_per_operation') for r in full_runs] + p95 = [r['load']['scheduled_ms']['p95'] for r in full_runs] + ok = (len(full_runs) == 3 and all(r['valid'] for r in full_runs) and + all(v is not None for v in spans + p95)) + return {'complete': ok, 'spans_per_operation_median': median(spans), + 'scheduled_p95_ms_median': median(p95), + 'run_dirs': [r.get('dir') for r in full_runs]} + + +def select_p25(full_runs, p25_runs): + ref = full_reference(full_runs) + checks = {'full_reference_complete': ref['complete']} + if not ref['complete'] or len(p25_runs) != 3: + checks['p25_runs'] = len(p25_runs) == 3 + return {'passed': False, 'checks': checks, 'reference': ref} + checks['all_valid_clean'] = all(_clean(r) for r in p25_runs) + checks['retained_error_and_slow_each_run'] = all( + _retained(r, 'error') >= 1 and _retained(r, 'slow') >= 1 for r in p25_runs) + checks['no_missing_spans_or_logs'] = all(_no_missing(r) for r in p25_runs) + spans = median([r.get('spans_per_operation') for r in p25_runs]) + checks['spans_median_le_50pct_full'] = ( + spans is not None and spans <= SPAN_RATIO_LIMIT * ref['spans_per_operation_median']) + p95 = median([r['load']['scheduled_ms']['p95'] for r in p25_runs]) + checks['scheduled_p95_le_110pct_full'] = ( + p95 is not None and p95 <= LATENCY_RATIO_LIMIT * ref['scheduled_p95_ms_median']) + return {'passed': all(checks.values()), 'checks': checks, 'reference': ref, + 'p25_spans_per_operation_median': spans, + 'p25_scheduled_p95_ms_median': p95} + + +def validate_single(run, mode, ref): + """One fresh run against the FROZEN full reference (never a 3-run median + of the validation itself).""" + checks = {'protocol_valid': run['valid'], + 'zero_errors_notready_loss': _clean(run)} + if mode == 'p25': + checks['complete_stdout_and_logs'] = _no_missing(run) and all( + (run['cohorts'].get(n) or {}).get('n') == 40 for n in ('error', 'slow')) + checks['retained_each_class'] = ( + _retained(run, 'error') >= 1 and _retained(run, 'slow') >= 1) + spans = run.get('spans_per_operation') + checks['spans_le_50pct_frozen_full'] = ( + spans is not None and spans <= SPAN_RATIO_LIMIT * ref['spans_per_operation_median']) + p95 = run['load']['scheduled_ms']['p95'] + checks['scheduled_p95_le_110pct_frozen_full'] = ( + p95 is not None and p95 <= LATENCY_RATIO_LIMIT * ref['scheduled_p95_ms_median']) + else: + checks['complete_stdout_and_logs'] = _no_missing(run) + checks['all_80_server_spans'] = all( + (run['cohorts'].get(n) or {}).get('sampled_present') == 40 + for n in ('error', 'slow')) + return {'passed': all(checks.values()), 'checks': checks, 'mode': mode} diff --git a/scripts/lab6/obs.py b/scripts/lab6/obs.py new file mode 100644 index 0000000..b9aff35 --- /dev/null +++ b/scripts/lab6/obs.py @@ -0,0 +1,675 @@ +"""Shared lab6 helpers: Prometheus/Loki/Tempo/Grafana client, controlled app +environment, SQL table lock, batch drain. Python 3.9+, standard library only.""" +import base64 +import binascii +import contextlib +import json +import os +import select +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from scripts.lab5 import stand # noqa: E402 + +Failure = stand.Failure + +HTTP_TIMEOUT = 10 +SCRAPE_JOBS = ('prometheus', 'otel-collector', 'haproxy', 'rabbitmq', 'loki', + 'tempo') +RULE_ALERTS = ('MessengerApiHighErrorRate', 'MessengerJobsQueueLagGrowing') +DASHBOARD_UIDS = ('messenger-overview', 'messenger-telemetry') +DATASOURCE_UIDS = ('prometheus', 'loki', 'tempo') +LOCKABLE_TABLES = ('messages', 'attachments') + +# Keys the controller may change/restore (identical for api and worker). +MUTABLE_KEYS = ( + 'OTEL_SDK_DISABLED', 'OTEL_TRACES_SAMPLER_ARG', 'OTEL_METRIC_EXPORT_INTERVAL', + 'OTEL_EXPORTER_OTLP_ENDPOINT', 'OTEL_EXPORTER_OTLP_PROTOCOL', + 'OTEL_EXPORTER_OTLP_TIMEOUT', 'OTEL_RESOURCE_ATTRIBUTES', + 'OTEL_BSP_MAX_QUEUE_SIZE', 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE', + 'OTEL_BSP_SCHEDULE_DELAY', 'OTEL_BLRP_MAX_QUEUE_SIZE', + 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE', 'OTEL_BLRP_SCHEDULE_DELAY', + 'LOG_LEVEL', 'CACHE_MODE', 'FAULT_INJECTION_ENABLED', +) +# Recorded as diagnostics, never settable. +DIAGNOSTIC_KEYS = ('OTEL_SERVICE_NAME', 'SERVICE_VERSION') + +# Baseline of the SDK knobs (compose defaults) used by track1 and incidents. +SDK_DEFAULTS = { + 'OTEL_SDK_DISABLED': 'false', + 'OTEL_TRACES_SAMPLER_ARG': '1', + 'OTEL_METRIC_EXPORT_INTERVAL': '10000', + 'OTEL_EXPORTER_OTLP_TIMEOUT': '5000', + 'OTEL_BSP_MAX_QUEUE_SIZE': '2048', + 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE': '512', + 'OTEL_BSP_SCHEDULE_DELAY': '1000', + 'OTEL_BLRP_MAX_QUEUE_SIZE': '2048', + 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE': '512', + 'OTEL_BLRP_SCHEDULE_DELAY': '1000', + 'LOG_LEVEL': 'INFO', +} + + +def utc_now(): + return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), + _NoRedirect()) + + +def http_get(url, headers=None, timeout=HTTP_TIMEOUT): + """GET returning (status, bytes); never prints the URL query/headers.""" + request = urllib.request.Request(url, headers=headers or {}) + try: + with _OPENER.open(request, timeout=timeout) as response: + return response.status, response.read() + except urllib.error.HTTPError as error: + with error: + return error.code, error.read() + except (urllib.error.URLError, TimeoutError, OSError) as exc: + raise Failure('GET ' + url.split('?')[0] + ': connection failure (' + + type(exc).__name__ + ')') from None + + +def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,)): + status, data = http_get(url, headers, timeout) + if status not in allow: + raise Failure('GET ' + url.split('?')[0] + ': status ' + str(status)) + try: + return status, json.loads(data) if data else None + except (ValueError, UnicodeError): + raise Failure('GET ' + url.split('?')[0] + ': invalid JSON') from None + + +# ---------------------------------------------------------------- trace JSON + +def normalize_id(value, nbytes): + """Hex or base64 ID -> lowercase hex of exactly nbytes; else Failure.""" + if not isinstance(value, str): + raise Failure('trace id is not a string') + if value == '': + return '' + if len(value) == nbytes * 2: + try: + int(value, 16) + return value.lower() + except ValueError: + pass + try: + raw = base64.b64decode(value, validate=True) + except (binascii.Error, ValueError): + raise Failure('unrecognised trace/span id encoding') from None + if len(raw) != nbytes: + raise Failure('trace/span id has wrong length') + return raw.hex() + + +def _any_value(node): + if not isinstance(node, dict): + return node + for key in ('stringValue', 'boolValue', 'doubleValue'): + if key in node: + return node[key] + if 'intValue' in node: + return int(node['intValue']) + if 'arrayValue' in node: + return [_any_value(v) for v in node['arrayValue'].get('values', [])] + return None + + +def _attributes(items): + out = {} + for item in items or []: + out[item['key']] = _any_value(item.get('value')) + return out + + +_KIND = {0: 'UNSPECIFIED', 1: 'INTERNAL', 2: 'SERVER', 3: 'CLIENT', + 4: 'PRODUCER', 5: 'CONSUMER'} +_STATUS = {0: 'UNSET', 1: 'OK', 2: 'ERROR'} + + +def normalize_trace(document): + """Tempo JSON (batches or resourceSpans) -> list of span dicts.""" + if not isinstance(document, dict): + raise Failure('unknown Tempo response format') + batches = document.get('batches', document.get('resourceSpans')) + if batches is None: + raise Failure('unknown Tempo response format (no batches/resourceSpans)') + spans = [] + for batch in batches: + resource = _attributes(batch.get('resource', {}).get('attributes')) + scopes = batch.get('scopeSpans', batch.get('instrumentationLibrarySpans')) + if scopes is None: + raise Failure('unknown Tempo batch format (no scopeSpans)') + for scope in scopes: + for span in scope.get('spans', []): + kind = span.get('kind', 0) + if isinstance(kind, str): + kind = kind.replace('SPAN_KIND_', '') + else: + kind = _KIND.get(kind, str(kind)) + status = span.get('status', {}).get('code', 0) + if isinstance(status, str): + status = status.replace('STATUS_CODE_', '') + else: + status = _STATUS.get(status, str(status)) + spans.append({ + 'trace_id': normalize_id(span.get('traceId', ''), 16), + 'span_id': normalize_id(span.get('spanId', ''), 8), + 'parent_span_id': normalize_id( + span.get('parentSpanId', ''), 8), + 'name': span.get('name', ''), + 'kind': kind, + 'start_ns': int(span.get('startTimeUnixNano', 0)), + 'end_ns': int(span.get('endTimeUnixNano', 0)), + 'attributes': _attributes(span.get('attributes')), + 'status': status, + 'links': [{ + 'trace_id': normalize_id(link.get('traceId', ''), 16), + 'span_id': normalize_id(link.get('spanId', ''), 8), + } for link in span.get('links', [])], + 'service': resource.get('service.name'), + 'instance': resource.get('service.instance.id'), + }) + return spans + + +# ------------------------------------------------------------------- client + +class ObsClient: + def __init__(self, prometheus_url, grafana_url, password_file=None, + base_url=None, ca_file=None): + self.prometheus = prometheus_url.rstrip('/') + self.grafana = grafana_url.rstrip('/') + self.base_url = base_url + self.ca_file = ca_file + path = Path(password_file) if password_file else ( + ROOT / 'secrets/grafana_admin_password') + self._auth = None + if path.exists(): + token = base64.b64encode( + b'admin:' + path.read_bytes().strip()).decode() + self._auth = {'Authorization': 'Basic ' + token} + + # -- Prometheus + def prom_query(self, expr, at=None): + params = {'query': expr} + if at is not None: + params['time'] = str(at) + _, body = http_json(self.prometheus + '/api/v1/query?' + + urllib.parse.urlencode(params)) + if not isinstance(body, dict) or body.get('status') != 'success': + raise Failure('Prometheus query failed') + return body['data']['result'] + + def prom_scalar(self, expr, default=None): + result = self.prom_query(expr) + if not result: + return default + return float(result[0]['value'][1]) + + def prom_range(self, expr, start, end, step): + params = {'query': expr, 'start': str(start), 'end': str(end), + 'step': str(step)} + _, body = http_json(self.prometheus + '/api/v1/query_range?' + + urllib.parse.urlencode(params)) + if not isinstance(body, dict) or body.get('status') != 'success': + raise Failure('Prometheus range query failed') + return body['data']['result'] + + def prom_names(self): + _, body = http_json(self.prometheus + '/api/v1/label/__name__/values') + return sorted(body['data']) + + # -- Grafana proxied backends + def _grafana_get(self, path, allow=(200,)): + if self._auth is None: + raise Failure('Grafana password file is missing') + return http_get(self.grafana + path, self._auth) + + def grafana_json(self, path, allow=(200,)): + status, data = self._grafana_get(path) + if status not in allow: + raise Failure('Grafana ' + path.split('?')[0] + ': status ' + + str(status)) + try: + return json.loads(data) + except (ValueError, UnicodeError): + raise Failure('Grafana ' + path.split('?')[0] + + ': invalid JSON') from None + + def loki_rows(self, query, start_ns, end_ns, deadline_s=60): + """All log rows in [start, end]: [{'ts', 'line', 'labels'}].""" + limit = 5000 + deadline = time.monotonic() + deadline_s + cursor = int(start_ns) + seen = set() + rows = [] + while True: + if time.monotonic() > deadline: + raise Failure('Loki query deadline exceeded; incomplete window') + params = urllib.parse.urlencode({ + 'query': query, 'start': str(cursor), 'end': str(int(end_ns)), + 'limit': str(limit), 'direction': 'forward'}) + body = self.grafana_json( + '/api/datasources/proxy/uid/loki/loki/api/v1/query_range?' + + params) + if body.get('status') != 'success': + raise Failure('Loki query failed') + fresh = 0 + page = 0 + last_ts = cursor + for stream in body['data']['result']: + labels = stream.get('stream', {}) + key = json.dumps(labels, sort_keys=True) + for value in stream.get('values', []): + page += 1 + ts, line = int(value[0]), value[1] + last_ts = max(last_ts, ts) + ident = (key, ts, line) + if ident in seen: + continue + seen.add(ident) + fresh += 1 + rows.append({'ts': ts, 'line': line, 'labels': labels}) + if page < limit: + return rows + if fresh == 0 or last_ts == cursor: + raise Failure('Loki pagination made no progress; ' + 'incomplete window') + cursor = last_ts # overlap on the last timestamp, deduped above + + def get_trace(self, trace_id, wait=0): + """Normalised spans, or None on 404; waits up to `wait` seconds.""" + deadline = time.monotonic() + min(wait, 60) + path = '/api/datasources/proxy/uid/tempo/api/traces/' + trace_id + while True: + if self._auth is None: + raise Failure('Grafana password file is missing') + status, data = http_get( + self.grafana + path, + {**self._auth, 'Accept': 'application/json'}) + if status == 200: + try: + return normalize_trace(json.loads(data)) + except (ValueError, UnicodeError): + raise Failure('Tempo returned invalid JSON') from None + if status != 404: + raise Failure('Tempo trace lookup: status ' + str(status)) + if time.monotonic() >= deadline: + return None + time.sleep(1) + + # -- closed backends from inside the compose network + def internal_get(self, service, port, path): + script = ( + "const [h,p,u]=process.argv.slice(1);" + "fetch('http://'+h+':'+p+u,{signal:AbortSignal.timeout(5000)})" + ".then(async r=>{const b=await r.text();" + "console.log(JSON.stringify({status:r.status,body:b.slice(0,1048576)}))})" + ".catch(e=>{console.log(JSON.stringify({status:0,body:String(e.name)}))})") + result = stand.compose('exec', '-T', 'api', 'node', '-e', script, + service, str(port), path, check_result=False) + try: + out = json.loads(result.stdout.strip().splitlines()[-1]) + except (ValueError, IndexError): + raise Failure('internal_get ' + service + ': no result') from None + return out['status'], out['body'] + + # -- readiness + def _check(self, problems, name, ok): + if not ok: + problems.append(name) + + def readiness_problems(self, app_telemetry=True, provisioning=True): + problems = [] + if self.base_url: + try: + status, _ = http_get(self.base_url.rstrip('/') + '/health/ready') + self._check(problems, 'api-ready', status == 200) + except Failure: + problems.append('api-ready') + probes = (('otel-collector', 13133, '/', 'collector-health'), + ('loki', 3100, '/ready', 'loki-ready'), + ('tempo', 3200, '/ready', 'tempo-ready')) + for service, port, path, name in probes: + try: + status, _ = self.internal_get(service, port, path) + self._check(problems, name, status == 200) + except Failure: + problems.append(name) + try: + status, _ = http_get(self.prometheus + '/-/ready') + self._check(problems, 'prometheus-ready', status == 200) + except Failure: + problems.append('prometheus-ready') + try: + status, _ = http_get(self.grafana + '/api/health') + self._check(problems, 'grafana-health', status == 200) + except Failure: + problems.append('grafana-health') + try: + up = {r['metric']['job']: r['value'][1] + for r in self.prom_query('up')} + for job in SCRAPE_JOBS: + self._check(problems, 'target-up:' + job, up.get(job) == '1') + if app_telemetry: + ages = self.prom_query( + 'time() - timestamp(target_info{job=~"messenger-.*"})') + fresh = {} + for r in ages: + if float(r['value'][1]) < 30: + fresh.setdefault(r['metric']['job'], set()).add( + r['metric'].get('instance')) + self._check(problems, 'api-instances>=2', + len(fresh.get('messenger-api', ())) >= 2) + self._check(problems, 'worker-instance', + len(fresh.get('messenger-worker', ())) >= 1) + except Failure: + problems.append('prometheus-queries') + if provisioning: + try: + for uid in DATASOURCE_UIDS: + if uid == 'tempo': + # The Tempo plugin has no health resource; its API echo + # through the datasource proxy proves the connection. + status, _ = self._grafana_get( + '/api/datasources/proxy/uid/tempo/api/echo') + self._check(problems, 'datasource:tempo', status == 200) + continue + body = self.grafana_json( + '/api/datasources/uid/' + uid + '/health', + allow=(200, 400, 404, 500)) + self._check(problems, 'datasource:' + uid, + isinstance(body, dict) and + body.get('status', '').upper() == 'OK') + _, rules = http_json(self.prometheus + '/api/v1/rules') + names = {r['name'] for g in rules['data']['groups'] + for r in g['rules']} + for alert in RULE_ALERTS: + self._check(problems, 'rule:' + alert, alert in names) + for uid in DASHBOARD_UIDS: + status, _ = self._grafana_get('/api/dashboards/uid/' + uid) + self._check(problems, 'dashboard:' + uid, status == 200) + except Failure: + problems.append('provisioning-queries') + return problems + + def wait_ready(self, timeout=120, app_telemetry=True, provisioning=True): + deadline = time.monotonic() + timeout + problems = ['not-checked'] + while time.monotonic() < deadline: + problems = self.readiness_problems(app_telemetry, provisioning) + if not problems: + return + time.sleep(2) + raise Failure('stack not ready: ' + ', '.join(problems)) + + def wait_telemetry_flushed(self, timeout=120): + """Two new Prometheus scrapes of the Collector and empty queues.""" + deadline = time.monotonic() + timeout + stamps = [] + while time.monotonic() < deadline: + result = self.prom_query('timestamp(up{job="otel-collector"})') + if result: + stamp = float(result[0]['value'][1]) + if not stamps or stamp > stamps[-1]: + stamps.append(stamp) + queue = self.prom_query('sum(otelcol_exporter_queue_size)') + empty = bool(queue) and float(queue[0]['value'][1]) == 0 + if len(stamps) >= 3 and empty: + return + time.sleep(2) + raise Failure('telemetry did not flush before deadline') + + # -- controlled application environment + def container_ids(self, service): + out = stand.compose('ps', '-q', service).stdout.split() + if not out: + raise Failure('no running container for ' + service) + return out + + def inspect_env(self, service): + """{container_id: {'env': {...}, 'image': id, 'restarts': n}}""" + result = {} + for cid in self.container_ids(service): + data = json.loads(stand.docker('inspect', cid).stdout)[0] + env = dict(item.split('=', 1) for item in data['Config']['Env'] + if '=' in item) + result[cid[:12]] = { + 'env': {k: env.get(k) for k in MUTABLE_KEYS + DIAGNOSTIC_KEYS}, + 'image': data['Image'], + 'restarts': data['RestartCount'], + 'oom_killed': data['State'].get('OOMKilled', False), + } + return result + + def app_state(self): + return {'api': self.inspect_env('api'), + 'worker': self.inspect_env('worker')} + + @contextlib.contextmanager + def app_environment(self, initial_overrides=None): + saved_state = self.app_state() + baseline = {} + for service in ('api', 'worker'): + for info in saved_state[service].values(): + for key in MUTABLE_KEYS: + baseline.setdefault((service, key), info['env'][key]) + saved_environ = {k: os.environ.get(k) for k in MUTABLE_KEYS} + touched = set() + dirty = [False] + + def effective(service): + return {cid: info for cid, info in self.inspect_env(service).items()} + + def set_overrides(values, force=False): + unknown = set(values) - set(MUTABLE_KEYS) + if unknown: + raise Failure('not a controllable key: ' + ', '.join(sorted(unknown))) + for key in values: + api = {i['env'][key] for i in effective('api').values()} + worker = {i['env'][key] for i in effective('worker').values()} + if len(api | worker) > 1 and api != worker: + raise Failure('api/worker disagree on ' + key + ' before change') + if not force and all( + info['env'][key] == str(value) + for service in ('api', 'worker') + for info in effective(service).values() + for key, value in values.items()): + return self.app_state() + for key, value in values.items(): + os.environ[key] = str(value) + touched.add(key) + dirty[0] = True + stand.compose('up', '-d', '--no-deps', '--force-recreate', + '--wait', 'api', 'worker') + for service in ('api', 'worker'): + state = effective(service) + for cid, info in state.items(): + for key, value in values.items(): + if info['env'][key] != str(value): + raise Failure('effective ' + key + ' differs in ' + + service + ' ' + cid) + sdk_on = os.environ.get('OTEL_SDK_DISABLED', 'false') != 'true' + self.wait_ready(app_telemetry=sdk_on, provisioning=True) + return self.app_state() + + try: + if initial_overrides: + set_overrides(initial_overrides) + yield set_overrides + finally: + if dirty[0]: + # Restore the original effective values as controller env so the + # recreated containers match what was running before. + for key in MUTABLE_KEYS: + original = baseline.get(('api', key)) + if original is not None and key in touched: + os.environ[key] = original + stand.compose('up', '-d', '--no-deps', '--force-recreate', + '--wait', 'api', 'worker') + for key in touched: + if saved_environ[key] is None: + os.environ.pop(key, None) + else: + os.environ[key] = saved_environ[key] + now = self.app_state() + for service in ('api', 'worker'): + for cid, info in now[service].items(): + for key in touched: + if info['env'][key] != baseline.get((service, key)): + print('WARNING: ' + key + ' not restored on ' + + service, file=sys.stderr) + with contextlib.suppress(Failure): + self.wait_ready(app_telemetry=True, provisioning=True, + timeout=120) + + # -- foreign faults + def foreign_faults(self): + result = stand.compose('exec', '-T', 'redis', 'redis-cli', '--scan', + '--pattern', 'fault:*') + return sorted(line for line in result.stdout.split() if line) + + def require_no_foreign_faults(self): + keys = self.foreign_faults() + if keys: + raise Failure('foreign fault keys present (finish the other ' + 'experiment first): ' + ', '.join(keys)) + + +# --------------------------------------------------------------- PostgreSQL + +def psql(sql, timeout=30): + script = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 ' \ + '-At -F , -c "$SQL"' + result = subprocess.run( + ['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T', + '-e', 'SQL=' + sql, 'postgres', 'sh', '-c', script], + cwd=ROOT, text=True, capture_output=True, timeout=timeout) + if result.returncode != 0: + raise Failure('psql failed: ' + ((result.stderr or '').strip() + .splitlines() or ['?'])[-1][:200]) + return result.stdout.strip() + + +@contextlib.contextmanager +def hold_table_lock(table): + """ACCESS EXCLUSIVE lock on messages/attachments held until exit.""" + if table not in LOCKABLE_TABLES: + raise Failure('table is not lockable: ' + table) + name = 'lab6-lock-' + uuid.uuid4().hex[:12] + process = subprocess.Popen( + ['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T', + 'postgres', 'sh', '-c', + 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -At'], + cwd=ROOT, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, bufsize=1) + pid = None + try: + process.stdin.write( + "SET application_name='" + name + "';\n" + "BEGIN;\n" + "SET LOCAL statement_timeout='120s';\n" + "SET LOCAL idle_in_transaction_session_timeout='120s';\n" + "LOCK TABLE " + table + " IN ACCESS EXCLUSIVE MODE;\n" + "SELECT 'LOCKED:'||pg_backend_pid();\n") + process.stdin.flush() + deadline = time.monotonic() + 30 + while pid is None: + if time.monotonic() > deadline: + raise Failure('table lock marker not received') + ready, _, _ = select.select([process.stdout], [], [], 1) + if not ready: + if process.poll() is not None: + raise Failure('psql exited before locking') + continue + line = process.stdout.readline() + if line.startswith('LOCKED:'): + pid = int(line.split(':')[1]) + elif line == '' and process.poll() is not None: + raise Failure('psql exited before locking') + yield pid + finally: + try: + if process.poll() is None: + process.stdin.write('ROLLBACK;\n\\q\n') + process.stdin.flush() + process.stdin.close() + except (OSError, ValueError): + pass + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + if pid is not None: + with contextlib.suppress(Failure, subprocess.TimeoutExpired): + psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity " + "WHERE pid=" + str(int(pid)) + + " AND application_name='" + name + "'") + for stream in (process.stdout, process.stderr): + with contextlib.suppress(Exception): + stream.close() + + +def wait_drained(attachment_ids, obs=None, timeout=120, flush_telemetry=True): + """Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling). + + Returns {'drained': bool, 'states': {id: status}, 'queued': n, + 'outbox': n, 'seconds': t, 'timestamps': ...}. A vanished known ID is a + Failure; non-ready at the deadline is reported, not raised. + """ + ids = list(attachment_ids) + for item in ids: + uuid.UUID(item) + array = "ARRAY[" + ",".join("'" + i + "'" for i in ids) + "]::uuid[]" \ + if ids else "ARRAY[]::uuid[]" + sql = ( + "SELECT (SELECT count(*) FROM attachment_jobs WHERE status IN " + "('queued','processing'))||','||" + "(SELECT count(*) FROM job_outbox WHERE published_at IS NULL)||','||" + "COALESCE((SELECT string_agg(id::text||':'||status,';') FROM attachments " + "WHERE id = ANY(" + array + ")),'')") + started = time.monotonic() + start_ts = utc_now() + states = {} + queued = outbox = -1 + drained = False + while time.monotonic() - started < timeout: + out = psql(sql) + queued_s, outbox_s, rest = (out.split(',', 2) + ['', ''])[:3] + queued, outbox = int(queued_s), int(outbox_s) + states = dict(part.split(':', 1) for part in rest.split(';') if part) + missing = set(ids) - set(states) + if missing: + raise Failure('known attachment vanished: ' + sorted(missing)[0]) + terminal = all(s in ('ready', 'failed') for s in states.values()) + if queued == 0 and outbox == 0 and terminal: + drained = True + break + time.sleep(1) + result = {'drained': drained, 'states': states, 'queued_jobs': queued, + 'unpublished_outbox': outbox, + 'seconds': round(time.monotonic() - started, 3), + 'started': start_ts, 'finished': utc_now()} + if flush_telemetry and obs is not None: + obs.wait_telemetry_flushed(timeout=timeout) + result['telemetry_flushed'] = utc_now() + return result diff --git a/scripts/lab6/reconcile.py b/scripts/lab6/reconcile.py new file mode 100644 index 0000000..c698b7f --- /dev/null +++ b/scripts/lab6/reconcile.py @@ -0,0 +1,106 @@ +"""Reconcile what the application wrote to stdout with what reached Loki and +Tempo (stdlib only). A record's stdout line is the ground truth for whether a +trace was sampled (trace_sampled) and which SERVER span ID it carries.""" +import json +import subprocess +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measurement # noqa: E402 +import obs # noqa: E402 +from obs import Failure, ROOT # noqa: E402 + +DEADLINE_S = 60 + + +def stdout_http_logs(since_utc, services=('api',), until_utc=None): + """{request_id: parsed stdout JSON} for event=http.request lines.""" + args = ['docker', 'compose', '--env-file', obs.stand.ENV_FILE, 'logs', + '--no-color', '--no-log-prefix', '--since', since_utc] + if until_utc: + args += ['--until', until_utc] + result = subprocess.run(args + list(services), cwd=ROOT, text=True, + capture_output=True, timeout=180) + if result.returncode != 0: + raise Failure('docker compose logs failed') + found = {} + for line in result.stdout.splitlines(): + if not line.startswith('{'): + continue + try: + row = json.loads(line) + except ValueError: + continue + if row.get('event') == 'http.request' and row.get('request_id'): + found[row['request_id']] = row + return found + + +def loki_by_request_id(client, request_ids, start_ns, end_ns, deadline_s=DEADLINE_S): + """Poll until every id is seen or the deadline passes. Returns + ({request_id: labels}, complete) where complete means every query returned + a full, un-truncated answer (a Failure would propagate otherwise).""" + ids = sorted(request_ids) + found = {} + deadline = time.monotonic() + deadline_s + while True: + for i in range(0, len(ids), 100): + chunk = [r for r in ids[i:i + 100] if r not in found] + if not chunk: + continue + query = ('{service_name="messenger-api"} | event_name="http.request" ' + '| request_id=~"' + '|'.join(chunk) + '"') + for row in client.loki_rows(query, start_ns, end_ns): + found[row['labels']['request_id']] = row['labels'] + if len(found) >= len(ids) or time.monotonic() >= deadline: + return found + time.sleep(3) + + +def tempo_server_spans(client, targets, deadline_s=DEADLINE_S): + """targets: {request_id: (trace_id, span_id)} -> {request_id: bool}.""" + found = {} + deadline = time.monotonic() + deadline_s + while True: + for rid, (tid, sid) in targets.items(): + if found.get(rid): + continue + spans = client.get_trace(tid) + found[rid] = bool(spans) and any( + s['span_id'] == sid and s['kind'] == 'SERVER' for s in spans) + if all(found.values()) or time.monotonic() >= deadline: + return found + time.sleep(3) + + +def reconcile(client, mode, requests, since_utc, start_ns, end_ns): + """requests: [{'request_id','status',...}] -> (records, summary). + + off: stdout only (Loki/Tempo not applicable). on: stdout -> Loki and + stdout span_id -> Tempo SERVER span.""" + stdout = stdout_http_logs(since_utc) + records = [] + for req in requests: + line = stdout.get(req.get('request_id')) + rec = {'request_id': req.get('request_id'), 'status': req.get('status'), + 'stdout': None, 'loki': None, 'span': None} + if line is not None: + rec['stdout'] = {k: line[k] for k in + ('trace_id', 'span_id', 'trace_sampled') if k in line} + records.append(rec) + if mode != 'off': + with_stdout = [r for r in records if r['stdout'] is not None] + loki = loki_by_request_id( + client, [r['request_id'] for r in with_stdout], start_ns, end_ns) + for rec in with_stdout: + rec['loki'] = rec['request_id'] in loki + targets = {r['request_id']: (r['stdout']['trace_id'], r['stdout']['span_id']) + for r in with_stdout + if r['stdout'].get('trace_sampled') is True} + spans = tempo_server_spans(client, targets) + for rec in with_stdout: + if rec['request_id'] in spans: + rec['span'] = spans[rec['request_id']] + return records, measurement.summarize_cohort(mode, records) diff --git a/scripts/lab6/resources.py b/scripts/lab6/resources.py new file mode 100644 index 0000000..6789940 --- /dev/null +++ b/scripts/lab6/resources.py @@ -0,0 +1,181 @@ +"""Container resource sampling for lab6: docker stats (container CPU/memory) and +docker top (process RSS) every few seconds. Stdlib only. + +MemUsage is *container* memory usage (cgroup, includes page cache); RSS is the +sum of process RSS from `docker top` (KiB -> bytes). They are never mixed.""" +import json +import re +import subprocess +import threading +import time +from pathlib import Path + +import sys # noqa: E402 + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measurement # noqa: E402 +import obs # noqa: E402 + +UNITS = {'B': 1, 'kB': 1000, 'MB': 1000 ** 2, 'GB': 1000 ** 3, 'TB': 1000 ** 4, + 'KiB': 1024, 'MiB': 1024 ** 2, 'GiB': 1024 ** 3, 'TiB': 1024 ** 4} +SIZE = re.compile(r'^\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]+)\s*$') +SERVICES = ('api', 'worker', 'otel-collector', 'prometheus', 'loki', 'tempo', + 'grafana') + + +def parse_size(text): + """'147.5MiB' -> bytes; SI and IEC units differ; unknown unit is an error.""" + match = SIZE.match(text) + if not match or match.group(2) not in UNITS: + raise ValueError('unparseable size: ' + repr(text)) + return int(float(match.group(1)) * UNITS[match.group(2)]) + + +def parse_stats_row(row): + usage, limit = row['MemUsage'].split('/') + cpu = row['CPUPerc'].strip() + if not cpu.endswith('%'): + raise ValueError('unparseable CPU: ' + repr(cpu)) + return {'cpu_pct': float(cpu[:-1]), 'mem_usage_bytes': parse_size(usage), + 'mem_limit_bytes': parse_size(limit)} + + +def parse_top_rss(text): + """`docker top -eo pid,rss` output -> bytes (KiB x 1024).""" + lines = [line.split() for line in text.strip().splitlines()] + if not lines or [h.upper() for h in lines[0]] != ['PID', 'RSS']: + raise ValueError('unexpected docker top header') + return sum(int(row[1]) for row in lines[1:]) * 1024 + + +def container_map(): + """{short_id: service} for all observed services.""" + result = {} + for service in SERVICES: + ids = obs.stand.compose('ps', '-q', service, check_result=False) + for cid in ids.stdout.split(): + result[cid[:12]] = service + return result + + +class ResourceSampler(threading.Thread): + def __init__(self, containers, interval=5.0, path=None): + super().__init__(daemon=True) + self.containers = dict(containers) + self.interval = interval + self.path = Path(path) if path else None + self.stop_event = threading.Event() + self.samples = [] + self.errors = [] + + def one_tick(self, tick): + mono = time.monotonic() + stamp = obs.utc_now() + ids = list(self.containers) + stats = subprocess.run( + ['docker', 'stats', '--no-stream', '--format', '{{json .}}'] + ids, + capture_output=True, text=True, timeout=60) + rows = {} + for line in stats.stdout.splitlines(): + if line.strip(): + row = json.loads(line) + rows[row['ID'][:12]] = row + for cid in ids: + sample = {'tick': tick, 'utc': stamp, 'mono': mono, 'id': cid, + 'service': self.containers[cid]} + raw = rows.get(cid) + if raw is None: + sample['error'] = 'no_stats_row' + else: + sample['raw'] = {k: raw[k] for k in ('CPUPerc', 'MemUsage')} + try: + sample.update(parse_stats_row(raw)) + except ValueError as exc: + sample['error'] = str(exc) + top = subprocess.run( + ['docker', 'top', cid, '-eo', 'pid,rss'], + capture_output=True, text=True, timeout=30) + if top.returncode == 0: + try: + sample['rss_bytes'] = parse_top_rss(top.stdout) + except ValueError as exc: + sample['rss_error'] = str(exc) + else: + sample['rss_bytes'] = None + sample['rss_reason'] = 'not_running' + self.samples.append(sample) + if self.path is not None: + with self.path.open('a') as handle: + handle.write(json.dumps(sample) + '\n') + if 'error' in sample: + self.errors.append(sample['error']) + + def run(self): + tick = 0 + while not self.stop_event.is_set(): + begun = time.monotonic() + try: + self.one_tick(tick) + except (subprocess.SubprocessError, ValueError, KeyError) as exc: + self.errors.append(type(exc).__name__) + tick += 1 + self.stop_event.wait(max(0.0, self.interval - (time.monotonic() - begun))) + + def stop(self): + self.stop_event.set() + self.join(timeout=90) + + +def _summarise(values): + values = [v for v in values if v is not None] + return {'median': measurement.median(values), + 'p95': measurement.nearest_rank(values, 0.95), + 'max': max(values) if values else None, 'n': len(values)} + + +def summarize(samples, container_ids=None): + """Per-service statistics. For API the replicas are summed on a common + tick first; individual values are kept in `per_container`.""" + ticks = {} + for sample in samples: + if 'error' in sample: + continue + ticks.setdefault(sample['tick'], {}).setdefault( + sample['service'], []).append(sample) + order = sorted(ticks) + result = {} + services = {s['service'] for s in samples} + for service in sorted(services): + cpu, mem, rss, times = [], [], [], [] + for tick in order: + group = ticks[tick].get(service) + if not group: + continue + times.append(min(s['mono'] for s in group)) + cpu.append(sum(s['cpu_pct'] for s in group)) + mem.append(sum(s['mem_usage_bytes'] for s in group)) + values = [s.get('rss_bytes') for s in group] + rss.append(None if any(v is None for v in values) else sum(values)) + weights = [times[i + 1] - times[i] for i in range(len(times) - 1)] + if times: + weights.append(sum(weights) / len(weights) if weights else 1.0) + mean_cpu = (sum(c * w for c, w in zip(cpu, weights)) / sum(weights) + if weights and sum(weights) > 0 else None) + per_container = {} + for s in samples: + if s['service'] == service and 'error' not in s: + per_container.setdefault(s['id'], []).append(s['cpu_pct']) + result[service] = { + 'cpu_pct_time_weighted_mean': mean_cpu, + 'container_memory_bytes': _summarise(mem), + 'process_rss_bytes': _summarise(rss), + 'mem_limit_bytes': max((s['mem_limit_bytes'] for s in samples + if s['service'] == service and + 'mem_limit_bytes' in s), default=None), + 'ticks': len(times), + 'per_container_cpu_mean': {k: sum(v) / len(v) + for k, v in per_container.items()}, + } + result['sample_errors'] = len( + [s for s in samples if 'error' in s]) + return result diff --git a/scripts/lab6/test_measurement.py b/scripts/lab6/test_measurement.py new file mode 100644 index 0000000..20216ff --- /dev/null +++ b/scripts/lab6/test_measurement.py @@ -0,0 +1,199 @@ +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measurement as m # noqa: E402 + + +def slot(i, status=201, service=10.0, lag=1.0, outcome='http'): + if outcome != 'http': + return {'i': i, 'outcome': outcome, 'start_lag_ms': None} + return {'i': i, 'outcome': 'http', 'status': status, + 'service_ms': service, 'scheduled_ms': service + lag, + 'start_lag_ms': lag} + + +def cohort(**kw): + base = {'n': 40, 'retained_traces': 5, 'sampled_present': 5, + 'intentional_unsampled': 35} + base.update(kw) + return base + + +def run(mode='p25', spans=10.0, p95=100.0, failures=(), valid=True, + error=None, slow=None): + return { + 'mode': mode, 'valid': valid, 'invalid_reasons': [], + 'configuration_failures': list(failures), + 'spans_per_operation': spans, + 'load': {'scheduled_ms': {'p95': p95}}, + 'cohorts': {'error': error or cohort(), 'slow': slow or cohort()}, + 'dir': mode, + } + + +def summary(load_slots, **extra): + load = m.summarize_load(load_slots, 10) + base = {'mode': 'off', 'load': load, 'cohorts': {}, 'ingest': {}, + 'export_failures': {'loss': False}} + base.update(extra) + return base + + +class SamplingIsNotLoss(unittest.TestCase): + def test_false_flag_is_not_export_loss_or_missing_span(self): + rec = {'stdout': {'trace_id': 'a' * 32, 'span_id': 'b' * 16, + 'trace_sampled': False}, 'loki': True, 'span': False} + self.assertEqual(m.classify_record('p25', rec), + ('intentional_unsampled', 'exported')) + counts = m.summarize_cohort('p25', [rec] * 3) + self.assertEqual(counts.get('sampled_missing', 0), 0) + self.assertFalse(m.export_loss(0, 0.0, 0.0)['loss']) + + def test_sampled_without_span_is_a_measured_loss(self): + rec = {'stdout': {'trace_id': 'a' * 32, 'span_id': 'b' * 16, + 'trace_sampled': True}, 'loki': True, 'span': False} + self.assertEqual(m.classify_record('full', rec)[0], 'sampled_missing') + + def test_missing_stdout_is_not_intentional_sampling(self): + self.assertEqual(m.classify_record('p25', {'stdout': None})[0], + 'unmatched_stdout') + no_flag = {'stdout': {'trace_id': 'a' * 32, 'span_id': 'b' * 16}} + self.assertEqual(m.classify_record('p25', no_flag)[0], 'unmatched_stdout') + incomplete = {'stdout': {'trace_id': 'a' * 32, 'span_id': 'b' * 16, + 'trace_sampled': True}, 'loki': None, 'span': None} + self.assertEqual(m.classify_record('p25', incomplete), + ('incomplete_observation', 'incomplete_observation')) + + def test_full_observation_without_log_is_missing_exported_log(self): + rec = {'stdout': {'trace_id': 'a' * 32, 'span_id': 'b' * 16, + 'trace_sampled': False}, 'loki': False} + self.assertEqual(m.classify_record('p10', rec)[1], 'missing_exported_logs') + + def test_off_needs_neither_loki_nor_app_counters(self): + rec = {'stdout': {'event': 'http.request'}, 'loki': None, 'span': None} + self.assertEqual(m.classify_record('off', rec), + ('not_applicable', 'not_applicable')) + leaked = {'stdout': {'trace_id': 'x'}} + self.assertEqual(m.classify_record('off', leaked)[0], 'ids_present_with_sdk_off') + s = summary([slot(i) for i in range(100)], cohorts={ + 'error': m.summarize_cohort('off', [rec] * 4)}) + valid, invalid, failures = m.evaluate_run(s) + self.assertTrue(valid, invalid) + self.assertEqual(failures, []) + + +class Counters(unittest.TestCase): + def test_reset_is_not_a_negative_loss(self): + self.assertEqual(m.counter_delta(10.0, 3.0), (None, 'counter_reset')) + loss = m.export_loss(None, 0.0, 2.0) + self.assertEqual(loss['total_known'], 2.0) + self.assertTrue(all(v >= 0 for v in loss['parts'].values() if v is not None)) + + def test_missing_positive_series_is_not_zero_failure_series_may_be(self): + self.assertEqual(m.counter_delta(None, None), (None, 'missing_series')) + self.assertEqual(m.counter_delta(None, None, failure_only=True)[0], 0.0) + self.assertEqual(m.counter_delta(5.0, 9.0), (4.0, None)) + + def test_unexplained_reset_invalidates_but_restart_explains_it(self): + s = summary([slot(i) for i in range(100)], + ingest={'spans': {'delta': None, 'reason': 'counter_reset'}}) + self.assertFalse(m.evaluate_run(s)[0]) + s['restarts'] = ['collector'] + valid, _, failures = m.evaluate_run(s) + self.assertTrue(valid) + self.assertIn('restart_or_oom', failures) + + +class LoadAccounting(unittest.TestCase): + def test_dropped_and_late_slots_stay_in_denominator(self): + slots = [slot(i) for i in range(90)] + \ + [slot(90 + i, outcome='client_dropped') for i in range(5)] + \ + [slot(95 + i, lag=300.0) for i in range(5)] + load = m.summarize_load(slots, 10) + self.assertEqual(load['scheduled'], 100) + self.assertEqual(load['completed'], 95) + self.assertAlmostEqual(load['completed_ratio'], 0.95) + valid, invalid, _ = m.evaluate_run(summary(slots)) + self.assertFalse(valid) + self.assertTrue(any('client_dropped' in r for r in invalid)) + self.assertTrue(any('completed_ratio' in r for r in invalid)) + + def test_late_scheduler_fails_start_lag_even_without_drops(self): + slots = [slot(i, lag=80.0) for i in range(100)] + self.assertFalse(m.evaluate_run(summary(slots))[0]) + + def test_overall_p95_includes_error_responses(self): + slots = [slot(i, service=10.0) for i in range(90)] + \ + [slot(90 + i, status=500, service=900.0) for i in range(10)] + load = m.summarize_load(slots, 10) + self.assertEqual(load['service_ms']['p95'], 900.0) + self.assertEqual(load['success_service_ms']['p95'], 10.0) + self.assertEqual(m.load_errors(load), 10) + + def test_nearest_rank(self): + self.assertEqual(m.nearest_rank(list(range(1, 101)), 0.95), 95) + self.assertEqual(m.nearest_rank([7], 0.99), 7) + self.assertIsNone(m.nearest_rank([], 0.5)) + + +class MatrixAndSelection(unittest.TestCase): + def test_valid_adverse_run_stays_in_matrix(self): + s = summary([slot(i) for i in range(100)], mode='p25', + export_failures={'loss': True}, + cohorts={'error': cohort(sampled_missing=2)}) + valid, invalid, failures = m.evaluate_run(s) + self.assertTrue(valid, invalid) + self.assertIn('export_loss', failures) + self.assertTrue(any(f.startswith('sampled_missing') for f in failures)) + s.update(valid=valid, invalid_reasons=invalid, + configuration_failures=failures, repeat=1) + entry = m.matrix_entry(s) + self.assertTrue(entry['valid']) + self.assertTrue(entry['configuration_failures']) + + def full_runs(self): + return [run('full', spans=100.0, p95=100.0) for _ in range(3)] + + def test_p25_selected_only_against_complete_full_reference(self): + good = [run('p25', spans=40.0, p95=105.0) for _ in range(3)] + self.assertTrue(m.select_p25(self.full_runs(), good)['passed']) + broken_full = self.full_runs() + broken_full[1]['spans_per_operation'] = None + self.assertFalse(m.select_p25(broken_full, good)['passed']) + heavy = [run('p25', spans=60.0, p95=105.0) for _ in range(3)] + self.assertFalse(m.select_p25(self.full_runs(), heavy)['passed']) + slow = [run('p25', spans=40.0, p95=120.0) for _ in range(3)] + self.assertFalse(m.select_p25(self.full_runs(), slow)['passed']) + + def test_p25_rejected_when_an_error_class_has_no_retained_trace(self): + runs = [run('p25', spans=40.0, p95=100.0) for _ in range(3)] + runs[2]['cohorts']['slow'] = cohort(retained_traces=0, sampled_present=0) + self.assertFalse(m.select_p25(self.full_runs(), runs)['passed']) + + def test_single_validation_uses_frozen_full_reference(self): + ref = m.full_reference(self.full_runs()) + ok = run('p25', spans=45.0, p95=108.0) + self.assertTrue(m.validate_single(ok, 'p25', ref)['passed']) + # Would pass a "median of its own" comparison, fails the frozen one. + bad = run('p25', spans=55.0, p95=108.0) + result = m.validate_single(bad, 'p25', ref) + self.assertFalse(result['passed']) + self.assertFalse(result['checks']['spans_le_50pct_frozen_full']) + + def test_full_validation_needs_all_eighty_server_spans(self): + ref = m.full_reference(self.full_runs()) + ok = run('full', error=cohort(sampled_present=40, retained_traces=40), + slow=cohort(sampled_present=40, retained_traces=40)) + self.assertTrue(m.validate_single(ok, 'full', ref)['passed']) + short = run('full', error=cohort(sampled_present=39, retained_traces=39), + slow=cohort(sampled_present=40, retained_traces=40)) + self.assertFalse(m.validate_single(short, 'full', ref)['passed']) + + def test_miss_all_probability_model(self): + self.assertAlmostEqual(m.miss_all_probability(0.25, 40), 0.75 ** 40) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/lab6/track1.py b/scripts/lab6/track1.py new file mode 100755 index 0000000..50fc2ac --- /dev/null +++ b/scripts/lab6/track1.py @@ -0,0 +1,457 @@ +#!/usr/bin/env python3 +"""lab6 track 1 "cost of observability": off / full / p25 / p10 under the same +fixed-rate workload. Stdlib only. The protocol (rate calibration, 3x4 matrix, +diagnostic cohorts, p25 acceptance, one independent validation) is frozen in +this file; see REPORT.md for the description.""" +import argparse +import json +import os +import resource +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import incidents # noqa: E402 +import measurement as m # noqa: E402 +import obs # noqa: E402 +import reconcile # noqa: E402 +import resources # noqa: E402 +import verify # noqa: E402 +import workload # noqa: E402 +from obs import Failure, stand, utc_now # noqa: E402 + +BASELINE_ENV = dict(obs.SDK_DEFAULTS) +BASELINE_ENV.update({'CACHE_MODE': 'protected', 'FAULT_INJECTION_ENABLED': '1', + 'LOG_LEVEL': 'INFO'}) +WARMUP_S, MEASURE_S = 60, 180 +CALIBRATION = ((20, 20, 40), (10, 20, 40), (5, 20, 40)) # rate, warmup, measure +N_SLOW, ERR_RATE, ERR_SECONDS = 40, 4, 10 + +COUNTERS = ( + ('accepted_spans', 'sum(otelcol_receiver_accepted_spans)', False), + ('accepted_log_records', 'sum(otelcol_receiver_accepted_log_records)', False), + ('accepted_metric_points', 'sum(otelcol_receiver_accepted_metric_points)', False), + ('sent_spans', 'sum(otelcol_exporter_sent_spans)', False), + ('sent_log_records', 'sum(otelcol_exporter_sent_log_records)', False), + ('sent_metric_points', 'sum(otelcol_exporter_sent_metric_points)', False), + ('send_failed_spans', 'sum(otelcol_exporter_send_failed_spans)', True), + ('send_failed_log_records', 'sum(otelcol_exporter_send_failed_log_records)', True), + ('send_failed_metric_points', 'sum(otelcol_exporter_send_failed_metric_points)', True), + ('enqueue_failed_spans', 'sum(otelcol_exporter_enqueue_failed_spans)', True), + ('enqueue_failed_log_records', 'sum(otelcol_exporter_enqueue_failed_log_records)', True), + ('enqueue_failed_metric_points', 'sum(otelcol_exporter_enqueue_failed_metric_points)', True), + ('tempo_bytes_received', 'sum(tempo_distributor_bytes_received_total)', False), + ('loki_bytes_received', 'sum(loki_distributor_bytes_received_total)', False), +) + + +def write(path, data): + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True) + '\n') + + +def unique_dir(base): + base = Path(base) + if not base.exists(): + return base + n = 2 + while Path('%s-attempt-%d' % (base, n)).exists(): + n += 1 + return Path('%s-attempt-%d' % (base, n)) + + +def snapshot(client, instance_ids, sdk_on): + snap = {'utc': utc_now(), 'values': {}, 'sample_ts': {}} + for name, expr, _ in COUNTERS: + result = client.prom_query(expr) + snap['values'][name] = float(result[0]['value'][1]) if result else None + snap['sample_ts'][name] = float(result[0]['value'][0]) if result else None + if sdk_on: + selector = 'instance=~"%s"' % '|'.join(instance_ids) + for outcome in ('failed', 'success'): + result = client.prom_query( + 'sum(messenger_telemetry_export_items_total{outcome="%s",%s})' % (outcome, selector)) + snap['values']['app_export_' + outcome] = float(result[0]['value'][1]) if result else None + return snap + + +def deltas(a, b, operations, sdk_on): + out = {} + for name, _, failure_only in COUNTERS: + delta, reason = m.counter_delta(a['values'][name], b['values'][name], failure_only) + if name.endswith('_bytes_received') and reason == 'missing_series': + out[name] = {'status': 'not_exposed'} + continue + out[name] = {'start': a['values'][name], 'end': b['values'][name], + 'delta': delta, 'reason': reason, + 'per_operation': (delta / operations) if delta is not None and operations else None} + for outcome in ('failed', 'success'): + key = 'app_export_' + outcome + if not sdk_on: + out[key] = {'status': 'not_applicable'} + else: + delta, reason = m.counter_delta(a['values'].get(key), b['values'].get(key), + failure_only=(outcome == 'failed')) + out[key] = {'start': a['values'].get(key), 'end': b['values'].get(key), + 'delta': delta, 'reason': reason} + return out + + +def container_health(ids): + """{short_id: (service, restarts, oom)} from docker inspect.""" + out = {} + for cid, service in ids.items(): + data = json.loads(stand.docker('inspect', cid).stdout)[0] + out[cid] = (service, data['RestartCount'], bool(data['State'].get('OOMKilled')), + data['State'].get('Running')) + return out + + +def rusage(): + own, kids = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + return {'self_cpu_s': own.ru_utime + own.ru_stime, 'children_cpu_s': kids.ru_utime + kids.ru_stime, + 'loadavg': os.getloadavg()} + + +class Track: + def __init__(self, args): + self.args = args + self.obs = verify.make_obs(args) + self.out = Path(args.output_dir) + self.image_ids = None + self.set_env = None + + # -- environment + def configure(self, mode, force=True): + env = dict(BASELINE_ENV) + env.update(m.MODES[mode]) + state = self.set_env(env, force=force) + for service in ('api', 'worker'): + for cid, info in state[service].items(): + for key, value in env.items(): + if info['env'][key] != value: + raise Failure('effective %s=%s in %s %s' % (key, info['env'][key], service, cid)) + images = {svc: sorted(i['image'] for i in state[svc].values()) for svc in ('api', 'worker')} + if self.image_ids is None: + self.image_ids = images + ok = images == self.image_ids + instance_ids = sorted(list(state['api']) + list(state['worker'])) + return state, instance_ids, ok, {k: env[k] for k in obs.MUTABLE_KEYS if k in env} + + # -- one protocol run + def execute_run(self, mode, rate, run_dir, repeat=None, warmup=WARMUP_S, measure=MEASURE_S, + n_slow=N_SLOW, err_rate=ERR_RATE, err_seconds=ERR_SECONDS, label=None): + run_dir = Path(run_dir) + run_dir.mkdir(parents=True, exist_ok=True) + sdk_on = mode != 'off' + defects, stamps = [], {} + self.obs.require_no_foreign_faults() + pre = obs.wait_drained([], obs=self.obs, timeout=180) + if not pre['drained']: + raise Failure('stack did not drain before the run (%s)' % mode) + state, instance_ids, image_ok, effective = self.configure(mode) + ids = resources.container_map() + health0 = container_health(ids) + c = stand.new_client(self.args.base_url, self.args.ca_file) + alice, _, _, chat = c.bootstrap() + stamps['warmup_start'] = utc_now() + warm = workload.run_window(self.args.base_url, self.args.ca_file, alice, chat, rate, + warmup, 'warmup', settle=False) + warm_drain = obs.wait_drained(warm['uploads'], obs=self.obs, timeout=180) + stamps['warmup_end'] = utc_now() + if not warm_drain['drained']: + defects.append('warmup_did_not_drain') + snap0 = snapshot(self.obs, instance_ids, sdk_on) + usage0 = rusage() + sampler = resources.ResourceSampler(ids, 5.0, run_dir / 'docker-stats.jsonl') + sampler.start() + stamps['measure_start'] = utc_now() + result = workload.run_window(self.args.base_url, self.args.ca_file, alice, chat, rate, + measure, 'measure', settle=False) + sampler.stop() + stamps['measure_dispatch_end'] = utc_now() + usage1 = rusage() + drain = obs.wait_drained(result['uploads'], obs=self.obs, timeout=180) + snap1 = snapshot(self.obs, instance_ids, sdk_on) + stamps['measure_drained'] = utc_now() + load = result['load'] + # -- integrity after the final ingest snapshot (HTTP is allowed now) + integrity = 0 + reference = stand.sha256(stand.sample_bytes()) + for upload_id in result['uploads']: + meta = stand.metadata(c, alice, upload_id) + if meta['status'] != 'ready' or meta['sha256'] != reference: + integrity += 1 + not_ready = sum(1 for s in drain['states'].values() if s != 'ready') + write(run_dir / 'drain.json', {'warmup': warm_drain, 'measurement': drain}) + # -- diagnostic cohorts, never mixed with the healthy statistics + cohort_since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 2)) + cohort_start_ns = time.time_ns() - 10 * 10 ** 9 + stamps['cohorts_start'] = utc_now() + slow_rows = incidents.sequential_uploads(self, alice, chat, n_slow, 500) + slow_valid = all(r['consumed'] and r['status'] == 202 for r in slow_rows) + err_slots = [] + with obs.hold_table_lock('messages'): + err = workload.run_window(self.args.base_url, self.args.ca_file, alice, chat, + err_rate, err_seconds, 'error', upload_every=0, settle=False) + err_slots = err['slots'] + err_expected = err_rate * err_seconds + err_valid = (len(err_slots) == err_expected and all( + s['outcome'] == 'http' and s['status'] >= 500 and s.get('instance_id') and s.get('request_id') + for s in err_slots)) + stamps['cohorts_end'] = utc_now() + slow_drain = obs.wait_drained([r['attachment_id'] for r in slow_rows if r['attachment_id']], + obs=self.obs, timeout=180) + snap2 = snapshot(self.obs, instance_ids, sdk_on) + end_ns = time.time_ns() + 60 * 10 ** 9 + slow_records, slow_summary = reconcile.reconcile( + self.obs, mode, [{'request_id': r['request_id'], 'status': r['status']} for r in slow_rows], + cohort_since, cohort_start_ns, end_ns) + err_records, err_summary = reconcile.reconcile( + self.obs, mode, [{'request_id': s.get('request_id'), 'status': s.get('status')} + for s in err_slots if s.get('request_id')], + cohort_since, cohort_start_ns, end_ns) + slow_summary['invalid'] = not slow_valid + err_summary['invalid'] = not err_valid + err_summary['responses'] = len(err_slots) + write(run_dir / 'cohorts.json', {'slow': {'requests': slow_rows, 'records': slow_records, + 'summary': slow_summary}, + 'error': {'slots': [{k: s.get(k) for k in ( + 'i', 'outcome', 'status', 'request_id', 'instance_id', 'service_ms')} + for s in err_slots], + 'records': err_records, 'summary': err_summary}}) + health1 = container_health(ids) + restarts = [health1[cid][0] for cid in ids + if health1[cid][1] != health0[cid][1] or health1[cid][2]] + # -- independent proof that SDK-off sends nothing + d_final = deltas(snap0, snap2, load['completed'], sdk_on) + if not sdk_on: + for name in ('accepted_spans', 'accepted_log_records', 'accepted_metric_points'): + if (d_final[name]['delta'] or 0) != 0: + defects.append('sdk_off_but_collector_ingest:' + name) + ingest = deltas(snap0, snap1, load['completed'], sdk_on) + loss = m.export_loss( + ingest['app_export_failed'].get('delta') if sdk_on else None, + sum(ingest[k]['delta'] or 0 for k in ingest if k.startswith('send_failed')), + sum(ingest[k]['delta'] or 0 for k in ingest if k.startswith('enqueue_failed'))) + res_summary = resources.summarize(sampler.samples) + spans_op = ingest['accepted_spans']['per_operation'] + summary = { + 'mode': mode, 'sampler_ratio': m.SAMPLER_RATIO[mode], 'repeat': repeat, 'label': label, + 'rate_rps': rate, 'warmup_s': warmup, 'measurement_s': measure, + 'effective_env': effective, 'effective_mode_ok': True, + 'image_ids': self.image_ids, 'image_ids_ok': image_ok, 'instance_ids': instance_ids, + 'load': load, 'resources': res_summary, + 'controller_usage': {'start': usage0, 'end': usage1, + 'cpu_s_during_dispatch': (usage1['self_cpu_s'] + usage1['children_cpu_s'] + - usage0['self_cpu_s'] - usage0['children_cpu_s'])}, + 'ingest': ingest, 'ingest_through_cohorts': d_final, 'export_failures': loss, + 'spans_per_operation': spans_op, + 'log_records_per_operation': ingest['accepted_log_records']['per_operation'], + 'metric_points_per_operation': ingest['accepted_metric_points']['per_operation'], + 'cohorts': {'slow': slow_summary, 'error': err_summary}, + 'not_ready_at_deadline': not_ready, 'integrity_errors': integrity, + 'restarts': restarts, 'measurement_defects': defects, 'timestamps': stamps, + 'foreign_faults': self.obs.foreign_faults(), 'dir': str(run_dir), + 'slow_drain': {k: slow_drain[k] for k in ('drained', 'seconds')}, + } + valid, invalid, failures = m.evaluate_run(summary) + summary.update(valid=valid, invalid_reasons=invalid, configuration_failures=failures) + with (run_dir / 'requests.jsonl').open('w') as handle: + for slot in result['slots']: + handle.write(json.dumps({k: slot.get(k) for k in ( + 'i', 'kind', 'scheduled', 'start', 'end', 'service_ms', 'scheduled_ms', + 'start_lag_ms', 'status', 'outcome', 'request_id', 'attachment_id', 'error')}) + '\n') + write(run_dir / 'summary.json', summary) + print('run %s -> valid=%s invalid=%s failures=%s spans/op=%s p95=%s' % ( + run_dir, valid, invalid, failures, spans_op, load['scheduled_ms']['p95']), flush=True) + return summary + + # -- calibration + def calibrate(self): + rows = [] + self.configure('full') + for rate, warm, measure in CALIBRATION: + ctx_dir = self.out / 'calibration' / ('rate-%d' % rate) + ctx_dir.mkdir(parents=True, exist_ok=True) + c = stand.new_client(self.args.base_url, self.args.ca_file) + alice, _, _, chat = c.bootstrap() + workload.run_window(self.args.base_url, self.args.ca_file, alice, chat, rate, warm, + 'cal-warmup', settle=False) + result = workload.run_window(self.args.base_url, self.args.ca_file, alice, chat, rate, + measure, 'cal-measure', settle=True, obs_client=self.obs) + load = result['load'] + drain = result['drain'] + checks = { + 'zero_client_dropped': load['client_dropped'] == 0, + 'zero_http_errors': m.load_errors(load) == 0 and load['http_4xx'] == 0, + 'all_uploads_ready': drain['drained'] and all(s == 'ready' for s in drain['states'].values()), + 'start_lag_p95_le_50ms': (load['start_lag_ms_p95'] or 1e9) <= m.START_LAG_LIMIT_MS, + 'completed_ge_99pct': (load['completed_ratio'] or 0) >= m.COMPLETION_LIMIT, + } + row = {'rate_rps': rate, 'warmup_s': warm, 'measure_s': measure, 'load': load, + 'drain': drain, 'checks': checks, 'passed': all(checks.values())} + rows.append(row) + write(ctx_dir / 'calibration.json', row) + print('calibration rate=%d passed=%s %s' % (rate, row['passed'], checks), flush=True) + if row['passed']: + write(self.out / 'calibration.json', {'selected_rate_rps': rate, 'candidates': rows}) + return rate + write(self.out / 'calibration.json', {'selected_rate_rps': None, 'candidates': rows}) + raise Failure('no candidate rate (20/10/5) passed; fix the stand before the study') + + # -- smoke + def smoke(self): + out = self.out / 'smoke' + results = {} + problems = [] + for mode in ('off', 'full', 'p25', 'p10'): + s = self.execute_run(mode, 5, unique_dir(out / mode), warmup=5, measure=15, + n_slow=3, err_rate=2, err_seconds=2, label='smoke') + results[mode] = {'valid': s['valid'], 'invalid_reasons': s['invalid_reasons'], + 'spans_per_operation': s['spans_per_operation'], + 'cohorts': s['cohorts'], + 'effective_otel': {k: s['effective_env'][k] for k in + ('OTEL_SDK_DISABLED', 'OTEL_TRACES_SAMPLER_ARG')}} + if not s['valid']: + problems.append('%s: invalid %s' % (mode, s['invalid_reasons'])) + if mode == 'off' and (s['ingest_through_cohorts']['accepted_spans']['delta'] or 0) != 0: + problems.append('off sent spans') + if mode == 'full' and not s['cohorts']['error'].get('sampled_present'): + problems.append('full has no sampled roots in Tempo') + write(out / 'smoke.json', {'note': 'technical smoke only; not a study result', + 'results': results, 'problems': problems}) + if problems: + raise Failure('smoke: ' + '; '.join(problems)) + print('PASS: smoke (technical only, not a study result)') + + # -- full protocol + def full(self, attempt_label): + rate = self.calibrate() + base = self.out / 'runs' + runs, entries = [], [] + for repeat, order in enumerate(m.ORDERS, start=1): + for mode in order: + s = self.execute_run(mode, rate, unique_dir(base / ('%d-%s' % (repeat, mode))), + repeat=repeat) + runs.append(s) + entries.append(m.matrix_entry(s)) + write(self.out / 'matrix.json', {'rate_rps': rate, 'runs': entries, + 'complete': False}) + if not s['valid']: + raise Failure('protocol-invalid run %s: %s (fix the measurement defect and ' + 'rerun the whole block; raw evidence kept)' % (s['dir'], s['invalid_reasons'])) + by_mode = {mode: [r for r in runs if r['mode'] == mode] for mode in m.MODES} + write(self.out / 'matrix.json', {'rate_rps': rate, 'runs': entries, 'complete': True, + 'comparisons': comparisons(by_mode)}) + selection = m.select_p25(by_mode['full'], by_mode['p25']) + ref = selection['reference'] + selected = 'p25' if selection['passed'] else 'full' + write(self.out / 'selected.json', { + 'selected': selected, 'candidate': 'p25', 'candidate_passed': selection['passed'], + 'selection': selection, 'rate_rps': rate, + 'rare_event_miss_all_probability_model': rare_events(by_mode)}) + validations = [] + verdict = None + order = [selected] if selected == 'full' else ['p25', 'full'] + for mode in order: + s = self.execute_run(mode, rate, unique_dir(self.out / 'validation' / mode), label='validation') + result = m.validate_single(s, mode, ref) if ref['complete'] else { + 'passed': False, 'checks': {'frozen_full_reference_complete': False}, 'mode': mode} + validations.append({'mode': mode, 'run_dir': s['dir'], **result}) + if result['passed']: + verdict = mode + break + final = {'selected_before_validation': selected, 'validated_mode': verdict, + 'validations': validations, 'passed': verdict is not None, + 'frozen_full_reference': ref} + write(self.out / 'selected-validation.json', final) + if verdict is None: + raise Failure('selected-validation FAIL: neither p25 nor full passed independent validation') + print('PASS: track1 selected=%s validated=%s' % (selected, verdict)) + + +def metric_paths(run): + r = run['resources'] + api = r.get('api', {}) + return { + 'scheduled_p95_ms': run['load']['scheduled_ms']['p95'], + 'service_p95_ms': run['load']['service_ms']['p95'], + 'scheduled_p99_ms': run['load']['scheduled_ms']['p99'], + 'success_scheduled_p95_ms': run['load']['success_scheduled_ms']['p95'], + 'api_cpu_pct_sum_replicas': api.get('cpu_pct_time_weighted_mean'), + 'worker_cpu_pct': r.get('worker', {}).get('cpu_pct_time_weighted_mean'), + 'collector_cpu_pct': r.get('otel-collector', {}).get('cpu_pct_time_weighted_mean'), + 'api_container_mem_median': api.get('container_memory_bytes', {}).get('median'), + 'api_rss_median': api.get('process_rss_bytes', {}).get('median'), + 'worker_container_mem_median': r.get('worker', {}).get('container_memory_bytes', {}).get('median'), + 'spans_per_operation': run.get('spans_per_operation'), + 'log_records_per_operation': run.get('log_records_per_operation'), + 'metric_points_per_operation': run.get('metric_points_per_operation'), + 'retained_error_traces': run['cohorts']['error'].get('retained_traces'), + 'retained_slow_traces': run['cohorts']['slow'].get('retained_traces'), + } + + +def comparisons(by_mode): + table = {mode: {} for mode in by_mode} + for mode, runs in by_mode.items(): + keys = metric_paths(runs[0]).keys() if runs else [] + for key in keys: + table[mode][key] = m.spread([metric_paths(r)[key] for r in runs]) + versus = {} + for mode in by_mode: + versus[mode] = {} + for key in ('scheduled_p95_ms', 'service_p95_ms', 'api_cpu_pct_sum_replicas', + 'worker_cpu_pct', 'api_container_mem_median', 'api_rss_median'): + versus[mode][key + '_vs_off'] = m.relative( + table[mode].get(key, {}).get('median'), table['off'].get(key, {}).get('median')) + for key in ('spans_per_operation', 'log_records_per_operation', 'metric_points_per_operation'): + versus[mode][key + '_vs_full'] = m.relative( + table[mode].get(key, {}).get('median'), table['full'].get(key, {}).get('median')) + failures = {mode: [r['configuration_failures'] for r in runs] for mode, runs in by_mode.items()} + return {'per_mode': table, 'relative': versus, 'configuration_failures': failures} + + +def rare_events(by_mode): + out = {} + for mode, runs in by_mode.items(): + ratio = m.SAMPLER_RATIO[mode] + if ratio is None: + continue + for cls in ('error', 'slow'): + kept = sum(r['cohorts'][cls].get('retained_traces', 0) for r in runs) + n = sum(r['cohorts'][cls].get('n', 0) for r in runs) + out['%s/%s' % (mode, cls)] = { + 'N_total_over_runs': n, 'observed_kept': kept, + 'per_run_N': 40, 'miss_all_probability_per_run_model': m.miss_all_probability(ratio, 40), + 'note': '(1-r)^N assumes independent root sampling; a model, not a measurement'} + return out + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--base-url', default='http://localhost:8080') + parser.add_argument('--ca-file') + parser.add_argument('--prometheus-url', default='http://localhost:9090') + parser.add_argument('--grafana-url', default='http://localhost:3000') + parser.add_argument('--output-dir', default='evidence/lab6/track1') + parser.add_argument('--smoke', action='store_true') + args = parser.parse_args(argv) + track = Track(args) + try: + with track.obs.app_environment(BASELINE_ENV) as set_env: + track.set_env = set_env + if args.smoke: + track.smoke() + else: + track.full('attempt') + except Failure as error: + print('FAIL: ' + str(error), file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/lab6/verify.py b/scripts/lab6/verify.py new file mode 100755 index 0000000..7ba524a --- /dev/null +++ b/scripts/lab6/verify.py @@ -0,0 +1,671 @@ +#!/usr/bin/env python3 +"""lab6 verification: ready | inventory | signals | correlation | redaction | +history. Python 3.9+, standard library only. Every subcommand writes its own +evidence file under --output-dir and exits non-zero on any failed criterion.""" +import argparse +import base64 +import hashlib +import json +import re +import sys +import time +import urllib.parse +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import obs # noqa: E402 +from obs import Failure, stand, utc_now # noqa: E402 + +FORBIDDEN_LABEL = re.compile( + r'(^|_)(user|chat|message|attachment|request|trace|span|job)_id$|' + r'(^|_)(url|filename|text|body|username|password|token)($|_)') +EXPECTED_SIGNALS = [ + # logical signal, metric, required label names (normalised), unit + ('HTTP duration/count', 'http_server_request_duration_seconds_count', + ('http_request_method', 'http_route', 'http_response_status_code'), 's'), + ('HTTP duration buckets', 'http_server_request_duration_seconds_bucket', ('le',), 's'), + ('HTTP duration sum', 'http_server_request_duration_seconds_sum', (), 's'), + ('Jobs processed', 'messenger_jobs_processed_total', ('job_type', 'outcome'), '{job}'), + ('Job duration', 'messenger_job_duration_seconds_count', ('job_type', 'outcome'), 's'), + ('Time to ready', 'messenger_attachment_time_to_ready_seconds_count', ('job_type',), 's'), + ('Queue depth', 'messenger_jobs_queue_depth', ('state',), '{job}'), + ('Queue oldest age', 'messenger_jobs_queue_oldest_age_seconds', (), 's'), + ('Outbox pending', 'messenger_outbox_pending', (), '{message}'), + ('Outbox oldest age', 'messenger_outbox_oldest_age_seconds', (), 's'), + ('DB pool connections', 'db_client_connection_count', ('db_client_connection_state',), '{connection}'), + ('DB pool max', 'db_client_connection_max', (), '{connection}'), + ('DB pool pending', 'db_client_connection_pending_requests', (), '{request}'), + ('DB pool wait', 'db_client_connection_wait_time_seconds_count', (), 's'), + ('DB operation duration', 'db_client_operation_duration_seconds_count', ('db_operation_name',), 's'), + ('Worker active', 'messenger_worker_jobs_active', (), '{job}'), + ('Worker capacity', 'messenger_worker_jobs_capacity', (), '{job}'), + ('Broker published', 'messenger_broker_published_total', ('outcome',), '{message}'), + ('Telemetry export', 'messenger_telemetry_export_items_total', ('signal', 'outcome'), '{item}'), + ('Process CPU', 'process_cpu_time_seconds_total', ('cpu_mode',), 's'), + ('Process RAM', 'process_memory_usage_bytes', (), 'By'), + ('V8 heap', 'v8js_memory_heap_used_bytes', (), 'By'), + ('Event loop delay', 'nodejs_eventloop_delay_p99_seconds', (), 's'), +] +COLLECTOR_SIGNALS = [ + 'otelcol_receiver_accepted_spans', 'otelcol_receiver_accepted_log_records', + 'otelcol_receiver_accepted_metric_points', 'otelcol_exporter_sent_spans', + 'otelcol_exporter_sent_log_records', 'otelcol_exporter_sent_metric_points', + 'otelcol_exporter_queue_size', 'otelcol_exporter_queue_capacity', +] +COLLECTOR_FAILURE_ONLY = [ + 'otelcol_exporter_send_failed_spans', 'otelcol_exporter_send_failed_log_records', + 'otelcol_exporter_send_failed_metric_points', 'otelcol_exporter_enqueue_failed_spans', + 'otelcol_exporter_enqueue_failed_log_records', 'otelcol_exporter_enqueue_failed_metric_points', +] + + +# ------------------------------------------------------------------ helpers + +def write_json(out, name, data): + out.mkdir(parents=True, exist_ok=True) + (out / name).write_text(json.dumps(data, indent=2, ensure_ascii=False, + sort_keys=True) + '\n') + + +def make_obs(args): + return obs.ObsClient(args.prometheus_url, args.grafana_url, + base_url=args.base_url, ca_file=args.ca_file) + + +def ns_window(seconds_back=600, forward=30): + now = time.time_ns() + return now - seconds_back * 10 ** 9, now + forward * 10 ** 9 + + +def wait_rows(client, query, minimum=1, timeout=60, back=900): + deadline = time.monotonic() + timeout + rows = [] + while time.monotonic() < deadline: + start, end = ns_window(back) + rows = client.loki_rows(query, start, end) + if len(rows) >= minimum: + return rows + time.sleep(2) + raise Failure('expected log rows not found in Loki (' + str(len(rows)) + + '/' + str(minimum) + ')') + + +def http_log(client, request_id, timeout=60): + rows = wait_rows( + client, '{service_name="messenger-api"} | event_name="http.request" ' + '| request_id="' + request_id + '"', timeout=timeout) + if len(rows) != 1: + raise Failure('expected exactly one http.request log for the request') + return rows[0] + + +def chain_to_root(spans, span): + by_id = {s['span_id']: s for s in spans} + path = [span] + while path[-1]['parent_span_id']: + parent = by_id.get(path[-1]['parent_span_id']) + if parent is None: + raise Failure('broken parent chain at ' + path[-1]['name']) + path.append(parent) + if len(path) > 64: + raise Failure('parent chain too long') + return path + + +def descendants(spans, root_id): + children = {} + for s in spans: + children.setdefault(s['parent_span_id'], []).append(s) + out, stack = [], [root_id] + while stack: + for child in children.get(stack.pop(), []): + out.append(child) + stack.append(child['span_id']) + return out + + +def safe_span(s): + return {k: s[k] for k in ('span_id', 'parent_span_id', 'name', 'kind', + 'status', 'service', 'instance')} + + +def trace_with(client, trace_id, predicate, timeout=60, description='trace'): + deadline = time.monotonic() + timeout + spans = None + while time.monotonic() < deadline: + spans = client.get_trace(trace_id) + if spans and predicate(spans): + return spans + time.sleep(2) + raise Failure(description + ' did not reach the expected shape in Tempo') + + +def new_context(base_url, ca_file): + c = stand.new_client(base_url, ca_file) + alice, bob, eve, chat = c.bootstrap() + return c, alice, chat + + +def instrumented_env(): + return {'OTEL_SDK_DISABLED': 'false', 'OTEL_TRACES_SAMPLER_ARG': '1', + 'FAULT_INJECTION_ENABLED': '1', 'LOG_LEVEL': 'INFO'} + + +# -------------------------------------------------------------------- ready + +def cmd_ready(args): + client = make_obs(args) + client.wait_ready(app_telemetry=True, provisioning=not args.backend_only) + result = {'passed': True, 'backend_only': args.backend_only, + 'finished': utc_now()} + write_json(Path(args.output_dir), 'ready-backend.json' if args.backend_only + else 'ready.json', result) + print('PASS: ready' + (' (backend only)' if args.backend_only else '')) + + +# ---------------------------------------------------------------- inventory + +def inventory(client): + names = client.prom_names() + rows = [] + _, meta = obs.http_json(client.prometheus + '/api/v1/metadata') + for name in names: + if not re.match(r'(http_server|messenger|db_client|process|nodejs|v8js|target_info)', name): + continue + _, series = obs.http_json( + client.prometheus + '/api/v1/series?' + + urllib.parse.urlencode({'match[]': '{__name__="' + name + '"}'})) + labels = sorted({k for s in series['data'] for k in s} - {'__name__'}) + base = re.sub(r'_(bucket|count|sum|total)$', '', name) + info = (meta['data'].get(name) or meta['data'].get(base) or [{}])[0] + rows.append({'metric': name, 'type': info.get('type'), + 'unit': info.get('unit') or None, 'labels': labels, + 'series': len(series['data'])}) + return names, rows + + +def cmd_inventory(args): + client = make_obs(args) + names, rows = inventory(client) + out = Path(args.output_dir) + out.mkdir(parents=True, exist_ok=True) + (out / 'metric-names.txt').write_text('\n'.join(names) + '\n') + write_json(out, 'inventory.json', {'captured': utc_now(), 'metrics': rows}) + print('inventory: %d names, %d application/runtime metrics' % + (len(names), len(rows))) + + +# ------------------------------------------------------------------ signals + +def series_labels(client, name): + _, series = obs.http_json( + client.prometheus + '/api/v1/series?' + + urllib.parse.urlencode({'match[]': '{__name__="' + name + '"}'})) + return series['data'] + + +def cmd_signals(args): + client = make_obs(args) + names, rows = inventory(client) + out = Path(args.output_dir) + out.mkdir(parents=True, exist_ok=True) + (out / 'metric-names.txt').write_text('\n'.join(names) + '\n') + problems, table = [], [] + for logical, metric, required, unit in EXPECTED_SIGNALS: + data = series_labels(client, metric) + labels = sorted({k for s in data for k in s} - {'__name__'}) + missing = [r for r in required if r not in labels] + table.append({'signal': logical, 'metric': metric, 'labels': labels, + 'unit': unit, 'series': len(data)}) + if not data: + problems.append('missing metric ' + metric) + elif missing: + problems.append(metric + ' lacks labels ' + ','.join(missing)) + # Contract: forbidden labels on any application/runtime metric. + for row in rows: + for label in row['labels']: + if FORBIDDEN_LABEL.search(label): + problems.append('forbidden label ' + label + ' on ' + row['metric']) + # Business facts: routes, replicas, outcomes. + routes = {s.get('http_route') for s in series_labels( + client, 'http_server_request_duration_seconds_count')} + if not any(r and r.startswith('/api/v1/') and '{' in r for r in routes): + problems.append('no route templates with {param} placeholders') + if any(r and re.search(r'[0-9a-f]{8}-[0-9a-f]{4}', r) for r in routes): + problems.append('raw UUID in http_route') + replicas = {s['instance'] for s in series_labels( + client, 'http_server_request_duration_seconds_count') + if s.get('job') == 'messenger-api'} + if len(replicas) < 2: + problems.append('fewer than two API replicas in HTTP metrics') + outcomes = {s.get('outcome') for s in series_labels( + client, 'messenger_jobs_processed_total')} + for needed in ('succeeded', 'retry', 'failed'): + if needed not in outcomes: + problems.append('job outcome not observed: ' + needed + + ' (run lab6-correlate first)') + for job in ('messenger-api', 'messenger-worker'): + if not client.prom_query('target_info{job="%s"}' % job): + problems.append('no metrics from ' + job) + # Queue snapshot is not doubled by the two API replicas. + depth_series = client.prom_query('messenger_jobs_queue_depth{state="ready"}') + # Collector. + collector = {} + for metric in COLLECTOR_SIGNALS: + data = series_labels(client, metric) + collector[metric] = len(data) + if not data: + problems.append('missing Collector metric ' + metric) + for metric in COLLECTOR_FAILURE_ONLY: + collector[metric] = len(series_labels(client, metric)) + if not client.prom_query('otelcol_process_memory_rss'): + problems.append('no Collector RSS') + # Logs/traces for both services. + for service in ('messenger-api', 'messenger-worker'): + rows_ = wait_rows(client, '{service_name="%s"}' % service, timeout=30) + if not rows_: + problems.append('no logs from ' + service) + result = {'captured': utc_now(), 'signals': table, + 'collector_series': collector, + 'job_outcomes_observed': sorted(o for o in outcomes if o), + 'api_replicas_with_http_metrics': sorted(replicas), + 'queue_depth_ready_series': len(depth_series), + 'route_templates': sorted(r for r in routes if r), + 'problems': problems, 'passed': not problems} + write_json(out, 'signals.json', result) + if problems: + raise Failure('signals: ' + '; '.join(problems)) + print('PASS: signals (%d logical signals)' % len(table)) + + +# -------------------------------------------------------------- correlation + +def status_of(attachment_id): + code, body = stand.cli('status', attachment_id) + if code != 0: + raise Failure('jobs.cli status failed') + return body + + +def correlate_http(client, base_url, ca_file, obs_client): + c, alice, chat = new_context(base_url, ca_file) + key = uuid.uuid4().hex + r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, + actor=alice, body={'text': 'lab6 correlation'}, + headers={'Idempotency-Key': key}, schema='Message') + rid = r['headers']['X-Request-Id'] + log = http_log(obs_client, rid) + labels = log['labels'] + if labels.get('trace_sampled') != 'true': + raise Failure('HTTP log is not marked sampled') + spans = trace_with( + obs_client, labels['trace_id'], + lambda sp: any(s['span_id'] == labels['span_id'] for s in sp) and + len(descendants(sp, labels['span_id'])) > 0, description='HTTP trace') + server = next(s for s in spans if s['span_id'] == labels['span_id']) + if server['kind'] != 'SERVER' or \ + server['attributes'].get('messenger.request_id') != rid: + raise Failure('SERVER span does not match the logged request') + db = [s for s in descendants(spans, server['span_id']) + if s['kind'] == 'CLIENT' and 'db.operation.name' in s['attributes']] + if not db: + raise Failure('no DB CLIENT child spans under the SERVER span') + return {'request_id': rid, 'trace_id': labels['trace_id'], + 'server_span': safe_span(server), + 'log_span_id': labels['span_id'], + 'db_children': [safe_span(s) for s in db]} + + +def upload_and_trace(c, alice, chat, obs_client, require_attempts=1): + r = c.call('POST', '/api/v1/chats/' + chat['id'] + + '/attachments?filename=sample.png', 202, actor=alice, + raw=stand.sample_bytes(), headers={'Content-Type': 'image/png'}, + schema='Attachment') + return r['json'], r['headers']['X-Request-Id'] + + +def consumer_spans(spans): + return sorted((s for s in spans if s['kind'] == 'CONSUMER'), + key=lambda s: s['start_ns']) + + +def correlate_upload(client_args, obs_client): + c, alice, chat = new_context(client_args.base_url, client_args.ca_file) + att, rid = upload_and_trace(c, alice, chat, obs_client) + stand.wait_ready(c, alice, att['id']) + log = http_log(obs_client, rid) + tid = log['labels']['trace_id'] + + def complete(sp): + cons = consumer_spans(sp) + return bool(cons) and any(s['kind'] == 'SERVER' for s in sp) + + spans = trace_with(obs_client, tid, complete, description='upload trace') + consumer = consumer_spans(spans)[0] + path = chain_to_root(spans, consumer) + kinds = [s['kind'] for s in path] + if path[-1]['kind'] != 'SERVER' or 'PRODUCER' not in kinds: + raise Failure('consumer is not linked to the HTTP SERVER via PRODUCER') + if path[-1]['service'] != 'messenger-api' or consumer['service'] != 'messenger-worker': + raise Failure('services along the chain are wrong') + below = descendants(spans, consumer['span_id']) + s3 = [s for s in below if s['attributes'].get('rpc.system') == 'aws-api'] + db = [s for s in below if 'db.operation.name' in s['attributes']] + if not s3 or not db: + raise Failure('consumer has no S3/DB child spans') + return {'request_id': rid, 'trace_id': tid, 'attachment_id': att['id'], + 'chain_consumer_to_root': [safe_span(s) for s in path], + 'consumer_attempt': consumer['attributes'].get('messenger.job.attempt'), + 'consumer_outcome': consumer['attributes'].get('messenger.job.outcome'), + 's3_children': len(s3), 'db_children': len(db), + 'chain_fields_are_real_parent_child': True} + + +def start_worker(): + stand.compose('up', '-d', '--no-deps', '--wait', 'worker') + + +def targeted_job(c, alice, chat, obs_client): + """Stop the worker, accept an upload, return (att, rid, job_id, version).""" + stand.compose('stop', 'worker') + att, rid = upload_and_trace(c, alice, chat, obs_client) + body = status_of(att['id']) + jobs = body.get('jobs') + if not isinstance(jobs, list) or len(jobs) != 1: + raise Failure('expected exactly one job for the new upload') + return att, rid, jobs[0]['job_id'], jobs[0]['pipeline_version'] + + +def correlate_fault(client_args, obs_client, kind): + c, alice, chat = new_context(client_args.base_url, client_args.ca_file) + obs_client.require_no_foreign_faults() + key = None + try: + att, rid, job_id, version = targeted_job(c, alice, chat, obs_client) + key = 'fault:worker.before_side_effect:%s:%s' % (att['id'], version) + stand.set_fault(key, kind) + start_worker() + if kind == 'transient': + def retried(): + job = status_of(att['id'])['jobs'][0] + return job['attempt'] >= 2 or job['last_error_code'] + stand.wait_for(retried, 90, 'first retry') + stand.clear_fault(key) + key = None + stand.wait_ready(c, alice, att['id'], timeout=120) + else: + def failed(): + return status_of(att['id'])['jobs'][0]['status'] == 'failed' + stand.wait_for(failed, 90, 'terminal failed job') + meta = stand.wait_ready(c, alice, att['id'], allow_failed=True) + if meta['status'] != 'failed': + raise Failure('attachment did not become failed') + final = status_of(att['id']) + log = http_log(obs_client, rid) + tid = log['labels']['trace_id'] + wanted = 2 if kind == 'transient' else 1 + + def enough(sp): + return len(consumer_spans(sp)) >= wanted + + spans = trace_with(obs_client, tid, enough, timeout=90, + description=kind + ' trace') + consumers = consumer_spans(spans) + ids = {s['span_id'] for s in consumers} + if len(ids) != len(consumers): + raise Failure('consumer attempts share a span ID') + attempts = [s['attributes'].get('messenger.job.attempt') for s in consumers] + outcomes = [s['attributes'].get('messenger.job.outcome') for s in consumers] + if kind == 'transient': + if sorted(attempts)[:2] != [1, 2] or 'retry' not in outcomes: + raise Failure('retry attempts not visible in the trace: %s %s' % (attempts, outcomes)) + else: + if 'failed' not in outcomes: + raise Failure('failed outcome not visible in the trace') + return {'kind': kind, 'request_id': rid, 'trace_id': tid, + 'attachment_id': att['id'], 'job_id': job_id, + 'pipeline_version': version, + 'consumer_spans': [safe_span(s) | { + 'attempt': s['attributes'].get('messenger.job.attempt'), + 'outcome': s['attributes'].get('messenger.job.outcome')} + for s in consumers], + 'final_job': {k: final['jobs'][0].get(k) for k in + ('status', 'attempt', 'last_error_code')}, + 'final_attachment_status': final['attachment']['status']} + finally: + if key: + stand.clear_fault(key) + start_worker() + + +def cmd_correlation(args): + client = make_obs(args) + out = Path(args.output_dir) + with client.app_environment(instrumented_env()): + client.require_no_foreign_faults() + results = { + 'correlation-http.json': correlate_http(client, args.base_url, args.ca_file, client), + 'correlation-upload.json': correlate_upload(args, client), + 'correlation-retry.json': correlate_fault(args, client, 'transient'), + 'correlation-failed.json': correlate_fault(args, client, 'permanent'), + } + for name, data in results.items(): + data['captured'] = utc_now() + write_json(out, name, data) + print('PASS: correlation (http, upload, retry, failed)') + + +# ---------------------------------------------------------------- redaction + +PEM = re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----') + + +def fragments(text, size=48, stride=16): + return [text[i:i + size] for i in range(0, max(1, len(text) - size + 1), stride)] + + +def flatten(value, path=''): + if isinstance(value, dict): + for k, v in value.items(): + yield from flatten(v, path + '.' + str(k)) + yield path + '.key:' + str(k) + elif isinstance(value, list): + for i, v in enumerate(value): + yield from flatten(v, path + '[' + str(i) + ']') + else: + yield path + '=' + str(value) + + +def scan(texts, secrets): + """texts: [(source, text)]; secrets: {category: [needle,...]}.""" + leaks = [] + for source, text in texts: + for category, needles in secrets.items(): + for needle in needles: + if needle and needle in text: + leaks.append({'category': category, 'source': source, + 'hash': hashlib.sha256(needle.encode()).hexdigest()[:12]}) + break + if PEM.search(text): + leaks.append({'category': 'private_key_pem', 'source': source, 'hash': ''}) + return leaks + + +def cmd_redaction(args): + client = make_obs(args) + out = Path(args.output_dir) + with client.app_environment(instrumented_env()): + c = stand.new_client(args.base_url, args.ca_file) + actor = c.user('redact') + marker = 'LAB6-REDACT-' + uuid.uuid4().hex + password = actor['registration']['password'] + token = actor['token'] + username = actor['registration']['username'] + basic = base64.b64encode((username + ':' + password).encode()).decode() + signature = 'sig' + uuid.uuid4().hex + uuid.uuid4().hex + own_chat = c.call('POST', '/api/v1/chats', 201, actor=actor, + body={'title': 'redaction', 'member_ids': [actor['id']]}, + schema='Chat')['json'] + requests = {} + r = c.call('POST', '/api/v1/chats/' + own_chat['id'] + '/messages', 201, + actor=actor, body={'text': 'body ' + marker}, + headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message') + requests['message'] = r['headers']['X-Request-Id'] + r = c.call('GET', '/api/v1/chats?X-Amz-Signature=' + signature, range(200, 500), + actor=actor, headers={'X-Marker': marker}) + requests['signed_query'] = r['headers']['X-Request-Id'] + r = c.call('POST', '/api/v1/auth/sessions', 401, + headers={'Authorization': 'Basic ' + base64.b64encode( + (username + ':wrong-' + marker).encode()).decode()}) + requests['bad_login'] = r['headers']['X-Request-Id'] + att, rid = upload_and_trace(c, actor, own_chat, client) + requests['upload'] = rid + stand.wait_ready(c, actor, att['id']) + sample = stand.sample_bytes() + b64 = base64.b64encode(sample).decode() + hexs = sample.hex() + secrets = { + 'marker': [marker], 'password': [password], 'session_token': [token], + 'basic_credential': [basic], 'bearer_header': ['Bearer ' + token], + 'signature': [signature], 'image_base64': [b64], + 'image_hex': [hexs], + 'image_base64_fragment': fragments(b64), 'image_hex_fragment': fragments(hexs), + 'wrong_password_marker': ['wrong-' + marker], + } + coverage = {'http_logs': {}, 'server_spans': {}, 'worker_chain': False} + texts = [] + trace_ids = {} + for name, request_id in requests.items(): + log = http_log(client, request_id) + coverage['http_logs'][name] = True + texts.append(('log:' + name, log['line'] + json.dumps(log['labels'], sort_keys=True))) + trace_ids[name] = log['labels']['trace_id'] + for name, tid in trace_ids.items(): + def has_server(sp, tid=tid, name=name): + return any(s['kind'] == 'SERVER' and + s['attributes'].get('messenger.request_id') == requests[name] + for s in sp) + spans = trace_with(client, tid, has_server, description='trace ' + name) + coverage['server_spans'][name] = True + if name == 'upload': + coverage['worker_chain'] = any(s['kind'] == 'CONSUMER' for s in spans) \ + if any(s['kind'] == 'CONSUMER' for s in spans) else False + if not coverage['worker_chain']: + spans = trace_with(client, tid, lambda sp: any( + s['kind'] == 'CONSUMER' for s in sp), description='worker chain') + coverage['worker_chain'] = True + for s in spans: + for item in flatten({k: s[k] for k in ('name', 'attributes', 'status')}): + texts.append(('span:' + name + ':' + s['kind'], item)) + logs = wait_rows(client, '{service_name=~"messenger-.*"} | trace_id="%s"' % tid) + for row in logs: + texts.append(('tracelog:' + name, row['line'] + json.dumps(row['labels'], sort_keys=True))) + worker_logs = wait_rows( + client, '{service_name="messenger-worker"} | messenger_attachment_id="%s"' % att['id']) + coverage['worker_logs'] = len(worker_logs) + for row in worker_logs: + texts.append(('workerlog', row['line'] + json.dumps(row['labels'], sort_keys=True))) + leaks = scan(texts, secrets) + complete = (all(coverage['http_logs'].get(n) for n in requests) and + all(coverage['server_spans'].get(n) for n in requests) and + coverage['worker_chain'] and coverage['worker_logs'] > 0) + result = {'captured': utc_now(), 'coverage': coverage, 'coverage_complete': complete, + 'scanned_items': len(texts), 'leak_count': len(leaks), 'leaks': leaks, + 'passed': complete and not leaks} + write_json(out, 'redaction.json', result) + (out / 'redaction.txt').write_text( + 'coverage_complete=%s scanned_items=%d leaks=%d\n' % + (complete, len(texts), len(leaks))) + if not result['passed']: + raise Failure('redaction: coverage_complete=%s leaks=%d' % (complete, len(leaks))) + print('PASS: redaction (%d items scanned, 0 leaks)' % len(texts)) + + +# ------------------------------------------------------------------ history + +def raw_samples(client, selector, at, window='30s'): + result = client.prom_query(selector + '[' + window + ']', at=at) + return {json.dumps(r['metric'], sort_keys=True): r['values'] for r in result} + + +def cmd_history(args): + client = make_obs(args) + out = Path(args.output_dir) + with client.app_environment(instrumented_env()): + c, alice, chat = new_context(args.base_url, args.ca_file) + r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, + actor=alice, body={'text': 'history'}, + headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message') + rid_message = r['headers']['X-Request-Id'] + att, rid = upload_and_trace(c, alice, chat, client) + stand.wait_ready(c, alice, att['id']) + log = http_log(client, rid) + tid = log['labels']['trace_id'] + spans = trace_with(client, tid, lambda sp: any(s['kind'] == 'CONSUMER' for s in sp), + description='history trace') + msg_log = http_log(client, rid_message) + client.wait_telemetry_flushed() + time.sleep(12) + client.wait_telemetry_flushed() + at = time.time() + selector = 'messenger_jobs_processed_total{job="messenger-worker",outcome="succeeded"}' + before = raw_samples(client, selector, at) + if not before: + raise Failure('no Prometheus samples to preserve') + series_key, values = next(iter(before.items())) + old_sample = {'labels': json.loads(series_key), 'timestamp': values[-1][0], + 'value': values[-1][1]} + old_log = {'ts': log['ts'], 'request_id': rid, 'trace_id': tid, + 'span_id': log['labels']['span_id']} + old_trace = sorted(s['span_id'] for s in spans) + old_msg = {'ts': msg_log['ts'], 'trace_id': msg_log['labels']['trace_id']} + stand.compose('restart', 'prometheus', 'loki', 'tempo', 'grafana') + client.wait_ready(timeout=180, app_telemetry=True, provisioning=True) + after_samples = raw_samples(client, selector, at) + after = after_samples.get(series_key, []) + prom_ok = any(abs(v[0] - old_sample['timestamp']) < 1e-6 and + v[1] == old_sample['value'] for v in after) + rows = wait_rows(client, '{service_name="messenger-api"} | request_id="%s"' % rid) + loki_ok = any(row['ts'] == old_log['ts'] and + row['labels'].get('trace_id') == tid for row in rows) + spans_after = client.get_trace(tid, wait=30) + tempo_ok = bool(spans_after) and \ + sorted(s['span_id'] for s in spans_after) == old_trace + result = {'captured': utc_now(), 'prometheus_old_sample': old_sample, + 'prometheus_read_back': prom_ok, 'loki_old_log': old_log, + 'loki_read_back': loki_ok, 'tempo_old_trace_span_ids': old_trace, + 'tempo_read_back': tempo_ok, + 'passed': prom_ok and loki_ok and tempo_ok} + write_json(out, 'history.json', result) + if not result['passed']: + raise Failure('history: old data not readable after restart: %s' % { + k: result[k] for k in ('prometheus_read_back', 'loki_read_back', 'tempo_read_back')}) + print('PASS: history (old Prometheus sample, Loki log and Tempo trace survive restart)') + + +COMMANDS = {'ready': cmd_ready, 'inventory': cmd_inventory, 'signals': cmd_signals, + 'correlation': cmd_correlation, 'redaction': cmd_redaction, + 'history': cmd_history} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('command', choices=sorted(COMMANDS)) + parser.add_argument('--base-url', default='http://localhost:8080') + parser.add_argument('--ca-file') + parser.add_argument('--prometheus-url', default='http://localhost:9090') + parser.add_argument('--grafana-url', default='http://localhost:3000') + parser.add_argument('--output-dir', default='evidence/lab6') + parser.add_argument('--backend-only', action='store_true') + args = parser.parse_args(argv) + try: + COMMANDS[args.command](args) + except Failure as error: + print('FAIL: ' + str(error), file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/lab6/workload.py b/scripts/lab6/workload.py new file mode 100644 index 0000000..1f05491 --- /dev/null +++ b/scripts/lab6/workload.py @@ -0,0 +1,140 @@ +"""Fixed-rate open-loop workload for lab6 (stdlib only). + +Slot i is planned at t0 + i/rate on a monotonic clock; the generator never +waits for earlier requests and never catches up with a burst. When no +in-flight slot is available the slot is recorded as client_dropped and stays +in the denominator.""" +import math +import sys +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import measurement # noqa: E402 +import obs # noqa: E402 +from obs import Failure, stand # noqa: E402 + +REQUEST_TIMEOUT = 30 +MESSAGE_TEXT = 'lab6-track1' + + +def slot_kind(i, upload_every): + if upload_every == 0: + return 'message' + if upload_every == 1: + return 'upload' + return 'upload' if (i + 1) % upload_every == 0 else 'message' + + +class _Local(threading.local): + client = None + + +def run_window(base_url, ca_file, actor, chat, rate, duration, phase_id, + upload_every=20, max_inflight=64, stop_event=None, settle=True, + obs_client=None): + """Run one window and return {'slots', 'load', 'uploads', 'drain', ...}. + + stop_event stops only new slots; started requests complete. settle=False + returns right after HTTP (no job/Collector drain).""" + local = _Local() + image = stand.sample_bytes() + lock = threading.Lock() + inflight = [0] + planned = [] + + def client(): + if local.client is None: + local.client = stand.new_client(base_url, ca_file) + local.client.timeout = REQUEST_TIMEOUT + return local.client + + def execute(record, kind, t0_mono): + record['start'] = time.monotonic() - t0_mono + record['start_lag_ms'] = (record['start'] - record['scheduled']) * 1000.0 + started = time.monotonic() + try: + c = client() + if kind == 'message': + result = c.call( + 'POST', '/api/v1/chats/' + chat['id'] + '/messages', + range(200, 600), actor=actor, body={'text': MESSAGE_TEXT}, + headers={'Idempotency-Key': uuid.uuid4().hex, + 'X-Request-Id': uuid.uuid4().hex}, + schema='Message') + else: + result = c.call( + 'POST', '/api/v1/chats/' + chat['id'] + + '/attachments?filename=sample.png', range(200, 600), + actor=actor, raw=image, + headers={'Content-Type': 'image/png', + 'X-Request-Id': uuid.uuid4().hex}, + schema='Attachment') + end = time.monotonic() + record['status'] = result['status'] + record['request_id'] = result['headers'].get('X-Request-Id') + record['instance_id'] = result['headers'].get('X-Instance-Id') + if kind == 'upload' and result['status'] == 202 and result['json']: + record['attachment_id'] = result['json']['id'] + record['outcome'] = 'http' + except Failure as error: + end = time.monotonic() + text = str(error) + record['outcome'] = ('timeout' if 'TimeoutError' in text else + 'transport_error' if 'connection/TLS' in text + else 'protocol_error') + record['error'] = text[:160] + finally: + with lock: + inflight[0] -= 1 + record['end'] = end - t0_mono + record['service_ms'] = (end - started) * 1000.0 + record['scheduled_ms'] = (record['end'] - record['scheduled']) * 1000.0 + + pool = ThreadPoolExecutor(max_workers=max_inflight) + futures = [] + t0 = time.monotonic() + started_utc = obs.utc_now() + total = int(math.floor(rate * duration)) + try: + for i in range(total): + due = t0 + i / rate + while True: + if stop_event is not None and stop_event.is_set(): + break + remaining = due - time.monotonic() + if remaining <= 0: + break + time.sleep(min(remaining, 0.05)) + if stop_event is not None and stop_event.is_set(): + break + kind = slot_kind(i, upload_every) + record = {'i': i, 'phase': phase_id, 'name': '%s-%d' % (phase_id, i), + 'kind': kind, 'scheduled': i / rate, 'outcome': None, + 'start_lag_ms': None} + planned.append(record) + with lock: + free = inflight[0] < max_inflight + if free: + inflight[0] += 1 + if not free: + record['outcome'] = 'client_dropped' + continue + futures.append(pool.submit(execute, record, kind, t0)) + for future in futures: + future.result() + finally: + pool.shutdown(wait=True) + dispatch_end = time.monotonic() - t0 + load = measurement.summarize_load(planned, rate) + uploads = [s['attachment_id'] for s in planned if s.get('attachment_id')] + result = {'phase': phase_id, 'slots': planned, 'load': load, + 'uploads': uploads, 'started': started_utc, + 'dispatch_seconds': dispatch_end, 'finished_dispatch': obs.utc_now(), + 'stopped_early': bool(stop_event is not None and stop_event.is_set())} + if settle: + result['drain'] = obs.wait_drained(uploads, obs=obs_client) + return result diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..ac946b5 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`. +# Semantic and evidence notes: tests/README.md ("Проверка сохранности") and REPORT.md. +set -euo pipefail + +compose=(docker compose --env-file .env) +"${compose[@]}" restart postgres redis s3 broker api worker haproxy otel-collector prometheus loki tempo grafana +"${compose[@]}" up -d --no-recreate --no-deps --wait postgres redis s3 broker api worker haproxy otel-collector prometheus loki tempo grafana diff --git a/scripts/start-replica.sh b/scripts/start-replica.sh new file mode 100755 index 0000000..bf24b82 --- /dev/null +++ b/scripts/start-replica.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Восстанавливает недостающую API-реплику до объявленного числа реплик. +set -eu + +env_file="${COMPOSE_ENV_FILE:-.env}" +replicas="${API_REPLICAS:-}" +if [ -z "$replicas" ] && [ -f "$env_file" ]; then + replicas=$(sed -n 's/^API_REPLICAS=//p' "$env_file" | tail -n 1) +fi +replicas="${replicas:-2}" +exec docker compose --env-file "$env_file" up -d --no-deps --scale "api=${replicas}" api diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..c0d206e --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# Останавливает ровно одну API-реплику стенда — ту, которую обслужила текущая +# сессия. TARGET_INSTANCE_ID приходит из теста (значение X-Instance-Id ответа), +# а в Docker hostname контейнера равен его короткому ID, поэтому сопоставление +# однозначно. Ничего, кроме этой реплики, скрипт не трогает: ни LB, ни БД, ни +# тома. Возврат управления — быстрый (SIGTERM -> дрейн DRAIN_DELAY_MS=3s -> +# выход), останавливать реплику "навсегда" не требуется. +set -eu + +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +project="${LAB_PROJECT:-mtusi-lab7}" + +target='' +for container in $( + docker ps \ + --filter "label=com.docker.compose.project=${project}" \ + --filter 'label=com.docker.compose.service=api' \ + --format '{{.ID}}' +); do + case "$container" in + "$TARGET_INSTANCE_ID"*) + target="$container" + break + ;; + esac +done + +if [ -z "$target" ]; then + printf 'stop-one: no running api replica of project %s whose id starts with %s\n' \ + "$project" "$TARGET_INSTANCE_ID" >&2 + exit 1 +fi + +printf 'stop-one: stopping api replica %s\n' "$target" >&2 +docker stop --time 10 "$target" >/dev/null