From 98d5787545cd7b7fc428faae886d2dd996a58c7e Mon Sep 17 00:00:00 2001 From: aegor Date: Wed, 18 Nov 2026 18:40:47 +0300 Subject: [PATCH 1/8] chore: port lab5 solution as lab6 base --- .dockerignore | 4 + .env.example | 4 + .gitattributes | 2 + .prettierrc.json | 6 + Dockerfile | 45 + compose.test.yaml | 55 + compose.yaml | 334 + contracts/extensions.openapi.json | 36 + infra/haproxy/haproxy.cfg | 43 + nest-cli.json | 8 + package-lock.json | 12296 ++++++++++++++++ package.json | 54 + .../20261021000000_init/migration.sql | 50 + .../migration.sql | 14 + .../migration.sql | 13 + .../20261105000000_attachments/migration.sql | 45 + .../migration.sql | 97 + prisma/migrations/migration_lock.toml | 3 + prisma/schema.prisma | 190 + scripts/check-s3-anonymous.py | 21 + scripts/check-s3.sh | 46 + scripts/collect-evidence.sh | 123 + scripts/job-scenario.py | 394 + scripts/probe.py | 88 + scripts/restart.sh | 9 + scripts/stop-one.sh | 11 + src/app.module.ts | 25 + src/attachments/attachments.controller.ts | 79 + src/attachments/attachments.module.ts | 9 + src/attachments/attachments.service.ts | 244 + src/attachments/dto/attachment.response.ts | 55 + src/attachments/image-validation.ts | 105 + src/attachments/reconciler.ts | 163 + src/attachments/upload-body.ts | 98 + src/auth/auth.controller.ts | 51 + src/auth/auth.guard.ts | 25 + src/auth/auth.module.ts | 12 + src/auth/auth.service.ts | 155 + src/auth/current-user.decorator.ts | 20 + src/auth/password.ts | 17 + src/broker/broker.ts | 57 + src/cache/cache.module.ts | 9 + src/cache/cache.service.ts | 98 + src/chats/chat-access.ts | 19 + src/chats/chats.controller.ts | 57 + src/chats/chats.module.ts | 10 + src/chats/chats.service.ts | 131 + src/chats/dto/chat.response.ts | 22 + src/chats/dto/create-chat.dto.ts | 22 + src/common/cursor.ts | 49 + src/common/domain.ts | 22 + src/common/dto/code-point-length.validator.ts | 33 + src/common/dto/not-blank.validator.ts | 20 + src/common/dto/pagination-query.dto.ts | 35 + src/common/filters/api-error.ts | 34 + src/common/filters/http-exception.filter.ts | 115 + src/common/interceptors/request-id.ts | 23 + src/common/uuid.ts | 6 + src/configure-app.ts | 21 + src/db/db.module.ts | 9 + src/db/prisma.service.ts | 49 + src/docs/examples.ts | 351 + src/docs/swagger.ts | 43 + src/health/health.controller.ts | 44 + src/health/health.module.ts | 7 + src/health/shutdown.ts | 26 + src/jobs/job-message.ts | 69 + src/jobs/job-store.ts | 257 + src/jobs/processor.ts | 273 + src/jobs/variants.ts | 111 + src/main.ts | 34 + src/messages/dto/create-message.dto.ts | 41 + src/messages/dto/message.response.ts | 26 + src/messages/messages.controller.ts | 70 + src/messages/messages.module.ts | 9 + src/messages/messages.service.ts | 198 + src/reconcile.ts | 57 + src/relay.ts | 129 + src/replay.ts | 54 + src/storage/s3.service.ts | 245 + src/storage/storage.module.ts | 9 + src/users/dto/create-user.dto.ts | 18 + src/users/dto/user.response.ts | 17 + src/users/users.controller.ts | 36 + src/users/users.module.ts | 10 + src/users/users.service.ts | 48 + src/worker.ts | 137 + test/api.e2e-spec.ts | 686 + test/attachment-access.e2e-spec.ts | 302 + test/attachments.e2e-spec.ts | 401 + test/auth.e2e-spec.ts | 179 + test/concurrency.e2e-spec.ts | 119 + test/contract.e2e-spec.ts | 241 + test/docs.e2e-spec.ts | 69 + test/failures.e2e-spec.ts | 166 + test/global-setup.ts | 28 + test/helpers.ts | 110 + test/idempotency.e2e-spec.ts | 139 + test/images.ts | 150 + test/jest-e2e.json | 11 + test/jobs.e2e-spec.ts | 513 + test/reconciler.e2e-spec.ts | 343 + test/request-constraints.e2e-spec.ts | 206 + tsconfig.build.json | 4 + tsconfig.json | 22 + 105 files changed, 21898 insertions(+) create mode 100644 .gitattributes create mode 100644 .prettierrc.json create mode 100644 Dockerfile create mode 100644 compose.test.yaml create mode 100644 compose.yaml create mode 100644 contracts/extensions.openapi.json create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 nest-cli.json create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 prisma/migrations/20261021000000_init/migration.sql create mode 100644 prisma/migrations/20261021010000_auth_sessions/migration.sql create mode 100644 prisma/migrations/20261101000000_idempotency_keys/migration.sql create mode 100644 prisma/migrations/20261105000000_attachments/migration.sql create mode 100644 prisma/migrations/20261115000000_attachment_jobs/migration.sql create mode 100644 prisma/migrations/migration_lock.toml create mode 100644 prisma/schema.prisma create mode 100755 scripts/check-s3-anonymous.py create mode 100755 scripts/check-s3.sh create mode 100755 scripts/collect-evidence.sh create mode 100755 scripts/job-scenario.py create mode 100755 scripts/probe.py create mode 100755 scripts/restart.sh create mode 100755 scripts/stop-one.sh create mode 100644 src/app.module.ts create mode 100644 src/attachments/attachments.controller.ts create mode 100644 src/attachments/attachments.module.ts create mode 100644 src/attachments/attachments.service.ts create mode 100644 src/attachments/dto/attachment.response.ts create mode 100644 src/attachments/image-validation.ts create mode 100644 src/attachments/reconciler.ts create mode 100644 src/attachments/upload-body.ts create mode 100644 src/auth/auth.controller.ts create mode 100644 src/auth/auth.guard.ts create mode 100644 src/auth/auth.module.ts create mode 100644 src/auth/auth.service.ts create mode 100644 src/auth/current-user.decorator.ts create mode 100644 src/auth/password.ts create mode 100644 src/broker/broker.ts create mode 100644 src/cache/cache.module.ts create mode 100644 src/cache/cache.service.ts create mode 100644 src/chats/chat-access.ts create mode 100644 src/chats/chats.controller.ts create mode 100644 src/chats/chats.module.ts create mode 100644 src/chats/chats.service.ts create mode 100644 src/chats/dto/chat.response.ts create mode 100644 src/chats/dto/create-chat.dto.ts create mode 100644 src/common/cursor.ts create mode 100644 src/common/domain.ts create mode 100644 src/common/dto/code-point-length.validator.ts create mode 100644 src/common/dto/not-blank.validator.ts create mode 100644 src/common/dto/pagination-query.dto.ts create mode 100644 src/common/filters/api-error.ts create mode 100644 src/common/filters/http-exception.filter.ts create mode 100644 src/common/interceptors/request-id.ts create mode 100644 src/common/uuid.ts create mode 100644 src/configure-app.ts create mode 100644 src/db/db.module.ts create mode 100644 src/db/prisma.service.ts create mode 100644 src/docs/examples.ts create mode 100644 src/docs/swagger.ts create mode 100644 src/health/health.controller.ts create mode 100644 src/health/health.module.ts create mode 100644 src/health/shutdown.ts create mode 100644 src/jobs/job-message.ts create mode 100644 src/jobs/job-store.ts create mode 100644 src/jobs/processor.ts create mode 100644 src/jobs/variants.ts create mode 100644 src/main.ts create mode 100644 src/messages/dto/create-message.dto.ts create mode 100644 src/messages/dto/message.response.ts create mode 100644 src/messages/messages.controller.ts create mode 100644 src/messages/messages.module.ts create mode 100644 src/messages/messages.service.ts create mode 100644 src/reconcile.ts create mode 100644 src/relay.ts create mode 100644 src/replay.ts create mode 100644 src/storage/s3.service.ts create mode 100644 src/storage/storage.module.ts create mode 100644 src/users/dto/create-user.dto.ts create mode 100644 src/users/dto/user.response.ts create mode 100644 src/users/users.controller.ts create mode 100644 src/users/users.module.ts create mode 100644 src/users/users.service.ts create mode 100644 src/worker.ts create mode 100644 test/api.e2e-spec.ts create mode 100644 test/attachment-access.e2e-spec.ts create mode 100644 test/attachments.e2e-spec.ts create mode 100644 test/auth.e2e-spec.ts create mode 100644 test/concurrency.e2e-spec.ts create mode 100644 test/contract.e2e-spec.ts create mode 100644 test/docs.e2e-spec.ts create mode 100644 test/failures.e2e-spec.ts create mode 100644 test/global-setup.ts create mode 100644 test/helpers.ts create mode 100644 test/idempotency.e2e-spec.ts create mode 100644 test/images.ts create mode 100644 test/jest-e2e.json create mode 100644 test/jobs.e2e-spec.ts create mode 100644 test/reconciler.e2e-spec.ts create mode 100644 test/request-constraints.e2e-spec.ts create mode 100644 tsconfig.build.json create mode 100644 tsconfig.json diff --git a/.dockerignore b/.dockerignore index bc16e55..88b78fa 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,5 +16,9 @@ backups .venv __pycache__ node_modules +dist +coverage evidence .DS_Store +.idea +.vscode diff --git a/.env.example b/.env.example index 2b32655..67176b4 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,10 @@ WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 STAGING_RETENTION_SECONDS=86400 +JOB_LEASE_SECONDS=90 +JOB_STALE_SECONDS=300 +RECONCILE_GRACE_SECONDS=3600 +RECONCILE_INTERVAL_SECONDS=300 OTEL_SERVICE_NAME=messenger-api # Worker must set a distinct service.name. OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d0d6371 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.png binary diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..43017ac --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "useTabs": true, + "tabWidth": 4, + "singleQuote": true, + "trailingComma": "all" +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..13d717b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +# syntax=docker/dockerfile:1 + +FROM node:20.17.0-slim AS base +RUN apt-get update \ + && apt-get install -y --no-install-recommends openssl \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /app + +FROM base AS deps +COPY package.json package-lock.json ./ +RUN npm ci + +FROM deps AS build +COPY prisma ./prisma +RUN npx prisma generate +COPY tsconfig.json tsconfig.build.json nest-cli.json ./ +COPY src ./src +RUN npm run build + +FROM build AS test +COPY contracts/openapi.json ./contracts/openapi.json +COPY tests/fixtures/sample.png ./tests/fixtures/sample.png +COPY test ./test +CMD ["npm", "test"] + +FROM build AS migrate +CMD ["sh", "-c", "DATABASE_URL=\"$(cat \"$DATABASE_URL_FILE\")\" exec npx prisma migrate deploy"] + +FROM build AS prod-deps +RUN npm prune --omit=dev + +FROM base AS runtime +ENV NODE_ENV=production +COPY package.json ./ +COPY --from=prod-deps /app/node_modules ./node_modules +COPY --from=build /app/dist ./dist +COPY contracts/openapi.json ./contracts/openapi.json + +USER node +EXPOSE 8080 + +HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \ + CMD node -e "require('http').get('http://127.0.0.1:8080/health/core',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))" + +CMD ["node", "dist/main.js"] diff --git a/compose.test.yaml b/compose.test.yaml new file mode 100644 index 0000000..4f8b898 --- /dev/null +++ b/compose.test.yaml @@ -0,0 +1,55 @@ +name: messenger-lab6-test + +services: + postgres: + image: postgres:17.2-alpine + environment: + POSTGRES_USER: test + POSTGRES_PASSWORD: test + POSTGRES_DB: messenger_test + tmpfs: + - /var/lib/postgresql/data + healthcheck: + test: ["CMD", "pg_isready", "-U", "test", "-d", "messenger_test"] + interval: 2s + timeout: 3s + retries: 15 + + redis: + image: redis:7.4.1-alpine + command: ["redis-server", "--save", "", "--appendonly", "no"] + + s3: + image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 + command: ["server", "/data", "--address", ":9000"] + environment: + MINIO_ROOT_USER: test-root + MINIO_ROOT_PASSWORD: test-root-password + MINIO_BROWSER: "off" + tmpfs: + - /data + healthcheck: + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:9000/minio/health/live"] + interval: 2s + timeout: 3s + retries: 15 + + tests: + build: + context: . + target: test + image: mtusi-messenger-lab6-test:dev + environment: + DATABASE_URL: postgresql://test:test@postgres:5432/messenger_test?connection_limit=20 + CACHE_URL: redis://redis:6379/0 + S3_ENDPOINT: http://s3:9000 + S3_BUCKET: messenger-test + S3_ACCESS_KEY_ID: test-root + S3_SECRET_ACCESS_KEY: test-root-password + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_started + s3: + condition: service_healthy diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..dcce9f8 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,334 @@ +name: messenger-lab6 + +services: + secrets-init: + image: alpine:3.20.3 + volumes: + - secrets:/secrets + command: + - sh + - -ec + - | + cd /secrets + mkdir -p postgres redis api migrate s3 s3-init reconciler broker rabbitmq relay worker + for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20 broker_password:broker:24; do + file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:} + [ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file" + done + rm -f s3-init/* rabbitmq/* relay/* worker/* + cp s3/s3_root_user s3/s3_root_password api/s3_access_key_id api/s3_secret_access_key s3-init/ + db_url() { printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=%s&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=%s&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" "$$1" "$$2"; } + db_url 10 api > api/database_url + db_url 5 worker > worker/database_url + db_url 3 relay > relay/database_url + printf 'redis://:%s@redis:6379/0' "$$(cat redis/redis_password)" > api/cache_url + printf 'postgresql://messenger:%s@postgres:5432/messenger' "$$(cat postgres/pg_password)" > migrate/database_url + printf 'amqp://messenger:%s@rabbitmq:5672/' "$$(cat broker/broker_password)" > worker/broker_url + cp worker/broker_url relay/ + printf 'default_user = messenger\ndefault_pass = %s\nloopback_users = none\nlog.console = true\nlisteners.tcp.default = 5672\n' "$$(cat broker/broker_password)" > rabbitmq/10-messenger.conf + cp api/database_url api/s3_access_key_id api/s3_secret_access_key reconciler/ + cp api/s3_access_key_id api/s3_secret_access_key worker/ + chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/* broker/* rabbitmq/* relay/* worker/* + deploy: + resources: + limits: { cpus: "0.1", memory: 32M } + + postgres: + image: postgres:17.2-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/pg_password + volumes: + - pgdata:/var/lib/postgresql/data + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: postgres } } + deploy: + resources: + limits: { cpus: "1.0", memory: 512M } + healthcheck: + test: ["CMD", "pg_isready", "-U", "messenger", "-d", "messenger"] + interval: 5s + timeout: 3s + retries: 10 + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + + redis: + image: redis:7.4.1-alpine + user: redis + command: + - sh + - -c + - exec redis-server --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru --requirepass "$$(cat /run/secrets/redis_password)" + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: redis } } + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + healthcheck: + test: ["CMD-SHELL", "redis-cli --no-auth-warning -a \"$$(cat /run/secrets/redis_password)\" ping | grep -q PONG"] + interval: 5s + timeout: 3s + retries: 10 + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + + s3: + image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 + command: ["server", "/data", "--address", ":9000"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/s3_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_root_password + MINIO_BROWSER: "off" + volumes: + - s3data:/data + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: s3 } } + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + healthcheck: + test: ["CMD", "curl", "-fsS", "-o", "/dev/null", "http://127.0.0.1:9000/minio/health/live"] + interval: 5s + timeout: 3s + retries: 10 + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + + s3-init: + image: pgsty/mc:RELEASE.2026-10-26T00-00-00Z@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8 + entrypoint: ["sh", "-ec"] + command: + - | + cd /run/secrets + export MC_HOST_root="http://$$(cat s3_root_user):$$(cat s3_root_password)@s3:9000" + mc mb --ignore-existing "root/$$S3_BUCKET" + mc anonymous set none "root/$$S3_BUCKET" + cat > /tmp/policy.json < /dev/null + mc admin policy attach root messenger-api --user "$$(cat s3_access_key_id)" > /dev/null + echo "bucket $$S3_BUCKET ready" + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: s3-init } } + deploy: + resources: + limits: { cpus: "0.25", memory: 256M } + depends_on: + s3: + condition: service_healthy + + migrate: + build: + context: . + target: migrate + image: mtusi-messenger-lab6-migrate:dev + environment: + DATABASE_URL_FILE: /run/secrets/database_url + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: migrate } } + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + depends_on: + postgres: + condition: service_healthy + + api: + build: + context: . + target: runtime + image: mtusi-messenger-lab6-api:dev + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + SHUTDOWN_DELAY_MS: 3000 + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${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 + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } } + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: { cpus: "0.5", memory: 256M } + stop_grace_period: 10s + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_started + s3-init: + condition: service_completed_successfully + restart: unless-stopped + + reconciler: + build: + context: . + target: runtime + image: mtusi-messenger-lab6-api:dev + command: ["node", "dist/reconcile.js", "--apply", "--loop", "--grace-seconds=${RECONCILE_GRACE_SECONDS:-3600}", "--interval-seconds=${RECONCILE_INTERVAL_SECONDS:-300}"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${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 + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: reconciler } } + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + healthcheck: + disable: true + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + restart: unless-stopped + + rabbitmq: + image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 + hostname: rabbitmq + volumes: + - rabbitmqdata:/var/lib/rabbitmq + - { type: volume, source: secrets, target: /etc/rabbitmq/conf.d, read_only: true, volume: { subpath: rabbitmq } } + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"] + interval: 10s + timeout: 10s + retries: 12 + start_period: 20s + stop_grace_period: 30s + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + + relay: + build: + context: . + target: runtime + image: mtusi-messenger-lab6-api:dev + command: ["node", "dist/relay.js"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} + RELAY_FAULT: ${RELAY_FAULT:-} + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: relay } } + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + healthcheck: + disable: true + stop_grace_period: 10s + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + restart: unless-stopped + + worker: + build: + context: . + target: runtime + image: mtusi-messenger-lab6-api:dev + command: ["node", "dist/worker.js"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${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 + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-90} + WORKER_FAULT: ${WORKER_FAULT:-} + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: worker } } + deploy: + resources: + limits: { cpus: "1.0", memory: 768M } + healthcheck: + disable: true + stop_grace_period: 30s + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + s3-init: + condition: service_completed_successfully + restart: unless-stopped + + lb: + image: haproxy:3.0.6-alpine + ports: + - "127.0.0.1:${APP_PORT:-8080}:8080" + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + deploy: + resources: + limits: { cpus: "0.25", memory: 64M } + depends_on: + api: + condition: service_healthy + restart: unless-stopped + + tools: + profiles: [tools] + build: + dockerfile_inline: | + FROM docker:27.3.1-cli + RUN apk add --no-cache python3 make git && git config --global --add safe.directory /work + WORKDIR /work + image: mtusi-messenger-lab6-tools:dev + environment: + BASE_URL: http://lb:8080 + volumes: + - .:/work + - /var/run/docker.sock:/var/run/docker.sock + deploy: + resources: + limits: { cpus: "1.0", memory: 256M } + +volumes: + pgdata: + s3data: + rabbitmqdata: + secrets: diff --git a/contracts/extensions.openapi.json b/contracts/extensions.openapi.json new file mode 100644 index 0000000..55c0228 --- /dev/null +++ b/contracts/extensions.openapi.json @@ -0,0 +1,36 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "MTUSI Messenger — расширения лабораторной 5", + "version": "1.5.0", + "description": "Обратно совместимое дополнение к contracts/openapi.json (см. COURSE.md, раздел «Контракт и совместимость»). Обязательный контракт не меняется. Обоснование — REPORT.md, раздел «Критичные зависимости и проверка готовности»." + }, + "paths": { + "/health/core": { + "get": { + "operationId": "getCoreReadiness", + "summary": "Служебная проверка для балансировщика и Docker healthcheck: может ли реплика обслуживать API без вложений", + "description": "В отличие от /health/ready не учитывает S3. Проверяет PostgreSQL и то, что процесс не останавливается. Падение общего S3 не выводит реплики из балансировки: сообщения продолжают работать, вложения отвечают 503.", + "responses": { + "200": { + "description": "Реплика готова", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { "status": { "const": "ok" } }, + "required": ["status"], + "additionalProperties": false + } + } + } + }, + "503": { + "description": "PostgreSQL недоступен или процесс останавливается; тело в общем формате Error", + "content": { "application/json": { "schema": { "type": "object" } } } + } + } + } + } + } +} diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 0000000..22e7790 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,43 @@ +global + log stdout format raw local0 info + maxconn 2000 + +defaults + mode http + log global + option httplog + option dontlognull + timeout connect 1s + timeout client 30s + timeout server 10s + timeout http-request 10s + timeout queue 5s + timeout check 1s + retries 2 + option redispatch 1 + retry-on conn-failure + unique-id-format %[uuid()] + http-error status 502 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"bad gateway\",\"request_id\":\"%[unique-id]\"}}" + http-error status 503 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"no API replica available\",\"request_id\":\"%[unique-id]\"}}" + http-error status 504 content-type application/json hdr X-Request-Id "%[unique-id]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"gateway timeout\",\"request_id\":\"%[unique-id]\"}}" + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + hold obsolete 5s + accepted_payload_size 8192 + +frontend public + bind :8080 + default_backend api + +backend api + balance roundrobin + http-request set-timeout server 60s if { method POST } { path_reg ^/api/v1/chats/[^/]+/attachments$ } + option httpchk GET /health/core + http-check expect status 200 + default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none + server-template api 1-4 api:8080 diff --git a/nest-cli.json b/nest-cli.json new file mode 100644 index 0000000..95538fb --- /dev/null +++ b/nest-cli.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src", + "compilerOptions": { + "deleteOutDir": true + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..d306d52 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,12296 @@ +{ + "name": "mtusi-messenger-lab6", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mtusi-messenger-lab6", + "version": "1.0.0", + "license": "UNLICENSED", + "dependencies": { + "@aws-sdk/client-s3": "3.700.0", + "@fastify/static": "7.0.4", + "@nestjs/common": "^10.4.15", + "@nestjs/core": "^10.4.15", + "@nestjs/platform-fastify": "^10.4.15", + "@nestjs/swagger": "7.4.2", + "@prisma/client": "6.1.0", + "amqplib": "0.10.5", + "argon2": "0.41.1", + "class-transformer": "^0.5.1", + "class-validator": "^0.14.1", + "ioredis": "5.4.1", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "sharp": "0.33.5" + }, + "devDependencies": { + "@nestjs/cli": "^10.4.9", + "@nestjs/schematics": "^10.2.3", + "@nestjs/testing": "^10.4.15", + "@types/amqplib": "0.10.6", + "@types/jest": "^29.5.14", + "@types/node": "^20.17.9", + "@types/supertest": "^6.0.2", + "@typescript-eslint/eslint-plugin": "^8.18.1", + "@typescript-eslint/parser": "^8.18.1", + "ajv": "8.12.0", + "eslint": "^8.57.1", + "jest": "^29.7.0", + "prisma": "6.1.0", + "source-map-support": "^0.5.21", + "supertest": "^7.0.0", + "ts-jest": "^29.2.5", + "ts-loader": "^9.5.1", + "ts-node": "^10.9.2", + "tsconfig-paths": "^4.2.0", + "typescript": "^5.7.2" + } + }, + "node_modules/@acuminous/bitsyntax": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@acuminous/bitsyntax/-/bitsyntax-0.1.2.tgz", + "integrity": "sha512-29lUK80d1muEQqiUsSo+3A0yP6CdspgC95EnKBMi22Xlwt79i/En4Vr67+cXhU+cZjbti3TgGGC5wy1stIywVQ==", + "license": "MIT", + "dependencies": { + "buffer-more-ints": "~1.0.0", + "debug": "^4.3.4", + "safe-buffer": "~5.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/@acuminous/bitsyntax/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/@angular-devkit/core": { + "version": "17.3.11", + "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-17.3.11.tgz", + "integrity": "sha512-vTNDYNsLIWpYk2I969LMQFH29GTsLzxNk/0cLw5q56ARF0v5sIWfHYwGTS88jdDqIpuuettcSczbxeA7EuAmqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "8.12.0", + "ajv-formats": "2.1.1", + "jsonc-parser": "3.2.1", + "picomatch": "4.0.1", + "rxjs": "7.8.1", + "source-map": "0.7.4" + }, + "engines": { + "node": "^18.13.0 || >=20.9.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + }, + "peerDependencies": { + "chokidar": "^3.5.2" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, + "node_modules/@angular-devkit/core/node_modules/rxjs": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", + "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@angular-devkit/schematics": { + "version": "17.3.11", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-17.3.11.tgz", + "integrity": "sha512-I5wviiIqiFwar9Pdk30Lujk8FczEEc18i22A5c6Z9lbmhPQdTroDnEQdsfXjy404wPe8H62s0I15o4pmMGfTYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "17.3.11", + "jsonc-parser": "3.2.1", + "magic-string": "0.30.8", + "ora": "5.4.1", + "rxjs": "7.8.1" + }, + "engines": { + "node": "^18.13.0 || >=20.9.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular-devkit/schematics-cli": { + "version": "17.3.11", + "resolved": "https://registry.npmjs.org/@angular-devkit/schematics-cli/-/schematics-cli-17.3.11.tgz", + "integrity": "sha512-kcOMqp+PHAKkqRad7Zd7PbpqJ0LqLaNZdY1+k66lLWmkEBozgq8v4ASn/puPWf9Bo0HpCiK+EzLf0VHE8Z/y6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "17.3.11", + "@angular-devkit/schematics": "17.3.11", + "ansi-colors": "4.1.3", + "inquirer": "9.2.15", + "symbol-observable": "4.0.0", + "yargs-parser": "21.1.1" + }, + "bin": { + "schematics": "bin/schematics.js" + }, + "engines": { + "node": "^18.13.0 || >=20.9.0", + "npm": "^6.11.0 || ^7.5.6 || >=8.0.0", + "yarn": ">= 1.13.0" + } + }, + "node_modules/@angular-devkit/schematics-cli/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/@angular-devkit/schematics-cli/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/@angular-devkit/schematics-cli/node_modules/inquirer": { + "version": "9.2.15", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-9.2.15.tgz", + "integrity": "sha512-vI2w4zl/mDluHt9YEQ/543VTCwPKWiHzKtm9dM2V0NdFcqEexDAjUHzO1oA60HRNaVifGXXM1tRRNluLVHa0Kg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ljharb/through": "^2.3.12", + "ansi-escapes": "^4.3.2", + "chalk": "^5.3.0", + "cli-cursor": "^3.1.0", + "cli-width": "^4.1.0", + "external-editor": "^3.1.0", + "figures": "^3.2.0", + "lodash": "^4.17.21", + "mute-stream": "1.0.0", + "ora": "^5.4.1", + "run-async": "^3.0.0", + "rxjs": "^7.8.1", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^6.2.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@angular-devkit/schematics-cli/node_modules/mute-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-1.0.0.tgz", + "integrity": "sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@angular-devkit/schematics-cli/node_modules/run-async": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-3.0.0.tgz", + "integrity": "sha512-540WwVDOMxA6dN6We19EcT9sc3hkXPw5mzRNGM3FkdN/vtE9NFvj5lFAPNwUDmJjXidm3v7TC1cTE7t17Ulm1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/@angular-devkit/schematics/node_modules/rxjs": { + "version": "7.8.1", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", + "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@aws-crypto/crc32": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", + "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/crc32c": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32c/-/crc32c-5.2.0.tgz", + "integrity": "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha1-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha1-browser/-/sha1-browser-5.2.0.tgz", + "integrity": "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/client-s3": { + "version": "3.700.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.700.0.tgz", + "integrity": "sha512-TZTc8OZ873VodJNcsQ4Y/60f0Y0Ws5Z3Xm5QBgPCvhqQS7/+V28pXM3fAomJsKDWTxzH0nP9csX5cPvLybgdZQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha1-browser": "5.2.0", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.699.0", + "@aws-sdk/client-sts": "3.699.0", + "@aws-sdk/core": "3.696.0", + "@aws-sdk/credential-provider-node": "3.699.0", + "@aws-sdk/middleware-bucket-endpoint": "3.696.0", + "@aws-sdk/middleware-expect-continue": "3.696.0", + "@aws-sdk/middleware-flexible-checksums": "3.697.0", + "@aws-sdk/middleware-host-header": "3.696.0", + "@aws-sdk/middleware-location-constraint": "3.696.0", + "@aws-sdk/middleware-logger": "3.696.0", + "@aws-sdk/middleware-recursion-detection": "3.696.0", + "@aws-sdk/middleware-sdk-s3": "3.696.0", + "@aws-sdk/middleware-ssec": "3.696.0", + "@aws-sdk/middleware-user-agent": "3.696.0", + "@aws-sdk/region-config-resolver": "3.696.0", + "@aws-sdk/signature-v4-multi-region": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-endpoints": "3.696.0", + "@aws-sdk/util-user-agent-browser": "3.696.0", + "@aws-sdk/util-user-agent-node": "3.696.0", + "@aws-sdk/xml-builder": "3.696.0", + "@smithy/config-resolver": "^3.0.12", + "@smithy/core": "^2.5.3", + "@smithy/eventstream-serde-browser": "^3.0.13", + "@smithy/eventstream-serde-config-resolver": "^3.0.10", + "@smithy/eventstream-serde-node": "^3.0.12", + "@smithy/fetch-http-handler": "^4.1.1", + "@smithy/hash-blob-browser": "^3.1.9", + "@smithy/hash-node": "^3.0.10", + "@smithy/hash-stream-node": "^3.1.9", + "@smithy/invalid-dependency": "^3.0.10", + "@smithy/md5-js": "^3.0.10", + "@smithy/middleware-content-length": "^3.0.12", + "@smithy/middleware-endpoint": "^3.2.3", + "@smithy/middleware-retry": "^3.0.27", + "@smithy/middleware-serde": "^3.0.10", + "@smithy/middleware-stack": "^3.0.10", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/node-http-handler": "^3.3.1", + "@smithy/protocol-http": "^4.1.7", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/url-parser": "^3.0.10", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.27", + "@smithy/util-defaults-mode-node": "^3.0.27", + "@smithy/util-endpoints": "^2.1.6", + "@smithy/util-middleware": "^3.0.10", + "@smithy/util-retry": "^3.0.10", + "@smithy/util-stream": "^3.3.1", + "@smithy/util-utf8": "^3.0.0", + "@smithy/util-waiter": "^3.1.9", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.696.0.tgz", + "integrity": "sha512-q5TTkd08JS0DOkHfUL853tuArf7NrPeqoS5UOvqJho8ibV9Ak/a/HO4kNvy9Nj3cib/toHYHsQIEtecUPSUUrQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.696.0", + "@aws-sdk/middleware-host-header": "3.696.0", + "@aws-sdk/middleware-logger": "3.696.0", + "@aws-sdk/middleware-recursion-detection": "3.696.0", + "@aws-sdk/middleware-user-agent": "3.696.0", + "@aws-sdk/region-config-resolver": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-endpoints": "3.696.0", + "@aws-sdk/util-user-agent-browser": "3.696.0", + "@aws-sdk/util-user-agent-node": "3.696.0", + "@smithy/config-resolver": "^3.0.12", + "@smithy/core": "^2.5.3", + "@smithy/fetch-http-handler": "^4.1.1", + "@smithy/hash-node": "^3.0.10", + "@smithy/invalid-dependency": "^3.0.10", + "@smithy/middleware-content-length": "^3.0.12", + "@smithy/middleware-endpoint": "^3.2.3", + "@smithy/middleware-retry": "^3.0.27", + "@smithy/middleware-serde": "^3.0.10", + "@smithy/middleware-stack": "^3.0.10", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/node-http-handler": "^3.3.1", + "@smithy/protocol-http": "^4.1.7", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/url-parser": "^3.0.10", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.27", + "@smithy/util-defaults-mode-node": "^3.0.27", + "@smithy/util-endpoints": "^2.1.6", + "@smithy/util-middleware": "^3.0.10", + "@smithy/util-retry": "^3.0.10", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/client-sso-oidc": { + "version": "3.699.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso-oidc/-/client-sso-oidc-3.699.0.tgz", + "integrity": "sha512-u8a1GorY5D1l+4FQAf4XBUC1T10/t7neuwT21r0ymrtMFSK2a9QqVHKMoLkvavAwyhJnARSBM9/UQC797PFOFw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.696.0", + "@aws-sdk/credential-provider-node": "3.699.0", + "@aws-sdk/middleware-host-header": "3.696.0", + "@aws-sdk/middleware-logger": "3.696.0", + "@aws-sdk/middleware-recursion-detection": "3.696.0", + "@aws-sdk/middleware-user-agent": "3.696.0", + "@aws-sdk/region-config-resolver": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-endpoints": "3.696.0", + "@aws-sdk/util-user-agent-browser": "3.696.0", + "@aws-sdk/util-user-agent-node": "3.696.0", + "@smithy/config-resolver": "^3.0.12", + "@smithy/core": "^2.5.3", + "@smithy/fetch-http-handler": "^4.1.1", + "@smithy/hash-node": "^3.0.10", + "@smithy/invalid-dependency": "^3.0.10", + "@smithy/middleware-content-length": "^3.0.12", + "@smithy/middleware-endpoint": "^3.2.3", + "@smithy/middleware-retry": "^3.0.27", + "@smithy/middleware-serde": "^3.0.10", + "@smithy/middleware-stack": "^3.0.10", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/node-http-handler": "^3.3.1", + "@smithy/protocol-http": "^4.1.7", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/url-parser": "^3.0.10", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.27", + "@smithy/util-defaults-mode-node": "^3.0.27", + "@smithy/util-endpoints": "^2.1.6", + "@smithy/util-middleware": "^3.0.10", + "@smithy/util-retry": "^3.0.10", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sts": "^3.699.0" + } + }, + "node_modules/@aws-sdk/client-sts": { + "version": "3.699.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.699.0.tgz", + "integrity": "sha512-++lsn4x2YXsZPIzFVwv3fSUVM55ZT0WRFmPeNilYIhZClxHLmVAWKH4I55cY9ry60/aTKYjzOXkWwyBKGsGvQg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/client-sso-oidc": "3.699.0", + "@aws-sdk/core": "3.696.0", + "@aws-sdk/credential-provider-node": "3.699.0", + "@aws-sdk/middleware-host-header": "3.696.0", + "@aws-sdk/middleware-logger": "3.696.0", + "@aws-sdk/middleware-recursion-detection": "3.696.0", + "@aws-sdk/middleware-user-agent": "3.696.0", + "@aws-sdk/region-config-resolver": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-endpoints": "3.696.0", + "@aws-sdk/util-user-agent-browser": "3.696.0", + "@aws-sdk/util-user-agent-node": "3.696.0", + "@smithy/config-resolver": "^3.0.12", + "@smithy/core": "^2.5.3", + "@smithy/fetch-http-handler": "^4.1.1", + "@smithy/hash-node": "^3.0.10", + "@smithy/invalid-dependency": "^3.0.10", + "@smithy/middleware-content-length": "^3.0.12", + "@smithy/middleware-endpoint": "^3.2.3", + "@smithy/middleware-retry": "^3.0.27", + "@smithy/middleware-serde": "^3.0.10", + "@smithy/middleware-stack": "^3.0.10", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/node-http-handler": "^3.3.1", + "@smithy/protocol-http": "^4.1.7", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/url-parser": "^3.0.10", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-body-length-node": "^3.0.0", + "@smithy/util-defaults-mode-browser": "^3.0.27", + "@smithy/util-defaults-mode-node": "^3.0.27", + "@smithy/util-endpoints": "^2.1.6", + "@smithy/util-middleware": "^3.0.10", + "@smithy/util-retry": "^3.0.10", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.696.0.tgz", + "integrity": "sha512-3c9III1k03DgvRZWg8vhVmfIXPG6hAciN9MzQTzqGngzWAELZF/WONRTRQuDFixVtarQatmLHYVw/atGeA2Byw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/core": "^2.5.3", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/property-provider": "^3.1.9", + "@smithy/protocol-http": "^4.1.7", + "@smithy/signature-v4": "^4.2.2", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/util-middleware": "^3.0.10", + "fast-xml-parser": "4.4.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.696.0.tgz", + "integrity": "sha512-T9iMFnJL7YTlESLpVFT3fg1Lkb1lD+oiaIC8KMpepb01gDUBIpj9+Y+pA/cgRWW0yRxmkDXNazAE2qQTVFGJzA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/property-provider": "^3.1.9", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.696.0.tgz", + "integrity": "sha512-GV6EbvPi2eq1+WgY/o2RFA3P7HGmnkIzCNmhwtALFlqMroLYWKE7PSeHw66Uh1dFQeVESn0/+hiUNhu1mB0emA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/fetch-http-handler": "^4.1.1", + "@smithy/node-http-handler": "^3.3.1", + "@smithy/property-provider": "^3.1.9", + "@smithy/protocol-http": "^4.1.7", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/util-stream": "^3.3.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.699.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.699.0.tgz", + "integrity": "sha512-dXmCqjJnKmG37Q+nLjPVu22mNkrGHY8hYoOt3Jo9R2zr5MYV7s/NHsCHr+7E+BZ+tfZYLRPeB1wkpTeHiEcdRw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/credential-provider-env": "3.696.0", + "@aws-sdk/credential-provider-http": "3.696.0", + "@aws-sdk/credential-provider-process": "3.696.0", + "@aws-sdk/credential-provider-sso": "3.699.0", + "@aws-sdk/credential-provider-web-identity": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/credential-provider-imds": "^3.2.6", + "@smithy/property-provider": "^3.1.9", + "@smithy/shared-ini-file-loader": "^3.1.10", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sts": "^3.699.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.699.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.699.0.tgz", + "integrity": "sha512-MmEmNDo1bBtTgRmdNfdQksXu4uXe66s0p1hi1YPrn1h59Q605eq/xiWbGL6/3KdkViH6eGUuABeV2ODld86ylg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.696.0", + "@aws-sdk/credential-provider-http": "3.696.0", + "@aws-sdk/credential-provider-ini": "3.699.0", + "@aws-sdk/credential-provider-process": "3.696.0", + "@aws-sdk/credential-provider-sso": "3.699.0", + "@aws-sdk/credential-provider-web-identity": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/credential-provider-imds": "^3.2.6", + "@smithy/property-provider": "^3.1.9", + "@smithy/shared-ini-file-loader": "^3.1.10", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.696.0.tgz", + "integrity": "sha512-mL1RcFDe9sfmyU5K1nuFkO8UiJXXxLX4JO1gVaDIOvPqwStpUAwi3A1BoeZhWZZNQsiKI810RnYGo0E0WB/hUA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/property-provider": "^3.1.9", + "@smithy/shared-ini-file-loader": "^3.1.10", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.699.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.699.0.tgz", + "integrity": "sha512-Ekp2cZG4pl9D8+uKWm4qO1xcm8/MeiI8f+dnlZm8aQzizeC+aXYy9GyoclSf6daK8KfRPiRfM7ZHBBL5dAfdMA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.696.0", + "@aws-sdk/core": "3.696.0", + "@aws-sdk/token-providers": "3.699.0", + "@aws-sdk/types": "3.696.0", + "@smithy/property-provider": "^3.1.9", + "@smithy/shared-ini-file-loader": "^3.1.10", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.696.0.tgz", + "integrity": "sha512-XJ/CVlWChM0VCoc259vWguFUjJDn/QwDqHwbx+K9cg3v6yrqXfK5ai+p/6lx0nQpnk4JzPVeYYxWRpaTsGC9rg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/property-provider": "^3.1.9", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sts": "^3.696.0" + } + }, + "node_modules/@aws-sdk/middleware-bucket-endpoint": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.696.0.tgz", + "integrity": "sha512-V07jishKHUS5heRNGFpCWCSTjRJyQLynS/ncUeE8ZYtG66StOOQWftTwDfFOSoXlIqrXgb4oT9atryzXq7Z4LQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-arn-parser": "3.693.0", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/protocol-http": "^4.1.7", + "@smithy/types": "^3.7.1", + "@smithy/util-config-provider": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-expect-continue": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.696.0.tgz", + "integrity": "sha512-vpVukqY3U2pb+ULeX0shs6L0aadNep6kKzjme/MyulPjtUDJpD3AekHsXRrCCGLmOqSKqRgQn5zhV9pQhHsb6Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/protocol-http": "^4.1.7", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-flexible-checksums": { + "version": "3.697.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.697.0.tgz", + "integrity": "sha512-K/y43P+NuHu5+21/29BoJSltcPekvcCU8i74KlGGHbW2Z105e5QVZlFjxivcPOjOA3gdC0W4SoFSIWam5RBhzw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@aws-crypto/crc32c": "5.2.0", + "@aws-crypto/util": "5.2.0", + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/is-array-buffer": "^3.0.0", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/protocol-http": "^4.1.7", + "@smithy/types": "^3.7.1", + "@smithy/util-middleware": "^3.0.10", + "@smithy/util-stream": "^3.3.1", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.696.0.tgz", + "integrity": "sha512-zELJp9Ta2zkX7ELggMN9qMCgekqZhFC5V2rOr4hJDEb/Tte7gpfKSObAnw/3AYiVqt36sjHKfdkoTsuwGdEoDg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/protocol-http": "^4.1.7", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-location-constraint": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.696.0.tgz", + "integrity": "sha512-FgH12OB0q+DtTrP2aiDBddDKwL4BPOrm7w3VV9BJrSdkqQCNBPz8S1lb0y5eVH4tBG+2j7gKPlOv1wde4jF/iw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-logger": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.696.0.tgz", + "integrity": "sha512-KhkHt+8AjCxcR/5Zp3++YPJPpFQzxpr+jmONiT/Jw2yqnSngZ0Yspm5wGoRx2hS1HJbyZNuaOWEGuJoxLeBKfA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.696.0.tgz", + "integrity": "sha512-si/maV3Z0hH7qa99f9ru2xpS5HlfSVcasRlNUXKSDm611i7jFMWwGNLUOXFAOLhXotPX5G3Z6BLwL34oDeBMug==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/protocol-http": "^4.1.7", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.696.0.tgz", + "integrity": "sha512-M7fEiAiN7DBMHflzOFzh1I2MNSlLpbiH2ubs87bdRc2wZsDPSbs4l3v6h3WLhxoQK0bq6vcfroudrLBgvCuX3Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-arn-parser": "3.693.0", + "@smithy/core": "^2.5.3", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/protocol-http": "^4.1.7", + "@smithy/signature-v4": "^4.2.2", + "@smithy/smithy-client": "^3.4.4", + "@smithy/types": "^3.7.1", + "@smithy/util-config-provider": "^3.0.0", + "@smithy/util-middleware": "^3.0.10", + "@smithy/util-stream": "^3.3.1", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-ssec": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.696.0.tgz", + "integrity": "sha512-w/d6O7AOZ7Pg3w2d3BxnX5RmGNWb5X4RNxF19rJqcgu/xqxxE/QwZTNd5a7eTsqLXAUIfbbR8hh0czVfC1pJLA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.696.0.tgz", + "integrity": "sha512-Lvyj8CTyxrHI6GHd2YVZKIRI5Fmnugt3cpJo0VrKKEgK5zMySwEZ1n4dqPK6czYRWKd5+WnYHYAuU+Wdk6Jsjw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@aws-sdk/util-endpoints": "3.696.0", + "@smithy/core": "^2.5.3", + "@smithy/protocol-http": "^4.1.7", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/region-config-resolver": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.696.0.tgz", + "integrity": "sha512-7EuH142lBXjI8yH6dVS/CZeiK/WZsmb/8zP6bQbVYpMrppSTgB3MzZZdxVZGzL5r8zPQOU10wLC4kIMy0qdBVQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/types": "^3.7.1", + "@smithy/util-config-provider": "^3.0.0", + "@smithy/util-middleware": "^3.0.10", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.696.0.tgz", + "integrity": "sha512-ijPkoLjXuPtgxAYlDoYls8UaG/VKigROn9ebbvPL/orEY5umedd3iZTcS9T+uAf4Ur3GELLxMQiERZpfDKaz3g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-sdk-s3": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/protocol-http": "^4.1.7", + "@smithy/signature-v4": "^4.2.2", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.699.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.699.0.tgz", + "integrity": "sha512-kuiEW9DWs7fNos/SM+y58HCPhcIzm1nEZLhe2/7/6+TvAYLuEWURYsbK48gzsxXlaJ2k/jGY3nIsA7RptbMOwA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/property-provider": "^3.1.9", + "@smithy/shared-ini-file-loader": "^3.1.10", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "@aws-sdk/client-sso-oidc": "^3.699.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.696.0.tgz", + "integrity": "sha512-9rTvUJIAj5d3//U5FDPWGJ1nFJLuWb30vugGOrWk7aNZ6y9tuA3PI7Cc9dP8WEXKVyK1vuuk8rSFP2iqXnlgrw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/util-arn-parser": { + "version": "3.693.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-arn-parser/-/util-arn-parser-3.693.0.tgz", + "integrity": "sha512-WC8x6ca+NRrtpAH64rWu+ryDZI3HuLwlEr8EU6/dbC/pt+r/zC0PBoC15VEygUaBA+isppCikQpGyEDu0Yj7gQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/util-endpoints": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.696.0.tgz", + "integrity": "sha512-T5s0IlBVX+gkb9g/I6CLt4yAZVzMSiGnbUqWihWsHvQR1WOoIcndQy/Oz/IJXT9T2ipoy7a80gzV6a5mglrioA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/types": "^3.7.1", + "@smithy/util-endpoints": "^2.1.6", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.965.10", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.10.tgz", + "integrity": "sha512-ycwH6Zd2GhuSqdXX9ihbCjeGTB6xOJs+O3+Jb8/zDG9978XU80qs75dfkPJRMNKe5MvBZPuNeFpd4JZKPoUF4g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.696.0.tgz", + "integrity": "sha512-Z5rVNDdmPOe6ELoM5AhF/ja5tSjbe6ctSctDPb0JdDf4dT0v2MfwhJKzXju2RzX8Es/77Glh7MlaXLE0kCB9+Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.696.0", + "@smithy/types": "^3.7.1", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.696.0.tgz", + "integrity": "sha512-KhKqcfyXIB0SCCt+qsu4eJjsfiOrNzK5dCV7RAW2YIpp+msxGUUX0NdRE9rkzjiv+3EMktgJm3eEIS+yxtlVdQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.696.0", + "@aws-sdk/types": "3.696.0", + "@smithy/node-config-provider": "^3.1.11", + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.696.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.696.0.tgz", + "integrity": "sha512-dn1mX+EeqivoLYnY7p2qLrir0waPnCgS/0YdRCAVU2x14FgfUYCH6Im3w3oi2dMwhxfKY5lYVB5NKvZu7uI9lQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.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/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.29.7.tgz", + "integrity": "sha512-zGYcYfq/WmZ4V+kBIXQon9dSSc8ircGZqw9ZaNhhGj9nZkeBu1jHLBDQqYYi5WA9uawvA2sIMbry2nCFhf5Djg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", + "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", + "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.8", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.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": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", + "dev": true, + "license": "MIT" + }, + "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/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "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/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^9.6.0", + "globals": "^13.19.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@eslint/eslintrc/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", + "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/@fastify/accept-negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@fastify/accept-negotiator/-/accept-negotiator-1.1.0.tgz", + "integrity": "sha512-OIHZrb2ImZ7XG85HXOONLcJWGosv7sIvM2ifAPQVhg9Lv7qdmMBNVaai4QTdyuaqbKM5eO6sLSQOYI7wEQeCJQ==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@fastify/ajv-compiler": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-3.6.0.tgz", + "integrity": "sha512-LwdXQJjmMD+GwLOkP7TVC68qa+pSSogeWWmznRJ/coyTcfe9qA05AHFSe1eZFwK6q+xVRpChnvFUkf1iYaSZsQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.11.0", + "ajv-formats": "^2.1.1", + "fast-uri": "^2.0.0" + } + }, + "node_modules/@fastify/cors": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-9.0.1.tgz", + "integrity": "sha512-YY9Ho3ovI+QHIL2hW+9X4XqQjXLjJqsU+sMV/xFsxZkE8p3GNnYVFpoOxF7SsP5ZL76gwvbo3V9L+FIekBGU4Q==", + "license": "MIT", + "dependencies": { + "fastify-plugin": "^4.0.0", + "mnemonist": "0.39.6" + } + }, + "node_modules/@fastify/error": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/@fastify/error/-/error-3.4.1.tgz", + "integrity": "sha512-wWSvph+29GR783IhmvdwWnN4bUxTD01Vm5Xad4i7i1VuAOItLvbPAb69sb0IQ2N57yprvhNIwAP5B6xfKTmjmQ==", + "license": "MIT" + }, + "node_modules/@fastify/fast-json-stringify-compiler": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-4.3.0.tgz", + "integrity": "sha512-aZAXGYo6m22Fk1zZzEUKBvut/CIIQe/BapEORnxiD5Qr0kPHqqI69NtEMCme74h+at72sPhbkb4ZrLd1W3KRLA==", + "license": "MIT", + "dependencies": { + "fast-json-stringify": "^5.7.0" + } + }, + "node_modules/@fastify/formbody": { + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/@fastify/formbody/-/formbody-7.4.0.tgz", + "integrity": "sha512-H3C6h1GN56/SMrZS8N2vCT2cZr7mIHzBHzOBa5OPpjfB/D6FzP9mMpE02ZzrFX0ANeh0BAJdoXKOF2e7IbV+Og==", + "license": "MIT", + "dependencies": { + "fast-querystring": "^1.0.0", + "fastify-plugin": "^4.0.0" + } + }, + "node_modules/@fastify/merge-json-schemas": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.1.1.tgz", + "integrity": "sha512-fERDVz7topgNjtXsJTTW1JKLy0rhuLRcquYqNR9rF7OcVpCa2OVW49ZPDIhaRRCaUuvVxI+N416xUoF76HNSXA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3" + } + }, + "node_modules/@fastify/middie": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/@fastify/middie/-/middie-8.3.3.tgz", + "integrity": "sha512-+WHavMQr9CNTZoy2cjoDxoWp76kZ3JKjAtZj5sXNlxX5XBzHig0TeCPfPc+1+NQmliXtndT3PFwAjrQHE/6wnQ==", + "license": "MIT", + "dependencies": { + "@fastify/error": "^3.2.0", + "fastify-plugin": "^4.0.0", + "path-to-regexp": "^6.3.0", + "reusify": "^1.0.4" + } + }, + "node_modules/@fastify/middie/node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "license": "MIT" + }, + "node_modules/@fastify/send": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@fastify/send/-/send-2.1.0.tgz", + "integrity": "sha512-yNYiY6sDkexoJR0D8IDy3aRP3+L4wdqCpvx5WP+VtEU58sn7USmKynBzDQex5X42Zzvw2gNzzYgP90UfWShLFA==", + "license": "MIT", + "dependencies": { + "@lukeed/ms": "^2.0.1", + "escape-html": "~1.0.3", + "fast-decode-uri-component": "^1.0.1", + "http-errors": "2.0.0", + "mime": "^3.0.0" + } + }, + "node_modules/@fastify/send/node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@fastify/static": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/@fastify/static/-/static-7.0.4.tgz", + "integrity": "sha512-p2uKtaf8BMOZWLs6wu+Ihg7bWNBdjNgCwDza4MJtTqg+5ovKmcbgbR9Xs5/smZ1YISfzKOCNYmZV8LaCj+eJ1Q==", + "license": "MIT", + "dependencies": { + "@fastify/accept-negotiator": "^1.0.0", + "@fastify/send": "^2.0.0", + "content-disposition": "^0.5.3", + "fastify-plugin": "^4.0.0", + "fastq": "^1.17.0", + "glob": "^10.3.4" + } + }, + "node_modules/@humanwhocodes/config-array": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", + "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", + "deprecated": "Use @eslint/config-array instead", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanwhocodes/object-schema": "^2.0.3", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + }, + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@humanwhocodes/config-array/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/object-schema": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", + "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", + "deprecated": "Use @eslint/object-schema instead", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "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.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "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.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "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.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "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.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "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.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "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.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "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.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "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.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.2.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@ioredis/commands": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.11.0.tgz", + "integrity": "sha512-tuMmOu6dtyGFv/fzCjtapCJj/zgoHaFsqs3wKsroJSRXtlLmyL/t+B7uaQiavGk1F3WWFQcUqZwk92bpp9jKcA==", + "license": "MIT" + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/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==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/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==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", + "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", + "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/core": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", + "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/reporters": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.7.0", + "jest-config": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-resolve-dependencies": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "jest-watcher": "^29.7.0", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/environment": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", + "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.7.0", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", + "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", + "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "*", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", + "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/types": "^29.6.3", + "jest-mock": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", + "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/reporters/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jest/reporters/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@jest/reporters/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@jest/reporters/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", + "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.18", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", + "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", + "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", + "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.6.3", + "@jridgewell/trace-mapping": "^0.3.18", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "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/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "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/@ljharb/through": { + "version": "2.3.14", + "resolved": "https://registry.npmjs.org/@ljharb/through/-/through-2.3.14.tgz", + "integrity": "sha512-ajBvlKpWucBB17FuQYUShqpqy8GRgYEpJW0vWJbUu1CV9lWyrDCapy0lScU8T8Z6qn49sSwJB3+M+evYIdGg+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8" + }, + "engines": { + "node": ">= 0.4" + } + }, + "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/@lukeed/ms": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz", + "integrity": "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@microsoft/tsdoc": { + "version": "0.15.1", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.15.1.tgz", + "integrity": "sha512-4aErSrCR/On/e5G2hDP0wjooqDdauzEbIq8hIkIe5pXV0rtWJZvdCEKL0ykZxex+IxIwBp0eGeV48hQN07dXtw==", + "license": "MIT" + }, + "node_modules/@nestjs/cli": { + "version": "10.4.9", + "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-10.4.9.tgz", + "integrity": "sha512-s8qYd97bggqeK7Op3iD49X2MpFtW4LVNLAwXFkfbRxKME6IYT7X0muNTJ2+QfI8hpbNx9isWkrLWIp+g5FOhiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "17.3.11", + "@angular-devkit/schematics": "17.3.11", + "@angular-devkit/schematics-cli": "17.3.11", + "@nestjs/schematics": "^10.0.1", + "chalk": "4.1.2", + "chokidar": "3.6.0", + "cli-table3": "0.6.5", + "commander": "4.1.1", + "fork-ts-checker-webpack-plugin": "9.0.2", + "glob": "10.4.5", + "inquirer": "8.2.6", + "node-emoji": "1.11.0", + "ora": "5.4.1", + "tree-kill": "1.2.2", + "tsconfig-paths": "4.2.0", + "tsconfig-paths-webpack-plugin": "4.2.0", + "typescript": "5.7.2", + "webpack": "5.97.1", + "webpack-node-externals": "3.0.0" + }, + "bin": { + "nest": "bin/nest.js" + }, + "engines": { + "node": ">= 16.14" + }, + "peerDependencies": { + "@swc/cli": "^0.1.62 || ^0.3.0 || ^0.4.0 || ^0.5.0", + "@swc/core": "^1.3.62" + }, + "peerDependenciesMeta": { + "@swc/cli": { + "optional": true + }, + "@swc/core": { + "optional": true + } + } + }, + "node_modules/@nestjs/cli/node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@nestjs/cli/node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@nestjs/cli/node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/@nestjs/cli/node_modules/typescript": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz", + "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/@nestjs/cli/node_modules/webpack": { + "version": "5.97.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.97.1.tgz", + "integrity": "sha512-EksG6gFY3L1eFMROS/7Wzgrii5mBAFe4rIr3r2BTfo7bcc+DWwFZ4OJ/miOuHJO/A85HwyI4eQ0F6IKXesO7Fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/eslint-scope": "^3.7.7", + "@types/estree": "^1.0.6", + "@webassemblyjs/ast": "^1.14.1", + "@webassemblyjs/wasm-edit": "^1.14.1", + "@webassemblyjs/wasm-parser": "^1.14.1", + "acorn": "^8.14.0", + "browserslist": "^4.24.0", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.17.1", + "es-module-lexer": "^1.2.1", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.11", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.2.0", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^3.2.0", + "tapable": "^2.1.1", + "terser-webpack-plugin": "^5.3.10", + "watchpack": "^2.4.1", + "webpack-sources": "^3.2.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/@nestjs/common": { + "version": "10.4.22", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-10.4.22.tgz", + "integrity": "sha512-fxJ4v85nDHaqT1PmfNCQ37b/jcv2OojtXTaK1P2uAXhzLf9qq6WNUOFvxBrV4fhQek1EQoT1o9oj5xAZmv3NRw==", + "license": "MIT", + "dependencies": { + "file-type": "20.4.1", + "iterare": "1.2.1", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "class-transformer": "*", + "class-validator": "*", + "reflect-metadata": "^0.1.12 || ^0.2.0", + "rxjs": "^7.1.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/core": { + "version": "10.4.22", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-10.4.22.tgz", + "integrity": "sha512-6IX9+VwjiKtCjx+mXVPncpkQ5ZjKfmssOZPFexmT+6T9H9wZ3svpYACAo7+9e7Nr9DZSoRZw3pffkJP7Z0UjaA==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@nuxtjs/opencollective": "0.3.2", + "fast-safe-stringify": "2.1.1", + "iterare": "1.2.1", + "path-to-regexp": "3.3.0", + "tslib": "2.8.1", + "uid": "2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^10.0.0", + "@nestjs/microservices": "^10.0.0", + "@nestjs/platform-express": "^10.0.0", + "@nestjs/websockets": "^10.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/mapped-types": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-2.0.5.tgz", + "integrity": "sha512-bSJv4pd6EY99NX9CjBIyn4TVDoSit82DUZlL4I3bqNfy5Gt+gXTa86i3I/i0iIV9P4hntcGM5GyO+FhZAhxtyg==", + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0", + "class-transformer": "^0.4.0 || ^0.5.0", + "class-validator": "^0.13.0 || ^0.14.0", + "reflect-metadata": "^0.1.12 || ^0.2.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/platform-fastify": { + "version": "10.4.22", + "resolved": "https://registry.npmjs.org/@nestjs/platform-fastify/-/platform-fastify-10.4.22.tgz", + "integrity": "sha512-Y/8wX43806NIAAIx7nWY3A7kSiZc5ivPfIl4RIgo4goxuwVOjAwgytBtPhgtyP/O1nrighbMXtgHh2e/kWnHGA==", + "license": "MIT", + "dependencies": { + "@fastify/cors": "9.0.1", + "@fastify/formbody": "7.4.0", + "@fastify/middie": "8.3.3", + "fastify": "4.28.1", + "light-my-request": "6.3.0", + "path-to-regexp": "3.3.0", + "tslib": "2.8.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@fastify/static": "^6.0.0 || ^7.0.0", + "@fastify/view": "^7.0.0 || ^8.0.0", + "@nestjs/common": "^10.0.0", + "@nestjs/core": "^10.0.0" + }, + "peerDependenciesMeta": { + "@fastify/static": { + "optional": true + }, + "@fastify/view": { + "optional": true + } + } + }, + "node_modules/@nestjs/schematics": { + "version": "10.2.3", + "resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-10.2.3.tgz", + "integrity": "sha512-4e8gxaCk7DhBxVUly2PjYL4xC2ifDFexCqq1/u4TtivLGXotVk0wHdYuPYe1tHTHuR1lsOkRbfOCpkdTnigLVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@angular-devkit/core": "17.3.11", + "@angular-devkit/schematics": "17.3.11", + "comment-json": "4.2.5", + "jsonc-parser": "3.3.1", + "pluralize": "8.0.0" + }, + "peerDependencies": { + "typescript": ">=4.8.2" + } + }, + "node_modules/@nestjs/schematics/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/@nestjs/swagger": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/@nestjs/swagger/-/swagger-7.4.2.tgz", + "integrity": "sha512-Mu6TEn1M/owIvAx2B4DUQObQXqo2028R2s9rSZ/hJEgBK95+doTwS0DjmVA2wTeZTyVtXOoN7CsoM5pONBzvKQ==", + "license": "MIT", + "dependencies": { + "@microsoft/tsdoc": "^0.15.0", + "@nestjs/mapped-types": "2.0.5", + "js-yaml": "4.1.0", + "lodash": "4.17.21", + "path-to-regexp": "3.3.0", + "swagger-ui-dist": "5.17.14" + }, + "peerDependencies": { + "@fastify/static": "^6.0.0 || ^7.0.0", + "@nestjs/common": "^9.0.0 || ^10.0.0", + "@nestjs/core": "^9.0.0 || ^10.0.0", + "class-transformer": "*", + "class-validator": "*", + "reflect-metadata": "^0.1.12 || ^0.2.0" + }, + "peerDependenciesMeta": { + "@fastify/static": { + "optional": true + }, + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/swagger/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@nestjs/swagger/node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/@nestjs/testing": { + "version": "10.4.22", + "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-10.4.22.tgz", + "integrity": "sha512-HO9aPus3bAedAC+jKVAA8jTdaj4fs5M9fing4giHrcYV2txe9CvC1l1WAjwQ9RDhEHdugjY4y+FZA/U/YqPZrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nest" + }, + "peerDependencies": { + "@nestjs/common": "^10.0.0", + "@nestjs/core": "^10.0.0", + "@nestjs/microservices": "^10.0.0", + "@nestjs/platform-express": "^10.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/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nuxtjs/opencollective": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.3.2.tgz", + "integrity": "sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==", + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "consola": "^2.15.0", + "node-fetch": "^2.6.1" + }, + "bin": { + "opencollective": "bin/opencollective.js" + }, + "engines": { + "node": ">=8.0.0", + "npm": ">=5.0.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/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@prisma/client": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.1.0.tgz", + "integrity": "sha512-AbQYc5+EJKm1Ydfq3KxwcGiy7wIbm4/QbjCKWWoNROtvy7d6a3gmAGkKjK0iUCzh+rHV8xDhD5Cge8ke/kiy5Q==", + "hasInstallScript": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "prisma": "*" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + } + } + }, + "node_modules/@prisma/debug": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.1.0.tgz", + "integrity": "sha512-0himsvcM4DGBTtvXkd2Tggv6sl2JyUYLzEGXXleFY+7Kp6rZeSS3hiTW9mwtUlXrwYbJP6pwlVNB7jYElrjWUg==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.1.0.tgz", + "integrity": "sha512-GnYJbCiep3Vyr1P/415ReYrgJUjP79fBNc1wCo7NP6Eia0CzL2Ot9vK7Infczv3oK7JLrCcawOSAxFxNFsAERQ==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.1.0", + "@prisma/engines-version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959", + "@prisma/fetch-engine": "6.1.0", + "@prisma/get-platform": "6.1.0" + } + }, + "node_modules/@prisma/engines-version": { + "version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959.tgz", + "integrity": "sha512-PdJqmYM2Fd8K0weOOtQThWylwjsDlTig+8Pcg47/jszMuLL9iLIaygC3cjWJLda69siRW4STlCTMSgOjZzvKPQ==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/fetch-engine": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.1.0.tgz", + "integrity": "sha512-asdFi7TvPlEZ8CzSZ/+Du5wZ27q6OJbRSXh+S8ISZguu+S9KtS/gP7NeXceZyb1Jv1SM1S5YfiCv+STDsG6rrg==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.1.0", + "@prisma/engines-version": "6.1.0-21.11f085a2012c0f4778414c8db2651556ee0ef959", + "@prisma/get-platform": "6.1.0" + } + }, + "node_modules/@prisma/get-platform": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.1.0.tgz", + "integrity": "sha512-ia8bNjboBoHkmKGGaWtqtlgQOhCi7+f85aOkPJKgNwWvYrT6l78KgojLekE8zMhVk0R9lWcifV0Pf8l3/15V0Q==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.1.0" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.27.12", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", + "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sinonjs/commons": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", + "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/@smithy/abort-controller": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-3.1.9.tgz", + "integrity": "sha512-yiW0WI30zj8ZKoSYNx90no7ugVn3khlyH/z5W8qtKBtVE6awRALbhSG+2SAHA1r6bO/6M9utxYKVZ3PCJ1rWxw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/chunked-blob-reader": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@smithy/chunked-blob-reader/-/chunked-blob-reader-4.0.0.tgz", + "integrity": "sha512-jSqRnZvkT4egkq/7b6/QRCNXmmYVcHwnJldqJ3IhVpQE2atObVJ137xmGeuGFhjFUr8gCEVAOKwSY79OvpbDaQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/chunked-blob-reader-native": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@smithy/chunked-blob-reader-native/-/chunked-blob-reader-native-3.0.1.tgz", + "integrity": "sha512-VEYtPvh5rs/xlyqpm5NRnfYLZn+q0SRPELbvBV+C/G7IQ+ouTuo+NKKa3ShG5OaFR8NYVMXls9hPYLTvIKKDrQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-base64": "^3.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/config-resolver": { + "version": "3.0.13", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-3.0.13.tgz", + "integrity": "sha512-Gr/qwzyPaTL1tZcq8WQyHhTZREER5R1Wytmz4WnVGL4onA3dNk6Btll55c8Vr58pLdvWZmtG8oZxJTw3t3q7Jg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^3.1.12", + "@smithy/types": "^3.7.2", + "@smithy/util-config-provider": "^3.0.0", + "@smithy/util-middleware": "^3.0.11", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/core": { + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-2.5.7.tgz", + "integrity": "sha512-8olpW6mKCa0v+ibCjoCzgZHQx1SQmZuW/WkrdZo73wiTprTH6qhmskT60QLFdT9DRa5mXxjz89kQPZ7ZSsoqqg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/middleware-serde": "^3.0.11", + "@smithy/protocol-http": "^4.1.8", + "@smithy/types": "^3.7.2", + "@smithy/util-body-length-browser": "^3.0.0", + "@smithy/util-middleware": "^3.0.11", + "@smithy/util-stream": "^3.3.4", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-3.2.8.tgz", + "integrity": "sha512-ZCY2yD0BY+K9iMXkkbnjo+08T2h8/34oHd0Jmh6BZUSZwaaGlGCyBT/3wnS7u7Xl33/EEfN4B6nQr3Gx5bYxgw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^3.1.12", + "@smithy/property-provider": "^3.1.11", + "@smithy/types": "^3.7.2", + "@smithy/url-parser": "^3.0.11", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/eventstream-codec": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-3.1.10.tgz", + "integrity": "sha512-323B8YckSbUH0nMIpXn7HZsAVKHYHFUODa8gG9cHo0ySvA1fr5iWaNT+iIL0UCqUzG6QPHA3BSsBtRQou4mMqQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@smithy/types": "^3.7.2", + "@smithy/util-hex-encoding": "^3.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/eventstream-serde-browser": { + "version": "3.0.14", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-3.0.14.tgz", + "integrity": "sha512-kbrt0vjOIihW3V7Cqj1SXQvAI5BR8SnyQYsandva0AOR307cXAc+IhPngxIPslxTLfxwDpNu0HzCAq6g42kCPg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^3.0.13", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-config-resolver": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-3.0.11.tgz", + "integrity": "sha512-P2pnEp4n75O+QHjyO7cbw/vsw5l93K/8EWyjNCAAybYwUmj3M+hjSQZ9P5TVdUgEG08ueMAP5R4FkuSkElZ5tQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-node": { + "version": "3.0.13", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-3.0.13.tgz", + "integrity": "sha512-zqy/9iwbj8Wysmvi7Lq7XFLeDgjRpTbCfwBhJa8WbrylTAHiAu6oQTwdY7iu2lxigbc9YYr9vPv5SzYny5tCXQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^3.0.13", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-universal": { + "version": "3.0.13", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-3.0.13.tgz", + "integrity": "sha512-L1Ib66+gg9uTnqp/18Gz4MDpJPKRE44geOjOQ2SVc0eiaO5l255ADziATZgjQjqumC7yPtp1XnjHlF1srcwjKw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-codec": "^3.1.10", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-4.1.3.tgz", + "integrity": "sha512-6SxNltSncI8s689nvnzZQc/dPXcpHQ34KUj6gR/HBroytKOd/isMG3gJF/zBE1TBmTT18TXyzhg3O3SOOqGEhA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^4.1.8", + "@smithy/querystring-builder": "^3.0.11", + "@smithy/types": "^3.7.2", + "@smithy/util-base64": "^3.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/hash-blob-browser": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/@smithy/hash-blob-browser/-/hash-blob-browser-3.1.10.tgz", + "integrity": "sha512-elwslXOoNunmfS0fh55jHggyhccobFkexLYC1ZeZ1xP2BTSrcIBaHV2b4xUQOdctrSNOpMqOZH1r2XzWTEhyfA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/chunked-blob-reader": "^4.0.0", + "@smithy/chunked-blob-reader-native": "^3.0.1", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/hash-node": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-3.0.11.tgz", + "integrity": "sha512-emP23rwYyZhQBvklqTtwetkQlqbNYirDiEEwXl2v0GYWMnCzxst7ZaRAnWuy28njp5kAH54lvkdG37MblZzaHA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/hash-stream-node": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/@smithy/hash-stream-node/-/hash-stream-node-3.1.10.tgz", + "integrity": "sha512-olomK/jZQ93OMayW1zfTHwcbwBdhcZOHsyWyiZ9h9IXvc1mCD/VuvzbLb3Gy/qNJwI4MANPLctTp2BucV2oU/Q==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/invalid-dependency": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-3.0.11.tgz", + "integrity": "sha512-NuQmVPEJjUX6c+UELyVz8kUx8Q539EDeNwbRyu4IIF8MeV7hUtq1FB3SHVyki2u++5XLMFqngeMKk7ccspnNyQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-3.0.0.tgz", + "integrity": "sha512-+Fsu6Q6C4RSJiy81Y8eApjEB5gVtM+oFKTffg+jSuwtvomJJrhUJBu2zS8wjXSgH/g1MKEWrzyChTBe6clb5FQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/md5-js": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-3.0.11.tgz", + "integrity": "sha512-3NM0L3i2Zm4bbgG6Ymi9NBcxXhryi3uE8fIfHJZIOfZVxOkGdjdgjR9A06SFIZCfnEIWKXZdm6Yq5/aPXFFhsQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/middleware-content-length": { + "version": "3.0.13", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-3.0.13.tgz", + "integrity": "sha512-zfMhzojhFpIX3P5ug7jxTjfUcIPcGjcQYzB9t+rv0g1TX7B0QdwONW+ATouaLoD7h7LOw/ZlXfkq4xJ/g2TrIw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^4.1.8", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-endpoint": { + "version": "3.2.8", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-3.2.8.tgz", + "integrity": "sha512-OEJZKVUEhMOqMs3ktrTWp7UvvluMJEvD5XgQwRePSbDg1VvBaL8pX8mwPltFn6wk1GySbcVwwyldL8S+iqnrEQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^2.5.7", + "@smithy/middleware-serde": "^3.0.11", + "@smithy/node-config-provider": "^3.1.12", + "@smithy/shared-ini-file-loader": "^3.1.12", + "@smithy/types": "^3.7.2", + "@smithy/url-parser": "^3.0.11", + "@smithy/util-middleware": "^3.0.11", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-retry": { + "version": "3.0.34", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-3.0.34.tgz", + "integrity": "sha512-yVRr/AAtPZlUvwEkrq7S3x7Z8/xCd97m2hLDaqdz6ucP2RKHsBjEqaUA2ebNv2SsZoPEi+ZD0dZbOB1u37tGCA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^3.1.12", + "@smithy/protocol-http": "^4.1.8", + "@smithy/service-error-classification": "^3.0.11", + "@smithy/smithy-client": "^3.7.0", + "@smithy/types": "^3.7.2", + "@smithy/util-middleware": "^3.0.11", + "@smithy/util-retry": "^3.0.11", + "tslib": "^2.6.2", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-serde": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-3.0.11.tgz", + "integrity": "sha512-KzPAeySp/fOoQA82TpnwItvX8BBURecpx6ZMu75EZDkAcnPtO6vf7q4aH5QHs/F1s3/snQaSFbbUMcFFZ086Mw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/middleware-stack": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-3.0.11.tgz", + "integrity": "sha512-1HGo9a6/ikgOMrTrWL/WiN9N8GSVYpuRQO5kjstAq4CvV59bjqnh7TbdXGQ4vxLD3xlSjfBjq5t1SOELePsLnA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/node-config-provider": { + "version": "3.1.12", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-3.1.12.tgz", + "integrity": "sha512-O9LVEu5J/u/FuNlZs+L7Ikn3lz7VB9hb0GtPT9MQeiBmtK8RSY3ULmsZgXhe6VAlgTw0YO+paQx4p8xdbs43vQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^3.1.11", + "@smithy/shared-ini-file-loader": "^3.1.12", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-3.3.3.tgz", + "integrity": "sha512-BrpZOaZ4RCbcJ2igiSNG16S+kgAc65l/2hmxWdmhyoGWHTLlzQzr06PXavJp9OBlPEG/sHlqdxjWmjzV66+BSQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^3.1.9", + "@smithy/protocol-http": "^4.1.8", + "@smithy/querystring-builder": "^3.0.11", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/property-provider": { + "version": "3.1.11", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-3.1.11.tgz", + "integrity": "sha512-I/+TMc4XTQ3QAjXfOcUWbSS073oOEAxgx4aZy8jHaf8JQnRkq2SZWw8+PfDtBvLUjcGMdxl+YwtzWe6i5uhL/A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/protocol-http": { + "version": "4.1.8", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-4.1.8.tgz", + "integrity": "sha512-hmgIAVyxw1LySOwkgMIUN0kjN8TG9Nc85LJeEmEE/cNEe2rkHDUWhnJf2gxcSRFLWsyqWsrZGw40ROjUogg+Iw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/querystring-builder": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-3.0.11.tgz", + "integrity": "sha512-u+5HV/9uJaeLj5XTb6+IEF/dokWWkEqJ0XiaRRogyREmKGUgZnNecLucADLdauWFKUNbQfulHFEZEdjwEBjXRg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "@smithy/util-uri-escape": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/querystring-parser": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-3.0.11.tgz", + "integrity": "sha512-Je3kFvCsFMnso1ilPwA7GtlbPaTixa3WwC+K21kmMZHsBEOZYQaqxcMqeFFoU7/slFjKDIpiiPydvdJm8Q/MCw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/service-error-classification": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-3.0.11.tgz", + "integrity": "sha512-QnYDPkyewrJzCyaeI2Rmp7pDwbUETe+hU8ADkXmgNusO1bgHBH7ovXJiYmba8t0fNfJx75fE8dlM6SEmZxheog==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/shared-ini-file-loader": { + "version": "3.1.12", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-3.1.12.tgz", + "integrity": "sha512-1xKSGI+U9KKdbG2qDvIR9dGrw3CNx+baqJfyr0igKEpjbHL5stsqAesYBzHChYHlelWtb87VnLWlhvfCz13H8Q==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-4.2.4.tgz", + "integrity": "sha512-5JWeMQYg81TgU4cG+OexAWdvDTs5JDdbEZx+Qr1iPbvo91QFGzjy0IkXAKaXUHqmKUJgSHK0ZxnCkgZpzkeNTA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^3.0.0", + "@smithy/protocol-http": "^4.1.8", + "@smithy/types": "^3.7.2", + "@smithy/util-hex-encoding": "^3.0.0", + "@smithy/util-middleware": "^3.0.11", + "@smithy/util-uri-escape": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/smithy-client": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-3.7.0.tgz", + "integrity": "sha512-9wYrjAZFlqWhgVo3C4y/9kpc68jgiSsKUnsFPzr/MSiRL93+QRDafGTfhhKAb2wsr69Ru87WTiqSfQusSmWipA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^2.5.7", + "@smithy/middleware-endpoint": "^3.2.8", + "@smithy/middleware-stack": "^3.0.11", + "@smithy/protocol-http": "^4.1.8", + "@smithy/types": "^3.7.2", + "@smithy/util-stream": "^3.3.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-3.7.2.tgz", + "integrity": "sha512-bNwBYYmN8Eh9RyjS1p2gW6MIhSO2rl7X9QeLM8iTdcGRP+eDiIWDt66c9IysCc22gefKszZv+ubV9qZc7hdESg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/url-parser": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-3.0.11.tgz", + "integrity": "sha512-TmlqXkSk8ZPhfc+SQutjmFr5FjC0av3GZP4B/10caK1SbRwe/v+Wzu/R6xEKxoNqL+8nY18s1byiy6HqPG37Aw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/querystring-parser": "^3.0.11", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/util-base64": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-3.0.0.tgz", + "integrity": "sha512-Kxvoh5Qtt0CDsfajiZOCpJxgtPHXOKwmM+Zy4waD43UoEMA+qPxxa98aE/7ZhdnBFZFXMOiBR5xbcaMhLtznQQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-body-length-browser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-3.0.0.tgz", + "integrity": "sha512-cbjJs2A1mLYmqmyVl80uoLTJhAcfzMOyPgjwAYusWKMdLeNtzmMz9YxNl3/jRLoxSS3wkqkf0jwNdtXWtyEBaQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@smithy/util-body-length-node": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-3.0.0.tgz", + "integrity": "sha512-Tj7pZ4bUloNUP6PzwhN7K386tmSmEET9QtQg0TgdNOnxhZvCssHji+oZTUIuzxECRfG8rdm2PMw2WCFs6eIYkA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-3.0.0.tgz", + "integrity": "sha512-aEOHCgq5RWFbP+UDPvPot26EJHjOC+bRgse5A8V3FSShqd5E5UN4qc7zkwsvJPPAVsf73QwYcHN1/gt/rtLwQA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-config-provider": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-3.0.0.tgz", + "integrity": "sha512-pbjk4s0fwq3Di/ANL+rCvJMKM5bzAQdE5S/6RL5NXgMExFAi6UgQMPOm5yPaIWPpr+EOXKXRonJ3FoxKf4mCJQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-browser": { + "version": "3.0.34", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-3.0.34.tgz", + "integrity": "sha512-FumjjF631lR521cX+svMLBj3SwSDh9VdtyynTYDAiBDEf8YPP5xORNXKQ9j0105o5+ARAGnOOP/RqSl40uXddA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^3.1.11", + "@smithy/smithy-client": "^3.7.0", + "@smithy/types": "^3.7.2", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-node": { + "version": "3.0.34", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-3.0.34.tgz", + "integrity": "sha512-vN6aHfzW9dVVzkI0wcZoUXvfjkl4CSbM9nE//08lmUMyf00S75uuCpTrqF9uD4bD9eldIXlt53colrlwKAT8Gw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/config-resolver": "^3.0.13", + "@smithy/credential-provider-imds": "^3.2.8", + "@smithy/node-config-provider": "^3.1.12", + "@smithy/property-provider": "^3.1.11", + "@smithy/smithy-client": "^3.7.0", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/@smithy/util-endpoints": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-2.1.7.tgz", + "integrity": "sha512-tSfcqKcN/Oo2STEYCABVuKgJ76nyyr6skGl9t15hs+YaiU06sgMkN7QYjo0BbVw+KT26zok3IzbdSOksQ4YzVw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^3.1.12", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-hex-encoding": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-3.0.0.tgz", + "integrity": "sha512-eFndh1WEK5YMUYvy3lPlVmYY/fZcQE1D8oSf41Id2vCeIkKJXPcYDCZD+4+xViI6b1XSd7tE+s5AmXzz5ilabQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-middleware": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-3.0.11.tgz", + "integrity": "sha512-dWpyc1e1R6VoXrwLoLDd57U1z6CwNSdkM69Ie4+6uYh2GC7Vg51Qtan7ITzczuVpqezdDTKJGJB95fFvvjU/ow==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-retry": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-3.0.11.tgz", + "integrity": "sha512-hJUC6W7A3DQgaee3Hp9ZFcOxVDZzmBIRBPlUAk8/fSOEl7pE/aX7Dci0JycNOnm9Mfr0KV2XjIlUOcGWXQUdVQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/service-error-classification": "^3.0.11", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-stream": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-3.3.4.tgz", + "integrity": "sha512-SGhGBG/KupieJvJSZp/rfHHka8BFgj56eek9px4pp7lZbOF+fRiVr4U7A3y3zJD8uGhxq32C5D96HxsTC9BckQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/fetch-http-handler": "^4.1.3", + "@smithy/node-http-handler": "^3.3.3", + "@smithy/types": "^3.7.2", + "@smithy/util-base64": "^3.0.0", + "@smithy/util-buffer-from": "^3.0.0", + "@smithy/util-hex-encoding": "^3.0.0", + "@smithy/util-utf8": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-uri-escape": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-3.0.0.tgz", + "integrity": "sha512-LqR7qYLgZTD7nWLBecUi4aqolw8Mhza9ArpNEQ881MJJIU2sE5iHCK6TdyqqzcDLy0OPe10IY4T8ctVdtynubg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-3.0.0.tgz", + "integrity": "sha512-rUeT12bxFnplYDe815GXbq/oixEGHfRFFtcTF3YdDi/JaENIM6aSYYLJydG83UNzLXeRI5K8abYd/8Sp/QM0kA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^3.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@smithy/util-waiter": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-3.2.0.tgz", + "integrity": "sha512-PpjSboaDUE6yl+1qlg3Si57++e84oXdWGbuFUSAciXsVfEZJJJupR2Nb0QuXHiunt2vGR+1PTizOMvnUPaG2Qg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^3.1.9", + "@smithy/types": "^3.7.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@tokenizer/inflate": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.2.7.tgz", + "integrity": "sha512-MADQgmZT1eKjp06jpI2yozxaU9uVs4GzzgSL+uEq7bVcJ9V1ZXQkeGNql1fsSI0gMy1vhvNTNbUqrx+pZfJVmg==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "fflate": "^0.8.2", + "token-types": "^6.0.0" + }, + "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/@tsconfig/node10": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.13.tgz", + "integrity": "sha512-gcLdvR9HO1ZJBypsOGqaP6TFEzb6vIta0KSTLt9NAQ6pXQO3cRgSVyCN6pzYqI9DlJgY71XKO0dpDhCf08b3pg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/amqplib": { + "version": "0.10.6", + "resolved": "https://registry.npmjs.org/@types/amqplib/-/amqplib-0.10.6.tgz", + "integrity": "sha512-vQLVypBS1JQcfTXhl1Td1EEeLdtb+vuulOb4TrzYiLyP2aYLMAEzB3pNmEA0jBm0xIXu946Y7Xwl19Eidl32SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "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/eslint": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", + "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.7", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz", + "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "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/graceful-fs": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", + "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", + "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", + "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", + "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/jest": { + "version": "29.5.14", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", + "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "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": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/stack-utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", + "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", + "dev": true, + "license": "MIT" + }, + "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": "6.0.3", + "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-6.0.3.tgz", + "integrity": "sha512-8WzXq62EXFhJ7QsH3Ocb/iKQ/Ty9ZVWnVzoTKc9tyyFRRF3a74Tk2+TLFgaFFw364Ere+npzHKEJ6ga2LzIL7w==", + "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/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz", + "integrity": "sha512-/v8HZt6RlyIZxB3ntehELOcUcfxKPVGWXnQdJuHRmzrqgF8nQypcC/oxGW+Ot4VGKDq81XugPKxx0n5PBtf9PA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.70.0", + "@typescript-eslint/type-utils": "8.70.0", + "@typescript-eslint/utils": "8.70.0", + "@typescript-eslint/visitor-keys": "8.70.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.70.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.70.0.tgz", + "integrity": "sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.70.0", + "@typescript-eslint/types": "8.70.0", + "@typescript-eslint/typescript-estree": "8.70.0", + "@typescript-eslint/visitor-keys": "8.70.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.70.0.tgz", + "integrity": "sha512-hFHbTNqhU9G+2eKFXCBVb1tjFT/LceiJ4+HfLO4pTpDI0KHi6iajpcFFkaSQ9gXmCh7n82A0PthaayEdN6mspQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.70.0", + "@typescript-eslint/types": "^8.70.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.70.0.tgz", + "integrity": "sha512-8nP3Kwh5hlgZ4FicGvmznAmJe8UL4sdU8tLukrPaMuQmDuk4Y8xYfzu/aYZW4xT2JCgc7H/TpDI5cGlxcWJSqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.70.0", + "@typescript-eslint/visitor-keys": "8.70.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.70.0.tgz", + "integrity": "sha512-adnkeeNq9Sq1sUf4+FRVc0KdgYghzsgFpZSQVZVvY0LCuUuN0FnQgyGzCJeC4fW1cdXseBAjU2EOqUIjbNcZUw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.70.0.tgz", + "integrity": "sha512-NUMKIhYVaVIVLnRL9CRt+VVcuLgSHUCpXn4/+K8wql+vdInUzvx8BjUO1oJ7cG9shjFJKtF8F8Hh2kCh3/KBVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.70.0", + "@typescript-eslint/typescript-estree": "8.70.0", + "@typescript-eslint/utils": "8.70.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.70.0.tgz", + "integrity": "sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.70.0.tgz", + "integrity": "sha512-d9NmHMPEKQ7QCLLm1jI3zmoQBwT5KwFYjXBJ9ymZfKCUU+5rmTRykKAFvH5Qn/ZCds3CEAFS9OC9M/jkl0X2bA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.70.0", + "@typescript-eslint/tsconfig-utils": "8.70.0", + "@typescript-eslint/types": "8.70.0", + "@typescript-eslint/visitor-keys": "8.70.0", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.70.0.tgz", + "integrity": "sha512-oZmtKJz/4fufZ2p3+Cn3ijEojcdfR+1zYDH2xKYrEly0dR/Q/1xUPRCOlKGxod78nWlU2UnDe09GZ3TaknBFGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.70.0", + "@typescript-eslint/types": "8.70.0", + "@typescript-eslint/typescript-estree": "8.70.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.70.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.70.0.tgz", + "integrity": "sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.70.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", + "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/helper-numbers": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz", + "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz", + "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz", + "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz", + "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.13.2", + "@webassemblyjs/helper-api-error": "1.13.2", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz", + "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz", + "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/wasm-gen": "1.14.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz", + "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz", + "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz", + "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz", + "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/helper-wasm-section": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-opt": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1", + "@webassemblyjs/wast-printer": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz", + "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz", + "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz", + "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-api-error": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz", + "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true, + "license": "Apache-2.0" + }, + "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/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ajv": { + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/amqplib": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.10.5.tgz", + "integrity": "sha512-Dx5zmy0Ur+Q7LPPdhz+jx5IzmJBoHd15tOeAfQ8SuvEtyPJ20hBemhOBA4b1WeORCRa0ENM/kHCzmem1w/zHvQ==", + "license": "MIT", + "dependencies": { + "@acuminous/bitsyntax": "^0.1.2", + "buffer-more-ints": "~1.0.0", + "url-parse": "~1.5.10" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", + "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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-escapes/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/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "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==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true, + "license": "MIT" + }, + "node_modules/argon2": { + "version": "0.41.1", + "resolved": "https://registry.npmjs.org/argon2/-/argon2-0.41.1.tgz", + "integrity": "sha512-dqCW8kJXke8Ik+McUcMDltrbuAWETPyU6iq+4AhxqKphWi7pChB/Zgd/Tp/o8xRLbg8ksMj46F/vph9wnxpTzQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@phc/format": "^1.0.0", + "node-addon-api": "^8.1.0", + "node-gyp-build": "^4.8.1" + }, + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.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/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": "8.4.0", + "resolved": "https://registry.npmjs.org/avvio/-/avvio-8.4.0.tgz", + "integrity": "sha512-CDSwaxINFy59iNwhYnkvALBwZiTydGkOecZyPkqBpABYR1KqGEsET0VOOYDwtleZSUIdeY36DC2bSZ24CO1igA==", + "license": "MIT", + "dependencies": { + "@fastify/error": "^3.3.0", + "fastq": "^1.17.1" + } + }, + "node_modules/babel-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", + "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/transform": "^29.7.0", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.6.3", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-istanbul/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", + "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", + "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-import-attributes": "^7.24.7", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5" + }, + "peerDependencies": { + "@babel/core": "^7.0.0 || ^8.0.0-0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", + "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", + "dev": true, + "license": "MIT", + "dependencies": { + "babel-plugin-jest-hoist": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "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/baseline-browser-mapping": { + "version": "2.11.25", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.25.tgz", + "integrity": "sha512-gMmEShwwq7FJqMwvfRwvCl00v4kN+KOfJqXn+f4nrufak5gNHJOksd/60Dvjuz7sI8Y5WiSFBa8FEYr+zoyqCw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "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/bowser": { + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.15.0.tgz", + "integrity": "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==", + "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/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.29.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz", + "integrity": "sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.23", + "caniuse-lite": "^1.0.30001810", + "electron-to-chromium": "^1.5.427", + "node-releases": "^2.0.55", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-json-stable-stringify": "2.x" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "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/buffer-more-ints": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==", + "license": "MIT" + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001810", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", + "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "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": "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/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", + "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", + "dev": true, + "license": "MIT" + }, + "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.14.4", + "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.4.tgz", + "integrity": "sha512-AwNusCCam51q703dW82x95tOqQp6oC9HNUl724KxJJOfnKscI8dOloXFgyez7LbTTKWuRBA37FScqVbJEoq8Yw==", + "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-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/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": "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/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "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/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", + "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", + "dev": true, + "license": "MIT" + }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "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==", + "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==", + "license": "MIT" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "license": "MIT", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "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": "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/comment-json": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/comment-json/-/comment-json-4.2.5.tgz", + "integrity": "sha512-bKw/r35jR3HGt5PEPm1ljsQQGyCrR8sFGNiN5L+ykDHdpO8Smxkrkla9Yi6NkQyUrb8V54PGhfMs6NrIwtxtdw==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-timsort": "^1.0.3", + "core-util-is": "^1.0.3", + "esprima": "^4.0.1", + "has-own-prop": "^2.0.0", + "repeat-string": "^1.6.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/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "2.15.3", + "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", + "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "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": "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/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, + "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/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cosmiconfig": { + "version": "8.3.6", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.3.6.tgz", + "integrity": "sha512-kcZ6+W5QzcJ3P1Mt+83OUv/oHFqZHIx8DuxG6eZ5RGMERoLqp4BuGjhHLYGK+Kf5XVkQvqBSmAy/nGWN3qDgEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0", + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/create-jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", + "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "prompts": "^2.0.1" + }, + "bin": { + "create-jest": "bin/create-jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true, + "license": "MIT" + }, + "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/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/dedent": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" + }, + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "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/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "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/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/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "dev": true, + "license": "MIT", + "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/diff": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", + "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diff-sequences": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", + "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "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==", + "dev": true, + "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/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.433", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.433.tgz", + "integrity": "sha512-5lCAbyZBjtmUt/RAGHRqrL2q0oEFRThDAsZHHDn9XHa89Qw7gMYOeSicBTy+AHfvo0r6vwsZvqNJTQIQy1BLzA==", + "dev": true, + "license": "ISC" + }, + "node_modules/emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "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==", + "license": "MIT" + }, + "node_modules/enhanced-resolve": { + "version": "5.25.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.25.1.tgz", + "integrity": "sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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", + "peer": true + }, + "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==", + "dev": true, + "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/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", + "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.1", + "@humanwhocodes/config-array": "^0.13.0", + "@humanwhocodes/module-importer": "^1.0.1", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.2", + "debug": "^4.3.2", + "doctrine": "^3.0.0", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^6.0.1", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-scope": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", + "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/eslint/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/eslint/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/espree": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.9.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^3.4.1" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "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/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/execa/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/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expect": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", + "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/expect-utils": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "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/fast-content-type-parse": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-1.1.0.tgz", + "integrity": "sha512-fBHHqSTFLVnR61C+gltJuE5GkVQMV0S2nqUO8TJ+5Z3qAKG8vAx4FKai1s5jq/inV1+sREynIWSuQ6HgoSXpDQ==", + "license": "MIT" + }, + "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-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stringify": { + "version": "5.16.1", + "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-5.16.1.tgz", + "integrity": "sha512-KAdnLvy1yu/XrRtP+LJnxbBGrhN+xXu+gt3EUvZhYGKCr3lFHq/7UFJHHFgmJKoqlh6B40bZLEv7w46B0mqn1g==", + "license": "MIT", + "dependencies": { + "@fastify/merge-json-schemas": "^0.1.0", + "ajv": "^8.10.0", + "ajv-formats": "^3.0.1", + "fast-deep-equal": "^3.1.3", + "fast-uri": "^2.1.0", + "json-schema-ref-resolver": "^1.0.1", + "rfdc": "^1.2.0" + } + }, + "node_modules/fast-json-stringify/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/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "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-uri": { + "version": "2.4.7", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-2.4.7.tgz", + "integrity": "sha512-b8mggfg2R+m2OAb3Z+2HcJxUgU+2cY1JQondBDyXLdrEKNPxd96MvnB5yWKZdupsuX6GdBaAZHZo9msHX/Bb7A==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz", + "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + }, + { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^1.0.5" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fastify": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/fastify/-/fastify-4.28.1.tgz", + "integrity": "sha512-kFWUtpNr4i7t5vY2EJPCN2KgMVpuqfU4NjnJNCgiNB900oiDeYqaNDRcAfeBbOF5hGixixxcKnOU4KN9z6QncQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "@fastify/ajv-compiler": "^3.5.0", + "@fastify/error": "^3.4.0", + "@fastify/fast-json-stringify-compiler": "^4.3.0", + "abstract-logging": "^2.0.1", + "avvio": "^8.3.0", + "fast-content-type-parse": "^1.1.0", + "fast-json-stringify": "^5.8.0", + "find-my-way": "^8.0.0", + "light-my-request": "^5.11.0", + "pino": "^9.0.0", + "process-warning": "^3.0.0", + "proxy-addr": "^2.0.7", + "rfdc": "^1.3.0", + "secure-json-parse": "^2.7.0", + "semver": "^7.5.4", + "toad-cache": "^3.3.0" + } + }, + "node_modules/fastify-plugin": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-4.5.1.tgz", + "integrity": "sha512-stRHYGeuqpEZTL1Ef0Ovr2ltazUT9g844X5z/zEBFLG8RYlpDiOCIG+ATvYEp+/zmc7sN29mcIMp8gvYplYPIQ==", + "license": "MIT" + }, + "node_modules/fastify/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/fastify/node_modules/light-my-request": { + "version": "5.14.0", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-5.14.0.tgz", + "integrity": "sha512-aORPWntbpH5esaYpGOOmri0OHDOe3wC5M2MQxZ9dvMLZm6DnaAn0kJlcbU9hwsQgLzmZyReKwFwwPkR+nHu5kA==", + "license": "BSD-3-Clause", + "dependencies": { + "cookie": "^0.7.0", + "process-warning": "^3.0.0", + "set-cookie-parser": "^2.4.1" + } + }, + "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/fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bser": "2.1.1" + } + }, + "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/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, + "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/figures/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/file-entry-cache": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^3.0.4" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/file-type": { + "version": "20.4.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.4.1.tgz", + "integrity": "sha512-hw9gNZXUfZ02Jo0uafWLaFVPter5/k2rfcrjFJJHX/77xtSDOfJuEFb6oKlFV86FLP1SuyHMW1PSk0U9M5tKkQ==", + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.2.6", + "strtok3": "^10.2.0", + "token-types": "^6.0.0", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-my-way": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-8.2.2.tgz", + "integrity": "sha512-Dobi7gcTEq8yszimcfp/R7+owiT4WncAJ7VTTgFH1jYJ5GaG1FbhjwDG820hptN0QDFvzVY3RfCzdInvGPGzjA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-querystring": "^1.0.0", + "safe-regex2": "^3.1.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", + "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.3", + "rimraf": "^3.0.2" + }, + "engines": { + "node": "^10.12.0 || >=12.0.0" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fork-ts-checker-webpack-plugin": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/fork-ts-checker-webpack-plugin/-/fork-ts-checker-webpack-plugin-9.0.2.tgz", + "integrity": "sha512-Uochze2R8peoN1XqlSi/rGUkDQpRogtLFocP9+PGu68zk1BDAKXfdeCdyVZpgTk8V8WFVQXdEz426VKjXLO1Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.16.7", + "chalk": "^4.1.2", + "chokidar": "^3.5.3", + "cosmiconfig": "^8.2.0", + "deepmerge": "^4.2.2", + "fs-extra": "^10.0.0", + "memfs": "^3.4.1", + "minimatch": "^3.0.4", + "node-abort-controller": "^3.0.1", + "schema-utils": "^3.1.1", + "semver": "^7.3.5", + "tapable": "^2.2.1" + }, + "engines": { + "node": ">=12.13.0", + "yarn": ">=1.0.0" + }, + "peerDependencies": { + "typescript": ">3.6.0", + "webpack": "^5.11.0" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/fork-ts-checker-webpack-plugin/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "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/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/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/fs-monkey": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.1.0.tgz", + "integrity": "sha512-QMUezzXWII9EV5aTFXW1UBVUO77wYPpjqIF8/AviUCThNeSYZykpoTixUeaNNBwmCev0AMDWMAni+f8Hxb1IFw==", + "dev": true, + "license": "Unlicense" + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "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==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "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==", + "dev": true, + "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-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/glob/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/graphemer": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", + "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", + "dev": true, + "license": "MIT" + }, + "node_modules/handlebars": { + "version": "4.7.9", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.9.tgz", + "integrity": "sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.5", + "neo-async": "^2.6.2", + "source-map": "^0.6.1", + "wordwrap": "^1.0.0" + }, + "bin": { + "handlebars": "bin/handlebars" + }, + "engines": { + "node": ">=0.4.7" + }, + "optionalDependencies": { + "uglify-js": "^3.1.4" + } + }, + "node_modules/handlebars/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/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-own-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-own-prop/-/has-own-prop-2.0.0.tgz", + "integrity": "sha512-Pq0h+hvsVm6dDEa8x82GnLSYHOzNDt7f0ddFa3FqcQlgzEiptPqL+XrOJNavjOzSYiYWIrgeVYYgGlLmnxwilQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "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/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/ignore": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.9.tgz", + "integrity": "sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "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/ioredis": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.4.1.tgz", + "integrity": "sha512-2YZsvl7jopIa1gaePkeMtd9rAcSjOOjPtpcLlOeusyO+XH2SK5ZcT+UCrElPP+WVIInh2TzeI4XW9ENaSLVVHA==", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "^1.1.1", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "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-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.17.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", + "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "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/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "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/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-instrument": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", + "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@babel/core": "^7.23.9", + "@babel/parser": "^7.23.9", + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=10" + } + }, + "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-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps/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/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/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jest": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", + "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/types": "^29.6.3", + "import-local": "^3.0.2", + "jest-cli": "^29.7.0" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", + "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "execa": "^5.0.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", + "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/expect": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^1.0.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.7.0", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "p-limit": "^3.1.0", + "pretty-format": "^29.7.0", + "pure-rand": "^6.0.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-cli": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", + "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "create-jest": "^29.7.0", + "exit": "^0.1.2", + "import-local": "^3.0.2", + "jest-config": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", + "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-jest": "^29.7.0", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-runner": "^29.7.0", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-config/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-config/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/jest-config/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-config/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jest-diff": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", + "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.6.3", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-docblock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", + "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", + "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "jest-util": "^29.7.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-environment-node": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", + "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", + "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", + "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", + "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", + "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.6.3", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.7.0", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-mock": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", + "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "jest-util": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", + "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", + "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-regex-util": "^29.6.3", + "jest-snapshot": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", + "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "^29.7.0", + "@jest/environment": "^29.7.0", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.7.0", + "jest-environment-node": "^29.7.0", + "jest-haste-map": "^29.7.0", + "jest-leak-detector": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-resolve": "^29.7.0", + "jest-runtime": "^29.7.0", + "jest-util": "^29.7.0", + "jest-watcher": "^29.7.0", + "jest-worker": "^29.7.0", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner/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/jest-runner/node_modules/source-map-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", + "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/globals": "^29.7.0", + "@jest/source-map": "^29.6.3", + "@jest/test-result": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-mock": "^29.7.0", + "jest-regex-util": "^29.6.3", + "jest-resolve": "^29.7.0", + "jest-snapshot": "^29.7.0", + "jest-util": "^29.7.0", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-runtime/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/jest-runtime/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-runtime/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/jest-snapshot": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", + "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.7.0", + "@jest/transform": "^29.7.0", + "@jest/types": "^29.6.3", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.7.0", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.7.0", + "jest-get-type": "^29.6.3", + "jest-matcher-utils": "^29.7.0", + "jest-message-util": "^29.7.0", + "jest-util": "^29.7.0", + "natural-compare": "^1.4.0", + "pretty-format": "^29.7.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-util/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/jest-validate": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", + "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-watcher": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", + "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/test-result": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.7.0", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", + "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-ref-resolver": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-1.0.1.tgz", + "integrity": "sha512-EJAj1pgHc1hxF6vo2Z3s69fMjO1INq6eGHXZ8Z6wCQeldCuwxGK9Sxf4/cScGn3FZubCVUehfWtcDM/PLteCQw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.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/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "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.2.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.1.tgz", + "integrity": "sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "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.3.0", + "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.3.0.tgz", + "integrity": "sha512-bWTAPJmeWQH5suJNYwG0f5cs0p6ho9e6f1Ppoxv5qMosY+s9Ir2+ZLvvHcgA7VTDop4zl/NCHhOVVqU+kd++Ow==", + "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/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/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/loader-runner": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.2.tgz", + "integrity": "sha512-DFEqQ3ihfS9blba08cLfYf1NRAIEm+dDjic073DRDc3/JspI/8wYmtDsHwd3+4hwvdxSK7PGaElfTmm0awWJ4w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.11.5" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "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/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "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/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.30.8", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.8.tgz", + "integrity": "sha512-ISQTe55T2ao7XtlAStud6qwYPZjE4GK1S/BeVPus4jrq6JuOnQ00YKQC581RWhR122W7msZV263KzVeLoqidyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "engines": { + "node": ">=12" + } + }, + "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/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true, + "license": "ISC" + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/memfs": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/memfs/-/memfs-3.5.3.tgz", + "integrity": "sha512-UERzLsxzllchadvbPs5aolHh65ISpKpM+ccLbOJ8/vvpBKmAWf+la7dXFy7Mr0ySHbdHrFv5kGFCUHHe6GFEmw==", + "dev": true, + "license": "Unlicense", + "dependencies": { + "fs-monkey": "^1.0.4" + }, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "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/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "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.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/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/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/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/minimizer-webpack-plugin": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.11.0.tgz", + "integrity": "sha512-2JVy2DY+iBtfRyrQB5cRM7lfurnJIi6jFTgLip/7FxDu0WxswrIRzr4fBySQ0X7HqM7BcwE28zm+HfQ5V6y4Cg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "jest-worker": "^27.4.5", + "schema-utils": "^4.3.3", + "terser": "^5.51.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@minify-html/node": { + "optional": true + }, + "@napi-rs/image": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "@swc/html": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "cssnano": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "html-minifier-terser": { + "optional": true + }, + "imagemin": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "postcss": { + "optional": true + }, + "sharp": { + "optional": true + }, + "svgo": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/minimizer-webpack-plugin/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==", + "dev": true, + "license": "MIT", + "peer": true, + "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/minimizer-webpack-plugin/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==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/minimizer-webpack-plugin/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==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/minimizer-webpack-plugin/node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/minimizer-webpack-plugin/node_modules/schema-utils": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.5.0.tgz", + "integrity": "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/minimizer-webpack-plugin/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mnemonist": { + "version": "0.39.6", + "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.39.6.tgz", + "integrity": "sha512-A/0v5Z59y63US00cRSLiloEIw3t5G+MiKz4BhX21FI+YBJXBOGW0ohFxTxO08dsOYlzxo87T7vGfZKYp2bcAWA==", + "license": "MIT", + "dependencies": { + "obliterator": "^2.0.1" + } + }, + "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/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/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-abort-controller": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz", + "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==", + "dev": true, + "license": "MIT" + }, + "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": "1.11.0", + "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz", + "integrity": "sha512-wo2DpQkQp7Sjm2A0cq+sN7EHKO6Sl0ctXeBdFZrL9T9+UywORbufTcTZxom8YqpLQt/FqNMUkOpkZrJVYSKD3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash": "^4.17.21" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "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/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.56", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.56.tgz", + "integrity": "sha512-x0InOIyzgdk+eyaWaRJFH5snEtiImgBgblZ2CyPrLmqqcuMQkEvcDPHbzqbD8eDsSeJbVOjn+crzyzHaM4D+/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obliterator": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz", + "integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==", + "license": "MIT" + }, + "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/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "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/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "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/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/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "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-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/path-to-regexp": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz", + "integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==", + "license": "MIT" + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "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.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.1.tgz", + "integrity": "sha512-xUXwsxNjwTQ8K3GnT4pCJm+xq3RUPQbmkYJTP5aFIfNIvbcc/4MUxgBaaRSZJ6yGJZiGSyYlM6MzwTsRk8SYCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pino": { + "version": "9.14.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", + "integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.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": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "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/pino/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/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pkg-dir/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/pkg-dir/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "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/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prisma": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.1.0.tgz", + "integrity": "sha512-aFI3Yi+ApUxkwCJJwyQSwpyzUX7YX3ihzuHNHOyv4GJg3X5tQsmRaJEnZ+ZyfHpMtnyahhmXVfbTZ+lS8ZtfKw==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/engines": "6.1.0" + }, + "bin": { + "prisma": "build/index.js" + }, + "engines": { + "node": ">=18.18" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + } + }, + "node_modules/process-warning": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz", + "integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==", + "license": "MIT" + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "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/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "dev": true, + "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/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "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/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/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "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": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "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-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "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/repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.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/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-cwd/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.3.tgz", + "integrity": "sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "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.4.3", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.4.3.tgz", + "integrity": "sha512-0f4Memo5QP7WQyUEAYUO3esD/XjOc3Zjjg5CPsAq1p8sIu0XPeMbHJemKA0BO7tV0X7+A0FoEpbmHXWxPyD3wQ==", + "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/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "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/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "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": { + "queue-microtask": "^1.2.2" + } + }, + "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==", + "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": "3.1.0", + "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-3.1.0.tgz", + "integrity": "sha512-RAAZAGbap2kBfbVhvmnTFv73NWLMvDGOITFYTZBAaY8eR+Ir4ef7Up/e7amo+y1+AH+3PtLkrt9mvcTsG9LXug==", + "license": "MIT", + "dependencies": { + "ret": "~0.4.0" + } + }, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/schema-utils": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-3.3.0.tgz", + "integrity": "sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.8", + "ajv": "^6.12.5", + "ajv-keywords": "^3.5.2" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/schema-utils/node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/schema-utils/node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/schema-utils/node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "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/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/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "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.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/simple-swizzle/node_modules/is-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", + "license": "MIT" + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "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.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.4.tgz", + "integrity": "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 8" + } + }, + "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/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "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==", + "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/string-width-cjs": { + "name": "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==", + "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==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "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==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/swagger-ui-dist": { + "version": "5.17.14", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.17.14.tgz", + "integrity": "sha512-CVbSfaLpstV65OnSjbXfVd6Sta3q3F7Cj/yYuvHMp1P90LztOLs6PfUnKEVAeiIVQt9u2SaPwv0LiH/OyMjHRw==", + "license": "Apache-2.0" + }, + "node_modules/symbol-observable": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-4.0.0.tgz", + "integrity": "sha512-b19dMThMV4HVFynSAM1++gBHAbk2Tc/osgLIBZMKsyqh34jb2e8Os7T6ZW/Bt3pJFdBTd2JwAnAAEQV7rSNvcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/terser": { + "version": "5.51.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", + "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.6.1.tgz", + "integrity": "sha512-201R5j+sJpK8nFWwKVyNfZot8FaJbLZDq5evriVzbV1wDtSXDjRUDRfJzHpAaxFDMEhsZL1QkeqM61wgsS3KaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "jest-worker": "^27.4.5", + "schema-utils": "^4.3.0", + "terser": "^5.31.1" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@minify-html/node": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "@swc/html": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "cssnano": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "html-minifier-terser": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "postcss": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/terser-webpack-plugin/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==", + "dev": true, + "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/terser-webpack-plugin/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==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/terser-webpack-plugin/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==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/terser-webpack-plugin/node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/terser-webpack-plugin/node_modules/schema-utils": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.5.0.tgz", + "integrity": "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/terser-webpack-plugin/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/test-exclude/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/test-exclude/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/test-exclude/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/test-exclude/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", + "dev": true, + "license": "MIT" + }, + "node_modules/thread-stream": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz", + "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "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/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/tinyglobby/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/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/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.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/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ts-jest": { + "version": "29.4.12", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.12.tgz", + "integrity": "sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bs-logger": "^0.2.6", + "fast-json-stable-stringify": "^2.1.0", + "handlebars": "^4.7.9", + "json5": "^2.2.3", + "lodash.memoize": "^4.1.2", + "make-error": "^1.3.6", + "semver": "^7.8.5", + "type-fest": "^4.41.0", + "yargs-parser": "^21.1.1" + }, + "bin": { + "ts-jest": "cli.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0-beta.0 <8", + "@jest/transform": "^29.0.0 || ^30.0.0", + "@jest/types": "^29.0.0 || ^30.0.0", + "babel-jest": "^29.0.0 || ^30.0.0", + "jest": "^29.0.0 || ^30.0.0", + "jest-util": "^29.0.0 || ^30.0.0", + "typescript": ">=4.3 <7" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@jest/transform": { + "optional": true + }, + "@jest/types": { + "optional": true + }, + "babel-jest": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jest-util": { + "optional": true + } + } + }, + "node_modules/ts-jest/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ts-loader": { + "version": "9.6.2", + "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-9.6.2.tgz", + "integrity": "sha512-R4iuczmtgxvtuI556s+hTZ6/7Ee03VCAk/l/M8LY1OAsUgB7YydsCxkgq9D9pKRaD7GJqUi2u8fp9zZP/ufjKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "picomatch": "^4.0.0", + "source-map": "^0.7.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "loader-utils": "*", + "typescript": "*", + "webpack": "^4.0.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "loader-utils": { + "optional": true + } + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "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/tsconfig-paths-webpack-plugin": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths-webpack-plugin/-/tsconfig-paths-webpack-plugin-4.2.0.tgz", + "integrity": "sha512-zbem3rfRS8BgeNK50Zz5SIQgXzLafiHjOwUAvk/38/o1jHn/V5QAgVUcz884or7WYcPaH3N2CIfUc2u0ul7UcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "enhanced-resolve": "^5.7.0", + "tapable": "^2.2.1", + "tsconfig-paths": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/tsconfig-paths/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/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/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "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-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", + "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "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/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true, + "license": "MIT" + }, + "node_modules/v8-to-istanbul": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", + "dev": true, + "license": "ISC", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^2.0.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "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/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/watchpack": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.2.tgz", + "integrity": "sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "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/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/webpack": { + "version": "5.111.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.111.1.tgz", + "integrity": "sha512-cNypaz0RP+S4cvQVi1M/3bRUkvNP0xZpL0TjFx+c6jg64VbxD+2weWDgY9UnjRI6dhZgtaj8DU76GGFcJ79xPQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/estree": "^1.0.8", + "@types/json-schema": "^7.0.15", + "@webassemblyjs/ast": "^1.14.1", + "@webassemblyjs/wasm-edit": "^1.14.1", + "@webassemblyjs/wasm-parser": "^1.14.1", + "browserslist": "^4.28.1", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.25.0", + "es-module-lexer": "^2.1.0", + "events": "^3.2.0", + "graceful-fs": "^4.2.11", + "mime-db": "^1.54.0", + "minimizer-webpack-plugin": "^5.7.0", + "schema-utils": "^4.5.0", + "tapable": "^2.3.0", + "watchpack": "^2.5.2", + "webpack-sources": "^3.5.1" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-node-externals": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/webpack-node-externals/-/webpack-node-externals-3.0.0.tgz", + "integrity": "sha512-LnL6Z3GGDPht/AigwRh2dvL9PQPFQ8skEpVrWZXLWBYmqcaojHNN0onvHzie6rq7EWKrrBfPYqNEzTJgiwEQDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/webpack-sources": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz", + "integrity": "sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/webpack/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==", + "dev": true, + "license": "MIT", + "peer": true, + "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/webpack/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==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/webpack/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==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause", + "peer": true + }, + "node_modules/webpack/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==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack/node_modules/schema-utils": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.5.0.tgz", + "integrity": "sha512-zJlMCZ0cAR5p/Y4oVpRoqioDMJcGxaXRrQ/4rP4WyR84vc5z/DolXdbvXeDpTwbtocDFr2rhPqHPErDCUtz2kA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "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/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "dev": true, + "license": "MIT" + }, + "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/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "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==", + "dev": true, + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "dev": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/write-file-atomic/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/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..b392238 --- /dev/null +++ b/package.json @@ -0,0 +1,54 @@ +{ + "name": "mtusi-messenger-lab6", + "version": "1.0.0", + "description": "Lab 6: messenger API with S3 attachments and background image processing (NestJS + Fastify)", + "private": true, + "license": "UNLICENSED", + "scripts": { + "build": "nest build", + "start": "node dist/main.js", + "start:dev": "nest start --watch", + "lint": "eslint \"{src,test}/**/*.ts\"", + "test": "jest --config ./test/jest-e2e.json", + "test:watch": "jest --config ./test/jest-e2e.json --watch" + }, + "dependencies": { + "@aws-sdk/client-s3": "3.700.0", + "@fastify/static": "7.0.4", + "@nestjs/common": "^10.4.15", + "@nestjs/core": "^10.4.15", + "@nestjs/platform-fastify": "^10.4.15", + "@nestjs/swagger": "7.4.2", + "@prisma/client": "6.1.0", + "amqplib": "0.10.5", + "argon2": "0.41.1", + "class-transformer": "^0.5.1", + "class-validator": "^0.14.1", + "ioredis": "5.4.1", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "sharp": "0.33.5" + }, + "devDependencies": { + "@nestjs/cli": "^10.4.9", + "@nestjs/schematics": "^10.2.3", + "@nestjs/testing": "^10.4.15", + "@types/amqplib": "0.10.6", + "@types/jest": "^29.5.14", + "@types/node": "^20.17.9", + "@types/supertest": "^6.0.2", + "@typescript-eslint/eslint-plugin": "^8.18.1", + "@typescript-eslint/parser": "^8.18.1", + "ajv": "8.12.0", + "eslint": "^8.57.1", + "jest": "^29.7.0", + "prisma": "6.1.0", + "source-map-support": "^0.5.21", + "supertest": "^7.0.0", + "ts-jest": "^29.2.5", + "ts-loader": "^9.5.1", + "ts-node": "^10.9.2", + "tsconfig-paths": "^4.2.0", + "typescript": "^5.7.2" + } +} diff --git a/prisma/migrations/20261021000000_init/migration.sql b/prisma/migrations/20261021000000_init/migration.sql new file mode 100644 index 0000000..89e61f4 --- /dev/null +++ b/prisma/migrations/20261021000000_init/migration.sql @@ -0,0 +1,50 @@ +CREATE TABLE "users" ( + "id" UUID NOT NULL, + "username" VARCHAR(32) NOT NULL, + "display_name" VARCHAR(100) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "users_pkey" PRIMARY KEY ("id"), + CONSTRAINT "users_username_format" CHECK ("username" ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT "users_display_name_not_blank" CHECK (btrim("display_name") <> '') +); + +CREATE TABLE "chats" ( + "id" UUID NOT NULL, + "title" VARCHAR(100) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "chats_pkey" PRIMARY KEY ("id"), + CONSTRAINT "chats_title_not_blank" CHECK (btrim("title") <> '') +); + +CREATE TABLE "chat_members" ( + "chat_id" UUID NOT NULL, + "user_id" UUID NOT NULL, + + CONSTRAINT "chat_members_pkey" PRIMARY KEY ("chat_id","user_id") +); + +CREATE TABLE "messages" ( + "id" UUID NOT NULL, + "chat_id" UUID NOT NULL, + "sender_id" UUID NOT NULL, + "text" VARCHAR(4000) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "messages_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "users_username_key" ON "users"("username"); + +CREATE INDEX "chat_members_user_id_idx" ON "chat_members"("user_id"); + +CREATE INDEX "messages_chat_id_created_at_id_idx" ON "messages"("chat_id", "created_at", "id"); + +ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "chat_members" ADD CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE "messages" ADD CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY ("sender_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/prisma/migrations/20261021010000_auth_sessions/migration.sql b/prisma/migrations/20261021010000_auth_sessions/migration.sql new file mode 100644 index 0000000..f719e13 --- /dev/null +++ b/prisma/migrations/20261021010000_auth_sessions/migration.sql @@ -0,0 +1,14 @@ +ALTER TABLE "users" ADD COLUMN "password_hash" TEXT NOT NULL; + +CREATE TABLE "sessions" ( + "token_hash" CHAR(64) NOT NULL, + "user_id" UUID NOT NULL, + "expires_at" TIMESTAMPTZ(3) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "sessions_pkey" PRIMARY KEY ("token_hash") +); + +CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id"); + +ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/20261101000000_idempotency_keys/migration.sql b/prisma/migrations/20261101000000_idempotency_keys/migration.sql new file mode 100644 index 0000000..6d141b1 --- /dev/null +++ b/prisma/migrations/20261101000000_idempotency_keys/migration.sql @@ -0,0 +1,13 @@ +CREATE TABLE "idempotency_keys" ( + "user_id" UUID NOT NULL, + "chat_id" UUID NOT NULL, + "key" VARCHAR(128) NOT NULL, + "request_hash" CHAR(64) NOT NULL, + "message_id" UUID NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "idempotency_keys_pkey" PRIMARY KEY ("user_id","chat_id","key"), + CONSTRAINT "idempotency_keys_key_format" CHECK ("key" ~ '^[A-Za-z0-9._:-]{1,128}$') +); + +ALTER TABLE "idempotency_keys" ADD CONSTRAINT "idempotency_keys_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/20261105000000_attachments/migration.sql b/prisma/migrations/20261105000000_attachments/migration.sql new file mode 100644 index 0000000..a90a492 --- /dev/null +++ b/prisma/migrations/20261105000000_attachments/migration.sql @@ -0,0 +1,45 @@ +CREATE TABLE "attachments" ( + "id" UUID NOT NULL, + "chat_id" UUID NOT NULL, + "owner_id" UUID NOT NULL, + "filename" VARCHAR(255) NOT NULL, + "content_type" VARCHAR(32) NOT NULL, + "size_bytes" INTEGER NOT NULL, + "sha256" CHAR(64) NOT NULL, + "object_key" VARCHAR(128) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "attachments_pkey" PRIMARY KEY ("id"), + CONSTRAINT "attachments_filename_not_blank" CHECK (btrim("filename") <> ''), + CONSTRAINT "attachments_content_type_allowed" CHECK ("content_type" IN ('image/png', 'image/jpeg')), + CONSTRAINT "attachments_size_range" CHECK ("size_bytes" BETWEEN 1 AND 10485760), + CONSTRAINT "attachments_sha256_format" CHECK ("sha256" ~ '^[a-f0-9]{64}$') +); + +CREATE TABLE "message_attachments" ( + "message_id" UUID NOT NULL, + "position" SMALLINT NOT NULL, + "attachment_id" UUID NOT NULL, + + CONSTRAINT "message_attachments_pkey" PRIMARY KEY ("message_id","position"), + CONSTRAINT "message_attachments_position_range" CHECK ("position" BETWEEN 0 AND 9) +); + +CREATE UNIQUE INDEX "attachments_object_key_key" ON "attachments"("object_key"); + +CREATE INDEX "attachments_chat_id_idx" ON "attachments"("chat_id"); + +CREATE INDEX "attachments_owner_id_idx" ON "attachments"("owner_id"); + +CREATE UNIQUE INDEX "message_attachments_message_id_attachment_id_key" ON "message_attachments"("message_id", "attachment_id"); + +CREATE INDEX "message_attachments_attachment_id_idx" ON "message_attachments"("attachment_id"); + +ALTER TABLE "attachments" ADD CONSTRAINT "attachments_chat_id_fkey" FOREIGN KEY ("chat_id") REFERENCES "chats"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "attachments" ADD CONSTRAINT "attachments_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE "message_attachments" ADD CONSTRAINT "message_attachments_message_id_fkey" FOREIGN KEY ("message_id") REFERENCES "messages"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "message_attachments" ADD CONSTRAINT "message_attachments_attachment_id_fkey" FOREIGN KEY ("attachment_id") REFERENCES "attachments"("id") ON DELETE NO ACTION ON UPDATE CASCADE; diff --git a/prisma/migrations/20261115000000_attachment_jobs/migration.sql b/prisma/migrations/20261115000000_attachment_jobs/migration.sql new file mode 100644 index 0000000..1abbf3d --- /dev/null +++ b/prisma/migrations/20261115000000_attachment_jobs/migration.sql @@ -0,0 +1,97 @@ +ALTER TABLE "attachments" + ADD COLUMN "staging_key" VARCHAR(128), + ADD COLUMN "status" VARCHAR(16) NOT NULL DEFAULT 'ready', + ADD COLUMN "error_code" VARCHAR(64); + +ALTER TABLE "attachments" ALTER COLUMN "status" DROP DEFAULT; + +ALTER TABLE "attachments" + ADD CONSTRAINT "attachments_status_allowed" CHECK ("status" IN ('queued', 'processing', 'ready', 'failed')), + ADD CONSTRAINT "attachments_error_code_when_failed" CHECK (("status" = 'failed') = ("error_code" IS NOT NULL)); + +CREATE UNIQUE INDEX "attachments_staging_key_key" ON "attachments"("staging_key"); + +CREATE TABLE "attachment_variants" ( + "attachment_id" UUID NOT NULL, + "pipeline_version" INTEGER NOT NULL, + "name" VARCHAR(16) NOT NULL, + "content_type" VARCHAR(32) NOT NULL, + "object_key" VARCHAR(128) NOT NULL, + "size_bytes" INTEGER NOT NULL, + "width" INTEGER NOT NULL, + "height" INTEGER NOT NULL, + "sha256" CHAR(64) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "attachment_variants_pkey" PRIMARY KEY ("attachment_id","pipeline_version","name"), + CONSTRAINT "attachment_variants_name_allowed" CHECK ("name" IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT "attachment_variants_content_type_allowed" CHECK ("content_type" IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT "attachment_variants_positive" CHECK ("pipeline_version" >= 1 AND "size_bytes" >= 1 AND "width" >= 1 AND "height" >= 1), + CONSTRAINT "attachment_variants_sha256_format" CHECK ("sha256" ~ '^[a-f0-9]{64}$') +); + +CREATE TABLE "attachment_jobs" ( + "id" UUID NOT NULL, + "attachment_id" UUID NOT NULL, + "pipeline_version" INTEGER NOT NULL, + "status" VARCHAR(16) NOT NULL, + "attempt" INTEGER NOT NULL, + "max_attempts" INTEGER NOT NULL, + "next_attempt_at" TIMESTAMPTZ(3) NOT NULL, + "lease_owner" UUID, + "lease_until" TIMESTAMPTZ(3), + "error_code" VARCHAR(64), + "last_error" VARCHAR(200), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "finished_at" TIMESTAMPTZ(3), + + CONSTRAINT "attachment_jobs_pkey" PRIMARY KEY ("id"), + CONSTRAINT "attachment_jobs_status_allowed" CHECK ("status" IN ('queued', 'processing', 'ready', 'failed')), + CONSTRAINT "attachment_jobs_attempt_range" CHECK ("pipeline_version" >= 1 AND "attempt" >= 1 AND "attempt" <= "max_attempts"), + CONSTRAINT "attachment_jobs_lease_when_processing" CHECK ("status" <> 'processing' OR ("lease_owner" IS NOT NULL AND "lease_until" IS NOT NULL)), + CONSTRAINT "attachment_jobs_error_code_when_failed" CHECK (("status" = 'failed') = ("error_code" IS NOT NULL)) +); + +CREATE TABLE "job_events" ( + "id" BIGSERIAL NOT NULL, + "job_id" UUID NOT NULL, + "attempt" INTEGER NOT NULL, + "event" VARCHAR(32) NOT NULL, + "detail" VARCHAR(200), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "job_events_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "outbox" ( + "id" BIGSERIAL NOT NULL, + "job_id" UUID NOT NULL, + "payload" JSONB NOT NULL, + "available_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "published_at" TIMESTAMPTZ(3), + "publish_attempts" INTEGER NOT NULL DEFAULT 0, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "outbox_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "attachment_variants_object_key_key" ON "attachment_variants"("object_key"); + +CREATE UNIQUE INDEX "attachment_jobs_attachment_id_pipeline_version_key" ON "attachment_jobs"("attachment_id", "pipeline_version"); + +CREATE INDEX "attachment_jobs_status_lease_until_idx" ON "attachment_jobs"("status", "lease_until"); + +CREATE INDEX "job_events_job_id_idx" ON "job_events"("job_id"); + +CREATE INDEX "outbox_published_at_available_at_idx" ON "outbox"("published_at", "available_at"); + +CREATE INDEX "outbox_job_id_idx" ON "outbox"("job_id"); + +ALTER TABLE "attachment_variants" ADD CONSTRAINT "attachment_variants_attachment_id_fkey" FOREIGN KEY ("attachment_id") REFERENCES "attachments"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "attachment_jobs" ADD CONSTRAINT "attachment_jobs_attachment_id_fkey" FOREIGN KEY ("attachment_id") REFERENCES "attachments"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "job_events" ADD CONSTRAINT "job_events_job_id_fkey" FOREIGN KEY ("job_id") REFERENCES "attachment_jobs"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "outbox" ADD CONSTRAINT "outbox_job_id_fkey" FOREIGN KEY ("job_id") REFERENCES "attachment_jobs"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..99e4f20 --- /dev/null +++ b/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (i.e. Git) +provider = "postgresql" diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 0000000..2942712 --- /dev/null +++ b/prisma/schema.prisma @@ -0,0 +1,190 @@ +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model User { + id String @id @default(uuid()) @db.Uuid + username String @unique @db.VarChar(32) + displayName String @map("display_name") @db.VarChar(100) + passwordHash String @map("password_hash") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + memberships ChatMember[] + messages Message[] + sessions Session[] + attachments Attachment[] + + @@map("users") +} + +model Session { + tokenHash String @id @map("token_hash") @db.Char(64) + userId String @map("user_id") @db.Uuid + expiresAt DateTime @map("expires_at") @db.Timestamptz(3) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@index([userId]) + @@map("sessions") +} + +model Chat { + id String @id @default(uuid()) @db.Uuid + title String @db.VarChar(100) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + members ChatMember[] + messages Message[] + attachments Attachment[] + + @@map("chats") +} + +model ChatMember { + chatId String @map("chat_id") @db.Uuid + userId String @map("user_id") @db.Uuid + chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Restrict) + + @@id([chatId, userId]) + @@index([userId]) + @@map("chat_members") +} + +model Message { + id String @id @default(uuid()) @db.Uuid + chatId String @map("chat_id") @db.Uuid + senderId String @map("sender_id") @db.Uuid + text String @db.VarChar(4000) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade) + sender User @relation(fields: [senderId], references: [id], onDelete: Restrict) + idempotencyKeys IdempotencyKey[] + attachments MessageAttachment[] + + @@index([chatId, createdAt, id]) + @@map("messages") +} + +model Attachment { + id String @id @default(uuid()) @db.Uuid + chatId String @map("chat_id") @db.Uuid + ownerId String @map("owner_id") @db.Uuid + filename String @db.VarChar(255) + contentType String @map("content_type") @db.VarChar(32) + sizeBytes Int @map("size_bytes") + sha256 String @db.Char(64) + objectKey String @unique @map("object_key") @db.VarChar(128) + stagingKey String? @unique @map("staging_key") @db.VarChar(128) + status String @db.VarChar(16) + errorCode String? @map("error_code") @db.VarChar(64) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + chat Chat @relation(fields: [chatId], references: [id], onDelete: Cascade) + owner User @relation(fields: [ownerId], references: [id], onDelete: Restrict) + messages MessageAttachment[] + variants AttachmentVariant[] + jobs AttachmentJob[] + + @@index([chatId]) + @@index([ownerId]) + @@map("attachments") +} + +model AttachmentVariant { + attachmentId String @map("attachment_id") @db.Uuid + pipelineVersion Int @map("pipeline_version") + name String @db.VarChar(16) + contentType String @map("content_type") @db.VarChar(32) + objectKey String @unique @map("object_key") @db.VarChar(128) + sizeBytes Int @map("size_bytes") + width Int + height Int + sha256 String @db.Char(64) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + attachment Attachment @relation(fields: [attachmentId], references: [id], onDelete: Cascade) + + @@id([attachmentId, pipelineVersion, name]) + @@map("attachment_variants") +} + +model AttachmentJob { + id String @id @db.Uuid + attachmentId String @map("attachment_id") @db.Uuid + pipelineVersion Int @map("pipeline_version") + status String @db.VarChar(16) + attempt Int + maxAttempts Int @map("max_attempts") + nextAttemptAt DateTime @map("next_attempt_at") @db.Timestamptz(3) + leaseOwner String? @map("lease_owner") @db.Uuid + leaseUntil DateTime? @map("lease_until") @db.Timestamptz(3) + errorCode String? @map("error_code") @db.VarChar(64) + lastError String? @map("last_error") @db.VarChar(200) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + finishedAt DateTime? @map("finished_at") @db.Timestamptz(3) + attachment Attachment @relation(fields: [attachmentId], references: [id], onDelete: Cascade) + events JobEvent[] + outbox OutboxEntry[] + + @@unique([attachmentId, pipelineVersion]) + @@index([status, leaseUntil]) + @@map("attachment_jobs") +} + +model JobEvent { + id BigInt @id @default(autoincrement()) + jobId String @map("job_id") @db.Uuid + attempt Int + event String @db.VarChar(32) + detail String? @db.VarChar(200) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + job AttachmentJob @relation(fields: [jobId], references: [id], onDelete: Cascade) + + @@index([jobId]) + @@map("job_events") +} + +model OutboxEntry { + id BigInt @id @default(autoincrement()) + jobId String @map("job_id") @db.Uuid + payload Json + availableAt DateTime @default(now()) @map("available_at") @db.Timestamptz(3) + publishedAt DateTime? @map("published_at") @db.Timestamptz(3) + publishAttempts Int @default(0) @map("publish_attempts") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + job AttachmentJob @relation(fields: [jobId], references: [id], onDelete: Cascade) + + @@index([publishedAt, availableAt]) + @@index([jobId]) + @@map("outbox") +} + +model MessageAttachment { + messageId String @map("message_id") @db.Uuid + position Int @db.SmallInt + attachmentId String @map("attachment_id") @db.Uuid + message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + attachment Attachment @relation(fields: [attachmentId], references: [id], onDelete: NoAction) + + @@id([messageId, position]) + @@unique([messageId, attachmentId]) + @@index([attachmentId]) + @@map("message_attachments") +} + +model IdempotencyKey { + userId String @map("user_id") @db.Uuid + chatId String @map("chat_id") @db.Uuid + key String @db.VarChar(128) + requestHash String @map("request_hash") @db.Char(64) + messageId String @map("message_id") @db.Uuid + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + + @@id([userId, chatId, key]) + @@map("idempotency_keys") +} diff --git a/scripts/check-s3-anonymous.py b/scripts/check-s3-anonymous.py new file mode 100755 index 0000000..636f406 --- /dev/null +++ b/scripts/check-s3-anonymous.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +import sys +import urllib.error +import urllib.request + +bucket, key = sys.argv[1:3] +base = 'http://s3:9000/' + bucket +attempts = ( + ('GET', '/', base + '/' + key, None), + ('GET', '/', base + '/', None), + ('PUT', '/anon.txt', base + '/anon.txt', b'x'), +) +failed = False +for method, label, url, data in attempts: + try: + code = urllib.request.urlopen(urllib.request.Request(url, data=data, method=method), timeout=5).status + except urllib.error.HTTPError as error: + code = error.code + print(method, bucket + label, '->', code) + failed = failed or code != 403 +sys.exit(1 if failed else 0) diff --git a/scripts/check-s3.sh b/scripts/check-s3.sh new file mode 100755 index 0000000..d6fd983 --- /dev/null +++ b/scripts/check-s3.sh @@ -0,0 +1,46 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +bucket="${S3_BUCKET:-messenger-attachments}" +object="check/$(date +%s)-$$.txt" + +as_api() { + docker compose run --rm --no-deps -T -e BUCKET="$bucket" -e OBJECT="$object" --entrypoint sh s3-init -c "$1" +} + +echo "## S3 не опубликован наружу, консоль выключена" +docker compose ps s3 --format '{{.Service}} ports={{.Ports}}' +echo "MINIO_BROWSER=$(docker compose exec -T s3 printenv MINIO_BROWSER)" + +echo +echo "## Права пользователя API: только свой bucket" +as_api ' +set -e +cd /run/secrets +export MC_HOST_api="http://$(cat s3_access_key_id):$(cat s3_secret_access_key)@s3:9000" +export MC_HOST_root="http://$(cat s3_root_user):$(cat s3_root_password)@s3:9000" +expect() { want=$1; label=$2; shift 2; if "$@" >/dev/null 2>&1; then got=allowed; else got=denied; fi; echo "$label -> $got"; [ "$got" = "$want" ]; } +echo probe > /tmp/probe.txt +mc mb --ignore-existing root/check-other-bucket >/dev/null +mc cp /tmp/probe.txt root/check-other-bucket/probe.txt >/dev/null +trap "mc rb --force root/check-other-bucket >/dev/null" EXIT +expect allowed "PUT в свой bucket" mc cp /tmp/probe.txt "api/$BUCKET/$OBJECT" +expect allowed "GET из своего bucket" mc cat "api/$BUCKET/$OBJECT" +expect denied "создание другого bucket" mc mb api/forbidden-bucket +expect denied "GET из другого bucket" mc cat api/check-other-bucket/probe.txt +expect denied "PUT в другой bucket" mc cp /tmp/probe.txt api/check-other-bucket/new.txt +expect denied "изменение политики bucket" mc anonymous set public "api/$BUCKET" +expect denied "администрирование пользователей" mc admin user list api +' + +echo +echo "## Анонимный доступ напрямую к S3, мимо API" +python3 scripts/check-s3-anonymous.py "$bucket" "$object" + +as_api ' +cd /run/secrets +export MC_HOST_api="http://$(cat s3_access_key_id):$(cat s3_secret_access_key)@s3:9000" +mc rm "api/$BUCKET/$OBJECT" >/dev/null +' +echo +echo "PASS: bucket приватный, у API нет прав вне своего bucket" diff --git a/scripts/collect-evidence.sh b/scripts/collect-evidence.sh new file mode 100755 index 0000000..20da164 --- /dev/null +++ b/scripts/collect-evidence.sh @@ -0,0 +1,123 @@ +#!/bin/sh +set -u +cd "$(dirname "$0")/.." +mkdir -p evidence + +COMMIT="$(git rev-parse --short HEAD)$(git diff --quiet HEAD -- src prisma test scripts infra compose.yaml Dockerfile || echo ' (dirty)')" + +header() { + printf '# %s\n# date: %s\n# commit: %s\n\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$COMMIT" +} + +run() { + echo "\$ $*" + "$@" 2>&1 || echo "EXIT CODE $?" + echo +} + +started() { + docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis s3 rabbitmq api lb) +} + +api_states() { + docker inspect -f '{{.Name}} id={{slice .Id 0 12}} {{.State.Status}} exit={{.State.ExitCode}} finished={{.State.FinishedAt}}' $(docker compose ps -aq api) +} + +restore_api() { + for id in $(docker compose ps -aq --status exited api); do + docker start "$id" >/dev/null + done + python3 scripts/probe.py ready >/dev/null + sleep 3 +} + +echo 'container.txt' +{ + header 'Стенд: сервисы, порты, лимиты, секреты, миграции, топология брокера' + run docker compose ps -a --format 'table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' + echo '## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)' + run sh -c "docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' \$(docker compose ps -aq)" + echo '## Секреты: каждый сервис видит только свои файлы (содержимое не выводится)' + for service in postgres redis s3 api reconciler relay worker; do + run docker compose exec -T "$service" ls /run/secrets + done + run docker compose exec -T rabbitmq ls /etc/rabbitmq/conf.d + run docker compose exec -T lb sh -c 'ls /run/secrets 2>/dev/null || echo "no /run/secrets"' + echo '## Версии' + run docker compose exec -T lb haproxy -v + run docker compose exec -T postgres postgres --version + run docker compose exec -T redis redis-server --version + run docker compose exec -T s3 minio --version + run docker compose exec -T rabbitmq rabbitmqctl -q version + echo '## Топология брокера: durable quorum-очереди, delivery-limit и DLQ' + run docker compose exec -T rabbitmq rabbitmqctl -q list_queues name type durable arguments messages + run docker compose exec -T rabbitmq rabbitmqctl -q list_consumers queue_name prefetch_count ack_required + echo '## Таблицы' + run docker compose exec -T postgres psql -U messenger -d messenger -c '\d attachments' -c '\d attachment_variants' -c '\d attachment_jobs' -c '\d outbox' -c '\d job_events' + echo '## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет, схема совпадает с БД' + run docker compose run --rm migrate + run docker compose run --rm --no-deps migrate sh -c 'export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code' + run docker compose exec -T postgres psql -U messenger -d messenger -c 'SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at' +} > evidence/container.txt + +echo 'tests.txt' +{ + header 'Собственные e2e-тесты (PostgreSQL + Redis + MinIO из compose.test.yaml)' + docker compose -f compose.test.yaml build -q tests + run docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose + docker compose -f compose.test.yaml down -v >/dev/null 2>&1 +} > evidence/tests.txt + +echo 'smoke.txt' +{ + header 'Публичные проверки через LB; разные реплики обслуживают одну сессию' + run make check + run make test + run python3 scripts/probe.py instances 6 +} > evidence/smoke.txt + +echo 'persistence.txt' +{ + header 'make test-persistence: restart.sh перезапускает postgres, redis, s3, rabbitmq, api, lb с сохранением volumes' + echo '## до' + started + echo + run make test-persistence ACTION_SCRIPT=scripts/restart.sh + echo '## после' + started +} > evidence/persistence.txt + +echo 'failover.txt' +{ + header 'make test-failover: stop-one.sh останавливает реплику, обслужившую тест' + echo '## до' + api_states + echo + run make test-failover ACTION_SCRIPT=scripts/stop-one.sh + echo '## после: остановленная реплика Exited (0) — штатное завершение по SIGTERM' + api_states + restore_api +} > evidence/failover.txt + +echo 's3.txt' +{ + header 'S3 (минимум lab4): идемпотентный bootstrap, приватность мимо API, права пользователя API' + run docker compose run --rm --no-deps -T s3-init + run docker compose run --rm --no-deps -T s3-init + run sh scripts/check-s3.sh +} > evidence/s3.txt + +echo 'jobs.txt' +{ + header 'Фоновая обработка: сценарии защиты уровней 3 и 4 (scripts/job-scenario.py)' + for scenario in restart crash-after-store crash-after-commit outbox-gap relay-crash retry-replay broker; do + echo "## $scenario" + run python3 scripts/job-scenario.py "$scenario" + done + echo '## Итог по всем заданиям стенда' + run docker compose exec -T postgres psql -U messenger -d messenger -c 'SELECT status, count(*) FROM attachment_jobs GROUP BY status' -c 'SELECT count(*) AS unpublished_outbox FROM outbox WHERE published_at IS NULL' -c 'SELECT count(*) AS staging_left_on_ready FROM attachments WHERE status = '"'ready'"' AND staging_key IS NOT NULL' + echo '## Последний проход reconciler' + docker compose logs --no-log-prefix --tail 1 reconciler 2>&1 +} > evidence/jobs.txt + +echo 'done' diff --git a/scripts/job-scenario.py b/scripts/job-scenario.py new file mode 100755 index 0000000..c0613e9 --- /dev/null +++ b/scripts/job-scenario.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""Defense scenarios for background attachment processing; run inside the tools container.""" +import atexit +import base64 +import hashlib +import json +import os +import re +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid + +BASE = os.environ.get('BASE_URL', 'http://localhost:8080') +SAMPLE = open(os.path.join(os.path.dirname(__file__), '..', 'tests', 'fixtures', 'sample.png'), 'rb').read() +STARTED = time.monotonic() +ANSI = re.compile(chr(27) + re.escape('[') + '[0-9;]*m') + + +def log(*parts): + print('[%6.1fs]' % (time.monotonic() - STARTED), *parts, flush=True) + + +def call(method, path, body=None, headers=None, raw=None): + data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) + all_headers = dict(headers or {}) + if body is not None: + all_headers['Content-Type'] = 'application/json' + request = urllib.request.Request(BASE + path, data=data, method=method, headers=all_headers) + try: + with urllib.request.urlopen(request, timeout=15) as response: + return response.status, response.read(), response.headers + except urllib.error.HTTPError as error: + return error.code, error.read(), error.headers + except OSError as error: + return 0, str(error).encode(), {} + + +def json_of(raw): + try: + return json.loads(raw or b'null') + except ValueError: + return None + + +def compose(*args): + log('$ docker compose', ' '.join(args)) + subprocess.run(['docker', 'compose', *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def start_only(service): + """docker compose start also starts dependencies (worker -> s3-init -> s3); start just this container.""" + log('$ docker start', service, '(without dependencies)') + ids = subprocess.run(['docker', 'compose', 'ps', '-aq', service], check=True, capture_output=True, text=True).stdout.split() + subprocess.run(['docker', 'start', *ids], check=True, stdout=subprocess.DEVNULL) + + +def psql(sql): + out = subprocess.run( + ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tA', '-F', ' | ', '-c', sql], + check=True, capture_output=True, text=True, + ) + return out.stdout.strip() + + +def queue_depth(): + time.sleep(6) + out = subprocess.run( + ['docker', 'compose', 'exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'type', 'durable', 'messages_ready', 'messages_unacknowledged'], + capture_output=True, text=True, + ) + return out.stdout.strip() or out.stderr.strip() + + +def wait_ready(timeout=90): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if call('GET', '/health/ready')[0] == 200: + return + time.sleep(1) + sys.exit('API did not become ready') + + +def session(): + username = 'job_' + uuid.uuid4().hex[:8] + password = 'Job-scenario-' + uuid.uuid4().hex + code, raw, _ = call('POST', '/api/v1/users', {'username': username, 'display_name': 'Job scenario', 'password': password}) + if code != 201: + sys.exit('register failed: %s' % code) + user = json_of(raw) + credential = base64.b64encode((username + ':' + password).encode()).decode() + code, raw, _ = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential}) + if code != 201: + sys.exit('login failed: %s' % code) + auth = {'Authorization': 'Bearer ' + json_of(raw)['token']} + code, raw, _ = call('POST', '/api/v1/chats', {'title': 'Job scenario', 'member_ids': [user['id']]}, auth) + if code != 201: + sys.exit('chat failed: %s' % code) + chat = json_of(raw)['id'] + log('user', user['id'], 'chat', chat) + return auth, chat + + +def upload(auth, chat, body=SAMPLE): + code, raw, headers = call( + 'POST', '/api/v1/chats/%s/attachments?filename=sample.png' % chat, + headers={**auth, 'Content-Type': 'image/png'}, raw=body, + ) + attachment = json_of(raw) + log('POST attachment ->', code, 'status=%s' % attachment.get('status'), 'id=%s' % attachment.get('id'), + 'instance=%s' % headers.get('X-Instance-Id')) + if code != 202: + sys.exit('upload failed') + return attachment['id'] + + +def message(auth, chat, text, attachments=()): + code, raw, _ = call( + 'POST', '/api/v1/chats/%s/messages' % chat, {'text': text, 'attachment_ids': list(attachments)}, + {**auth, 'Idempotency-Key': uuid.uuid4().hex}, + ) + log('POST message', 'with %d attachment(s)' % len(attachments), '->', code, 'id=%s' % (json_of(raw) or {}).get('id')) + return code + + +def metadata(auth, attachment): + code, raw, _ = call('GET', '/api/v1/attachments/' + attachment, headers=auth) + return code, json_of(raw) + + +def content_status(auth, attachment, variant='original'): + return call('GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment, variant), headers=auth)[0] + + +def wait_status(auth, attachment, wanted, timeout=150): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + code, meta = metadata(auth, attachment) + if code == 200 and meta['status'] != last: + last = meta['status'] + log('GET attachment -> status=%s error_code=%s' % (last, meta['error_code'])) + if code == 200 and meta['status'] in wanted: + return meta + time.sleep(1) + sys.exit('attachment did not reach %s' % '/'.join(wanted)) + + +def check_ready(auth, attachment, meta): + code, raw, _ = call('GET', '/api/v1/attachments/%s/content' % attachment, headers=auth) + log('original ->', code, 'sha256 matches upload:', code == 200 and hashlib.sha256(raw).hexdigest() == hashlib.sha256(SAMPLE).hexdigest()) + for variant in meta['variants']: + code, raw, headers = call('GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment, variant['name']), headers=auth) + log('%-9s -> %s %s %dx%d sha256 matches metadata: %s' % ( + variant['name'], code, headers.get('Content-Type'), variant['width'], variant['height'], + hashlib.sha256(raw).hexdigest() == variant['sha256'])) + + +def job_state(attachment): + log('job:', psql("SELECT id, status, attempt, max_attempts, error_code FROM attachment_jobs WHERE attachment_id = '%s'" % attachment)) + log('variants rows:', psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % attachment)) + log('events:', psql("SELECT string_agg(e.event, ' -> ' ORDER BY e.id) FROM job_events e JOIN attachment_jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment)) + + +def scenario_restart(): + """Level 3: worker down -> upload 202 -> restart API and broker -> worker up -> ready.""" + wait_ready() + auth, chat = session() + compose('stop', 'worker') + attachment = upload(auth, chat) + log('content while queued ->', content_status(auth, attachment)) + message(auth, chat, '', [attachment]) + message(auth, chat, 'other messages keep working') + log('queues:', queue_depth()) + compose('restart', 'api', 'rabbitmq') + wait_ready() + log('queues after broker restart:', queue_depth()) + log('status after restarts:', metadata(auth, attachment)[1]['status']) + compose('start', 'worker') + meta = wait_status(auth, attachment, ['ready', 'failed']) + check_ready(auth, attachment, meta) + job_state(attachment) + + +def remove_container(name): + subprocess.run(['docker', 'rm', '-f', name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def plain(line): + return ANSI.sub('', line).split('] ')[-1].strip() + + +def faulty(service, env): + """Run a one-off copy of the service with fault injection; no restart policy, so it dies once.""" + name = 'lab6-fault-%s-%s' % (service, uuid.uuid4().hex[:8]) + atexit.register(remove_container, name) + args = ['docker', 'compose', 'run', '-d', '--no-deps', '--name', name] + for key, value in env.items(): + args += ['-e', '%s=%s' % (key, value)] + log('$ docker compose run --no-deps', ' '.join('-e %s=%s' % item for item in env.items()), service) + subprocess.run(args + [service], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + if 'connected to broker' in subprocess.run(['docker', 'logs', name], capture_output=True, text=True).stdout: + return name + time.sleep(0.5) + sys.exit('%s with fault did not start' % service) + + +def wait_exit(name, timeout=90): + try: + code = subprocess.run(['docker', 'wait', name], capture_output=True, text=True, timeout=timeout).stdout.strip() + except subprocess.TimeoutExpired: + code = 'timeout' + for line in subprocess.run(['docker', 'logs', name], capture_output=True, text=True).stdout.splitlines(): + if 'fault injection' in line or 'published' in line or 'job ' in line: + log(' one-off:', plain(line)) + remove_container(name) + log('one-off process exit code', code, '(137 = killed without ack)') + + +def service_logs(service, since, needle): + out = subprocess.run(['docker', 'compose', 'logs', '--no-log-prefix', '--no-color', '--since', since, service], + capture_output=True, text=True).stdout + for line in out.splitlines(): + if needle in line: + log(' %s:' % service, plain(line)) + + +def utc_now(): + return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) + + +def staging_key(attachment): + return psql("SELECT coalesce(staging_key, 'NULL') FROM attachments WHERE id = '%s'" % attachment) + + +def job_id(attachment): + return psql("SELECT id FROM attachment_jobs WHERE attachment_id = '%s'" % attachment) + + +def scenario_crash_after_store(): + """Level 4: worker killed after writing S3 objects, before COMMIT and ack; lease expires; same result.""" + wait_ready() + since = utc_now() + auth, chat = session() + compose('stop', 'worker') + proc = faulty('worker', {'WORKER_FAULT': 'exit-after-store', 'JOB_LEASE_SECONDS': '15'}) + attachment = upload(auth, chat) + wait_exit(proc) + log('status after crash:', metadata(auth, attachment)[1]['status']) + log('lease:', psql("SELECT status, attempt, lease_until > now() AS lease_active FROM attachment_jobs WHERE attachment_id = '%s'" % attachment)) + log('queues (unacked message returned):', queue_depth()) + compose('start', 'worker') + meta = wait_status(auth, attachment, ['ready', 'failed']) + check_ready(auth, attachment, meta) + job_state(attachment) + service_logs('worker', since, job_id(attachment)) + service_logs('relay', since, 'lease expired') + + +def scenario_crash_after_commit(): + """Level 4: worker killed after COMMIT ready, before ack; redelivery is a no-op and cleans staging.""" + wait_ready() + since = utc_now() + auth, chat = session() + compose('stop', 'worker') + proc = faulty('worker', {'WORKER_FAULT': 'exit-after-commit'}) + attachment = upload(auth, chat) + wait_exit(proc) + log('status after crash:', metadata(auth, attachment)[1]['status'], 'staging_key:', staging_key(attachment)) + log('queues (unacked message returned):', queue_depth()) + compose('start', 'worker') + deadline = time.monotonic() + 30 + while staging_key(attachment) != 'NULL' and time.monotonic() < deadline: + time.sleep(1) + log('staging_key after redelivery:', staging_key(attachment)) + check_ready(auth, attachment, metadata(auth, attachment)[1]) + job_state(attachment) + service_logs('worker', since, job_id(attachment)) + + +def scenario_outbox_gap(): + """Level 4: crash between COMMIT and publish; the outbox row is published after recovery.""" + wait_ready() + auth, chat = session() + compose('stop', 'relay') + attachment = upload(auth, chat) + outbox = "SELECT o.id, coalesce(o.published_at::text, 'NOT PUBLISHED'), o.publish_attempts FROM outbox o JOIN attachment_jobs j ON j.id = o.job_id WHERE j.attachment_id = '%s'" % attachment + log('outbox after COMMIT:', psql(outbox)) + log('queues:', queue_depth()) + compose('kill', 'api') + log('API killed (SIGKILL) after COMMIT, nothing was published') + compose('start', 'api') + wait_ready() + log('status after API restart:', metadata(auth, attachment)[1]['status']) + compose('start', 'relay') + meta = wait_status(auth, attachment, ['ready', 'failed']) + log('outbox after relay recovery:', psql(outbox)) + check_ready(auth, attachment, meta) + job_state(attachment) + + +def scenario_relay_crash(): + """Level 4: relay killed after broker confirm, before marking outbox; duplicate delivery is a no-op.""" + wait_ready() + since = utc_now() + auth, chat = session() + compose('stop', 'relay') + proc = faulty('relay', {'RELAY_FAULT': 'exit-after-confirm'}) + attachment = upload(auth, chat) + wait_exit(proc) + outbox = "SELECT o.id, coalesce(o.published_at::text, 'NOT MARKED'), o.publish_attempts FROM outbox o JOIN attachment_jobs j ON j.id = o.job_id WHERE j.attachment_id = '%s'" % attachment + log('outbox after relay crash:', psql(outbox)) + compose('start', 'relay') + meta = wait_status(auth, attachment, ['ready', 'failed']) + time.sleep(3) + log('outbox after relay restart:', psql(outbox)) + check_ready(auth, attachment, meta) + job_state(attachment) + service_logs('worker', since, job_id(attachment)) + + +def replay(*args): + out = subprocess.run(['docker', 'compose', 'exec', '-T', '-e', 'OPERATOR=defense-demo', 'worker', 'node', 'dist/replay.js', *args], + capture_output=True, text=True) + for line in (out.stdout.strip() or out.stderr.strip()).splitlines(): + log(' replay:', line) + + +def scenario_retry_replay(): + """Level 4: S3 down -> retries with backoff and jitter -> failed retry_exhausted -> explicit replay -> ready.""" + wait_ready() + auth, chat = session() + compose('stop', 'worker') + attachment = upload(auth, chat) + compose('stop', 's3') + start_only('worker') + meta = wait_status(auth, attachment, ['failed'], timeout=120) + log('failed attachment in a new message ->', message(auth, chat, '', [attachment])) + log('retries:') + for line in psql("SELECT e.attempt, e.event, coalesce(e.detail, ''), to_char(e.created_at, 'HH24:MI:SS.MS') FROM job_events e JOIN attachment_jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s' ORDER BY e.id" % attachment).splitlines(): + log(' ', line) + log('$ replay.js --list') + replay('--list') + compose('start', 's3') + wait_ready() + log('$ replay.js', attachment) + replay(attachment) + meta = wait_status(auth, attachment, ['ready', 'failed']) + check_ready(auth, attachment, meta) + log('$ replay.js', attachment, '(already ready)') + replay(attachment) + job_state(attachment) + + +def scenario_broker(): + """Level 4: prefetch/concurrency, limits and dead letter queue for a malformed message.""" + wait_ready() + since = utc_now() + log('consumers:', subprocess.run( + ['docker', 'compose', 'exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_consumers', 'queue_name', 'prefetch_count', 'ack_required'], + capture_output=True, text=True).stdout.strip()) + log('worker limits:', subprocess.run( + ['sh', '-c', "docker inspect -f 'cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' $(docker compose ps -q worker)"], + capture_output=True, text=True).stdout.strip()) + publish = ( + "const amqp=require('amqplib');const fs=require('fs');(async()=>{" + "const c=await amqp.connect(fs.readFileSync(process.env.BROKER_URL_FILE,'utf8').trim());" + "const ch=await c.createConfirmChannel();" + "ch.sendToQueue('attachment.jobs',Buffer.from(JSON.stringify({job_id:'not-a-uuid',url:'http://example.invalid/x'})),{persistent:true});" + "await ch.waitForConfirms();await c.close();console.log('malformed message published');})()" + ) + log(subprocess.run(['docker', 'compose', 'exec', '-T', 'worker', 'node', '-e', publish], capture_output=True, text=True).stdout.strip()) + log('queues:', queue_depth()) + service_logs('worker', since, 'malformed') + + +SCENARIOS = { + 'restart': scenario_restart, + 'crash-after-store': scenario_crash_after_store, + 'crash-after-commit': scenario_crash_after_commit, + 'outbox-gap': scenario_outbox_gap, + 'relay-crash': scenario_relay_crash, + 'retry-replay': scenario_retry_replay, + 'broker': scenario_broker, +} + +if __name__ == '__main__': + if len(sys.argv) != 2 or sys.argv[1] not in SCENARIOS: + sys.exit('usage: job-scenario.py %s' % '|'.join(SCENARIOS)) + SCENARIOS[sys.argv[1]]() diff --git a/scripts/probe.py b/scripts/probe.py new file mode 100755 index 0000000..8548371 --- /dev/null +++ b/scripts/probe.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +import base64 +import json +import os +import sys +import time +import urllib.error +import urllib.request +import uuid + +BASE = os.environ.get('BASE_URL', 'http://localhost:8080') + + +def call(method, path, body=None, headers=None, with_headers=False): + data = json.dumps(body).encode() if body is not None else None + content_type = {'Content-Type': 'application/json'} if data else {} + request = urllib.request.Request(BASE + path, data=data, method=method, headers={**content_type, **(headers or {})}) + try: + with urllib.request.urlopen(request, timeout=15) as response: + result = response.status, json.loads(response.read() or b'null'), response.headers + except urllib.error.HTTPError as error: + result = error.code, json.loads(error.read() or b'null'), error.headers + except OSError as error: + result = 0, str(error), {} + return result if with_headers else result[:2] + + +def login(): + username = 'probe_' + uuid.uuid4().hex[:8] + password = 'Probe-check-' + uuid.uuid4().hex + print('register ->', call('POST', '/api/v1/users', {'username': username, 'display_name': 'Probe', 'password': password})[0]) + credential = base64.b64encode((username + ':' + password).encode()).decode() + code, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential}) + if code != 201: + sys.exit('login failed: %s %s' % (code, session)) + print('login ->', code, 'expires_at:', session['expires_at']) + return {'Authorization': 'Bearer ' + session['token']} + + +def instances(count): + auth = login() + for _ in range(count): + code, _, headers = call('GET', '/api/v1/users/me', headers=auth, with_headers=True) + print('GET /api/v1/users/me ->', code, 'X-Instance-Id:', headers.get('X-Instance-Id')) + + +def logout(): + auth = login() + print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0]) + code, body = call('DELETE', '/api/v1/auth/sessions/current', headers=auth) + print('DELETE /api/v1/auth/sessions/current ->', code, json.dumps(body, ensure_ascii=False) if body else '') + print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0]) + + +def ready(timeout=90): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if call('GET', '/health/ready')[0] == 200: + print('ready') + return + time.sleep(0.5) + sys.exit('not ready within %ds' % timeout) + + +def status(method, path, authorization=None): + code, body = call(method, path, headers={'Authorization': authorization} if authorization else None) + print(method, path, '(%s)' % (authorization or 'anonymous'), '->', code, json.dumps(body, ensure_ascii=False)) + + +def expiry(ttl): + auth = login() + print('GET /api/v1/users/me (fresh) ->', call('GET', '/api/v1/users/me', headers=auth)[0]) + time.sleep(ttl + 1) + print('GET /api/v1/users/me (after %ds) ->' % (ttl + 1), call('GET', '/api/v1/users/me', headers=auth)[0]) + + +if __name__ == '__main__': + command = sys.argv[1] + if command == 'ready': + ready() + elif command == 'status': + status(*sys.argv[2:5]) + elif command == 'expiry': + expiry(int(sys.argv[2])) + elif command == 'instances': + instances(int(sys.argv[2])) + elif command == 'logout': + logout() diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..416c628 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +started() { + docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis s3 rabbitmq api lb) +} +started +docker compose restart postgres redis s3 rabbitmq api lb +started diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..3d083ad --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +project="${COMPOSE_PROJECT_NAME:-messenger-lab6}" +labels=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}/{{index .Config.Labels "com.docker.compose.service"}}' "$TARGET_INSTANCE_ID") +if [ "$labels" != "$project/api" ]; then + echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of $project ($labels)" >&2 + exit 1 +fi +docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null +docker inspect -f '{{.Name}} {{.State.Status}} finished={{.State.FinishedAt}}' "$TARGET_INSTANCE_ID" diff --git a/src/app.module.ts b/src/app.module.ts new file mode 100644 index 0000000..63be550 --- /dev/null +++ b/src/app.module.ts @@ -0,0 +1,25 @@ +import { Module } from '@nestjs/common'; +import { AttachmentsModule } from './attachments/attachments.module'; +import { AuthModule } from './auth/auth.module'; +import { CacheModule } from './cache/cache.module'; +import { ChatsModule } from './chats/chats.module'; +import { DbModule } from './db/db.module'; +import { HealthModule } from './health/health.module'; +import { MessagesModule } from './messages/messages.module'; +import { StorageModule } from './storage/storage.module'; +import { UsersModule } from './users/users.module'; + +@Module({ + imports: [ + DbModule, + CacheModule, + StorageModule, + AuthModule, + HealthModule, + UsersModule, + ChatsModule, + MessagesModule, + AttachmentsModule, + ], +}) +export class AppModule {} diff --git a/src/attachments/attachments.controller.ts b/src/attachments/attachments.controller.ts new file mode 100644 index 0000000..674eacf --- /dev/null +++ b/src/attachments/attachments.controller.ts @@ -0,0 +1,79 @@ +import { + Controller, + Get, + HttpCode, + Param, + Post, + Query, + Req, + Res, + UseGuards, +} from '@nestjs/common'; +import { FastifyReply, FastifyRequest } from 'fastify'; +import { Readable } from 'stream'; +import { AuthGuard } from '../auth/auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { User } from '../common/domain'; +import { AttachmentsService } from './attachments.service'; +import { + AttachmentResponse, + toAttachmentResponse, +} from './dto/attachment.response'; + +@Controller() +@UseGuards(AuthGuard) +export class AttachmentsController { + constructor(private readonly attachments: AttachmentsService) {} + + @Post('api/v1/chats/:chatId/attachments') + @HttpCode(202) + async upload( + @Param('chatId') chatId: string, + @Query('filename') filename: unknown, + @Req() request: FastifyRequest, + @CurrentUser() user: User, + ): Promise { + const attachment = await this.attachments.upload({ + chatId, + ownerId: user.id, + filename, + contentType: request.uploadContentType, + contentLength: request.headers['content-length'], + body: request.body as Readable | undefined, + }); + return toAttachmentResponse(attachment); + } + + @Get('api/v1/attachments/:attachmentId') + async metadata( + @Param('attachmentId') attachmentId: string, + @CurrentUser() user: User, + ): Promise { + return toAttachmentResponse( + await this.attachments.getVisible(attachmentId, user.id), + ); + } + + @Get('api/v1/attachments/:attachmentId/content') + async content( + @Param('attachmentId') attachmentId: string, + @Query('variant') variant: unknown, + @CurrentUser() user: User, + @Res() reply: FastifyReply, + ): Promise { + const download = await this.attachments.openContent( + attachmentId, + user.id, + variant, + ); + await reply + .header('content-type', download.contentType) + .header('content-length', download.sizeBytes) + .header('x-content-type-options', 'nosniff') + .header( + 'content-disposition', + `inline; filename*=UTF-8''${encodeURIComponent(download.filename)}`, + ) + .send(download.content); + } +} diff --git a/src/attachments/attachments.module.ts b/src/attachments/attachments.module.ts new file mode 100644 index 0000000..eacc907 --- /dev/null +++ b/src/attachments/attachments.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { AttachmentsController } from './attachments.controller'; +import { AttachmentsService } from './attachments.service'; + +@Module({ + controllers: [AttachmentsController], + providers: [AttachmentsService], +}) +export class AttachmentsModule {} diff --git a/src/attachments/attachments.service.ts b/src/attachments/attachments.service.ts new file mode 100644 index 0000000..a1f4d02 --- /dev/null +++ b/src/attachments/attachments.service.ts @@ -0,0 +1,244 @@ +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; +import { Attachment, AttachmentVariant, Prisma } from '@prisma/client'; +import { randomUUID } from 'crypto'; +import { mkdtemp, readdir, rm, stat } from 'fs/promises'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { Readable } from 'stream'; +import { assertChatMember } from '../chats/chat-access'; +import { codePointLength } from '../common/dto/code-point-length.validator'; +import { ApiError } from '../common/filters/api-error'; +import { validate as isUuid } from '../common/uuid'; +import { isDatabaseUnavailable, PrismaService } from '../db/prisma.service'; +import { PIPELINE_VERSION } from '../jobs/job-message'; +import { enqueueJob } from '../jobs/job-store'; +import { S3Service } from '../storage/s3.service'; +import { assertValidImage, isSupportedContentType } from './image-validation'; +import { receiveBody } from './upload-body'; + +const TEMP_PREFIX = 'messenger-upload-'; +const STALE_TEMP_MS = 60 * 60 * 1000; +const MAX_FILENAME_CODE_POINTS = 255; +const FORBIDDEN_FILENAME = /[/\\\p{Cc}\p{Zl}\p{Zp}]/u; +const KNOWN_VARIANTS = new Set(['original', 'thumbnail', 'crop', 'optimized']); + +export type AttachmentWithVariants = Attachment & { variants: AttachmentVariant[] }; + +export interface DownloadableContent { + filename: string; + contentType: string; + sizeBytes: number; + content: Readable; +} + +export interface UploadInput { + chatId: string; + ownerId: string; + filename: unknown; + contentType: string | undefined; + contentLength: string | undefined; + body: Readable | undefined; +} + +@Injectable() +export class AttachmentsService implements OnModuleInit { + private readonly logger = new Logger('AttachmentsService'); + private readonly maxBytes = Number(process.env.MAX_UPLOAD_BYTES ?? 10485760); + private readonly maxPixels = Number(process.env.MAX_IMAGE_PIXELS ?? 40000000); + private readonly maxConcurrent = Number(process.env.MAX_CONCURRENT_UPLOADS ?? 16); + private readonly bodyTimeoutMs = Number(process.env.UPLOAD_BODY_TIMEOUT_MS ?? 60000); + private readonly tempRoot = process.env.UPLOAD_TMP_DIR ?? tmpdir(); + private activeUploads = 0; + + constructor( + private readonly prisma: PrismaService, + private readonly s3: S3Service, + ) {} + + async onModuleInit(): Promise { + await this.removeStaleTempDirs(); + } + + async upload(input: UploadInput): Promise { + await assertChatMember(this.prisma, input.chatId, input.ownerId); + const filename = parseFilename(input.filename); + const contentType = parseContentType(input.contentType); + if (Number(input.contentLength) > this.maxBytes) { + throw new ApiError('payload_too_large', 'attachment exceeds size limit'); + } + if (this.activeUploads >= this.maxConcurrent) { + throw new ApiError('unavailable', 'too many concurrent uploads'); + } + this.activeUploads++; + const dir = await mkdtemp(join(this.tempRoot, TEMP_PREFIX)); + try { + return await this.store(input, filename, contentType, join(dir, 'body')); + } finally { + this.activeUploads--; + await rm(dir, { recursive: true, force: true }); + } + } + + async getVisible( + attachmentId: string, + userId: string, + ): Promise { + if (!isUuid(attachmentId)) { + throw new ApiError('invalid_request', 'attachmentId must be a valid UUID'); + } + const row = await this.prisma.attachment.findFirst({ + where: { + id: attachmentId, + chat: { members: { some: { userId } } }, + }, + include: { variants: { where: { pipelineVersion: PIPELINE_VERSION } } }, + }); + if (!row) { + throw new ApiError('not_found', 'attachment not found'); + } + return row; + } + + async openContent( + attachmentId: string, + userId: string, + variant: unknown, + ): Promise { + const attachment = await this.getVisible(attachmentId, userId); + const name = parseVariant(variant); + if (attachment.status !== 'ready') { + throw new ApiError('conflict', `attachment is ${attachment.status}`); + } + if (name === 'original') { + return { + filename: attachment.filename, + contentType: attachment.contentType, + sizeBytes: attachment.sizeBytes, + content: await this.s3.getStream(attachment.objectKey), + }; + } + const stored = attachment.variants.find((v) => v.name === name); + if (!stored) { + throw new ApiError('not_found', 'attachment variant not found'); + } + return { + filename: attachment.filename, + contentType: stored.contentType, + sizeBytes: stored.sizeBytes, + content: await this.s3.getStream(stored.objectKey), + }; + } + + private async store( + input: UploadInput, + filename: string, + contentType: string, + path: string, + ): Promise { + if (!input.body) { + throw new ApiError('invalid_request', 'request body must not be empty'); + } + const { size, sha256 } = await receiveBody( + input.body, + path, + this.maxBytes, + this.bodyTimeoutMs, + ); + if (size === 0) { + throw new ApiError('invalid_request', 'request body must not be empty'); + } + await assertValidImage(path, size, contentType, this.maxPixels); + const id = randomUUID(); + const stagingKey = `staging/${id}`; + await this.s3.putFile({ key: stagingKey, path, size, contentType, sha256 }); + const now = new Date(); + try { + return await this.prisma.$transaction(async (tx) => { + const attachment = await tx.attachment.create({ + data: { + id, + chatId: input.chatId, + ownerId: input.ownerId, + filename, + contentType, + sizeBytes: size, + sha256, + objectKey: `attachments/${id}/original`, + stagingKey, + status: 'queued', + createdAt: now, + updatedAt: now, + }, + }); + await enqueueJob(tx, id, now); + return { ...attachment, variants: [] }; + }); + } catch (error) { + if (isDefiniteRejection(error)) { + await this.s3.delete(stagingKey).catch(() => { + this.logger.warn(`compensation failed for ${stagingKey}`); + }); + } + if (error instanceof Prisma.PrismaClientUnknownRequestError) { + this.logger.error(`metadata insert failed for ${stagingKey}`); + throw new ApiError('unavailable', 'database unavailable'); + } + throw error; + } + } + + private async removeStaleTempDirs(): Promise { + const root = this.tempRoot; + const names = await readdir(root); + for (const name of names.filter((n) => n.startsWith(TEMP_PREFIX))) { + const path = join(root, name); + const info = await stat(path).catch(() => null); + if (info && Date.now() - info.mtimeMs > STALE_TEMP_MS) { + await rm(path, { recursive: true, force: true }); + } + } + } +} + +function parseVariant(raw: unknown): string { + if (raw === undefined) { + return 'original'; + } + if (typeof raw === 'string' && KNOWN_VARIANTS.has(raw)) { + return raw; + } + throw new ApiError('invalid_request', 'unknown attachment variant'); +} + +function isDefiniteRejection(error: unknown): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + !isDatabaseUnavailable(error) + ); +} + +function parseFilename(raw: unknown): string { + if ( + typeof raw !== 'string' || + raw.trim() === '' || + codePointLength(raw) > MAX_FILENAME_CODE_POINTS || + FORBIDDEN_FILENAME.test(raw) + ) { + throw new ApiError( + 'invalid_request', + 'filename must be 1-255 characters without path separators or control characters', + ); + } + return raw; +} + +function parseContentType(raw: string | undefined): string { + const contentType = raw?.split(';')[0].trim().toLowerCase() ?? ''; + if (!isSupportedContentType(contentType)) { + throw new ApiError( + 'unsupported_media_type', + 'Content-Type must be image/png or image/jpeg', + ); + } + return contentType; +} diff --git a/src/attachments/dto/attachment.response.ts b/src/attachments/dto/attachment.response.ts new file mode 100644 index 0000000..1559462 --- /dev/null +++ b/src/attachments/dto/attachment.response.ts @@ -0,0 +1,55 @@ +import { Attachment, AttachmentVariant } from '@prisma/client'; + +const VARIANT_ORDER = ['thumbnail', 'crop', 'optimized']; + +export interface VariantResponse { + name: string; + content_type: string; + size_bytes: number; + width: number; + height: number; + sha256: string; +} + +export interface AttachmentResponse { + id: string; + chat_id: string; + owner_id: string; + filename: string; + content_type: string; + size_bytes: number; + sha256: string; + status: string; + variants: VariantResponse[]; + error_code: string | null; + created_at: string; + updated_at: string; +} + +export function toAttachmentResponse( + row: Attachment & { variants: AttachmentVariant[] }, +): AttachmentResponse { + const variants = row.status === 'ready' ? [...row.variants] : []; + variants.sort((a, b) => VARIANT_ORDER.indexOf(a.name) - VARIANT_ORDER.indexOf(b.name)); + return { + id: row.id, + chat_id: row.chatId, + owner_id: row.ownerId, + filename: row.filename, + content_type: row.contentType, + size_bytes: row.sizeBytes, + sha256: row.sha256, + status: row.status, + variants: variants.map((variant) => ({ + name: variant.name, + content_type: variant.contentType, + size_bytes: variant.sizeBytes, + width: variant.width, + height: variant.height, + sha256: variant.sha256, + })), + error_code: row.errorCode, + created_at: row.createdAt.toISOString(), + updated_at: row.updatedAt.toISOString(), + }; +} diff --git a/src/attachments/image-validation.ts b/src/attachments/image-validation.ts new file mode 100644 index 0000000..d5bb319 --- /dev/null +++ b/src/attachments/image-validation.ts @@ -0,0 +1,105 @@ +import { open } from 'fs/promises'; +import sharp from 'sharp'; +import { ApiError } from '../common/filters/api-error'; + +sharp.cache(false); +sharp.concurrency(1); + +const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex'); +const JPEG_SIGNATURE = Buffer.from('ffd8ff', 'hex'); +const PNG_END_CHUNK = Buffer.from('0000000049454e44ae426082', 'hex'); +const PNG_TAIL_BYTES = 64 * 1024; +const MAX_CONCURRENT_DECODES = 2; + +const FORMAT_BY_CONTENT_TYPE: Record = { + 'image/png': 'png', + 'image/jpeg': 'jpeg', +}; + +let activeDecodes = 0; +const decodeQueue: (() => void)[] = []; + +export function isSupportedContentType(contentType: string): boolean { + return contentType in FORMAT_BY_CONTENT_TYPE; +} + +export async function assertValidImage( + path: string, + size: number, + contentType: string, + maxPixels: number, +): Promise { + const invalid = new ApiError( + 'unsupported_media_type', + 'file is not a valid image of the declared type', + ); + const format = FORMAT_BY_CONTENT_TYPE[contentType]; + if (!(await hasExpectedFraming(path, size, format))) { + throw invalid; + } + const { width, height, format: actual } = await sharp(path, { + limitInputPixels: false, + }) + .metadata() + .catch(() => { + throw invalid; + }); + if (!width || !height || actual !== format) { + throw invalid; + } + if (width * height > maxPixels) { + throw new ApiError('payload_too_large', 'image exceeds pixel limit'); + } + await acquireDecodeSlot(); + try { + await sharp(path, { + failOn: 'warning', + sequentialRead: true, + limitInputPixels: maxPixels, + }).stats(); + } catch { + throw invalid; + } finally { + releaseDecodeSlot(); + } +} + +async function hasExpectedFraming( + path: string, + size: number, + format: string, +): Promise { + const file = await open(path, 'r'); + try { + const head = Buffer.alloc(PNG_SIGNATURE.length); + await file.read(head, 0, head.length, 0); + if (format === 'jpeg') { + return head.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE); + } + if (!head.equals(PNG_SIGNATURE)) { + return false; + } + const tail = Buffer.alloc(Math.min(size, PNG_TAIL_BYTES)); + await file.read(tail, 0, tail.length, size - tail.length); + return tail.includes(PNG_END_CHUNK); + } finally { + await file.close(); + } +} + +function acquireDecodeSlot(): Promise { + if (activeDecodes < MAX_CONCURRENT_DECODES) { + activeDecodes++; + return Promise.resolve(); + } + return new Promise((resolve) => decodeQueue.push(resolve)); +} + +function releaseDecodeSlot(): void { + const next = decodeQueue.shift(); + if (next) { + next(); + } else { + activeDecodes--; + } +} diff --git a/src/attachments/reconciler.ts b/src/attachments/reconciler.ts new file mode 100644 index 0000000..24beeda --- /dev/null +++ b/src/attachments/reconciler.ts @@ -0,0 +1,163 @@ +import { PrismaClient } from '@prisma/client'; +import { S3Service } from '../storage/s3.service'; + +const MAX_REPORTED_KEYS = 20; +const DEFAULT_PREFIXES = ['attachments/', 'staging/']; + +type ReconcilePrisma = Pick; + +export interface ReconcileOptions { + apply: boolean; + graceMs: number; + stagingRetentionMs?: number; + prefix?: string; + now?: Date; + pageSize?: number; +} + +export interface ReconcileReport { + mode: 'apply' | 'dry-run'; + grace_seconds: number; + staging_expired: number; + scanned: number; + fresh_skipped: number; + referenced: number; + orphans: number; + deleted: number; + failed: number; + orphan_keys: string[]; + duration_ms: number; +} + +export async function reconcile( + prisma: ReconcilePrisma, + s3: S3Service, + options: ReconcileOptions, +): Promise { + const started = Date.now(); + const cutoff = (options.now ?? new Date()).getTime() - options.graceMs; + const report: ReconcileReport = { + mode: options.apply ? 'apply' : 'dry-run', + grace_seconds: options.graceMs / 1000, + staging_expired: 0, + scanned: 0, + fresh_skipped: 0, + referenced: 0, + orphans: 0, + deleted: 0, + failed: 0, + orphan_keys: [], + duration_ms: 0, + }; + if (options.stagingRetentionMs !== undefined) { + report.staging_expired = await expireFailedStaging( + prisma, + s3, + (options.now ?? new Date()).getTime() - options.stagingRetentionMs, + options.apply, + options.prefix, + ); + } + for (const prefix of options.prefix ? [options.prefix] : DEFAULT_PREFIXES) { + await reconcilePrefix(prisma, s3, prefix, cutoff, options, report); + } + report.duration_ms = Date.now() - started; + return report; +} + +async function expireFailedStaging( + prisma: ReconcilePrisma, + s3: S3Service, + before: number, + apply: boolean, + prefix?: string, +): Promise { + const rows = await prisma.attachment.findMany({ + where: { + stagingKey: { not: null, startsWith: prefix }, + OR: [{ status: 'ready' }, { status: 'failed', updatedAt: { lt: new Date(before) } }], + }, + select: { id: true, stagingKey: true }, + take: 500, + }); + if (!apply) { + return rows.length; + } + let expired = 0; + for (const row of rows) { + const released = await prisma.attachment.updateMany({ + where: { + id: row.id, + stagingKey: row.stagingKey, + OR: [{ status: 'ready' }, { status: 'failed', updatedAt: { lt: new Date(before) } }], + }, + data: { stagingKey: null }, + }); + if (released.count === 0) { + continue; + } + await s3.delete(row.stagingKey!).then( + () => expired++, + () => undefined, + ); + } + return expired; +} + +function attachmentIdOf(key: string): string | null { + const match = /^attachments\/([0-9a-f-]{36})(\/|$)/.exec(key); + return match ? match[1] : null; +} + +async function reconcilePrefix( + prisma: ReconcilePrisma, + s3: S3Service, + prefix: string, + cutoff: number, + options: ReconcileOptions, + report: ReconcileReport, +): Promise { + let token: string | undefined; + do { + const page = await s3.listObjects(prefix, options.pageSize ?? 500, token); + token = page.nextToken; + report.scanned += page.objects.length; + const old = page.objects.filter((object) => object.lastModified.getTime() < cutoff); + report.fresh_skipped += page.objects.length - old.length; + const keys = old.map((object) => object.key); + const rows = await prisma.attachment.findMany({ + where: { OR: [{ objectKey: { in: keys } }, { stagingKey: { in: keys } }] }, + select: { objectKey: true, stagingKey: true }, + }); + const variants = await prisma.attachmentVariant.findMany({ + where: { objectKey: { in: keys } }, + select: { objectKey: true }, + }); + const ids = [...new Set(keys.map(attachmentIdOf).filter((id): id is string => id !== null))]; + const owners = ids.length + ? await prisma.attachment.findMany({ where: { id: { in: ids } }, select: { id: true } }) + : []; + const owned = new Set(owners.map((row) => row.id)); + const known = new Set([ + ...rows.flatMap((row) => [row.objectKey, row.stagingKey]), + ...variants.map((row) => row.objectKey), + ]); + for (const { key } of old) { + const owner = attachmentIdOf(key); + if (known.has(key) || (owner !== null && owned.has(owner))) { + report.referenced++; + continue; + } + report.orphans++; + if (report.orphan_keys.length < MAX_REPORTED_KEYS) { + report.orphan_keys.push(key); + } + if (options.apply) { + await s3.delete(key).then( + () => report.deleted++, + () => report.failed++, + ); + } + } + } while (token); +} diff --git a/src/attachments/upload-body.ts b/src/attachments/upload-body.ts new file mode 100644 index 0000000..f97873d --- /dev/null +++ b/src/attachments/upload-body.ts @@ -0,0 +1,98 @@ +import { createHash } from 'crypto'; +import { FastifyInstance, FastifyRequest } from 'fastify'; +import { createWriteStream } from 'fs'; +import { Readable } from 'stream'; +import { ApiError } from '../common/filters/api-error'; + +const UPLOAD_ROUTE = '/api/v1/chats/:chatId/attachments'; +const PASS_THROUGH_TYPE = 'application/x-messenger-upload'; + +declare module 'fastify' { + interface FastifyRequest { + uploadContentType?: string; + } +} + +export function registerUploadBody(instance: FastifyInstance): void { + instance.addContentTypeParser(PASS_THROUGH_TYPE, (_request, payload, done) => { + done(null, payload); + }); + instance.addHook('onRequest', (request: FastifyRequest, _reply, done) => { + if (request.method === 'POST' && request.routeOptions.url === UPLOAD_ROUTE) { + request.uploadContentType = request.headers['content-type']; + request.headers['content-type'] = PASS_THROUGH_TYPE; + } + done(); + }); +} + +export interface ReceivedBody { + size: number; + sha256: string; +} + +export function receiveBody( + body: Readable, + path: string, + maxBytes: number, + timeoutMs: number, +): Promise { + return new Promise((resolve, reject) => { + const hash = createHash('sha256'); + const out = createWriteStream(path, { flags: 'wx', mode: 0o600 }); + let size = 0; + let settled = false; + + const timer = setTimeout(() => body.destroy(), timeoutMs); + const settle = (done: () => void): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + body.off('data', onData); + body.off('end', onEnd); + body.off('close', onClose); + done(); + }; + const fail = (error: ApiError): void => { + settle(() => { + out.destroy(); + reject(error); + }); + }; + const onData = (chunk: Buffer): void => { + size += chunk.length; + if (size > maxBytes) { + fail(new ApiError('payload_too_large', 'attachment exceeds size limit')); + return; + } + hash.update(chunk); + if (!out.write(chunk)) { + body.pause(); + out.once('drain', () => { + if (!settled) { + body.resume(); + } + }); + } + }; + const onEnd = (): void => { + settle(() => { + out.end(() => + resolve({ size, sha256: hash.digest('hex') }), + ); + }); + }; + const onClose = (): void => { + fail(new ApiError('invalid_request', 'upload was interrupted')); + }; + + out.on('error', () => { + fail(new ApiError('unavailable', 'temporary storage unavailable')); + }); + body.on('data', onData); + body.on('end', onEnd); + body.on('close', onClose); + }); +} diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts new file mode 100644 index 0000000..ebd38d7 --- /dev/null +++ b/src/auth/auth.controller.ts @@ -0,0 +1,51 @@ +import { + Controller, + Delete, + Headers, + HttpCode, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import { FastifyRequest } from 'fastify'; +import { ApiError } from '../common/filters/api-error'; +import { toUserResponse, UserResponse } from '../users/dto/user.response'; +import { AuthGuard } from './auth.guard'; +import { AuthService } from './auth.service'; + +interface SessionResponse { + token: string; + token_type: 'Bearer'; + expires_at: string; + user: UserResponse; +} + +@Controller('api/v1/auth/sessions') +export class AuthController { + constructor(private readonly auth: AuthService) {} + + @Post() + @HttpCode(201) + async create( + @Headers('authorization') authorization: string | undefined, + @Req() request: FastifyRequest, + ): Promise { + if (request.body !== undefined) { + throw new ApiError('invalid_request', 'request body is not allowed'); + } + const session = await this.auth.login(authorization); + return { + token: session.token, + token_type: 'Bearer', + expires_at: session.expiresAt.toISOString(), + user: toUserResponse(session.user), + }; + } + + @Delete('current') + @HttpCode(204) + @UseGuards(AuthGuard) + async revoke(@Req() request: FastifyRequest): Promise { + await this.auth.revoke(request.sessionTokenHash!); + } +} diff --git a/src/auth/auth.guard.ts b/src/auth/auth.guard.ts new file mode 100644 index 0000000..ca0c983 --- /dev/null +++ b/src/auth/auth.guard.ts @@ -0,0 +1,25 @@ +import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; +import { FastifyRequest } from 'fastify'; +import { ApiError } from '../common/filters/api-error'; +import { AuthService } from './auth.service'; + +const BEARER_CHALLENGE = 'Bearer realm="messenger"'; + +@Injectable() +export class AuthGuard implements CanActivate { + constructor(private readonly auth: AuthService) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const match = /^Bearer (\S+)$/i.exec(request.headers.authorization ?? ''); + const session = match ? await this.auth.resolve(match[1]) : null; + if (!session) { + throw new ApiError('unauthorized', 'missing or invalid session', { + 'WWW-Authenticate': BEARER_CHALLENGE, + }); + } + request.currentUser = session.user; + request.sessionTokenHash = session.tokenHash; + return true; + } +} diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts new file mode 100644 index 0000000..65ae152 --- /dev/null +++ b/src/auth/auth.module.ts @@ -0,0 +1,12 @@ +import { Global, Module } from '@nestjs/common'; +import { AuthController } from './auth.controller'; +import { AuthGuard } from './auth.guard'; +import { AuthService } from './auth.service'; + +@Global() +@Module({ + controllers: [AuthController], + providers: [AuthService, AuthGuard], + exports: [AuthService, AuthGuard], +}) +export class AuthModule {} diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts new file mode 100644 index 0000000..c7bafd2 --- /dev/null +++ b/src/auth/auth.service.ts @@ -0,0 +1,155 @@ +import { Injectable } from '@nestjs/common'; +import { createHash, randomBytes } from 'crypto'; +import { CacheService } from '../cache/cache.service'; +import { codePointLength } from '../common/dto/code-point-length.validator'; +import { User } from '../common/domain'; +import { ApiError } from '../common/filters/api-error'; +import { PrismaService } from '../db/prisma.service'; +import { toUser } from '../users/users.service'; +import { verifyPassword } from './password'; + +const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'; +const USERNAME_PATTERN = /^[a-z0-9_]{3,32}$/; +const CACHE_TTL_MS = 60_000; +const REVOKED = 'revoked'; + +interface CachedSession { + user: User; + expiresAt: number; +} + +export interface CreatedSession { + token: string; + expiresAt: Date; + user: User; +} + +export interface ResolvedSession { + tokenHash: string; + user: User; +} + +@Injectable() +export class AuthService { + private readonly ttlSeconds = readSessionTtl(); + + constructor( + private readonly prisma: PrismaService, + private readonly cache: CacheService, + ) {} + + async login(authorization: string | undefined): Promise { + const credentials = parseBasic(authorization); + if (!credentials) { + throw invalidCredentials(); + } + const row = await this.prisma.user.findUnique({ + where: { username: credentials.username }, + }); + const valid = await verifyPassword( + row?.passwordHash ?? null, + credentials.password, + ); + if (!row || !valid) { + throw invalidCredentials(); + } + const token = randomBytes(32).toString('base64url'); + const expiresAt = new Date(Date.now() + this.ttlSeconds * 1000); + await this.prisma.session.create({ + data: { tokenHash: hashToken(token), userId: row.id, expiresAt }, + }); + return { token, expiresAt, user: toUser(row) }; + } + + async resolve(token: string): Promise { + const tokenHash = hashToken(token); + const key = cacheKey(tokenHash); + const cached = await this.cache.get(key); + if (cached === REVOKED) { + return null; + } + if (cached) { + const entry = JSON.parse(cached) as CachedSession; + if (entry.expiresAt > Date.now()) { + return { tokenHash, user: entry.user }; + } + } + const session = await this.prisma.session.findUnique({ + where: { tokenHash }, + include: { user: true }, + }); + const remainingMs = session + ? session.expiresAt.getTime() - Date.now() + : 0; + if (!session || remainingMs <= 0) { + return null; + } + const user = toUser(session.user); + const entry: CachedSession = { + user, + expiresAt: session.expiresAt.getTime(), + }; + await this.cache.set( + key, + JSON.stringify(entry), + Math.min(remainingMs, CACHE_TTL_MS), + true, + ); + return { tokenHash, user }; + } + + async revoke(tokenHash: string): Promise { + const marked = await this.cache.setStrict( + cacheKey(tokenHash), + REVOKED, + CACHE_TTL_MS, + ); + if (!marked) { + throw new ApiError('unavailable', 'session cache unavailable'); + } + await this.prisma.session.deleteMany({ where: { tokenHash } }); + } +} + +function cacheKey(tokenHash: string): string { + return `session:v1:${tokenHash}`; +} + +function parseBasic( + header: string | undefined, +): { username: string; password: string } | null { + const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header ?? ''); + if (!match) { + return null; + } + const decoded = Buffer.from(match[1], 'base64').toString('utf8'); + const separator = decoded.indexOf(':'); + if (separator < 0) { + return null; + } + const username = decoded.slice(0, separator); + const password = decoded.slice(separator + 1); + const length = codePointLength(password); + if (!USERNAME_PATTERN.test(username) || length < 12 || length > 128) { + return null; + } + return { username, password }; +} + +function hashToken(token: string): string { + return createHash('sha256').update(token).digest('hex'); +} + +function invalidCredentials(): ApiError { + return new ApiError('unauthorized', 'invalid credentials', { + 'WWW-Authenticate': BASIC_CHALLENGE, + }); +} + +function readSessionTtl(): number { + const ttl = Number(process.env.SESSION_TTL_SECONDS ?? 3600); + if (!Number.isInteger(ttl) || ttl <= 0) { + throw new Error('SESSION_TTL_SECONDS must be a positive integer'); + } + return ttl; +} diff --git a/src/auth/current-user.decorator.ts b/src/auth/current-user.decorator.ts new file mode 100644 index 0000000..c9b55f9 --- /dev/null +++ b/src/auth/current-user.decorator.ts @@ -0,0 +1,20 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import { FastifyRequest } from 'fastify'; +import { User } from '../common/domain'; + +declare module 'fastify' { + interface FastifyRequest { + currentUser?: User; + sessionTokenHash?: string; + } +} + +export const CurrentUser = createParamDecorator( + (_data: unknown, ctx: ExecutionContext): User => { + const request = ctx.switchToHttp().getRequest(); + if (!request.currentUser) { + throw new Error('CurrentUser used without AuthGuard'); + } + return request.currentUser; + }, +); diff --git a/src/auth/password.ts b/src/auth/password.ts new file mode 100644 index 0000000..49cc9d2 --- /dev/null +++ b/src/auth/password.ts @@ -0,0 +1,17 @@ +import { argon2id, hash, verify } from 'argon2'; + +const OPTIONS = { type: argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 }; + +const dummyHash = hash('timing-equalizer-password', OPTIONS); + +export function hashPassword(password: string): Promise { + return hash(password, OPTIONS); +} + +export async function verifyPassword( + passwordHash: string | null, + password: string, +): Promise { + const valid = await verify(passwordHash ?? (await dummyHash), password); + return passwordHash !== null && valid; +} diff --git a/src/broker/broker.ts b/src/broker/broker.ts new file mode 100644 index 0000000..700efb4 --- /dev/null +++ b/src/broker/broker.ts @@ -0,0 +1,57 @@ +import { Logger } from '@nestjs/common'; +import amqp, { Channel, Connection } from 'amqplib'; +import { readFileSync } from 'fs'; + +export const JOB_QUEUE = 'attachment.jobs'; +export const DEAD_LETTER_QUEUE = 'attachment.jobs.dlq'; +const DELIVERY_LIMIT = 20; +const RECONNECT_MAX_MS = 10000; + +export function brokerUrl(): string { + const file = process.env.BROKER_URL_FILE; + const url = file ? readFileSync(file, 'utf8').trim() : process.env.BROKER_URL; + if (!url) { + throw new Error('BROKER_URL_FILE or BROKER_URL must be set'); + } + return url; +} + +export async function assertTopology(channel: Channel): Promise { + await channel.assertQueue(DEAD_LETTER_QUEUE, { + durable: true, + arguments: { 'x-queue-type': 'quorum' }, + }); + await channel.assertQueue(JOB_QUEUE, { + durable: true, + arguments: { + 'x-queue-type': 'quorum', + 'x-delivery-limit': DELIVERY_LIMIT, + 'x-dead-letter-exchange': '', + 'x-dead-letter-routing-key': DEAD_LETTER_QUEUE, + }, + }); +} + +export async function connectWithRetry( + logger: Logger, + stopping: () => boolean, +): Promise { + let delay = 500; + while (!stopping()) { + try { + const connection = await amqp.connect(brokerUrl(), { timeout: 5000 }); + logger.log('connected to broker'); + return connection; + } catch (error) { + const reason = error instanceof Error ? error.message.split(' ')[0] : 'unknown'; + logger.warn(`broker unavailable (${reason}), retry in ${delay} ms`); + await sleep(delay); + delay = Math.min(RECONNECT_MAX_MS, delay * 2); + } + } + return null; +} + +export function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/src/cache/cache.module.ts b/src/cache/cache.module.ts new file mode 100644 index 0000000..e67c549 --- /dev/null +++ b/src/cache/cache.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { CacheService } from './cache.service'; + +@Global() +@Module({ + providers: [CacheService], + exports: [CacheService], +}) +export class CacheModule {} diff --git a/src/cache/cache.service.ts b/src/cache/cache.service.ts new file mode 100644 index 0000000..0c7c0cd --- /dev/null +++ b/src/cache/cache.service.ts @@ -0,0 +1,98 @@ +import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; +import { readFileSync } from 'fs'; +import Redis from 'ioredis'; + +@Injectable() +export class CacheService implements OnModuleDestroy { + private readonly logger = new Logger('CacheService'); + private readonly client: Redis | null; + private trusted = false; + + constructor() { + const url = readCacheUrl(); + this.client = url + ? new Redis(url, { + enableOfflineQueue: false, + maxRetriesPerRequest: 0, + connectTimeout: 1000, + commandTimeout: 200, + }) + : null; + this.client?.on('error', (error) => + this.logger.warn(`redis unavailable: ${error.message}`), + ); + this.client?.on('close', () => { + this.trusted = false; + }); + this.client?.on('ready', () => { + this.client!.flushdb().then( + () => { + this.trusted = true; + }, + () => this.distrust(), + ); + }); + } + + async get(key: string): Promise { + if (!this.client || !this.trusted) { + return null; + } + try { + return await this.client.get(key); + } catch { + this.distrust(); + return null; + } + } + + async set( + key: string, + value: string, + ttlMs: number, + onlyIfAbsent = false, + ): Promise { + if (!this.client || !this.trusted) { + return; + } + try { + if (onlyIfAbsent) { + await this.client.set(key, value, 'PX', ttlMs, 'NX'); + } else { + await this.client.set(key, value, 'PX', ttlMs); + } + } catch { + this.distrust(); + } + } + + async setStrict(key: string, value: string, ttlMs: number): Promise { + if (!this.client) { + return true; + } + if (!this.trusted) { + return false; + } + try { + await this.client.set(key, value, 'PX', ttlMs); + return true; + } catch { + this.distrust(); + return false; + } + } + + onModuleDestroy(): void { + this.client?.disconnect(); + } + + private distrust(): void { + this.trusted = false; + this.client?.disconnect(true); + } +} + +function readCacheUrl(): string | undefined { + const file = process.env.CACHE_URL_FILE; + return file ? readFileSync(file, 'utf8').trim() : process.env.CACHE_URL; +} diff --git a/src/chats/chat-access.ts b/src/chats/chat-access.ts new file mode 100644 index 0000000..b456f3e --- /dev/null +++ b/src/chats/chat-access.ts @@ -0,0 +1,19 @@ +import { ApiError } from '../common/filters/api-error'; +import { validate as isUuid } from '../common/uuid'; +import { PrismaService } from '../db/prisma.service'; + +export async function assertChatMember( + prisma: PrismaService, + chatId: string, + userId: string, +): Promise { + if (!isUuid(chatId)) { + throw new ApiError('invalid_request', 'chatId must be a valid UUID'); + } + const member = await prisma.chatMember.findUnique({ + where: { chatId_userId: { chatId, userId } }, + }); + if (!member) { + throw new ApiError('not_found', 'chat not found'); + } +} diff --git a/src/chats/chats.controller.ts b/src/chats/chats.controller.ts new file mode 100644 index 0000000..b5f8d2c --- /dev/null +++ b/src/chats/chats.controller.ts @@ -0,0 +1,57 @@ +import { + Body, + Controller, + Get, + HttpCode, + Param, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import { AuthGuard } from '../auth/auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto'; +import { User } from '../common/domain'; +import { ChatsService } from './chats.service'; +import { + ChatPageResponse, + ChatResponse, + toChatResponse, +} from './dto/chat.response'; +import { CreateChatDto } from './dto/create-chat.dto'; + +@Controller('api/v1/chats') +@UseGuards(AuthGuard) +export class ChatsController { + constructor(private readonly chats: ChatsService) {} + + @Post() + @HttpCode(201) + async create( + @Body() dto: CreateChatDto, + @CurrentUser() user: User, + ): Promise { + const chat = await this.chats.create(dto.title, dto.member_ids, user.id); + return toChatResponse(chat); + } + + @Get() + async list( + @CurrentUser() user: User, + @Query('limit') limitRaw: unknown, + @Query('cursor') cursorRaw: unknown, + ): Promise { + const limit = parseLimit(limitRaw); + const cursor = rawCursorParam(cursorRaw); + return this.chats.listForMember(user.id, limit, cursor); + } + + @Get(':chatId') + async getOne( + @Param('chatId') chatId: string, + @CurrentUser() user: User, + ): Promise { + const chat = await this.chats.getForMember(chatId, user.id); + return toChatResponse(chat); + } +} diff --git a/src/chats/chats.module.ts b/src/chats/chats.module.ts new file mode 100644 index 0000000..fbba7e0 --- /dev/null +++ b/src/chats/chats.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { ChatsController } from './chats.controller'; +import { ChatsService } from './chats.service'; + +@Module({ + controllers: [ChatsController], + providers: [ChatsService], + exports: [ChatsService], +}) +export class ChatsModule {} diff --git a/src/chats/chats.service.ts b/src/chats/chats.service.ts new file mode 100644 index 0000000..d16853e --- /dev/null +++ b/src/chats/chats.service.ts @@ -0,0 +1,131 @@ +import { Injectable } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { decodeChatCursor, encodeChatCursor } from '../common/cursor'; +import { Chat } from '../common/domain'; +import { ApiError } from '../common/filters/api-error'; +import { validate as isUuid } from '../common/uuid'; +import { PrismaService, isForeignKeyViolation } from '../db/prisma.service'; +import { ChatPageResponse, toChatResponse } from './dto/chat.response'; + +interface ChatRow { + id: string; + title: string; + createdAt: Date; + memberIds: string[]; +} + +@Injectable() +export class ChatsService { + constructor(private readonly prisma: PrismaService) {} + + async create( + title: string, + rawMemberIds: string[], + callerId: string, + ): Promise { + const invalid = rawMemberIds.find((id) => !isUuid(id)); + if (invalid) { + throw new ApiError('invalid_request', `unknown member_id: ${invalid}`); + } + const memberIds = rawMemberIds.map((id) => id.toLowerCase()); + if (new Set(memberIds).size !== memberIds.length) { + throw new ApiError( + 'invalid_request', + "All member_ids's elements must be unique", + ); + } + if (!memberIds.includes(callerId)) { + throw new ApiError( + 'invalid_request', + 'member_ids must include the caller', + ); + } + try { + const chat = await this.prisma.$transaction(async (tx) => { + const created = await tx.chat.create({ + data: { title: title.trim() }, + }); + await tx.chatMember.createMany({ + data: memberIds.map((userId) => ({ + chatId: created.id, + userId, + })), + }); + return created; + }); + return toChat({ ...chat, memberIds }); + } catch (error) { + if (isForeignKeyViolation(error)) { + throw new ApiError( + 'invalid_request', + 'member_ids contain an unknown user', + ); + } + throw error; + } + } + + async getForMember(chatId: string, callerId: string): Promise { + if (!isUuid(chatId)) { + throw new ApiError('invalid_request', 'chatId must be a valid UUID'); + } + const chat = await this.prisma.chat.findFirst({ + where: { id: chatId, members: { some: { userId: callerId } } }, + include: { members: { select: { userId: true } } }, + }); + if (!chat) { + throw new ApiError('not_found', 'chat not found'); + } + return toChat({ + ...chat, + memberIds: chat.members.map((m) => m.userId), + }); + } + + async listForMember( + callerId: string, + limit: number, + rawCursor: string | null, + ): Promise { + let after = Prisma.empty; + if (rawCursor !== null) { + const cursor = decodeChatCursor(rawCursor); + const member = cursor + ? await this.prisma.chatMember.findUnique({ + where: { + chatId_userId: { chatId: cursor.id, userId: callerId }, + }, + include: { chat: { select: { createdAt: true } } }, + }) + : null; + if (!member) { + throw new ApiError('invalid_request', 'invalid cursor'); + } + after = Prisma.sql`AND (c.created_at, c.id) > (${member.chat.createdAt}::timestamptz, ${member.chatId}::uuid)`; + } + const rows = await this.prisma.$queryRaw` + SELECT c.id, c.title, c.created_at AS "createdAt", + ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id = c.id) AS "memberIds" + FROM chat_members cm + JOIN chats c ON c.id = cm.chat_id + WHERE cm.user_id = ${callerId}::uuid ${after} + ORDER BY c.created_at, c.id + LIMIT ${limit + 1}`; + const items = rows.slice(0, limit).map(toChat); + const last = items[items.length - 1]; + return { + items: items.map(toChatResponse), + next_cursor: + rows.length > limit ? encodeChatCursor({ id: last.id }) : null, + }; + } +} + +function toChat(row: ChatRow): Chat { + return { + id: row.id, + title: row.title, + memberIds: row.memberIds, + createdAt: row.createdAt.toISOString(), + }; +} diff --git a/src/chats/dto/chat.response.ts b/src/chats/dto/chat.response.ts new file mode 100644 index 0000000..e10e4a6 --- /dev/null +++ b/src/chats/dto/chat.response.ts @@ -0,0 +1,22 @@ +import { Chat } from '../../common/domain'; + +export interface ChatResponse { + id: string; + title: string; + member_ids: string[]; + created_at: string; +} + +export interface ChatPageResponse { + items: ChatResponse[]; + next_cursor: string | null; +} + +export function toChatResponse(chat: Chat): ChatResponse { + return { + id: chat.id, + title: chat.title, + member_ids: chat.memberIds, + created_at: chat.createdAt, + }; +} diff --git a/src/chats/dto/create-chat.dto.ts b/src/chats/dto/create-chat.dto.ts new file mode 100644 index 0000000..d42750a --- /dev/null +++ b/src/chats/dto/create-chat.dto.ts @@ -0,0 +1,22 @@ +import { + ArrayMaxSize, + ArrayMinSize, + ArrayUnique, + IsArray, + IsString, +} from 'class-validator'; +import { CodePointLength } from '../../common/dto/code-point-length.validator'; +import { NotBlank } from '../../common/dto/not-blank.validator'; + +export class CreateChatDto { + @NotBlank() + @CodePointLength(1, 100) + title!: string; + + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(100) + @ArrayUnique() + @IsString({ each: true }) + member_ids!: string[]; +} diff --git a/src/common/cursor.ts b/src/common/cursor.ts new file mode 100644 index 0000000..76a22fa --- /dev/null +++ b/src/common/cursor.ts @@ -0,0 +1,49 @@ +import { validate as isUuid } from './uuid'; + +export interface ChatCursor { + id: string; +} + +export interface MessageCursor { + chatId: string; + id: string; +} + +export function encodeChatCursor(cursor: ChatCursor): string { + return encode(cursor); +} + +export function decodeChatCursor(raw: string): ChatCursor | null { + const decoded = decode(raw); + return decoded && isUuidField(decoded.id) ? { id: decoded.id } : null; +} + +export function encodeMessageCursor(cursor: MessageCursor): string { + return encode(cursor); +} + +export function decodeMessageCursor(raw: string): MessageCursor | null { + const decoded = decode(raw); + return decoded && isUuidField(decoded.chatId) && isUuidField(decoded.id) + ? { chatId: decoded.chatId, id: decoded.id } + : null; +} + +function isUuidField(value: unknown): value is string { + return typeof value === 'string' && isUuid(value); +} + +function encode(value: object): string { + return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url'); +} + +function decode(raw: string): Record | null { + try { + const parsed = JSON.parse( + Buffer.from(raw, 'base64url').toString('utf8'), + ); + return typeof parsed === 'object' && parsed !== null ? parsed : null; + } catch { + return null; + } +} diff --git a/src/common/domain.ts b/src/common/domain.ts new file mode 100644 index 0000000..d2d32dc --- /dev/null +++ b/src/common/domain.ts @@ -0,0 +1,22 @@ +export interface User { + id: string; + username: string; + displayName: string; + createdAt: string; +} + +export interface Chat { + id: string; + title: string; + memberIds: string[]; + createdAt: string; +} + +export interface Message { + id: string; + chatId: string; + senderId: string; + text: string; + createdAt: string; + attachmentIds: string[]; +} diff --git a/src/common/dto/code-point-length.validator.ts b/src/common/dto/code-point-length.validator.ts new file mode 100644 index 0000000..4683baa --- /dev/null +++ b/src/common/dto/code-point-length.validator.ts @@ -0,0 +1,33 @@ +import { registerDecorator, ValidationOptions } from 'class-validator'; + +export function codePointLength(value: string): number { + return [...value].length; +} + +export function CodePointLength( + min: number, + max: number, + options?: ValidationOptions, +) { + return function (object: object, propertyName: string) { + registerDecorator({ + name: 'codePointLength', + target: object.constructor, + propertyName, + constraints: [min, max], + options, + validator: { + validate(value: unknown): boolean { + if (typeof value !== 'string') { + return false; + } + const length = codePointLength(value); + return length >= min && length <= max; + }, + defaultMessage(): string { + return `${propertyName} must be between ${min} and ${max} Unicode code points`; + }, + }, + }); + }; +} diff --git a/src/common/dto/not-blank.validator.ts b/src/common/dto/not-blank.validator.ts new file mode 100644 index 0000000..eea1df0 --- /dev/null +++ b/src/common/dto/not-blank.validator.ts @@ -0,0 +1,20 @@ +import { registerDecorator, ValidationOptions } from 'class-validator'; + +export function NotBlank(options?: ValidationOptions) { + return function (object: object, propertyName: string) { + registerDecorator({ + name: 'notBlank', + target: object.constructor, + propertyName, + options, + validator: { + validate(value: unknown): boolean { + return typeof value === 'string' && value.trim().length > 0; + }, + defaultMessage(): string { + return `${propertyName} must not be empty or whitespace-only`; + }, + }, + }); + }; +} diff --git a/src/common/dto/pagination-query.dto.ts b/src/common/dto/pagination-query.dto.ts new file mode 100644 index 0000000..cdeefc3 --- /dev/null +++ b/src/common/dto/pagination-query.dto.ts @@ -0,0 +1,35 @@ +import { ApiError } from '../filters/api-error'; + +const DEFAULT_LIMIT = 50; +const MIN_LIMIT = 1; +const MAX_LIMIT = 100; + +export function parseLimit(raw: unknown): number { + if (raw === undefined) { + return DEFAULT_LIMIT; + } + if (typeof raw !== 'string' || !/^\d+$/.test(raw)) { + throw new ApiError('invalid_request', 'limit must be an integer'); + } + const limit = Number(raw); + if (limit < MIN_LIMIT || limit > MAX_LIMIT) { + throw new ApiError( + 'invalid_request', + `limit must be between ${MIN_LIMIT} and ${MAX_LIMIT}`, + ); + } + return limit; +} + +export function rawCursorParam(raw: unknown): string | null { + if (raw === undefined) { + return null; + } + if (typeof raw !== 'string' || raw.length === 0) { + throw new ApiError( + 'invalid_request', + 'cursor must be a non-empty string', + ); + } + return raw; +} diff --git a/src/common/filters/api-error.ts b/src/common/filters/api-error.ts new file mode 100644 index 0000000..f3f9d18 --- /dev/null +++ b/src/common/filters/api-error.ts @@ -0,0 +1,34 @@ +import { HttpException, HttpStatus } from '@nestjs/common'; + +export type ErrorCode = + | 'invalid_request' + | 'unauthorized' + | 'not_found' + | 'conflict' + | 'payload_too_large' + | 'unsupported_media_type' + | 'rate_limited' + | 'unavailable' + | 'internal_error'; + +const STATUS_BY_CODE: Record = { + invalid_request: HttpStatus.BAD_REQUEST, + unauthorized: HttpStatus.UNAUTHORIZED, + not_found: HttpStatus.NOT_FOUND, + conflict: HttpStatus.CONFLICT, + payload_too_large: HttpStatus.PAYLOAD_TOO_LARGE, + unsupported_media_type: HttpStatus.UNSUPPORTED_MEDIA_TYPE, + rate_limited: HttpStatus.TOO_MANY_REQUESTS, + unavailable: HttpStatus.SERVICE_UNAVAILABLE, + internal_error: HttpStatus.INTERNAL_SERVER_ERROR, +}; + +export class ApiError extends HttpException { + constructor( + public readonly code: ErrorCode, + message: string, + public readonly headers: Record = {}, + ) { + super(message, STATUS_BY_CODE[code]); + } +} diff --git a/src/common/filters/http-exception.filter.ts b/src/common/filters/http-exception.filter.ts new file mode 100644 index 0000000..0a79a1b --- /dev/null +++ b/src/common/filters/http-exception.filter.ts @@ -0,0 +1,115 @@ +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + HttpStatus, + Logger, +} from '@nestjs/common'; +import { FastifyReply, FastifyRequest } from 'fastify'; +import { isDatabaseUnavailable } from '../../db/prisma.service'; +import { ApiError, ErrorCode } from './api-error'; + +const CODE_BY_STATUS: Partial> = { + [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', +}; + +interface Resolved { + status: number; + code: ErrorCode; + message: string; +} + +@Catch() +export class HttpExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger('HttpExceptionFilter'); + + catch(exception: unknown, host: ArgumentsHost): void { + const ctx = host.switchToHttp(); + const reply = ctx.getResponse(); + const request = ctx.getRequest(); + const requestId = request.requestId; + + const { status, code, message } = this.resolve(exception); + if (status >= 500) { + this.logger.error( + `${request.method} ${request.url} -> ${status}: ${message}`, + ); + } + + if (exception instanceof ApiError) { + reply.headers(exception.headers); + } + reply + .code(status) + .header('x-request-id', requestId) + .send({ error: { code, message, request_id: requestId } }); + } + + private resolve(exception: unknown): Resolved { + if (exception instanceof ApiError) { + return { + status: exception.getStatus(), + code: exception.code, + message: exception.message, + }; + } + if (exception instanceof HttpException) { + const status = exception.getStatus(); + const code = CODE_BY_STATUS[status] ?? 'internal_error'; + const message = + extractMessage(exception.getResponse()) ?? exception.message; + return { status, code, message }; + } + const fastifyStatus = (exception as { statusCode?: unknown }) + ?.statusCode; + if (typeof fastifyStatus === 'number' && CODE_BY_STATUS[fastifyStatus]) { + const message = + exception instanceof Error ? exception.message : 'Invalid request'; + return { + status: fastifyStatus, + code: CODE_BY_STATUS[fastifyStatus]!, + message, + }; + } + if (isDatabaseUnavailable(exception)) { + return { + status: 503, + code: 'unavailable', + message: 'database unavailable', + }; + } + return { + status: 500, + code: 'internal_error', + message: 'Internal server error', + }; + } +} + +function extractMessage(response: unknown): string | null { + if (typeof response === 'string') { + return response; + } + if ( + typeof response === 'object' && + response !== null && + 'message' in response + ) { + const value = (response as { message: unknown }).message; + if (typeof value === 'string') { + return value; + } + if (Array.isArray(value) && value.every((v) => typeof v === 'string')) { + return value.join('; '); + } + } + return null; +} diff --git a/src/common/interceptors/request-id.ts b/src/common/interceptors/request-id.ts new file mode 100644 index 0000000..fc49470 --- /dev/null +++ b/src/common/interceptors/request-id.ts @@ -0,0 +1,23 @@ +import { randomUUID } from 'crypto'; +import { FastifyInstance, FastifyRequest } from 'fastify'; +import { hostname } from 'os'; + +const REQUEST_ID_HEADER = 'x-request-id'; +const INSTANCE_ID_HEADER = 'x-instance-id'; + +export const INSTANCE_ID = process.env.INSTANCE_ID ?? hostname(); + +declare module 'fastify' { + interface FastifyRequest { + requestId: string; + } +} + +export function registerRequestId(instance: FastifyInstance): void { + instance.addHook('onRequest', (request: FastifyRequest, reply, done) => { + request.requestId = randomUUID(); + reply.header(REQUEST_ID_HEADER, request.requestId); + reply.header(INSTANCE_ID_HEADER, INSTANCE_ID); + done(); + }); +} diff --git a/src/common/uuid.ts b/src/common/uuid.ts new file mode 100644 index 0000000..a148256 --- /dev/null +++ b/src/common/uuid.ts @@ -0,0 +1,6 @@ +const UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function validate(value: string): boolean { + return UUID_PATTERN.test(value); +} diff --git a/src/configure-app.ts b/src/configure-app.ts new file mode 100644 index 0000000..b369304 --- /dev/null +++ b/src/configure-app.ts @@ -0,0 +1,21 @@ +import { ValidationPipe } from '@nestjs/common'; +import { NestFastifyApplication } from '@nestjs/platform-fastify'; +import { registerUploadBody } from './attachments/upload-body'; +import { HttpExceptionFilter } from './common/filters/http-exception.filter'; +import { registerRequestId } from './common/interceptors/request-id'; + +export function configureApp(app: NestFastifyApplication): void { + const instance = app.getHttpAdapter().getInstance(); + registerRequestId(instance); + registerUploadBody(instance); + + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + forbidUnknownValues: true, + }), + ); + app.useGlobalFilters(new HttpExceptionFilter()); +} diff --git a/src/db/db.module.ts b/src/db/db.module.ts new file mode 100644 index 0000000..2dac775 --- /dev/null +++ b/src/db/db.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { PrismaService } from './prisma.service'; + +@Global() +@Module({ + providers: [PrismaService], + exports: [PrismaService], +}) +export class DbModule {} diff --git a/src/db/prisma.service.ts b/src/db/prisma.service.ts new file mode 100644 index 0000000..e391433 --- /dev/null +++ b/src/db/prisma.service.ts @@ -0,0 +1,49 @@ +import { Injectable, OnModuleDestroy } from '@nestjs/common'; +import { Prisma, PrismaClient } from '@prisma/client'; +import { readFileSync } from 'fs'; + +const UNAVAILABLE_CODES = new Set(['P1001', 'P1002', 'P1008', 'P1017', 'P2024']); + +@Injectable() +export class PrismaService extends PrismaClient implements OnModuleDestroy { + constructor() { + super({ datasourceUrl: readDatabaseUrl() }); + } + + async onModuleDestroy(): Promise { + await this.$disconnect(); + } +} + +function readDatabaseUrl(): string { + const file = process.env.DATABASE_URL_FILE; + const url = file ? readFileSync(file, 'utf8').trim() : process.env.DATABASE_URL; + if (!url) { + throw new Error('DATABASE_URL_FILE or DATABASE_URL must be set'); + } + return url; +} + +export function isUniqueViolation(error: unknown): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2002' + ); +} + +export function isForeignKeyViolation(error: unknown): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2003' + ); +} + +export function isDatabaseUnavailable(error: unknown): boolean { + if (error instanceof Prisma.PrismaClientInitializationError) { + return true; + } + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + UNAVAILABLE_CODES.has(error.code) + ); +} diff --git a/src/docs/examples.ts b/src/docs/examples.ts new file mode 100644 index 0000000..5fcf2cd --- /dev/null +++ b/src/docs/examples.ts @@ -0,0 +1,351 @@ +const ALICE_ID = '11111111-1111-4111-8111-111111111111'; +const BOB_ID = '22222222-2222-4222-8222-222222222222'; +const CHAT_ID = '33333333-3333-4333-8333-333333333333'; +const MESSAGE_ID = '44444444-4444-4444-8444-444444444444'; +const CURSOR = + 'eyJjaGF0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJpZCI6IjQ0NDQ0NDQ0LTQ0NDQtNDQ0NC04NDQ0LTQ0NDQ0NDQ0NDQ0NCJ9'; + +const ALICE = { + id: ALICE_ID, + username: 'alice', + display_name: 'Алиса', + created_at: '2026-09-01T12:00:00.000Z', +}; + +const CHAT = { + id: CHAT_ID, + title: 'Проект по ВНП', + member_ids: [ALICE_ID, BOB_ID], + created_at: '2026-09-01T12:01:00.000Z', +}; + +const MESSAGE = { + id: MESSAGE_ID, + chat_id: CHAT_ID, + sender_id: ALICE_ID, + text: 'Привет, Боб! 👋', + created_at: '2026-09-01T12:02:00.000Z', + attachment_ids: [], +}; + +export interface Example { + summary: string; + value: unknown; +} + +export interface OperationExamples { + request?: Record; + responses: Record>; +} + +function example(summary: string, value: unknown): Example { + return { summary, value }; +} + +function error(code: string, message: string): unknown { + return { + error: { + code, + message, + request_id: '9b2c6f1e-5d4a-4c3b-8a2f-1e0d9c8b7a6f', + }, + }; +} + +const UNAUTHORIZED = { + missing: example( + 'Нет/неверный/истёкший/отозванный Bearer-токен', + error('unauthorized', 'missing or invalid session'), + ), +}; + +const UNAVAILABLE = { + database: example( + 'PostgreSQL недоступен', + error('unavailable', 'database unavailable'), + ), +}; + +const CHAT_NOT_FOUND = { + notFound: example( + 'Чата нет или вызывающий не участник (не 403)', + error('not_found', 'chat not found'), + ), +}; + +const INVALID_CHAT_ID = example( + 'chat_id не UUID', + error('invalid_request', 'chatId must be a valid UUID'), +); + +export const GUIDE = ` +Учебный мессенджер, лабораторная 6: PostgreSQL, сессии, Redis-кэш сессий, вложения в S3 и их фоновая обработка. +Документ — обязательный контракт \`contracts/openapi.json\`, дополненный примерами запросов и ответов. + +**Как пройти сценарий в Swagger UI** + +1. \`POST /api/v1/users\` — зарегистрируйте пользователей (примеры alice, bob, eve в списке Examples). Повторная регистрация того же username — 409, меняйте username. +2. **Authorize → basicAuth**: username и password из шага 1 → \`POST /api/v1/auth/sessions\` → скопируйте \`token\`. +3. **Authorize → bearerAuth**: вставьте token (без слова Bearer). Basic отправляется только на вход, остальные запросы идут с Bearer. +4. \`GET /api/v1/users/me\` — свой id; id второго участника — из ответа его регистрации. +5. \`POST /api/v1/chats\` с \`member_ids\` = [свой id, id собеседника] → \`chat_id\`. +6. \`POST /api/v1/chats/{chat_id}/messages\` с заголовком \`Idempotency-Key\` (любая строка из \`A-Za-z0-9._:-\`, до 128 символов). Повтор с тем же ключом и телом вернёт то же сообщение, с другим телом — 409. Затем \`GET …/messages?limit=1\` и следующая страница с \`cursor\` = \`next_cursor\`. +7. \`POST /api/v1/chats/{chat_id}/attachments?filename=photo.png\` с телом PNG/JPEG → 202 \`queued\`. \`GET /api/v1/attachments/{id}\` повторять, пока \`status\` не станет \`ready\` (до этого \`/content\` отвечает 409), затем \`/content?variant=thumbnail\`, \`crop\` или \`optimized\`. +8. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token. +9. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401. + +Сессия живёт \`SESSION_TTL_SECONDS\` (по умолчанию 3600 с). Пароль — 12–128 символов Unicode, двоеточие допустимо. +`; + +export const OPERATION_EXAMPLES: Record = { + 'GET /health/live': { + responses: { + '200': { ok: example('Процесс жив', { status: 'ok' }) }, + }, + }, + 'GET /health/ready': { + responses: { + '200': { + ok: example('PostgreSQL доступен (Redis не критичен)', { + status: 'ok', + }), + }, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/users': { + request: { + alice: example('Алиса', { + username: 'alice', + display_name: 'Алиса', + password: 'Alice-password-123', + }), + bob: example('Боб', { + username: 'bob', + display_name: 'Боб', + password: 'Bob-password-123', + }), + eve: example('Ева (посторонняя)', { + username: 'eve', + display_name: 'Ева', + password: 'Eve-password-123', + }), + colon: example('Пароль с двоеточием и эмодзи', { + username: 'carol', + display_name: 'Кэрол 🌸', + password: 'пароль:с:двоеточием🔑', + }), + }, + responses: { + '201': { created: example('Пользователь создан', ALICE) }, + '400': { + username: example( + 'username не соответствует [a-z0-9_]{3,32}', + error('invalid_request', 'username must match [a-z0-9_]{3,32}'), + ), + password: example( + 'password короче 12 символов', + error( + 'invalid_request', + 'password must be between 12 and 128 Unicode code points', + ), + ), + extra: example( + 'Лишнее поле в JSON', + error('invalid_request', 'property extra should not exist'), + ), + }, + '409': { + taken: example( + 'username уже занят', + error('conflict', 'username is already taken'), + ), + }, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/auth/sessions': { + responses: { + '201': { + created: example('Сессия создана', { + token: 'q8Hn3vXl0ZbJ7mWcY2sRkT5uPaE9dFgVhN1oLxI4w6A', + token_type: 'Bearer', + expires_at: '2026-09-01T13:00:00.000Z', + user: ALICE, + }), + }, + '401': { + invalid: example( + 'Неверный пароль, неизвестный пользователь или нет Basic — ответ одинаковый', + error('unauthorized', 'invalid credentials'), + ), + }, + '503': UNAVAILABLE, + }, + }, + 'DELETE /api/v1/auth/sessions/current': { + responses: { + '401': UNAUTHORIZED, + '503': { + ...UNAVAILABLE, + cache: example( + 'Redis недоступен — отзыв не выполнен, повторите позже', + error('unavailable', 'session cache unavailable'), + ), + }, + }, + }, + 'GET /api/v1/users/me': { + responses: { + '200': { me: example('Текущий пользователь из сессии', ALICE) }, + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/chats': { + request: { + pair: example('Чат Алисы и Боба', { + title: CHAT.title, + member_ids: CHAT.member_ids, + }), + solo: example('Чат только с собой', { + title: 'Заметки', + member_ids: [ALICE_ID], + }), + }, + responses: { + '201': { created: example('Чат создан атомарно', CHAT) }, + '400': { + noCaller: example( + 'Вызывающий не в member_ids', + error('invalid_request', 'member_ids must include the caller'), + ), + unknown: example( + 'Неизвестный участник — транзакция откатывается', + error('invalid_request', 'member_ids contain an unknown user'), + ), + duplicate: example( + 'Дубликаты в member_ids', + error( + 'invalid_request', + "All member_ids's elements must be unique", + ), + ), + }, + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/chats': { + responses: { + '200': { + page: example('Страница чатов с продолжением', { + items: [CHAT], + next_cursor: 'eyJpZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyJ9', + }), + last: example('Последняя страница', { + items: [CHAT], + next_cursor: null, + }), + }, + '400': { + limit: example( + 'limit вне 1–100', + error('invalid_request', 'limit must be between 1 and 100'), + ), + cursor: example( + 'Испорченный или чужой cursor', + error('invalid_request', 'invalid cursor'), + ), + }, + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/chats/{chat_id}': { + responses: { + '200': { chat: example('Чат, где вызывающий — участник', CHAT) }, + '400': { chatId: INVALID_CHAT_ID }, + '401': UNAUTHORIZED, + '404': CHAT_NOT_FOUND, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/chats/{chat_id}/messages': { + request: { + text: example('Обычное сообщение', { text: MESSAGE.text }), + long: example('Максимум — 4000 символов Unicode', { + text: 'Длинный текст…', + }), + }, + responses: { + '201': { + created: example('Отправитель берётся из сессии', MESSAGE), + }, + '400': { + blank: example( + 'Пустой или пробельный текст', + error( + 'invalid_request', + 'text must not be empty or whitespace-only', + ), + ), + sender: example( + 'sender_id в теле не принимается', + error('invalid_request', 'property sender_id should not exist'), + ), + chatId: INVALID_CHAT_ID, + key: example( + 'Нет Idempotency-Key или неверный формат', + error( + 'invalid_request', + 'Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}', + ), + ), + }, + '401': UNAUTHORIZED, + '404': CHAT_NOT_FOUND, + '409': { + keyReused: example( + 'Тот же Idempotency-Key с другим телом', + error( + 'conflict', + 'Idempotency-Key was already used with a different request', + ), + ), + }, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/chats/{chat_id}/messages': { + responses: { + '200': { + page: example('Страница истории (limit=1) с cursor', { + items: [MESSAGE], + next_cursor: CURSOR, + }), + last: example('Последняя страница', { + items: [MESSAGE], + next_cursor: null, + }), + }, + '400': { + otherChat: example( + 'cursor от другого чата', + error('invalid_request', 'cursor belongs to a different chat'), + ), + cursor: example( + 'Испорченный cursor или cursor несуществующего сообщения', + error('invalid_request', 'invalid cursor'), + ), + limit: example( + 'limit вне 1–100', + error('invalid_request', 'limit must be between 1 and 100'), + ), + }, + '401': UNAUTHORIZED, + '404': CHAT_NOT_FOUND, + '503': UNAVAILABLE, + }, + }, +}; diff --git a/src/docs/swagger.ts b/src/docs/swagger.ts new file mode 100644 index 0000000..4cff8ac --- /dev/null +++ b/src/docs/swagger.ts @@ -0,0 +1,43 @@ +import { NestFastifyApplication } from '@nestjs/platform-fastify'; +import { OpenAPIObject, SwaggerModule } from '@nestjs/swagger'; +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { GUIDE, OPERATION_EXAMPLES } from './examples'; + +const CONTRACT_PATH = join(process.cwd(), 'contracts', 'openapi.json'); + +export function setupSwagger(app: NestFastifyApplication): void { + SwaggerModule.setup('docs', app, loadDocument(), { + customSiteTitle: 'Messenger lab6 API', + swaggerOptions: { + persistAuthorization: true, + displayRequestDuration: true, + tryItOutEnabled: true, + }, + }); +} + +export function loadDocument(): OpenAPIObject { + const document = JSON.parse(readFileSync(CONTRACT_PATH, 'utf8')); + document.info.description = GUIDE; + document.servers = [{ url: '/', description: 'Этот экземпляр API' }]; + for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) { + const [method, path] = key.split(' '); + const operation = document.paths[path]?.[method.toLowerCase()]; + if (!operation) { + throw new Error(`examples for unknown operation ${key}`); + } + if (examples.request) { + operation.requestBody.content['application/json'].examples = + examples.request; + } + for (const [status, named] of Object.entries(examples.responses)) { + const content = operation.responses[status]?.content; + if (!content) { + throw new Error(`examples for unknown response ${key} ${status}`); + } + content['application/json'].examples = named; + } + } + return document; +} diff --git a/src/health/health.controller.ts b/src/health/health.controller.ts new file mode 100644 index 0000000..54c8987 --- /dev/null +++ b/src/health/health.controller.ts @@ -0,0 +1,44 @@ +import { Controller, Get } from '@nestjs/common'; +import { ApiError } from '../common/filters/api-error'; +import { PrismaService } from '../db/prisma.service'; +import { S3Service } from '../storage/s3.service'; +import { isDraining } from './shutdown'; + +@Controller('health') +export class HealthController { + constructor( + private readonly prisma: PrismaService, + private readonly s3: S3Service, + ) {} + + @Get('live') + live(): { status: 'ok' } { + return { status: 'ok' }; + } + + @Get('core') + async core(): Promise<{ status: 'ok' }> { + await this.assertCoreReady(); + return { status: 'ok' }; + } + + @Get('ready') + async ready(): Promise<{ status: 'ok' }> { + await this.assertCoreReady(); + if (!(await this.s3.isAvailable())) { + throw new ApiError('unavailable', 'object storage unavailable'); + } + return { status: 'ok' }; + } + + private async assertCoreReady(): Promise { + if (isDraining()) { + throw new ApiError('unavailable', 'shutting down'); + } + try { + await this.prisma.$queryRaw`SELECT 1`; + } catch { + throw new ApiError('unavailable', 'database unavailable'); + } + } +} diff --git a/src/health/health.module.ts b/src/health/health.module.ts new file mode 100644 index 0000000..a61d8b0 --- /dev/null +++ b/src/health/health.module.ts @@ -0,0 +1,7 @@ +import { Module } from '@nestjs/common'; +import { HealthController } from './health.controller'; + +@Module({ + controllers: [HealthController], +}) +export class HealthModule {} diff --git a/src/health/shutdown.ts b/src/health/shutdown.ts new file mode 100644 index 0000000..329f27d --- /dev/null +++ b/src/health/shutdown.ts @@ -0,0 +1,26 @@ +import { INestApplication, Logger } from '@nestjs/common'; + +let draining = false; + +export function isDraining(): boolean { + return draining; +} + +export function enableGracefulShutdown(app: INestApplication): void { + const delayMs = Number(process.env.SHUTDOWN_DELAY_MS ?? 3000); + const shutdown = (signal: string): void => { + if (draining) { + return; + } + draining = true; + Logger.log(`${signal}: readiness → 503, closing in ${delayMs} ms`, 'Shutdown'); + setTimeout(() => { + app.close().then( + () => process.exit(0), + () => process.exit(1), + ); + }, delayMs); + }; + process.once('SIGTERM', () => shutdown('SIGTERM')); + process.once('SIGINT', () => shutdown('SIGINT')); +} diff --git a/src/jobs/job-message.ts b/src/jobs/job-message.ts new file mode 100644 index 0000000..3fbeeb4 --- /dev/null +++ b/src/jobs/job-message.ts @@ -0,0 +1,69 @@ +import { validate as isUuid } from '../common/uuid'; + +export const PIPELINE_VERSION = 1; +export const JOB_TYPE = 'attachment.process.v1'; + +export interface JobMessage { + schema_version: 1; + job_id: string; + type: typeof JOB_TYPE; + attachment_id: string; + pipeline_version: number; + attempt: number; + created_at: string; +} + +const FIELDS = [ + 'schema_version', + 'job_id', + 'type', + 'attachment_id', + 'pipeline_version', + 'attempt', + 'created_at', +]; + +export function jobMessage( + job: { id: string; attachmentId: string; pipelineVersion: number; attempt: number }, + createdAt: Date, +): JobMessage { + return { + schema_version: 1, + job_id: job.id, + type: JOB_TYPE, + attachment_id: job.attachmentId, + pipeline_version: job.pipelineVersion, + attempt: job.attempt, + created_at: createdAt.toISOString(), + }; +} + +export function parseJobMessage(raw: Buffer): JobMessage | null { + let value: any; + try { + value = JSON.parse(raw.toString('utf8')); + } catch { + return null; + } + if ( + typeof value !== 'object' || + value === null || + Array.isArray(value) || + Object.keys(value).some((key) => !FIELDS.includes(key)) || + value.schema_version !== 1 || + value.type !== JOB_TYPE || + typeof value.job_id !== 'string' || + !isUuid(value.job_id) || + typeof value.attachment_id !== 'string' || + !isUuid(value.attachment_id) || + !Number.isInteger(value.pipeline_version) || + value.pipeline_version < 1 || + !Number.isInteger(value.attempt) || + value.attempt < 1 || + typeof value.created_at !== 'string' || + Number.isNaN(Date.parse(value.created_at)) + ) { + return null; + } + return value as JobMessage; +} diff --git a/src/jobs/job-store.ts b/src/jobs/job-store.ts new file mode 100644 index 0000000..0893f9c --- /dev/null +++ b/src/jobs/job-store.ts @@ -0,0 +1,257 @@ +import { AttachmentJob, Prisma, PrismaClient } from '@prisma/client'; +import { randomUUID } from 'crypto'; +import { jobMessage, PIPELINE_VERSION } from './job-message'; + +type Tx = Prisma.TransactionClient; + +export const RETRY_EXHAUSTED = 'retry_exhausted'; + +export function maxAttempts(): number { + return Number(process.env.JOB_MAX_ATTEMPTS ?? 5); +} + +export function backoffMs(attempt: number, random = Math.random): number { + const base = Number(process.env.JOB_RETRY_BASE_MS ?? 1000); + const cap = Number(process.env.JOB_RETRY_MAX_MS ?? 30000); + const delay = Math.min(cap, base * 2 ** (attempt - 1)); + return Math.round(delay / 2 + random() * (delay / 2)); +} + +export async function enqueueJob( + tx: Tx, + attachmentId: string, + now: Date, +): Promise { + const job = await tx.attachmentJob.create({ + data: { + id: randomUUID(), + attachmentId, + pipelineVersion: PIPELINE_VERSION, + status: 'queued', + attempt: 1, + maxAttempts: maxAttempts(), + nextAttemptAt: now, + createdAt: now, + updatedAt: now, + }, + }); + await tx.jobEvent.create({ + data: { jobId: job.id, attempt: 1, event: 'enqueued', createdAt: now }, + }); + await publishLater(tx, job, now); + return job; +} + +export async function scheduleRetry( + tx: Tx, + job: AttachmentJob, + reason: string, + now: Date, + event = 'retry_scheduled', +): Promise { + const delay = backoffMs(job.attempt); + const next = await tx.attachmentJob.update({ + where: { id: job.id }, + data: { + status: 'queued', + attempt: job.attempt + 1, + nextAttemptAt: new Date(now.getTime() + delay), + leaseOwner: null, + leaseUntil: null, + lastError: reason, + }, + }); + await tx.attachment.update({ + where: { id: job.attachmentId }, + data: { status: 'queued' }, + }); + await tx.jobEvent.create({ + data: { + jobId: job.id, + attempt: job.attempt, + event, + detail: `${reason}; next attempt ${next.attempt} in ${delay} ms`, + createdAt: now, + }, + }); + await publishLater(tx, next, next.nextAttemptAt); + return next; +} + +export async function markFailed( + tx: Tx, + job: AttachmentJob, + errorCode: string, + reason: string, + now: Date, +): Promise { + await tx.attachmentJob.update({ + where: { id: job.id }, + data: { + status: 'failed', + errorCode, + lastError: reason, + leaseOwner: null, + leaseUntil: null, + finishedAt: now, + }, + }); + await tx.attachment.update({ + where: { id: job.attachmentId }, + data: { status: 'failed', errorCode }, + }); + await tx.jobEvent.create({ + data: { + jobId: job.id, + attempt: job.attempt, + event: 'failed', + detail: `${errorCode}: ${reason}`, + createdAt: now, + }, + }); +} + +export async function retryOrFail( + tx: Tx, + job: AttachmentJob, + reason: string, + now: Date, + event?: string, +): Promise<'retry' | 'failed'> { + if (job.attempt >= job.maxAttempts) { + await markFailed(tx, job, RETRY_EXHAUSTED, reason, now); + return 'failed'; + } + await scheduleRetry(tx, job, reason, now, event); + return 'retry'; +} + +export async function recoverExpiredLeases( + prisma: PrismaClient, + now = new Date(), + limit = 100, +): Promise { + const expired = await prisma.attachmentJob.findMany({ + where: { status: 'processing', leaseUntil: { lt: now } }, + orderBy: { leaseUntil: 'asc' }, + take: limit, + }); + let recovered = 0; + for (const candidate of expired) { + await prisma.$transaction(async (tx) => { + const taken = await tx.attachmentJob.updateMany({ + where: { + id: candidate.id, + status: 'processing', + leaseOwner: candidate.leaseOwner, + leaseUntil: { lt: now }, + }, + data: { leaseOwner: null, leaseUntil: null, status: 'queued' }, + }); + if (taken.count === 0) { + return; + } + await retryOrFail(tx, candidate, 'lease expired', now, 'lease_expired'); + recovered++; + }); + } + return recovered; +} + +export async function republishStale( + prisma: PrismaClient, + staleMs: number, + now = new Date(), + limit = 100, +): Promise { + const cutoff = new Date(now.getTime() - staleMs); + const stale = await prisma.$queryRaw` + SELECT j.id, j.attachment_id AS "attachmentId", j.pipeline_version AS "pipelineVersion", j.attempt + FROM attachment_jobs j + WHERE j.status = 'queued' + AND j.next_attempt_at < ${cutoff} + AND NOT EXISTS ( + SELECT 1 FROM outbox o + WHERE o.job_id = j.id AND (o.published_at IS NULL OR o.published_at > ${cutoff}) + ) + ORDER BY j.next_attempt_at + LIMIT ${limit}`; + for (const job of stale) { + await prisma.$transaction(async (tx) => { + await tx.jobEvent.create({ + data: { jobId: job.id, attempt: job.attempt, event: 'republished', createdAt: now }, + }); + await publishLater(tx, job, now); + }); + } + return stale.length; +} + +export type ReplayResult = + | 'replayed' + | 'already_ready' + | 'not_failed' + | 'source_missing' + | 'not_found'; + +export async function replayJob( + prisma: PrismaClient, + jobId: string, + actor: string, + now = new Date(), +): Promise { + return prisma.$transaction(async (tx) => { + const job = await tx.attachmentJob.findUnique({ where: { id: jobId } }); + if (!job) { + return 'not_found'; + } + if (job.status === 'ready') { + return 'already_ready'; + } + if (job.status !== 'failed') { + return 'not_failed'; + } + const source = await tx.attachment.updateMany({ + where: { id: job.attachmentId, status: 'failed', stagingKey: { not: null } }, + data: { status: 'queued', errorCode: null }, + }); + if (source.count === 0) { + return 'source_missing'; + } + const taken = await tx.attachmentJob.updateMany({ + where: { id: jobId, status: 'failed' }, + data: { + status: 'queued', + attempt: 1, + errorCode: null, + nextAttemptAt: now, + finishedAt: null, + }, + }); + if (taken.count === 0) { + throw new Error('job changed during replay'); + } + await tx.jobEvent.create({ + data: { + jobId, + attempt: 1, + event: 'replayed', + detail: `by ${actor}; previous ${job.errorCode} after attempt ${job.attempt}`, + createdAt: now, + }, + }); + await publishLater(tx, { ...job, attempt: 1 }, now); + return 'replayed'; + }); +} + +async function publishLater(tx: Tx, job: AttachmentJob, availableAt: Date): Promise { + await tx.outboxEntry.create({ + data: { + jobId: job.id, + payload: jobMessage(job, availableAt) as unknown as Prisma.InputJsonObject, + availableAt, + createdAt: new Date(), + }, + }); +} diff --git a/src/jobs/processor.ts b/src/jobs/processor.ts new file mode 100644 index 0000000..a1f1a1b --- /dev/null +++ b/src/jobs/processor.ts @@ -0,0 +1,273 @@ +import { Logger } from '@nestjs/common'; +import { Attachment, AttachmentJob, PrismaClient } from '@prisma/client'; +import { createHash, randomUUID } from 'crypto'; +import { + ObjectMissingError, + ObjectTooLargeError, + S3Service, +} from '../storage/s3.service'; +import { JobMessage, PIPELINE_VERSION } from './job-message'; +import { markFailed, retryOrFail } from './job-store'; +import { + InvalidImageError, + RenderedVariant, + RenderTimeoutError, + renderVariants, +} from './variants'; + +export type Outcome = 'ready' | 'retry' | 'failed' | 'skipped'; + +export interface ProcessorOptions { + timeoutMs: number; + leaseMs: number; + maxBytes: number; + maxPixels: number; +} + +export function processorOptions(): ProcessorOptions { + const timeoutMs = Number(process.env.JOB_TIMEOUT_SECONDS ?? 60) * 1000; + return { + timeoutMs, + leaseMs: Number(process.env.JOB_LEASE_SECONDS ?? timeoutMs / 1000 + 30) * 1000, + maxBytes: Number(process.env.MAX_UPLOAD_BYTES ?? 10485760), + maxPixels: Number(process.env.MAX_IMAGE_PIXELS ?? 40000000), + }; +} + +export interface ProcessorHooks { + afterStore?: () => Promise; + afterCommit?: () => Promise; +} + +class PermanentError extends Error { + constructor( + readonly code: string, + reason: string, + ) { + super(reason); + } +} + +class TimeoutError extends Error {} + +export class JobProcessor { + private readonly logger = new Logger('JobProcessor'); + + constructor( + private readonly prisma: PrismaClient, + private readonly s3: S3Service, + private readonly options: ProcessorOptions = processorOptions(), + private readonly hooks: ProcessorHooks = {}, + ) {} + + async handle(message: JobMessage): Promise { + const job = await this.prisma.attachmentJob.findUnique({ + where: { id: message.job_id }, + include: { attachment: true }, + }); + if ( + !job || + job.attachmentId !== message.attachment_id || + job.pipelineVersion !== message.pipeline_version || + job.pipelineVersion !== PIPELINE_VERSION + ) { + this.logger.warn(`job ${message.job_id}: unknown or mismatched, dropped`); + return 'skipped'; + } + const lease = await this.claim(job); + if (!lease) { + if (job.status === 'ready') { + await this.removeStaging(job.attachment); + } + this.logger.log(`job ${job.id}: ${job.status}, not due or leased elsewhere, skipped`); + return 'skipped'; + } + let variants: RenderedVariant[]; + try { + variants = await this.withTimeout(this.produce(job.attachment)); + } catch (error) { + return this.recordFailure(lease, error); + } + await this.hooks.afterStore?.(); + return this.commit(lease, job.attachment, variants); + } + + private async claim(job: AttachmentJob): Promise { + const now = new Date(); + const owner = randomUUID(); + return this.prisma.$transaction(async (tx) => { + const taken = await tx.attachmentJob.updateMany({ + where: { id: job.id, status: 'queued', nextAttemptAt: { lte: now } }, + data: { + status: 'processing', + leaseOwner: owner, + leaseUntil: new Date(now.getTime() + this.options.leaseMs), + }, + }); + if (taken.count === 0) { + return null; + } + await tx.attachment.update({ + where: { id: job.attachmentId }, + data: { status: 'processing' }, + }); + const leased = await tx.attachmentJob.findUniqueOrThrow({ where: { id: job.id } }); + await tx.jobEvent.create({ + data: { jobId: job.id, attempt: leased.attempt, event: 'processing', createdAt: now }, + }); + return leased; + }); + } + + private async produce(attachment: Attachment): Promise { + if (!attachment.stagingKey) { + throw new PermanentError('staging_missing', 'staging object was already removed'); + } + let original: Buffer; + try { + original = await this.s3.getBuffer(attachment.stagingKey, this.options.maxBytes); + } catch (error) { + if (error instanceof ObjectMissingError) { + throw new PermanentError('staging_missing', 'staging object not found'); + } + if (error instanceof ObjectTooLargeError) { + throw new PermanentError('invalid_image', 'staging object exceeds size limit'); + } + throw error; + } + const sha256 = createHash('sha256').update(original).digest('hex'); + if (original.length !== attachment.sizeBytes || sha256 !== attachment.sha256) { + throw new PermanentError('checksum_mismatch', 'staging object differs from accepted upload'); + } + let variants: RenderedVariant[]; + try { + variants = await renderVariants( + original, + this.options.maxPixels, + Math.ceil(this.options.timeoutMs / 1000), + ); + } catch (error) { + if (error instanceof InvalidImageError) { + throw new PermanentError('invalid_image', 'image cannot be decoded'); + } + throw error; + } + await this.s3.putBuffer(attachment.objectKey, original, attachment.contentType, sha256); + for (const variant of variants) { + await this.s3.putBuffer( + variantKey(attachment.id, variant), + variant.body, + variant.contentType, + variant.sha256, + ); + } + return variants; + } + + private async commit( + lease: AttachmentJob, + attachment: Attachment, + variants: RenderedVariant[], + ): Promise { + const now = new Date(); + const committed = await this.prisma.$transaction(async (tx) => { + const owned = await tx.attachmentJob.updateMany({ + where: { id: lease.id, status: 'processing', leaseOwner: lease.leaseOwner }, + data: { + status: 'ready', + leaseOwner: null, + leaseUntil: null, + lastError: null, + finishedAt: now, + }, + }); + if (owned.count === 0) { + return false; + } + await tx.attachmentVariant.createMany({ + data: variants.map((variant) => ({ + attachmentId: attachment.id, + pipelineVersion: PIPELINE_VERSION, + name: variant.name, + contentType: variant.contentType, + objectKey: variantKey(attachment.id, variant), + sizeBytes: variant.body.length, + width: variant.width, + height: variant.height, + sha256: variant.sha256, + createdAt: now, + })), + skipDuplicates: true, + }); + await tx.attachment.update({ + where: { id: attachment.id }, + data: { status: 'ready', errorCode: null }, + }); + await tx.jobEvent.create({ + data: { jobId: lease.id, attempt: lease.attempt, event: 'ready', createdAt: now }, + }); + return true; + }); + if (!committed) { + this.logger.warn(`job ${lease.id}: lease lost before commit, result left to owner`); + return 'skipped'; + } + await this.hooks.afterCommit?.(); + await this.removeStaging(attachment); + return 'ready'; + } + + private async recordFailure(lease: AttachmentJob, error: unknown): Promise { + const now = new Date(); + const reason = + error instanceof PermanentError + ? error.message + : error instanceof TimeoutError || error instanceof RenderTimeoutError + ? 'processing timed out' + : `temporary failure: ${error instanceof Error ? error.name : 'unknown'}`; + this.logger.warn(`job ${lease.id} attempt ${lease.attempt}: ${reason}`); + return this.prisma.$transaction(async (tx) => { + const owned = await tx.attachmentJob.count({ + where: { id: lease.id, status: 'processing', leaseOwner: lease.leaseOwner }, + }); + if (owned === 0) { + return 'skipped' as const; + } + if (error instanceof PermanentError) { + await markFailed(tx, lease, error.code, reason, now); + return 'failed' as const; + } + return retryOrFail(tx, lease, reason, now); + }); + } + + private async removeStaging(attachment: Attachment): Promise { + if (!attachment.stagingKey) { + return; + } + try { + await this.s3.delete(attachment.stagingKey); + await this.prisma.attachment.update({ + where: { id: attachment.id }, + data: { stagingKey: null }, + }); + } catch { + this.logger.warn(`staging cleanup postponed for ${attachment.id}`); + } + } + + private withTimeout(work: Promise): Promise { + let timer: NodeJS.Timeout; + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new TimeoutError()), this.options.timeoutMs); + }); + return Promise.race([work, deadline]).finally(() => clearTimeout(timer)); + } +} + +export function variantKey( + attachmentId: string, + variant: Pick, +): string { + return `attachments/${attachmentId}/v${PIPELINE_VERSION}/${variant.name}.${variant.extension}`; +} diff --git a/src/jobs/variants.ts b/src/jobs/variants.ts new file mode 100644 index 0000000..158f778 --- /dev/null +++ b/src/jobs/variants.ts @@ -0,0 +1,111 @@ +import { createHash } from 'crypto'; +import sharp, { Sharp } from 'sharp'; + +sharp.cache(false); +sharp.concurrency(1); + +const WHITE = { r: 255, g: 255, b: 255 }; +const JPEG_QUALITY = 82; +const WEBP_QUALITY = 80; + +export interface RenderedVariant { + name: 'thumbnail' | 'crop' | 'optimized'; + contentType: string; + extension: string; + body: Buffer; + width: number; + height: number; + sha256: string; +} + +export class InvalidImageError extends Error { + constructor(reason: string) { + super(reason); + this.name = 'InvalidImageError'; + } +} + +export class RenderTimeoutError extends Error { + constructor() { + super('image processing exceeded its time limit'); + this.name = 'RenderTimeoutError'; + } +} + +export function fitInside( + width: number, + height: number, + box: number, +): { width: number; height: number } { + if (width <= box && height <= box) { + return { width, height }; + } + if (width >= height) { + return { width: box, height: Math.max(1, Math.floor((height * box) / width)) }; + } + return { width: Math.max(1, Math.floor((width * box) / height)), height: box }; +} + +export async function renderVariants( + original: Buffer, + maxPixels: number, + timeoutSeconds = 0, +): Promise { + const open = (): Sharp => + sharp(original, { failOn: 'error', limitInputPixels: maxPixels }) + .timeout({ seconds: timeoutSeconds }) + .rotate(); + try { + const meta = await sharp(original, { limitInputPixels: maxPixels }).metadata(); + if (!meta.width || !meta.height) { + throw new InvalidImageError('image has no dimensions'); + } + const swapped = (meta.orientation ?? 1) >= 5; + const width = swapped ? meta.height : meta.width; + const height = swapped ? meta.width : meta.height; + const thumb = fitInside(width, height, 256); + const large = fitInside(width, height, 1280); + const thumbnail = open() + .resize(thumb.width, thumb.height, { fit: 'fill' }) + .flatten({ background: WHITE }) + .jpeg({ quality: JPEG_QUALITY }); + const crop = open() + .resize(128, 128, { fit: 'cover', position: 'centre' }) + .flatten({ background: WHITE }) + .jpeg({ quality: JPEG_QUALITY }); + const optimized = open() + .resize(large.width, large.height, { fit: 'fill' }) + .webp({ quality: WEBP_QUALITY, effort: 4 }); + return [ + await finish('thumbnail', 'image/jpeg', 'jpg', thumbnail), + await finish('crop', 'image/jpeg', 'jpg', crop), + await finish('optimized', 'image/webp', 'webp', optimized), + ]; + } catch (error) { + if (error instanceof InvalidImageError) { + throw error; + } + if (error instanceof Error && /timeout/i.test(error.message)) { + throw new RenderTimeoutError(); + } + throw new InvalidImageError(error instanceof Error ? error.message : 'decode failed'); + } +} + +async function finish( + name: RenderedVariant['name'], + contentType: string, + extension: string, + pipeline: Sharp, +): Promise { + const { data, info } = await pipeline.toBuffer({ resolveWithObject: true }); + return { + name, + contentType, + extension, + body: data, + width: info.width, + height: info.height, + sha256: createHash('sha256').update(data).digest('hex'), + }; +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..4e6043c --- /dev/null +++ b/src/main.ts @@ -0,0 +1,34 @@ +import { Logger } from '@nestjs/common'; +import { NestFactory } from '@nestjs/core'; +import { + FastifyAdapter, + NestFastifyApplication, +} from '@nestjs/platform-fastify'; +import { AppModule } from './app.module'; +import { configureApp } from './configure-app'; +import { setupSwagger } from './docs/swagger'; +import { enableGracefulShutdown } from './health/shutdown'; + +async function bootstrap(): Promise { + const app = await NestFactory.create( + AppModule, + new FastifyAdapter(), + { + bufferLogs: true, + }, + ); + + configureApp(app); + setupSwagger(app); + enableGracefulShutdown(app); + + const host = process.env.APP_HOST ?? '0.0.0.0'; + const port = Number(process.env.APP_PORT ?? 8080); + await app.listen(port, host); + Logger.log(`Listening on http://${host}:${port}`, 'Bootstrap'); +} + +bootstrap().catch((error) => { + Logger.error('Fatal error during bootstrap', error); + process.exit(1); +}); diff --git a/src/messages/dto/create-message.dto.ts b/src/messages/dto/create-message.dto.ts new file mode 100644 index 0000000..a1dfcb3 --- /dev/null +++ b/src/messages/dto/create-message.dto.ts @@ -0,0 +1,41 @@ +import { + ArrayMaxSize, + IsArray, + IsString, + Validate, + ValidateIf, + ValidatorConstraint, + ValidatorConstraintInterface, +} from 'class-validator'; +import { CodePointLength } from '../../common/dto/code-point-length.validator'; +import { validate as isUuid } from '../../common/uuid'; + +@ValidatorConstraint({ name: 'uniqueUuidList' }) +class UniqueUuidList implements ValidatorConstraintInterface { + validate(value: unknown): boolean { + if ( + !Array.isArray(value) || + !value.every((id) => typeof id === 'string' && isUuid(id)) + ) { + return false; + } + const normalized = (value as string[]).map((id) => id.toLowerCase()); + return new Set(normalized).size === normalized.length; + } + + defaultMessage(): string { + return 'attachment_ids must contain unique UUIDs'; + } +} + +export class CreateMessageDto { + @IsString() + @CodePointLength(0, 4000) + text!: string; + + @ValidateIf((dto: CreateMessageDto) => dto.attachment_ids !== undefined) + @IsArray() + @ArrayMaxSize(10) + @Validate(UniqueUuidList) + attachment_ids?: string[]; +} diff --git a/src/messages/dto/message.response.ts b/src/messages/dto/message.response.ts new file mode 100644 index 0000000..fcf2006 --- /dev/null +++ b/src/messages/dto/message.response.ts @@ -0,0 +1,26 @@ +import { Message } from '../../common/domain'; + +export interface MessageResponse { + id: string; + chat_id: string; + sender_id: string; + text: string; + created_at: string; + attachment_ids: string[]; +} + +export interface MessagePageResponse { + items: MessageResponse[]; + next_cursor: string | null; +} + +export function toMessageResponse(message: Message): MessageResponse { + return { + id: message.id, + chat_id: message.chatId, + sender_id: message.senderId, + text: message.text, + created_at: message.createdAt, + attachment_ids: message.attachmentIds, + }; +} diff --git a/src/messages/messages.controller.ts b/src/messages/messages.controller.ts new file mode 100644 index 0000000..793b4d2 --- /dev/null +++ b/src/messages/messages.controller.ts @@ -0,0 +1,70 @@ +import { + Body, + Controller, + Get, + Headers, + HttpCode, + Param, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import { AuthGuard } from '../auth/auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { parseLimit, rawCursorParam } from '../common/dto/pagination-query.dto'; +import { User } from '../common/domain'; +import { ApiError } from '../common/filters/api-error'; +import { CreateMessageDto } from './dto/create-message.dto'; +import { + MessagePageResponse, + MessageResponse, + toMessageResponse, +} from './dto/message.response'; +import { MessagesService } from './messages.service'; + +@Controller('api/v1/chats/:chatId/messages') +@UseGuards(AuthGuard) +export class MessagesController { + constructor(private readonly messages: MessagesService) {} + + @Post() + @HttpCode(201) + async create( + @Param('chatId') chatId: string, + @Body() dto: CreateMessageDto, + @Headers('idempotency-key') keyRaw: unknown, + @CurrentUser() user: User, + ): Promise { + const key = parseIdempotencyKey(keyRaw); + const message = await this.messages.create( + chatId, + user.id, + dto.text, + (dto.attachment_ids ?? []).map((id) => id.toLowerCase()), + key, + ); + return toMessageResponse(message); + } + + @Get() + async list( + @Param('chatId') chatId: string, + @CurrentUser() user: User, + @Query('limit') limitRaw: unknown, + @Query('cursor') cursorRaw: unknown, + ): Promise { + const limit = parseLimit(limitRaw); + const cursor = rawCursorParam(cursorRaw); + return this.messages.list(chatId, user.id, limit, cursor); + } +} + +function parseIdempotencyKey(raw: unknown): string { + if (typeof raw !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(raw)) { + throw new ApiError( + 'invalid_request', + 'Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}', + ); + } + return raw; +} diff --git a/src/messages/messages.module.ts b/src/messages/messages.module.ts new file mode 100644 index 0000000..2953661 --- /dev/null +++ b/src/messages/messages.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { MessagesController } from './messages.controller'; +import { MessagesService } from './messages.service'; + +@Module({ + controllers: [MessagesController], + providers: [MessagesService], +}) +export class MessagesModule {} diff --git a/src/messages/messages.service.ts b/src/messages/messages.service.ts new file mode 100644 index 0000000..3f1df67 --- /dev/null +++ b/src/messages/messages.service.ts @@ -0,0 +1,198 @@ +import { Injectable } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { createHash } from 'crypto'; +import { assertChatMember } from '../chats/chat-access'; +import { codePointLength } from '../common/dto/code-point-length.validator'; +import { decodeMessageCursor, encodeMessageCursor } from '../common/cursor'; +import { Message } from '../common/domain'; +import { ApiError } from '../common/filters/api-error'; +import { PrismaService } from '../db/prisma.service'; +import { MessagePageResponse, toMessageResponse } from './dto/message.response'; + +interface MessageRow { + id: string; + chatId: string; + senderId: string; + text: string; + createdAt: Date; + attachmentIds: string[]; +} + +const ATTACHMENT_LINKS = { + attachments: { + orderBy: { position: 'asc' }, + select: { attachmentId: true }, + }, +} satisfies Prisma.MessageInclude; + +type MessageWithLinks = Prisma.MessageGetPayload<{ + include: typeof ATTACHMENT_LINKS; +}>; + +class KeyAlreadyUsed extends Error {} + +@Injectable() +export class MessagesService { + private readonly keyTtlMs = + Number(process.env.IDEMPOTENCY_TTL_SECONDS ?? 86400) * 1000; + + constructor(private readonly prisma: PrismaService) {} + + async create( + chatId: string, + callerId: string, + text: string, + attachmentIds: string[], + key: string, + ): Promise { + await this.assertMember(chatId, callerId); + if (codePointLength(text.trim()) === 0 && attachmentIds.length === 0) { + throw new ApiError( + 'invalid_request', + 'text must not be empty or whitespace-only without attachments', + ); + } + await this.assertAttachmentsInChat(chatId, attachmentIds); + const scope = { userId: callerId, chatId, key }; + const requestHash = createHash('sha256') + .update(JSON.stringify({ text, attachment_ids: attachmentIds })) + .digest('hex'); + try { + return await this.prisma.$transaction(async (tx) => { + await tx.idempotencyKey.deleteMany({ + where: { + ...scope, + createdAt: { lt: new Date(Date.now() - this.keyTtlMs) }, + }, + }); + const row = await tx.message.create({ + data: { + chatId, + senderId: callerId, + text, + attachments: { + create: attachmentIds.map((attachmentId, position) => ({ + attachmentId, + position, + })), + }, + }, + include: ATTACHMENT_LINKS, + }); + const { count } = await tx.idempotencyKey.createMany({ + data: [{ ...scope, requestHash, messageId: row.id }], + skipDuplicates: true, + }); + if (count === 0) { + throw new KeyAlreadyUsed(); + } + return linkedMessage(row); + }); + } catch (error) { + if (!(error instanceof KeyAlreadyUsed)) { + throw error; + } + } + const stored = await this.prisma.idempotencyKey.findUnique({ + where: { userId_chatId_key: scope }, + include: { message: { include: ATTACHMENT_LINKS } }, + }); + if (!stored || stored.requestHash !== requestHash) { + throw new ApiError( + 'conflict', + 'Idempotency-Key was already used with a different request', + ); + } + return linkedMessage(stored.message); + } + + async list( + chatId: string, + callerId: string, + limit: number, + rawCursor: string | null, + ): Promise { + await this.assertMember(chatId, callerId); + let after = Prisma.empty; + if (rawCursor !== null) { + const cursor = decodeMessageCursor(rawCursor); + if (cursor && cursor.chatId !== chatId) { + throw new ApiError( + 'invalid_request', + 'cursor belongs to a different chat', + ); + } + const anchor = cursor + ? await this.prisma.message.findFirst({ + where: { id: cursor.id, chatId }, + select: { id: true, createdAt: true }, + }) + : null; + if (!anchor) { + throw new ApiError('invalid_request', 'invalid cursor'); + } + after = Prisma.sql`AND (created_at, id) > (${anchor.createdAt}::timestamptz, ${anchor.id}::uuid)`; + } + const rows = await this.prisma.$queryRaw` + SELECT id, chat_id AS "chatId", sender_id AS "senderId", text, created_at AS "createdAt", + ARRAY( + SELECT attachment_id::text FROM message_attachments + WHERE message_id = messages.id + ORDER BY position + ) AS "attachmentIds" + FROM messages + WHERE chat_id = ${chatId}::uuid ${after} + ORDER BY created_at, id + LIMIT ${limit + 1}`; + const items = rows.slice(0, limit).map(toMessage); + const last = items[items.length - 1]; + return { + items: items.map(toMessageResponse), + next_cursor: + rows.length > limit + ? encodeMessageCursor({ chatId, id: last.id }) + : null, + }; + } + + private assertMember(chatId: string, callerId: string): Promise { + return assertChatMember(this.prisma, chatId, callerId); + } + + private async assertAttachmentsInChat( + chatId: string, + attachmentIds: string[], + ): Promise { + if (attachmentIds.length === 0) { + return; + } + const found = await this.prisma.attachment.findMany({ + where: { id: { in: attachmentIds }, chatId }, + select: { status: true }, + }); + if (found.length !== attachmentIds.length) { + throw new ApiError('not_found', 'attachment not found'); + } + if (found.some((row) => row.status === 'failed')) { + throw new ApiError('conflict', 'failed attachment cannot be attached'); + } + } +} + +function linkedMessage(row: MessageWithLinks): Message { + return toMessage({ + ...row, + attachmentIds: row.attachments.map((link) => link.attachmentId), + }); +} + +function toMessage(row: MessageRow): Message { + return { + id: row.id, + chatId: row.chatId, + senderId: row.senderId, + text: row.text, + createdAt: row.createdAt.toISOString(), + attachmentIds: row.attachmentIds, + }; +} diff --git a/src/reconcile.ts b/src/reconcile.ts new file mode 100644 index 0000000..fa91566 --- /dev/null +++ b/src/reconcile.ts @@ -0,0 +1,57 @@ +import { Logger } from '@nestjs/common'; +import { reconcile } from './attachments/reconciler'; +import { PrismaService } from './db/prisma.service'; +import { S3Service } from './storage/s3.service'; + +const DEFAULT_GRACE_SECONDS = 3600; +const DEFAULT_INTERVAL_SECONDS = 300; +const DEFAULT_STAGING_RETENTION_SECONDS = 86400; + +function option(name: string, fallback: number): number { + const prefix = `--${name}=`; + const raw = process.argv.find((arg) => arg.startsWith(prefix)); + const value = raw ? Number(raw.slice(prefix.length)) : fallback; + if (!Number.isInteger(value) || value < 0) { + throw new Error(`--${name} must be a non-negative integer`); + } + return value; +} + +async function main(): Promise { + process.once('SIGTERM', () => process.exit(0)); + process.once('SIGINT', () => process.exit(0)); + const apply = process.argv.includes('--apply'); + const loop = process.argv.includes('--loop'); + const graceSeconds = option('grace-seconds', DEFAULT_GRACE_SECONDS); + const intervalSeconds = option('interval-seconds', DEFAULT_INTERVAL_SECONDS); + const stagingRetentionSeconds = option( + 'staging-retention-seconds', + Number(process.env.STAGING_RETENTION_SECONDS ?? DEFAULT_STAGING_RETENTION_SECONDS), + ); + const prisma = new PrismaService(); + const s3 = new S3Service(); + do { + try { + const report = await reconcile(prisma, s3, { + apply, + graceMs: graceSeconds * 1000, + stagingRetentionMs: stagingRetentionSeconds * 1000, + }); + process.stdout.write(`${JSON.stringify(report)}\n`); + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + Logger.error(`reconcile pass aborted: ${reason}`, 'Reconciler'); + process.exitCode = loop ? 0 : 1; + } + if (loop) { + await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000)); + } + } while (loop); + await prisma.$disconnect(); + s3.onModuleDestroy(); +} + +main().catch((error) => { + Logger.error(error instanceof Error ? error.message : 'fatal error', 'Reconciler'); + process.exit(1); +}); diff --git a/src/relay.ts b/src/relay.ts new file mode 100644 index 0000000..5f54987 --- /dev/null +++ b/src/relay.ts @@ -0,0 +1,129 @@ +import { Logger } from '@nestjs/common'; +import { ConfirmChannel } from 'amqplib'; +import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; +import { PrismaService } from './db/prisma.service'; +import { JobMessage } from './jobs/job-message'; +import { recoverExpiredLeases, republishStale } from './jobs/job-store'; + +const BATCH_SIZE = 100; +const POLL_MS = Number(process.env.RELAY_POLL_MS ?? 500); +const SWEEP_MS = Number(process.env.RELAY_SWEEP_MS ?? 5000); +const STALE_MS = Number(process.env.JOB_STALE_SECONDS ?? 300) * 1000; +const FAULT = process.env.RELAY_FAULT; + +const logger = new Logger('OutboxRelay'); +const prisma = new PrismaService(); +let stopping = false; + +async function publishBatch(channel: ConfirmChannel): Promise { + return prisma.$transaction( + async (tx) => { + const rows = await tx.$queryRaw<{ id: bigint; payload: JobMessage }[]>` + SELECT id, payload FROM outbox + WHERE published_at IS NULL AND available_at <= ${new Date()} + ORDER BY id + LIMIT ${BATCH_SIZE} + FOR UPDATE SKIP LOCKED`; + if (rows.length === 0) { + return 0; + } + for (const { payload } of rows) { + channel.sendToQueue(JOB_QUEUE, Buffer.from(JSON.stringify(payload)), { + persistent: true, + contentType: 'application/json', + messageId: payload.job_id, + type: payload.type, + }); + } + await channel.waitForConfirms(); + logger.log(`published ${rows.length} job message(s), broker confirmed`); + if (FAULT === 'exit-after-confirm') { + logger.warn('fault injection: exit after broker confirm, before outbox is marked'); + process.exit(137); + } + await tx.outboxEntry.updateMany({ + where: { id: { in: rows.map((row) => row.id) } }, + data: { publishedAt: new Date(), publishAttempts: { increment: 1 } }, + }); + return rows.length; + }, + { timeout: 15000 }, + ); +} + +async function sweep(): Promise { + const recovered = await recoverExpiredLeases(prisma); + const republished = await republishStale(prisma, STALE_MS); + if (recovered + republished > 0) { + logger.log(`lease expired: ${recovered}, stale queued republished: ${republished}`); + } +} + +async function run(): Promise { + let lastSweep = 0; + while (!stopping) { + const connection = await connectWithRetry(logger, () => stopping); + if (!connection) { + break; + } + let closed = false; + connection.on('close', () => { + closed = true; + }); + connection.on('error', () => { + closed = true; + }); + try { + const channel = await connection.createConfirmChannel(); + channel.on('error', () => { + closed = true; + }); + channel.on('close', () => { + closed = true; + }); + await assertTopology(channel); + while (!stopping && !closed) { + let published = 0; + try { + published = await publishBatch(channel); + if (Date.now() - lastSweep >= SWEEP_MS) { + await sweep(); + lastSweep = Date.now(); + } + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`relay pass failed: ${reason}`); + await sleep(1000); + } + if (published < BATCH_SIZE) { + await sleep(POLL_MS); + } + } + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`broker channel failed: ${reason}`); + } + await connection.close().catch(() => undefined); + if (!stopping) { + logger.warn('broker connection lost, reconnecting'); + await sleep(1000); + } + } +} + +for (const signal of ['SIGTERM', 'SIGINT'] as const) { + process.once(signal, () => { + stopping = true; + }); +} + +run() + .then(async () => { + await prisma.$disconnect(); + logger.log('stopped'); + process.exit(0); + }) + .catch((error) => { + logger.error(error instanceof Error ? error.message : 'fatal error'); + process.exit(1); + }); diff --git a/src/replay.ts b/src/replay.ts new file mode 100644 index 0000000..30148a8 --- /dev/null +++ b/src/replay.ts @@ -0,0 +1,54 @@ +import { Logger } from '@nestjs/common'; +import { validate as isUuid } from './common/uuid'; +import { PrismaService } from './db/prisma.service'; +import { PIPELINE_VERSION } from './jobs/job-message'; +import { replayJob } from './jobs/job-store'; + +const USAGE = 'usage: replay.js --list | ...'; + +async function main(): Promise { + const args = process.argv.slice(2); + if (args.length === 0 || (args[0] !== '--list' && args.some((arg) => !isUuid(arg)))) { + throw new Error(USAGE); + } + const prisma = new PrismaService(); + try { + if (args[0] === '--list') { + const failed = await prisma.attachmentJob.findMany({ + where: { status: 'failed' }, + orderBy: { finishedAt: 'asc' }, + take: 100, + }); + for (const job of failed) { + process.stdout.write( + `${JSON.stringify({ + job_id: job.id, + attachment_id: job.attachmentId, + error_code: job.errorCode, + attempt: job.attempt, + last_error: job.lastError, + finished_at: job.finishedAt?.toISOString(), + })}\n`, + ); + } + return; + } + const actor = process.env.OPERATOR ?? 'operator'; + for (const id of args) { + const job = await prisma.attachmentJob.findFirst({ + where: { + OR: [{ id }, { attachmentId: id, pipelineVersion: PIPELINE_VERSION }], + }, + }); + const result = job ? await replayJob(prisma, job.id, actor) : 'not_found'; + process.stdout.write(`${JSON.stringify({ id, job_id: job?.id ?? null, result })}\n`); + } + } finally { + await prisma.$disconnect(); + } +} + +main().catch((error) => { + Logger.error(error instanceof Error ? error.message : 'fatal error', 'Replay'); + process.exit(1); +}); diff --git a/src/storage/s3.service.ts b/src/storage/s3.service.ts new file mode 100644 index 0000000..20967bb --- /dev/null +++ b/src/storage/s3.service.ts @@ -0,0 +1,245 @@ +import { + DeleteObjectCommand, + GetObjectCommand, + HeadBucketCommand, + ListObjectsV2Command, + PutObjectCommand, + S3Client, +} from '@aws-sdk/client-s3'; +import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'; +import { createReadStream, readFileSync } from 'fs'; +import { Readable } from 'stream'; +import { ApiError } from '../common/filters/api-error'; + +const CONNECT_TIMEOUT_MS = 1000; +const IDLE_TIMEOUT_MS = 5000; +const OPERATION_TIMEOUT_MS = 20000; +const HEALTH_TIMEOUT_MS = 1000; + +export interface ObjectPage { + objects: { key: string; lastModified: Date }[]; + nextToken?: string; +} + +export interface StoredFile { + key: string; + path: string; + size: number; + contentType: string; + sha256: string; +} + +@Injectable() +export class S3Service implements OnModuleDestroy { + private readonly logger = new Logger('S3Service'); + private readonly client: S3Client; + private readonly streamClient: S3Client; + private readonly bucket = process.env.S3_BUCKET ?? 'messenger-attachments'; + + constructor() { + const config = { + endpoint: process.env.S3_ENDPOINT ?? 'http://s3:9000', + region: process.env.S3_REGION ?? 'us-east-1', + forcePathStyle: true, + maxAttempts: 1, + credentials: { + accessKeyId: readSecret('S3_ACCESS_KEY_ID'), + secretAccessKey: readSecret('S3_SECRET_ACCESS_KEY'), + }, + }; + this.client = new S3Client({ + ...config, + requestHandler: { + connectionTimeout: CONNECT_TIMEOUT_MS, + requestTimeout: IDLE_TIMEOUT_MS, + }, + }); + this.streamClient = new S3Client({ + ...config, + requestHandler: { connectionTimeout: CONNECT_TIMEOUT_MS }, + }); + } + + async putFile(file: StoredFile): Promise { + await this.guard(`put ${file.key}`, () => + this.client.send( + new PutObjectCommand({ + Bucket: this.bucket, + Key: file.key, + Body: createReadStream(file.path), + ContentLength: file.size, + ContentType: file.contentType, + ChecksumSHA256: Buffer.from(file.sha256, 'hex').toString('base64'), + }), + { abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) }, + ), + ); + } + + async putBuffer( + key: string, + body: Buffer, + contentType: string, + sha256: string, + ): Promise { + await this.guard(`put ${key}`, () => + this.client.send( + new PutObjectCommand({ + Bucket: this.bucket, + Key: key, + Body: body, + ContentLength: body.length, + ContentType: contentType, + ChecksumSHA256: Buffer.from(sha256, 'hex').toString('base64'), + }), + { abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) }, + ), + ); + } + + async getBuffer(key: string, maxBytes: number): Promise { + let body: Readable; + try { + const response = await this.client.send( + new GetObjectCommand({ Bucket: this.bucket, Key: key }), + { abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) }, + ); + if ((response.ContentLength ?? 0) > maxBytes) { + throw new ObjectTooLargeError(key); + } + body = response.Body as Readable; + } catch (error) { + if (error instanceof ObjectTooLargeError) { + throw error; + } + const name = error instanceof Error ? error.name : 'unknown error'; + this.logger.error(`get ${key} failed: ${name}`); + if (name === 'NoSuchKey') { + throw new ObjectMissingError(key); + } + throw new ApiError('unavailable', 'object storage unavailable'); + } + const chunks: Buffer[] = []; + let size = 0; + try { + for await (const chunk of body) { + size += chunk.length; + if (size > maxBytes) { + body.destroy(); + throw new ObjectTooLargeError(key); + } + chunks.push(chunk); + } + } catch (error) { + if (error instanceof ObjectTooLargeError) { + throw error; + } + throw new ApiError('unavailable', 'object storage unavailable'); + } + return Buffer.concat(chunks); + } + + async getStream(key: string): Promise { + const deadline = new AbortController(); + const timer = setTimeout(() => deadline.abort(), IDLE_TIMEOUT_MS); + try { + const { Body } = await this.streamClient.send( + new GetObjectCommand({ Bucket: this.bucket, Key: key }), + { abortSignal: deadline.signal }, + ); + return Body as Readable; + } catch (error) { + const name = error instanceof Error ? error.name : 'unknown error'; + this.logger.error(`get ${key} failed: ${name}`); + if (name === 'NoSuchKey') { + throw new Error(`object ${key} is missing from storage`); + } + throw new ApiError('unavailable', 'object storage unavailable'); + } finally { + clearTimeout(timer); + } + } + + async isAvailable(): Promise { + try { + await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }), { + abortSignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS), + }); + return true; + } catch { + return false; + } + } + + async listObjects( + prefix: string, + pageSize: number, + token?: string, + ): Promise { + const page = await this.guard(`list ${prefix}`, () => + this.client.send( + new ListObjectsV2Command({ + Bucket: this.bucket, + Prefix: prefix, + MaxKeys: pageSize, + ContinuationToken: token, + }), + { abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) }, + ), + ); + return { + objects: (page.Contents ?? []).map((object) => ({ + key: object.Key!, + lastModified: object.LastModified!, + })), + nextToken: page.NextContinuationToken, + }; + } + + async delete(key: string): Promise { + await this.guard(`delete ${key}`, () => + this.client.send( + new DeleteObjectCommand({ Bucket: this.bucket, Key: key }), + { abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) }, + ), + ); + } + + onModuleDestroy(): void { + this.client.destroy(); + this.streamClient.destroy(); + } + + private async guard(action: string, run: () => Promise): Promise { + try { + return await run(); + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + this.logger.error(`${action} failed: ${reason}`); + throw new ApiError('unavailable', 'object storage unavailable'); + } + } +} + +export class ObjectMissingError extends Error { + constructor(key: string) { + super(`object ${key} is missing from storage`); + this.name = 'ObjectMissingError'; + } +} + +export class ObjectTooLargeError extends Error { + constructor(key: string) { + super(`object ${key} exceeds size limit`); + this.name = 'ObjectTooLargeError'; + } +} + +function readSecret(name: string): string { + const file = process.env[`${name}_FILE`]; + const value = file ? readFileSync(file, 'utf8').trim() : process.env[name]; + if (!value) { + throw new Error(`${name}_FILE or ${name} must be set`); + } + return value; +} diff --git a/src/storage/storage.module.ts b/src/storage/storage.module.ts new file mode 100644 index 0000000..51825a0 --- /dev/null +++ b/src/storage/storage.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from '@nestjs/common'; +import { S3Service } from './s3.service'; + +@Global() +@Module({ + providers: [S3Service], + exports: [S3Service], +}) +export class StorageModule {} diff --git a/src/users/dto/create-user.dto.ts b/src/users/dto/create-user.dto.ts new file mode 100644 index 0000000..6f3612a --- /dev/null +++ b/src/users/dto/create-user.dto.ts @@ -0,0 +1,18 @@ +import { Matches } from 'class-validator'; +import { CodePointLength } from '../../common/dto/code-point-length.validator'; +import { NotBlank } from '../../common/dto/not-blank.validator'; + +export class CreateUserDto { + @Matches(/^[a-z0-9_]{3,32}$/, { + message: 'username must match [a-z0-9_]{3,32}', + }) + username!: string; + + @NotBlank() + @CodePointLength(1, 100) + display_name!: string; + + @NotBlank() + @CodePointLength(12, 128) + password!: string; +} diff --git a/src/users/dto/user.response.ts b/src/users/dto/user.response.ts new file mode 100644 index 0000000..b4626fb --- /dev/null +++ b/src/users/dto/user.response.ts @@ -0,0 +1,17 @@ +import { User } from '../../common/domain'; + +export interface UserResponse { + id: string; + username: string; + display_name: string; + created_at: string; +} + +export function toUserResponse(user: User): UserResponse { + return { + id: user.id, + username: user.username, + display_name: user.displayName, + created_at: user.createdAt, + }; +} diff --git a/src/users/users.controller.ts b/src/users/users.controller.ts new file mode 100644 index 0000000..aeb7baf --- /dev/null +++ b/src/users/users.controller.ts @@ -0,0 +1,36 @@ +import { + Body, + Controller, + Get, + HttpCode, + Post, + UseGuards, +} from '@nestjs/common'; +import { AuthGuard } from '../auth/auth.guard'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { User } from '../common/domain'; +import { CreateUserDto } from './dto/create-user.dto'; +import { toUserResponse, UserResponse } from './dto/user.response'; +import { UsersService } from './users.service'; + +@Controller('api/v1/users') +export class UsersController { + constructor(private readonly users: UsersService) {} + + @Post() + @HttpCode(201) + async create(@Body() dto: CreateUserDto): Promise { + const user = await this.users.register( + dto.username, + dto.display_name, + dto.password, + ); + return toUserResponse(user); + } + + @Get('me') + @UseGuards(AuthGuard) + me(@CurrentUser() user: User): UserResponse { + return toUserResponse(user); + } +} diff --git a/src/users/users.module.ts b/src/users/users.module.ts new file mode 100644 index 0000000..b155b2c --- /dev/null +++ b/src/users/users.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { UsersController } from './users.controller'; +import { UsersService } from './users.service'; + +@Module({ + controllers: [UsersController], + providers: [UsersService], + exports: [UsersService], +}) +export class UsersModule {} diff --git a/src/users/users.service.ts b/src/users/users.service.ts new file mode 100644 index 0000000..896fee1 --- /dev/null +++ b/src/users/users.service.ts @@ -0,0 +1,48 @@ +import { Injectable } from '@nestjs/common'; +import { hashPassword } from '../auth/password'; +import { ApiError } from '../common/filters/api-error'; +import { User } from '../common/domain'; +import { PrismaService, isUniqueViolation } from '../db/prisma.service'; + +@Injectable() +export class UsersService { + constructor(private readonly prisma: PrismaService) {} + + async register( + username: string, + displayName: string, + password: string, + ): Promise { + const passwordHash = await hashPassword(password); + try { + const row = await this.prisma.user.create({ + data: { username, displayName: displayName.trim(), passwordHash }, + }); + return toUser(row); + } catch (error) { + if (isUniqueViolation(error)) { + throw new ApiError('conflict', 'username is already taken'); + } + throw error; + } + } + + async findById(id: string): Promise { + const row = await this.prisma.user.findUnique({ where: { id } }); + return row ? toUser(row) : null; + } +} + +export function toUser(row: { + id: string; + username: string; + displayName: string; + createdAt: Date; +}): User { + return { + id: row.id, + username: row.username, + displayName: row.displayName, + createdAt: row.createdAt.toISOString(), + }; +} diff --git a/src/worker.ts b/src/worker.ts new file mode 100644 index 0000000..cec9146 --- /dev/null +++ b/src/worker.ts @@ -0,0 +1,137 @@ +import { Logger } from '@nestjs/common'; +import { Channel, ConsumeMessage } from 'amqplib'; +import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; +import { PrismaService } from './db/prisma.service'; +import { parseJobMessage } from './jobs/job-message'; +import { JobProcessor, ProcessorHooks, processorOptions } from './jobs/processor'; +import { S3Service } from './storage/s3.service'; + +const CONCURRENCY = Number(process.env.WORKER_CONCURRENCY ?? 2); +const INFRA_RETRY_MS = Number(process.env.WORKER_INFRA_RETRY_MS ?? 5000); +const DRAIN_TIMEOUT_MS = Number(process.env.WORKER_DRAIN_TIMEOUT_MS ?? 25000); +const FAULT = process.env.WORKER_FAULT; + +const logger = new Logger('Worker'); +const prisma = new PrismaService(); +const s3 = new S3Service(); +const processor = new JobProcessor(prisma, s3, processorOptions(), faultHooks()); +let stopping = false; +let inFlight = 0; + +function faultHooks(): ProcessorHooks { + const crash = (point: string) => async () => { + logger.warn(`fault injection: worker killed ${point}`); + process.exit(137); + }; + if (FAULT === 'exit-after-store') { + return { afterStore: crash('after storing objects, before commit and ack') }; + } + if (FAULT === 'exit-after-commit') { + return { afterCommit: crash('after commit, before ack') }; + } + return {}; +} + +async function handle(channel: Channel, delivery: ConsumeMessage): Promise { + inFlight++; + try { + const message = parseJobMessage(delivery.content); + if (!message) { + logger.warn('malformed job message moved to dead letter queue'); + channel.nack(delivery, false, false); + return; + } + const outcome = await processor.handle(message); + logger.log( + `job ${message.job_id} attempt ${message.attempt}` + + `${delivery.fields.redelivered ? ' (redelivered)' : ''}: ${outcome}`, + ); + channel.ack(delivery); + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`); + await sleep(INFRA_RETRY_MS); + try { + channel.nack(delivery, false, true); + } catch { + logger.warn('channel closed, broker will redeliver unacked message'); + } + } finally { + inFlight--; + } +} + +async function run(): Promise { + while (!stopping) { + const connection = await connectWithRetry(logger, () => stopping); + if (!connection) { + break; + } + const closed = new Promise((resolve) => { + connection.on('close', () => resolve()); + connection.on('error', () => resolve()); + }); + try { + const channel = await connection.createChannel(); + await assertTopology(channel); + await channel.prefetch(CONCURRENCY); + const { consumerTag } = await channel.consume( + JOB_QUEUE, + (delivery) => { + if (delivery) { + void handle(channel, delivery); + } + }, + { noAck: false }, + ); + logger.log(`consuming ${JOB_QUEUE} with prefetch ${CONCURRENCY}`); + const stop = new Promise((resolve) => { + const timer = setInterval(() => { + if (stopping) { + clearInterval(timer); + resolve(); + } + }, 200); + void closed.then(() => { + clearInterval(timer); + resolve(); + }); + }); + await stop; + if (stopping) { + await channel.cancel(consumerTag).catch(() => undefined); + const deadline = Date.now() + DRAIN_TIMEOUT_MS; + while (inFlight > 0 && Date.now() < deadline) { + await sleep(100); + } + logger.log(`drained, ${inFlight} job(s) left unacked for redelivery`); + } + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`broker channel failed: ${reason}`); + } + await connection.close().catch(() => undefined); + if (!stopping) { + logger.warn('broker connection lost, reconnecting'); + await sleep(1000); + } + } +} + +for (const signal of ['SIGTERM', 'SIGINT'] as const) { + process.once(signal, () => { + stopping = true; + }); +} + +run() + .then(async () => { + await prisma.$disconnect(); + s3.onModuleDestroy(); + logger.log('stopped'); + process.exit(0); + }) + .catch((error) => { + logger.error(error instanceof Error ? error.message : 'fatal error'); + process.exit(1); + }); diff --git a/test/api.e2e-spec.ts b/test/api.e2e-spec.ts new file mode 100644 index 0000000..4ec669e --- /dev/null +++ b/test/api.e2e-spec.ts @@ -0,0 +1,686 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { randomUUID } from 'crypto'; +import { PrismaService } from '../src/db/prisma.service'; +import { + bearer, + createTestApp, + PASSWORD, + registerUser, + TestUser, +} from './helpers'; + +describe('API мессенджера (e2e) — граничные случаи сверх публичного smoke', () => { + let app: INestApplication; + let server: any; + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + }); + + afterAll(async () => { + await app.close(); + }); + + function createUser(label: string): Promise { + return registerUser(server, label); + } + + describe('POST /api/v1/users', () => { + it('отклоняет некорректный JSON с кодом 400', async () => { + const res = await request(server) + .post('/api/v1/users') + .set('Content-Type', 'application/json') + .send('{not valid json') + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + expect(res.body.error.request_id).toBeTruthy(); + }); + + it('отклоняет тело с лишними полями', async () => { + const res = await request(server) + .post('/api/v1/users') + .send({ + username: 'validname1', + display_name: 'Valid', + password: PASSWORD, + extra: 'nope', + }) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('отклоняет username с заглавными буквами', async () => { + await request(server) + .post('/api/v1/users') + .send({ username: 'InvalidName', display_name: 'X', password: PASSWORD }) + .expect(400); + }); + + it('отклоняет display_name из одних пробелов', async () => { + await request(server) + .post('/api/v1/users') + .send({ username: 'wsonlyname1', display_name: ' ', password: PASSWORD }) + .expect(400); + }); + + it('отклоняет дубликат username с кодом 409', async () => { + const user = await createUser('dup'); + const res = await request(server) + .post('/api/v1/users') + .send({ username: user.username, display_name: 'Someone else', password: PASSWORD }) + .expect(409); + expect(res.body.error.code).toBe('conflict'); + }); + + it('никогда не возвращает поле пароля или его хэша', async () => { + const res = await request(server) + .post('/api/v1/users') + .send({ + username: `nopass_${randomUUID().slice(0, 8)}`, + display_name: 'X', + password: PASSWORD, + }) + .expect(201); + expect(res.body).not.toHaveProperty('password'); + expect(res.body).not.toHaveProperty('password_hash'); + }); + + it('отклоняет username короче 3 символов', async () => { + await request(server) + .post('/api/v1/users') + .send({ username: 'ab', display_name: 'X', password: PASSWORD }) + .expect(400); + }); + + it('отклоняет username длиннее 32 символов', async () => { + await request(server) + .post('/api/v1/users') + .send({ username: 'a'.repeat(33), display_name: 'X', password: PASSWORD }) + .expect(400); + }); + + it('отклоняет username с недопустимыми символами (дефис)', async () => { + await request(server) + .post('/api/v1/users') + .send({ username: 'has-hyphen', display_name: 'X', password: PASSWORD }) + .expect(400); + }); + + it('принимает username ровно на границах длины 3 и 32 символа', async () => { + await request(server) + .post('/api/v1/users') + .send({ + username: `a${randomUUID().slice(0, 2)}`, + display_name: 'X', + password: PASSWORD, + }) + .expect(201); + const longest = ('z' + randomUUID().replace(/-/g, '')).slice(0, 32); + await request(server) + .post('/api/v1/users') + .send({ username: longest, display_name: 'X', password: PASSWORD }) + .expect(201); + }); + + it('отклоняет display_name длиннее 100 Unicode code points', async () => { + await request(server) + .post('/api/v1/users') + .send({ + username: `toolongname_${randomUUID().slice(0, 6)}`, + display_name: 'x'.repeat(101), + password: PASSWORD, + }) + .expect(400); + }); + + it('принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ', async () => { + const displayName = '👋'.repeat(100); + expect([...displayName].length).toBe(100); + await request(server) + .post('/api/v1/users') + .send({ + username: `emojiname_${randomUUID().slice(0, 6)}`, + display_name: displayName, + password: PASSWORD, + }) + .expect(201); + }); + + it('отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP', async () => { + const displayName = '👋'.repeat(100) + 'x'; + expect([...displayName].length).toBe(101); + await request(server) + .post('/api/v1/users') + .send({ + username: `emojitoolong_${randomUUID().slice(0, 6)}`, + display_name: displayName, + password: PASSWORD, + }) + .expect(400); + }); + }); + + describe('контроль доступа', () => { + it('возвращает 401 раньше 404, если и актор, и ресурс невалидны', async () => { + const res = await request(server) + .get(`/api/v1/chats/${randomUUID()}`) + .set('Authorization', 'Bearer not-a-token') + .expect(401); + expect(res.body.error.code).toBe('unauthorized'); + }); + + it('возвращает 404 (не 403), когда чат запрашивает не его участник', async () => { + const alice = await createUser('alice'); + const bob = await createUser('bob'); + const eve = await createUser('eve'); + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Private', member_ids: [alice.id, bob.id] }) + .expect(201); + + const res = await request(server) + .get(`/api/v1/chats/${chat.body.id}`) + .set('Authorization', bearer(eve)) + .expect(404); + expect(res.body.error.code).toBe('not_found'); + }); + + it('отклоняет создание чата, если вызывающий не входит в member_ids', async () => { + const alice = await createUser('alice2'); + const bob = await createUser('bob2'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Missing caller', member_ids: [bob.id] }) + .expect(400); + }); + + it('отклоняет создание чата с дублирующимися member_ids', async () => { + const alice = await createUser('alice3'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ + title: 'Dup members', + member_ids: [alice.id, alice.id], + }) + .expect(400); + }); + + it('считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре', async () => { + const alice = await createUser('alicecase'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Case', member_ids: [alice.id, alice.id.toUpperCase()] }) + .expect(400); + const res = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Upper', member_ids: [alice.id.toUpperCase()] }) + .expect(201); + expect(res.body.member_ids).toEqual([alice.id]); + }); + + it('принимает ровно 100 участников и отклоняет 101', async () => { + const alice = await createUser('max'); + const ids = Array.from({ length: 100 }, () => randomUUID()); + await app.get(PrismaService).user.createMany({ + data: ids.map((id) => ({ + id, + username: `m_${id.replace(/-/g, '').slice(0, 30)}`, + displayName: 'Member', + passwordHash: 'not-a-real-hash', + })), + }); + const ok = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Max', member_ids: [alice.id, ...ids.slice(0, 99)] }) + .expect(201); + expect(ok.body.member_ids).toHaveLength(100); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Too many', member_ids: [alice.id, ...ids] }) + .expect(400); + }); + + it('отклоняет создание чата с неизвестным участником', async () => { + const alice = await createUser('alice4'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ + title: 'Unknown member', + member_ids: [alice.id, randomUUID()], + }) + .expect(400); + }); + + it('отклоняет создание чата с пустым/пробельным title', async () => { + const alice = await createUser('alice4b'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: ' ', member_ids: [alice.id] }) + .expect(400); + }); + + it('возвращает 400 для синтаксически некорректного chat_id (не UUID)', async () => { + const alice = await createUser('alice4c'); + const res = await request(server) + .get('/api/v1/chats/not-a-uuid') + .set('Authorization', bearer(alice)) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('возвращает 404 для корректного по формату, но несуществующего chat_id', async () => { + const alice = await createUser('alice4d'); + await request(server) + .get(`/api/v1/chats/${randomUUID()}`) + .set('Authorization', bearer(alice)) + .expect(404); + }); + }); + + describe('GET /api/v1/chats (пагинация)', () => { + it('использует limit=50 по умолчанию, если limit не передан', async () => { + const alice = await createUser('pgalice1'); + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Only chat', member_ids: [alice.id] }) + .expect(201); + const res = await request(server) + .get('/api/v1/chats') + .set('Authorization', bearer(alice)) + .expect(200); + expect(res.body.items.length).toBeGreaterThanOrEqual(1); + expect(res.body.items.length).toBeLessThanOrEqual(50); + }); + + it('отклоняет нечисловой limit', async () => { + const alice = await createUser('pgalice2'); + await request(server) + .get('/api/v1/chats?limit=abc') + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет limit=0', async () => { + const alice = await createUser('pgalice3'); + await request(server) + .get('/api/v1/chats?limit=0') + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет повторённые limit и cursor', async () => { + const alice = await createUser('pgrepeat'); + for (const query of ['limit=1&limit=2', 'cursor=a&cursor=b']) { + await request(server) + .get(`/api/v1/chats?${query}`) + .set('Authorization', bearer(alice)) + .expect(400); + } + }); + + it('отклоняет cursor, не являющийся корректным base64url JSON', async () => { + const alice = await createUser('pgalice4'); + await request(server) + .get('/api/v1/chats') + .query({ cursor: 'not-a-real-cursor!!!' }) + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет корректно закодированный cursor с id чата, который никогда не существовал', async () => { + const alice = await createUser('pgalice4b'); + const bogusCursor = Buffer.from( + JSON.stringify({ id: randomUUID() }), + 'utf8', + ).toString('base64url'); + const res = await request(server) + .get('/api/v1/chats') + .query({ cursor: bogusCursor }) + .set('Authorization', bearer(alice)) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('обходит весь список чатов по страницам без пропусков и дублей', async () => { + const alice = await createUser('pgalice5'); + const titles = ['c1', 'c2', 'c3', 'c4', 'c5']; + for (const title of titles) { + await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title, member_ids: [alice.id] }) + .expect(201); + } + + const seen: string[] = []; + let cursor: string | null = null; + do { + const res: request.Response = await request(server) + .get('/api/v1/chats') + .query({ limit: 2, ...(cursor ? { cursor } : {}) }) + .set('Authorization', bearer(alice)) + .expect(200); + seen.push( + ...res.body.items.map((c: { title: string }) => c.title), + ); + cursor = res.body.next_cursor; + } while (cursor); + + expect(seen).toEqual(titles); + }); + }); + + describe('сообщения', () => { + async function createChat(alice: TestUser, bob: TestUser) { + const res = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Chat', member_ids: [alice.id, bob.id] }) + .expect(201); + return res.body as { id: string }; + } + + it('не принимает sender_id, переданный клиентом', async () => { + const alice = await createUser('alice5'); + const bob = await createUser('bob5'); + const chat = await createChat(alice, bob); + + const res = await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'hi', sender_id: bob.id }) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('считает attachment_ids: [] равным отсутствию поля, неизвестный ID — 404, неверный тип — 400', async () => { + const alice = await createUser('aliceatt'); + const bob = await createUser('bobatt'); + const chat = await createChat(alice, bob); + const path = `/api/v1/chats/${chat.id}/messages`; + const key = randomUUID(); + const first = await request(server) + .post(path) + .set('Idempotency-Key', key) + .set('Authorization', bearer(alice)) + .send({ text: 'att' }) + .expect(201); + const replay = await request(server) + .post(path) + .set('Idempotency-Key', key) + .set('Authorization', bearer(alice)) + .send({ attachment_ids: [], text: 'att' }) + .expect(201); + expect(replay.body).toEqual(first.body); + await request(server) + .post(path) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'x', attachment_ids: [randomUUID()] }) + .expect(404); + for (const attachment_ids of [null, 'x']) { + await request(server) + .post(path) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'x', attachment_ids }) + .expect(400); + } + }); + + it('отклоняет пустое сообщение', async () => { + const alice = await createUser('alice6'); + const bob = await createUser('bob6'); + const chat = await createChat(alice, bob); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: '' }) + .expect(400); + }); + + it('отклоняет сообщение из одних пробелов', async () => { + const alice = await createUser('alice7'); + const bob = await createUser('bob7'); + const chat = await createChat(alice, bob); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: ' \n\t ' }) + .expect(400); + }); + + it('отклоняет отправку в чат, где вызывающий не участник', async () => { + const alice = await createUser('alice8'); + const bob = await createUser('bob8'); + const eve = await createUser('eve8'); + const chat = await createChat(alice, bob); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(eve)) + .send({ text: 'intrusion' }) + .expect(404); + }); + + it('отклоняет limit=0 при чтении истории', async () => { + const alice = await createUser('alice9'); + const bob = await createUser('bob9'); + const chat = await createChat(alice, bob); + await request(server) + .get(`/api/v1/chats/${chat.id}/messages?limit=0`) + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет limit=101 при чтении истории', async () => { + const alice = await createUser('alice10'); + const bob = await createUser('bob10'); + const chat = await createChat(alice, bob); + await request(server) + .get(`/api/v1/chats/${chat.id}/messages?limit=101`) + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет нечисловой limit', async () => { + const alice = await createUser('alice10b'); + const bob = await createUser('bob10b'); + const chat = await createChat(alice, bob); + await request(server) + .get(`/api/v1/chats/${chat.id}/messages?limit=abc`) + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет текст сообщения длиннее 4000 Unicode code points', async () => { + const alice = await createUser('alice10c'); + const bob = await createUser('bob10c'); + const chat = await createChat(alice, bob); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'x'.repeat(4001) }) + .expect(400); + }); + + it('принимает текст сообщения ровно из 4000 Unicode code points', async () => { + const alice = await createUser('alice10d'); + const bob = await createUser('bob10d'); + const chat = await createChat(alice, bob); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'x'.repeat(4000) }) + .expect(201); + }); + + it('отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP', async () => { + const alice = await createUser('alice10e'); + const bob = await createUser('bob10e'); + const chat = await createChat(alice, bob); + const text = '👋'.repeat(4001); + expect([...text].length).toBe(4001); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text }) + .expect(400); + }); + + it('отклоняет cursor, не являющийся корректным base64url JSON', async () => { + const alice = await createUser('alice10f'); + const bob = await createUser('bob10f'); + const chat = await createChat(alice, bob); + await request(server) + .get(`/api/v1/chats/${chat.id}/messages`) + .query({ cursor: '!!!not-valid!!!' }) + .set('Authorization', bearer(alice)) + .expect(400); + }); + + it('отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате', async () => { + const alice = await createUser('alice10i'); + const bob = await createUser('bob10i'); + const chat = await createChat(alice, bob); + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'only message' }) + .expect(201); + + const bogusCursor = Buffer.from( + JSON.stringify({ chatId: chat.id, id: randomUUID() }), + 'utf8', + ).toString('base64url'); + const res = await request(server) + .get(`/api/v1/chats/${chat.id}/messages`) + .query({ cursor: bogusCursor }) + .set('Authorization', bearer(alice)) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('возвращает 400 для синтаксически некорректного chat_id при отправке сообщения', async () => { + const alice = await createUser('alice10g'); + const res = await request(server) + .post('/api/v1/chats/not-a-uuid/messages') + .set('Authorization', bearer(alice)) + .send({ text: 'hi' }) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('возвращает 400 для синтаксически некорректного chat_id при чтении истории', async () => { + const alice = await createUser('alice10h'); + const res = await request(server) + .get('/api/v1/chats/not-a-uuid/messages') + .set('Authorization', bearer(alice)) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('отклоняет cursor, взятый из другого чата', async () => { + const alice = await createUser('alice11'); + const bob = await createUser('bob11'); + const chatA = await createChat(alice, bob); + const chatB = await createChat(alice, bob); + + await request(server) + .post(`/api/v1/chats/${chatA.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'first' }) + .expect(201); + await request(server) + .post(`/api/v1/chats/${chatA.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text: 'second' }) + .expect(201); + + const page1 = await request(server) + .get(`/api/v1/chats/${chatA.id}/messages?limit=1`) + .set('Authorization', bearer(alice)) + .expect(200); + expect(page1.body.next_cursor).toBeTruthy(); + + const res = await request(server) + .get(`/api/v1/chats/${chatB.id}/messages`) + .query({ cursor: page1.body.next_cursor }) + .set('Authorization', bearer(alice)) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + }); + + it('обходит всю историю по страницам без пропусков и дублей', async () => { + const alice = await createUser('alice12'); + const bob = await createUser('bob12'); + const chat = await createChat(alice, bob); + const sentTexts = ['m1', 'm2', 'm3', 'm4', 'm5']; + for (const text of sentTexts) { + await request(server) + .post(`/api/v1/chats/${chat.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(alice)) + .send({ text }) + .expect(201); + } + + const seen: string[] = []; + let cursor: string | null = null; + do { + const res: request.Response = await request(server) + .get(`/api/v1/chats/${chat.id}/messages`) + .query({ limit: 2, ...(cursor ? { cursor } : {}) }) + .set('Authorization', bearer(alice)) + .expect(200); + seen.push( + ...res.body.items.map((m: { text: string }) => m.text), + ); + cursor = res.body.next_cursor; + } while (cursor); + + expect(seen).toEqual(sentTexts); + }); + }); + + describe('X-Request-Id', () => { + it('присутствует и уникален для независимых запросов', async () => { + const first = await request(server).get('/health/live').expect(200); + const second = await request(server) + .get('/health/live') + .expect(200); + expect(first.headers['x-request-id']).toBeTruthy(); + expect(second.headers['x-request-id']).toBeTruthy(); + expect(first.headers['x-request-id']).not.toBe( + second.headers['x-request-id'], + ); + }); + + it('совпадает с request_id внутри тела ошибки', async () => { + const res = await request(server) + .get('/api/v1/users/me') + .expect(401); + expect(res.body.error.request_id).toBe(res.headers['x-request-id']); + }); + }); +}); diff --git a/test/attachment-access.e2e-spec.ts b/test/attachment-access.e2e-spec.ts new file mode 100644 index 0000000..316a8ac --- /dev/null +++ b/test/attachment-access.e2e-spec.ts @@ -0,0 +1,302 @@ +import { INestApplication } from '@nestjs/common'; +import { createHash, randomUUID } from 'crypto'; +import request from 'supertest'; +import { PrismaService } from '../src/db/prisma.service'; +import { S3Service } from '../src/storage/s3.service'; +import { + bearer, + createTestApp, + processAttachment, + registerUser, + TestUser, +} from './helpers'; +import { jpeg, SAMPLE_PNG } from './images'; + +describe('Скачивание и привязка вложений (e2e)', () => { + let app: INestApplication; + let server: any; + let alice: TestUser; + let bob: TestUser; + let eve: TestUser; + let chatId: string; + let otherChatId: string; + + const createChat = async (owner: TestUser, members: TestUser[]) => { + const res = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(owner)) + .send({ title: 'Files', member_ids: members.map((m) => m.id) }) + .expect(201); + return res.body.id as string; + }; + + const upload = async ( + user = alice, + chat = chatId, + body: Buffer = SAMPLE_PNG, + type = 'image/png', + ) => { + const res = await request(server) + .post(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent('фото 1.png')}`) + .set('Authorization', bearer(user)) + .set('Content-Type', type) + .send(body) + .expect(202); + expect(await processAttachment(app, res.body.id)).toBe('ready'); + const ready = await request(server) + .get(`/api/v1/attachments/${res.body.id}`) + .set('Authorization', bearer(user)) + .expect(200); + return ready.body; + }; + + const get = (path: string, user: TestUser | null = bob) => { + const req = request(server).get(path).buffer(true).parse(binaryParser); + return user ? req.set('Authorization', bearer(user)) : req; + }; + + const send = ( + body: unknown, + { user = alice, chat = chatId, key = randomUUID() }: { user?: TestUser; chat?: string; key?: string } = {}, + ) => + request(server) + .post(`/api/v1/chats/${chat}/messages`) + .set('Authorization', bearer(user)) + .set('Idempotency-Key', key) + .send(body as object); + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + alice = await registerUser(server, 'acc_alice'); + bob = await registerUser(server, 'acc_bob'); + eve = await registerUser(server, 'acc_eve'); + chatId = await createChat(alice, [alice, bob]); + otherChatId = await createChat(eve, [eve]); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('чтение', () => { + it('участник получает метаданные и оригинал побайтно', async () => { + const attachment = await upload(); + const meta = await request(server) + .get(`/api/v1/attachments/${attachment.id}`) + .set('Authorization', bearer(bob)) + .expect(200); + expect(meta.body).toEqual(attachment); + const res = await get(`/api/v1/attachments/${attachment.id}/content`).expect(200); + expect(res.headers['content-type']).toBe('image/png'); + expect(res.headers['content-length']).toBe(String(SAMPLE_PNG.length)); + expect(res.headers['x-content-type-options']).toBe('nosniff'); + expect(res.headers['x-request-id']).toBeTruthy(); + expect(res.headers['x-instance-id']).toBeTruthy(); + expect(res.headers['location']).toBeUndefined(); + expect(createHash('sha256').update(res.body).digest('hex')).toBe(attachment.sha256); + }); + + it('JPEG отдаётся с истинным Content-Type', async () => { + const body = await jpeg(); + const attachment = await upload(alice, chatId, body, 'image/jpeg'); + const res = await get(`/api/v1/attachments/${attachment.id}/content`).expect(200); + expect(res.headers['content-type']).toBe('image/jpeg'); + expect(Buffer.compare(res.body, body)).toBe(0); + }); + + it('посторонний и неизвестный ID получают одинаковый 404', async () => { + const attachment = await upload(); + for (const suffix of ['', '/content']) { + const foreign = await get(`/api/v1/attachments/${attachment.id}${suffix}`, eve); + const unknown = await get(`/api/v1/attachments/${randomUUID()}${suffix}`, eve); + expect(foreign.status).toBe(404); + expect(unknown.status).toBe(404); + const parsed = JSON.parse(foreign.body.toString()); + expect(parsed.error.code).toBe('not_found'); + expect(parsed.error.message).toBe(JSON.parse(unknown.body.toString()).error.message); + } + }); + + it.each([ + ['nil', '00000000-0000-0000-0000-000000000000'], + ['v7', '018f6f3a-7b1c-7def-8abc-0123456789ab'], + ])('UUID %s корректного формата — 404, а не 400', async (_name, id) => { + await get(`/api/v1/attachments/${id}`).expect(404); + await get(`/api/v1/attachments/${id}/content`).expect(404); + await get(`/api/v1/chats/${id}`, alice).expect(404); + await send({ text: 'x', attachment_ids: [id] }).expect(404); + await send({ text: 'x' }, { chat: id }).expect(404); + await request(server) + .post(`/api/v1/chats/${id}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(404); + }); + + it('без токена 401, неверный UUID 400', async () => { + const attachment = await upload(); + for (const suffix of ['', '/content']) { + await get(`/api/v1/attachments/${attachment.id}${suffix}`, null).expect(401); + await get(`/api/v1/attachments/not-a-uuid${suffix}`).expect(400); + } + }); + + it('variant: original явно, отсутствующий 404, неизвестный и повторённый 400', async () => { + const { id } = await upload(); + await get(`/api/v1/attachments/${id}/content?variant=original`).expect(200); + await get(`/api/v1/attachments/${id}/content?variant=thumbnail`).expect(200); + await app.get(PrismaService).attachmentVariant.deleteMany({ + where: { attachmentId: id, name: 'crop' }, + }); + await get(`/api/v1/attachments/${id}/content?variant=crop`).expect(404); + await get(`/api/v1/attachments/${id}/content?variant=nonsense`).expect(400); + await get(`/api/v1/attachments/${id}/content?variant=`).expect(400); + await get(`/api/v1/attachments/${id}/content?variant=original&variant=original`).expect(400); + await get(`/api/v1/attachments/${id}/content?variant=thumbnail`, eve).expect(404); + }); + + it('нет доступа к S3 — метаданные 200, content 503 с заголовками', async () => { + const attachment = await upload(); + const { app: down, server: downServer } = await createTestApp({ + S3_ENDPOINT: 'http://127.0.0.1:9', + }); + try { + await request(downServer) + .get(`/api/v1/attachments/${attachment.id}`) + .set('Authorization', bearer(bob)) + .expect(200); + const res = await request(downServer) + .get(`/api/v1/attachments/${attachment.id}/content`) + .set('Authorization', bearer(bob)) + .expect(503); + expect(res.body.error.code).toBe('unavailable'); + expect(res.headers['x-instance-id']).toBeTruthy(); + } finally { + await down.close(); + } + }); + + it('объект пропал из S3 — 500 без внутренних деталей', async () => { + const attachment = await upload(); + const row = await app.get(PrismaService).attachment.findUniqueOrThrow({ + where: { id: attachment.id }, + }); + await app.get(S3Service).delete(row.objectKey); + const res = await request(server) + .get(`/api/v1/attachments/${attachment.id}/content`) + .set('Authorization', bearer(bob)) + .expect(500); + expect(res.body.error.code).toBe('internal_error'); + expect(JSON.stringify(res.body)).not.toContain(row.objectKey); + }); + }); + + describe('attachment_ids в сообщениях', () => { + it('text="" с вложением принимается, Message читается вторым участником', async () => { + const attachment = await upload(); + const created = await send({ text: '', attachment_ids: [attachment.id] }).expect(201); + expect(created.body.attachment_ids).toEqual([attachment.id]); + const page = await request(server) + .get(`/api/v1/chats/${chatId}/messages?limit=100`) + .set('Authorization', bearer(bob)) + .expect(200); + expect(page.body.items).toContainEqual(created.body); + }); + + it('порядок [B, A] сохраняется в ответе, истории и повторе; перестановка с тем же ключом — 409', async () => { + const a = await upload(); + const b = await upload(); + const key = randomUUID(); + const body = { text: 'order', attachment_ids: [b.id, a.id] }; + const created = await send(body, { key }).expect(201); + expect(created.body.attachment_ids).toEqual([b.id, a.id]); + const replay = await send(body, { key }).expect(201); + expect(replay.body).toEqual(created.body); + const page = await request(server) + .get(`/api/v1/chats/${chatId}/messages?limit=100`) + .set('Authorization', bearer(alice)) + .expect(200); + expect(page.body.items.find((m: any) => m.id === created.body.id)).toEqual(created.body); + const conflict = await send({ text: 'order', attachment_ids: [a.id, b.id] }, { key }).expect(409); + expect(conflict.body.error.code).toBe('conflict'); + }); + + it('отсутствующий attachment_ids и [] равны при повторе, изменение списка — 409', async () => { + const attachment = await upload(); + const key = randomUUID(); + const first = await send({ text: 'same' }, { key }).expect(201); + expect(first.body.attachment_ids).toEqual([]); + const replay = await send({ attachment_ids: [], text: 'same' }, { key }).expect(201); + expect(replay.body).toEqual(first.body); + await send({ text: 'same', attachment_ids: [attachment.id] }, { key }).expect(409); + }); + + it('вложение другого чата и неизвестное — одинаковый 404, сообщение не создаётся', async () => { + const foreign = await upload(eve, otherChatId); + const key = randomUUID(); + const first = await send({ text: 'x', attachment_ids: [foreign.id] }, { key }).expect(404); + const second = await send({ text: 'x', attachment_ids: [randomUUID()] }).expect(404); + expect(first.body.error.code).toBe('not_found'); + expect(first.body.error.message).toBe(second.body.error.message); + await send({ text: 'x' }, { key }).expect(201); + }); + + it('смесь своего и чужого вложения — 404', async () => { + const own = await upload(); + const foreign = await upload(eve, otherChatId); + await send({ text: 'x', attachment_ids: [own.id, foreign.id] }).expect(404); + }); + + it('посторонний не может отправить вложение в чужой чат', async () => { + const attachment = await upload(); + await send({ text: 'x', attachment_ids: [attachment.id] }, { user: eve }).expect(404); + }); + + it('любой участник может сослаться на вложение чата, вложение можно использовать повторно', async () => { + const attachment = await upload(); + await send({ text: 'first', attachment_ids: [attachment.id] }).expect(201); + const res = await send({ text: 'second', attachment_ids: [attachment.id] }, { user: bob }).expect(201); + expect(res.body.sender_id).toBe(bob.id); + expect(res.body.attachment_ids).toEqual([attachment.id]); + }); + + it('ровно 10 вложений принимается, 11 — 400', async () => { + const attachment = await upload(); + const links = await Promise.all(Array.from({ length: 9 }, () => upload())); + const ten = [attachment.id, ...links.map((l) => l.id)]; + const created = await send({ text: 'ten', attachment_ids: ten }).expect(201); + expect(created.body.attachment_ids).toEqual(ten); + await send({ text: 'eleven', attachment_ids: [...ten, randomUUID()] }).expect(400); + }); + + it('UUID в другом регистре — тот же ID и дубль', async () => { + const attachment = await upload(); + const upper = attachment.id.toUpperCase(); + const created = await send({ text: 'case', attachment_ids: [upper] }).expect(201); + expect(created.body.attachment_ids).toEqual([attachment.id]); + await send({ text: 'dup', attachment_ids: [attachment.id, upper] }).expect(400); + }); + + it.each([ + ['text отсутствует', (id: string) => ({ attachment_ids: [id] })], + ['text null', (id: string) => ({ text: null, attachment_ids: [id] })], + ['attachment_ids null', () => ({ text: 'x', attachment_ids: null })], + ['attachment_ids строка', (id: string) => ({ text: 'x', attachment_ids: id })], + ['элемент не UUID', () => ({ text: 'x', attachment_ids: ['nope'] })], + ['элемент число', () => ({ text: 'x', attachment_ids: [1] })], + ['дубликат', (id: string) => ({ text: 'x', attachment_ids: [id, id] })], + ['пустой текст без вложений', () => ({ text: '', attachment_ids: [] })], + ['пробельный текст без вложений', () => ({ text: ' ' })], + ])('%s — 400', async (_name, build) => { + const attachment = await upload(); + await send(build(attachment.id)).expect(400); + }); + }); +}); + +function binaryParser(res: any, done: (error: Error | null, body: Buffer) => void): void { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => done(null, Buffer.concat(chunks))); +} diff --git a/test/attachments.e2e-spec.ts b/test/attachments.e2e-spec.ts new file mode 100644 index 0000000..f075713 --- /dev/null +++ b/test/attachments.e2e-spec.ts @@ -0,0 +1,401 @@ +import { INestApplication } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import Ajv2020 from 'ajv/dist/2020'; +import { createHash, randomUUID } from 'crypto'; +import { mkdtempSync, readdirSync, rmSync } from 'fs'; +import { connect } from 'net'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import request from 'supertest'; +import { PrismaService } from '../src/db/prisma.service'; +import { loadDocument } from '../src/docs/swagger'; +import { S3Service } from '../src/storage/s3.service'; +import { bearer, createTestApp, registerUser, TestUser } from './helpers'; +import { + corruptedJpegs, + corruptedPngs, + jpeg, + png, + pngHeaderOnly, + pngOfExactSize, + SAMPLE_PNG, +} from './images'; + +const MAX_BYTES = 10 * 1024 * 1024; + +describe('Загрузка вложений (e2e)', () => { + let app: INestApplication; + let server: any; + let alice: TestUser; + let eve: TestUser; + let chatId: string; + + const upload = ( + body: Buffer | undefined, + { + type = 'image/png', + filename = 'sample.png', + user = alice, + chat = chatId, + }: { + type?: string | null; + filename?: string | null; + user?: TestUser | null; + chat?: string; + } = {}, + ) => { + const query = filename === null ? '' : `?filename=${encodeURIComponent(filename)}`; + const req = request(server).post(`/api/v1/chats/${chat}/attachments${query}`); + if (user) { + req.set('Authorization', bearer(user)); + } + if (type) { + req.set('Content-Type', type); + } + return body ? req.send(body) : req; + }; + + const expectError = (res: request.Response, status: number, code: string) => { + expect({ status: res.status, code: res.body.error?.code }).toEqual({ status, code }); + expect(res.headers['x-request-id']).toBeTruthy(); + expect(res.headers['x-instance-id']).toBeTruthy(); + expect(res.body.error.request_id).toBe(res.headers['x-request-id']); + }; + + const uploadTmp = mkdtempSync(join(tmpdir(), 'attachments-test-')); + + const activeTempDirs = (): string[] => + readdirSync(uploadTmp).filter((name) => name.startsWith('messenger-upload-')); + + beforeAll(async () => { + ({ app, server } = await createTestApp({ UPLOAD_TMP_DIR: uploadTmp })); + alice = await registerUser(server, 'att_alice'); + eve = await registerUser(server, 'att_eve'); + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Files', member_ids: [alice.id] }) + .expect(201); + chatId = chat.body.id; + }); + + afterAll(async () => { + await app.close(); + rmSync(uploadTmp, { recursive: true, force: true }); + }); + + describe('успешная загрузка', () => { + it('возвращает 202 Attachment queued по контракту, staging и задание сохранены до ответа', async () => { + const res = await upload(SAMPLE_PNG).expect(202); + const document: any = loadDocument(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + ajv.addSchema(document, 'contract'); + const validate = ajv.compile({ $ref: 'contract#/components/schemas/Attachment' }); + expect({ valid: validate(res.body), errors: validate.errors }).toEqual({ + valid: true, + errors: null, + }); + expect(res.body).toMatchObject({ + chat_id: chatId, + owner_id: alice.id, + filename: 'sample.png', + content_type: 'image/png', + size_bytes: SAMPLE_PNG.length, + sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'), + status: 'queued', + variants: [], + error_code: null, + }); + const prisma = app.get(PrismaService); + const row = await prisma.attachment.findUnique({ + where: { id: res.body.id }, + include: { jobs: { include: { outbox: true } } }, + }); + expect(row).toMatchObject({ + status: 'queued', + objectKey: `attachments/${res.body.id}/original`, + stagingKey: `staging/${res.body.id}`, + }); + expect(row!.jobs).toHaveLength(1); + expect(row!.jobs[0]).toMatchObject({ status: 'queued', attempt: 1, pipelineVersion: 1 }); + expect(row!.jobs[0].outbox).toHaveLength(1); + expect(row!.jobs[0].outbox[0].payload).toEqual({ + schema_version: 1, + job_id: row!.jobs[0].id, + type: 'attachment.process.v1', + attachment_id: res.body.id, + pipeline_version: 1, + attempt: 1, + created_at: expect.any(String), + }); + const staged = await app.get(S3Service).getBuffer(`staging/${res.body.id}`, MAX_BYTES); + expect(Buffer.compare(staged, SAMPLE_PNG)).toBe(0); + expect(JSON.stringify(res.body)).not.toMatch(/attachments\/|staging\//); + }); + + it('принимает реальный JPEG', async () => { + const res = await upload(await jpeg(), { + type: 'image/jpeg', + filename: 'фото 1.jpg', + }).expect(202); + expect(res.body).toMatchObject({ + content_type: 'image/jpeg', + filename: 'фото 1.jpg', + }); + }); + + it('игнорирует параметры и регистр Content-Type', async () => { + await upload(SAMPLE_PNG, { type: 'IMAGE/PNG; charset=binary' }).expect(202); + }); + + it('принимает файл ровно 10 MiB, filename ровно 255 символов и PNG с байтами после IEND', async () => { + const exact = pngOfExactSize(MAX_BYTES); + expect(exact.length).toBe(MAX_BYTES); + const res = await upload(exact).expect(202); + expect(res.body.size_bytes).toBe(MAX_BYTES); + await upload(SAMPLE_PNG, { filename: `${'ф'.repeat(251)}.png` }).expect(202); + await upload(Buffer.concat([png(4, 4), Buffer.from('tail')])).expect(202); + }); + + it('принимает ровно 40 млн пикселей', async () => { + const res = await upload(await bigPng(8000, 5000)); + expect(res.status).toBe(202); + }); + }); + + describe('порядок проверок и доступ', () => { + it('без токена — 401 раньше любых проверок содержимого', async () => { + const cases: [string | null, string | null][] = [ + ['image/png', 'a.png'], + ['text/plain', 'a.png'], + ['application/json', 'a.png'], + ['image/png', '../a.png'], + [null, null], + ]; + for (const [type, filename] of cases) { + const res = await upload(Buffer.from('{bad'), { type, filename, user: null }); + expectError(res, 401, 'unauthorized'); + expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"'); + } + }); + + it('посторонний и несуществующий чат — одинаковый 404, чужой файл не сохраняется', async () => { + const prisma = app.get(PrismaService); + const before = await prisma.attachment.count({ where: { chatId } }); + expectError(await upload(SAMPLE_PNG, { user: eve }), 404, 'not_found'); + expectError(await upload(SAMPLE_PNG, { chat: randomUUID() }), 404, 'not_found'); + expect(await prisma.attachment.count({ where: { chatId } })).toBe(before); + }); + + it('неверный UUID чата — 400', async () => { + expectError(await upload(SAMPLE_PNG, { chat: 'not-a-uuid' }), 400, 'invalid_request'); + }); + }); + + describe('filename', () => { + const invalid = { + 'отсутствует': null, + 'пустой': '', + 'только пробелы': ' ', + '256 символов': 'x'.repeat(256), + 'путь через /': '../x.png', + 'путь через \\': 'a\\b.png', + 'NUL': 'a\u0000b.png', + 'перевод строки': 'a\nb.png', + 'DEL': 'bad\u007f.png', + 'C1 U+0085': 'c1\u0085.png', + 'разделитель строк U+2028': 'a
b.png', + }; + it.each(Object.entries(invalid))('%s — 400', async (_name, filename) => { + expectError(await upload(SAMPLE_PNG, { filename }), 400, 'invalid_request'); + }); + + it('повторённый параметр — 400', async () => { + const res = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png&filename=b.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG); + expectError(res, 400, 'invalid_request'); + }); + }); + + describe('тип содержимого', () => { + it.each(['text/plain', 'application/json', 'application/octet-stream', 'multipart/form-data; boundary=x', 'image/gif', 'image/webp'])( + 'Content-Type %s — 415', + async (type) => { + expectError(await upload(SAMPLE_PNG, { type }), 415, 'unsupported_media_type'); + }, + ); + + it('без Content-Type — 415', async () => { + expectError(await upload(SAMPLE_PNG, { type: null }), 415, 'unsupported_media_type'); + }); + + it('подмена MIME в обе стороны и чужие форматы — 415', async () => { + const realJpeg = await jpeg(); + expectError(await upload(SAMPLE_PNG, { type: 'image/jpeg' }), 415, 'unsupported_media_type'); + expectError(await upload(realJpeg, { type: 'image/png' }), 415, 'unsupported_media_type'); + for (const body of [ + Buffer.from('просто текст'), + Buffer.from('GIF89a\u0001\u0000\u0001\u0000'), + Buffer.from(''), + ]) { + expectError(await upload(body), 415, 'unsupported_media_type'); + } + }); + + it('пустое тело — 400', async () => { + expectError(await upload(undefined), 400, 'invalid_request'); + expectError(await upload(Buffer.alloc(0)), 400, 'invalid_request'); + }); + }); + + describe('повреждённые изображения', () => { + it.each(Object.entries(corruptedPngs()))('PNG: %s — 415', async (_name, body) => { + expectError(await upload(body), 415, 'unsupported_media_type'); + }); + + it('JPEG: все повреждения — 415', async () => { + for (const body of Object.values(corruptedJpegs(await jpeg()))) { + expectError(await upload(body, { type: 'image/jpeg' }), 415, 'unsupported_media_type'); + } + }); + }); + + describe('лимиты', () => { + it('10 MiB + 1 байт — 413 и без чтения объявленного тела', async () => { + expectError(await upload(pngOfExactSize(MAX_BYTES + 1)), 413, 'payload_too_large'); + }); + + it('превышение при chunked без Content-Length — 413', async () => { + const res = await new Promise((resolve, reject) => { + const req = upload(undefined); + req.set('Transfer-Encoding', 'chunked'); + req.write(pngOfExactSize(MAX_BYTES)); + req.write(Buffer.alloc(1024)); + req.end((error, response) => (response ? resolve(response) : reject(error))); + }); + expectError(res, 413, 'payload_too_large'); + }); + + it('превышение лимита пикселей — 413 до декодирования', async () => { + for (const body of [pngHeaderOnly(8001, 5000), pngHeaderOnly(20000, 10000)]) { + expectError(await upload(body), 413, 'payload_too_large'); + } + }); + + it('оборванная загрузка не оставляет временных файлов и строк в БД', async () => { + const prisma = app.get(PrismaService); + const before = await prisma.attachment.count({ where: { chatId } }); + const { port } = server.address(); + await new Promise((resolve, reject) => { + const socket = connect(port, '127.0.0.1', () => { + socket.write( + `POST /api/v1/chats/${chatId}/attachments?filename=a.png HTTP/1.1\r\n` + + `Host: test\r\nAuthorization: ${bearer(alice)}\r\n` + + `Content-Type: image/png\r\nContent-Length: ${SAMPLE_PNG.length}\r\n\r\n`, + ); + socket.write(SAMPLE_PNG.subarray(0, 1000)); + setTimeout(() => { + socket.destroy(); + resolve(); + }, 300); + }); + socket.on('error', reject); + }); + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(await prisma.attachment.count({ where: { chatId } })).toBe(before); + expect(activeTempDirs()).toEqual([]); + }); + }); + + describe('отказы', () => { + it('S3 недоступен — 503 с заголовками, метаданные не создаются', async () => { + const { app: down, server: downServer } = await createTestApp({ + S3_ENDPOINT: 'http://127.0.0.1:9', + }); + try { + const prisma = app.get(PrismaService); + const before = await prisma.attachment.count({ where: { chatId } }); + const started = Date.now(); + const res = await request(downServer) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG); + expectError(res, 503, 'unavailable'); + expect(Date.now() - started).toBeLessThan(3000); + expect(await prisma.attachment.count({ where: { chatId } })).toBe(before); + } finally { + await down.close(); + } + }); + + it('явный отказ транзакции после PUT удаляет объект staging', async () => { + const prisma = app.get(PrismaService); + const s3 = app.get(S3Service); + const remove = jest.spyOn(s3, 'delete'); + const create = jest.spyOn(prisma, '$transaction').mockRejectedValueOnce( + new Prisma.PrismaClientKnownRequestError('rejected', { + code: 'P2003', + clientVersion: 'test', + }), + ); + try { + const res = await upload(SAMPLE_PNG); + expect(res.status).toBe(500); + expect(remove).toHaveBeenCalledTimes(1); + expect(remove.mock.calls[0][0]).toMatch(/^staging\//); + } finally { + create.mockRestore(); + remove.mockRestore(); + } + }); + + it('необработанная ошибка PostgreSQL при INSERT — 503, объект не удаляется', async () => { + const prisma = app.get(PrismaService); + const s3 = app.get(S3Service); + const remove = jest.spyOn(s3, 'delete'); + const create = jest.spyOn(prisma, '$transaction').mockRejectedValueOnce( + new Prisma.PrismaClientUnknownRequestError('server closed the connection', { + clientVersion: 'test', + }), + ); + try { + expectError(await upload(SAMPLE_PNG), 503, 'unavailable'); + expect(remove).not.toHaveBeenCalled(); + } finally { + create.mockRestore(); + remove.mockRestore(); + } + }); + + it('при неясном исходе COMMIT объект не удаляется', async () => { + const prisma = app.get(PrismaService); + const s3 = app.get(S3Service); + const remove = jest.spyOn(s3, 'delete'); + const create = jest.spyOn(prisma, '$transaction').mockRejectedValueOnce( + new Prisma.PrismaClientKnownRequestError('connection lost', { + code: 'P1017', + clientVersion: 'test', + }), + ); + try { + expectError(await upload(SAMPLE_PNG), 503, 'unavailable'); + expect(remove).not.toHaveBeenCalled(); + } finally { + create.mockRestore(); + remove.mockRestore(); + } + }); + }); +}); + + +async function bigPng(width: number, height: number): Promise { + const { default: sharp } = await import('sharp'); + return sharp({ create: { width, height, channels: 3, background: '#336699' } }) + .png({ compressionLevel: 9 }) + .toBuffer(); +} diff --git a/test/auth.e2e-spec.ts b/test/auth.e2e-spec.ts new file mode 100644 index 0000000..59c59a7 --- /dev/null +++ b/test/auth.e2e-spec.ts @@ -0,0 +1,179 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { randomUUID } from 'crypto'; +import { PrismaService } from '../src/db/prisma.service'; +import { + basic, + bearer, + createTestApp, + login, + PASSWORD, + registerUser, +} from './helpers'; + +describe('Аутентификация и сессии (e2e)', () => { + let app: INestApplication; + let server: any; + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + }); + + afterAll(async () => { + await app.close(); + }); + + describe('регистрация', () => { + it('требует password', async () => { + await request(server) + .post('/api/v1/users') + .send({ username: `nopw_${randomUUID().slice(0, 8)}`, display_name: 'X' }) + .expect(400); + }); + + it('отклоняет password короче 12 code points', async () => { + await request(server) + .post('/api/v1/users') + .send({ + username: `short_${randomUUID().slice(0, 8)}`, + display_name: 'X', + password: 'x'.repeat(11), + }) + .expect(400); + }); + + it('хранит пароль как Argon2id-хеш, а не открытым текстом', async () => { + const user = await registerUser(server, 'hash'); + const row = await app + .get(PrismaService) + .user.findUniqueOrThrow({ where: { id: user.id } }); + expect(row.passwordHash.startsWith('$argon2id$')).toBe(true); + expect(row.passwordHash).not.toContain(PASSWORD); + }); + }); + + describe('POST /api/v1/auth/sessions', () => { + it('выдаёт непрозрачный Bearer-токен с expires_at и пользователем', async () => { + const user = await registerUser(server, 'login'); + const res = await request(server) + .post('/api/v1/auth/sessions') + .set('Authorization', basic(user.username, PASSWORD)) + .expect(201); + expect(res.body.token_type).toBe('Bearer'); + expect(res.body.token.length).toBeGreaterThanOrEqual(43); + expect(res.body.token).not.toContain(user.id); + expect(res.body.user.id).toBe(user.id); + const expiresIn = Date.parse(res.body.expires_at) - Date.now(); + expect(expiresIn).toBeGreaterThan(3500 * 1000); + expect(expiresIn).toBeLessThanOrEqual(3600 * 1000); + }); + + it('принимает пароль с двоеточием и не-ASCII символами', async () => { + const username = `colon_${randomUUID().slice(0, 8)}`; + const password = 'пароль:с:двоеточием🔑'; + await request(server) + .post('/api/v1/users') + .send({ username, display_name: 'X', password }) + .expect(201); + await login(server, username, password); + }); + + it('отвечает одинаковым 401 на неверный пароль и неизвестного пользователя', async () => { + const user = await registerUser(server, 'wrong'); + const wrong = await request(server) + .post('/api/v1/auth/sessions') + .set('Authorization', basic(user.username, 'wrong-password-123')) + .expect(401); + const unknown = await request(server) + .post('/api/v1/auth/sessions') + .set('Authorization', basic(`ghost_${randomUUID().slice(0, 8)}`, PASSWORD)) + .expect(401); + for (const res of [wrong, unknown]) { + expect(res.headers['www-authenticate']).toBe( + 'Basic realm="messenger", charset="UTF-8"', + ); + expect(res.body.error.code).toBe('unauthorized'); + } + expect(wrong.body.error.message).toBe(unknown.body.error.message); + }); + + it('отклоняет JSON body при входе даже с верным Basic', async () => { + const user = await registerUser(server, 'body'); + for (const body of [{ extra: 'forbidden' }, {}]) { + const res = await request(server) + .post('/api/v1/auth/sessions') + .set('Authorization', basic(user.username, PASSWORD)) + .send(body) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + } + }); + + it('отвечает 401 без заголовка Authorization', async () => { + const res = await request(server) + .post('/api/v1/auth/sessions') + .expect(401); + expect(res.headers['www-authenticate']).toContain('Basic'); + }); + }); + + describe('защищённые endpoint', () => { + it('не принимают Basic', async () => { + const user = await registerUser(server, 'basic'); + const res = await request(server) + .get('/api/v1/users/me') + .set('Authorization', basic(user.username, PASSWORD)) + .expect(401); + expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"'); + }); + + it('не принимают X-User-Id сам по себе', async () => { + const user = await registerUser(server, 'xuid'); + await request(server) + .get('/api/v1/users/me') + .set('X-User-Id', user.id) + .expect(401); + }); + + it('игнорируют X-User-Id рядом с Bearer', async () => { + const alice = await registerUser(server, 'alice'); + const eve = await registerUser(server, 'eve'); + const res = await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(alice)) + .set('X-User-Id', eve.id) + .expect(200); + expect(res.body.id).toBe(alice.id); + }); + + it('отвечают 401 на неизвестный токен', async () => { + await request(server) + .get('/api/v1/users/me') + .set('Authorization', 'Bearer unknown-token-value') + .expect(401); + }); + }); + + describe('DELETE /api/v1/auth/sessions/current', () => { + it('отзывает только текущий токен: 204, затем 401 на повтор', async () => { + const user = await registerUser(server, 'logout'); + const other = await login(server, user.username); + await request(server) + .delete('/api/v1/auth/sessions/current') + .set('Authorization', bearer(user)) + .expect(204); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(401); + await request(server) + .delete('/api/v1/auth/sessions/current') + .set('Authorization', bearer(user)) + .expect(401); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', `Bearer ${other}`) + .expect(200); + }); + }); +}); diff --git a/test/concurrency.e2e-spec.ts b/test/concurrency.e2e-spec.ts new file mode 100644 index 0000000..92fcfbc --- /dev/null +++ b/test/concurrency.e2e-spec.ts @@ -0,0 +1,119 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { randomUUID } from 'crypto'; +import { + bearer, + createTestApp, + login, + PASSWORD, + registerUser, +} from './helpers'; + +describe('Безопасность при конкурентном доступе (e2e)', () => { + let app: INestApplication; + let server: any; + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + }); + + afterAll(async () => { + await app.close(); + }); + + it('принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных', async () => { + const CLIENTS = 10; + const MESSAGES_PER_CLIENT = 10; + + const owner = await registerUser(server, 'owner'); + const clients = await Promise.all( + Array.from({ length: CLIENTS }, (_, i) => + registerUser(server, `racer${i}`), + ), + ); + const memberIds = [owner.id, ...clients.map((c) => c.id)]; + + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(owner)) + .send({ title: 'Race', member_ids: memberIds }) + .expect(201); + + const sendTasks: Promise[] = []; + for (let c = 0; c < CLIENTS; c++) { + for (let m = 0; m < MESSAGES_PER_CLIENT; m++) { + sendTasks.push( + request(server) + .post(`/api/v1/chats/${chat.body.id}/messages`) + .set('Idempotency-Key', randomUUID()) + .set('Authorization', bearer(clients[c])) + .send({ text: `client-${c}-message-${m}` }), + ); + } + } + + const responses = await Promise.all(sendTasks); + for (const res of responses) { + expect(res.status).toBe(201); + } + + const sentIds = new Set(responses.map((r) => r.body.id)); + expect(sentIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT); + + const collected: { id: string; text: string }[] = []; + let cursor: string | null = null; + do { + const res: request.Response = await request(server) + .get(`/api/v1/chats/${chat.body.id}/messages`) + .query({ limit: 25, ...(cursor ? { cursor } : {}) }) + .set('Authorization', bearer(owner)) + .expect(200); + collected.push(...res.body.items); + cursor = res.body.next_cursor; + } while (cursor); + + expect(collected.length).toBe(CLIENTS * MESSAGES_PER_CLIENT); + const uniqueIds = new Set(collected.map((m) => m.id)); + expect(uniqueIds.size).toBe(CLIENTS * MESSAGES_PER_CLIENT); + + const uniqueTexts = new Set(collected.map((m) => m.text)); + expect(uniqueTexts.size).toBe(CLIENTS * MESSAGES_PER_CLIENT); + + const fullHistory: { id: string; created_at: string }[] = + await request(server) + .get(`/api/v1/chats/${chat.body.id}/messages`) + .query({ limit: 100 }) + .set('Authorization', bearer(owner)) + .expect(200) + .then((res) => res.body.items); + const sortKeys = fullHistory.map((m) => `${m.created_at}#${m.id}`); + const sortedKeys = [...sortKeys].sort(); + expect(sortKeys).toEqual(sortedKeys); + }); + + it('регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username', async () => { + const username = `racer_username_${randomUUID().slice(0, 8)}`; + const attempts = 10; + + const responses = await Promise.all( + Array.from({ length: attempts }, () => + request(server) + .post('/api/v1/users') + .send({ username, display_name: 'Racer', password: PASSWORD }), + ), + ); + + const succeeded = responses.filter((r) => r.status === 201); + const conflicted = responses.filter((r) => r.status === 409); + + expect(succeeded.length).toBe(1); + expect(conflicted.length).toBe(attempts - 1); + + const token = await login(server, username); + const me = await request(server) + .get('/api/v1/users/me') + .set('Authorization', `Bearer ${token}`) + .expect(200); + expect(me.body.id).toBe(succeeded[0].body.id); + }); +}); diff --git a/test/contract.e2e-spec.ts b/test/contract.e2e-spec.ts new file mode 100644 index 0000000..da59665 --- /dev/null +++ b/test/contract.e2e-spec.ts @@ -0,0 +1,241 @@ +import { INestApplication } from '@nestjs/common'; +import Ajv2020 from 'ajv/dist/2020'; +import { randomUUID } from 'crypto'; +import request from 'supertest'; +import { PrismaService } from '../src/db/prisma.service'; +import { loadDocument } from '../src/docs/swagger'; +import { + basic, + bearer, + createTestApp, + PASSWORD, + processAttachment, + registerUser, + TestUser, +} from './helpers'; +import { jpeg, SAMPLE_PNG } from './images'; + +const CONTRACT_ID = 'https://contract.local/openapi.json'; + +describe('Все ответы соответствуют контракту: коды, схемы, заголовки (e2e)', () => { + let app: INestApplication; + let server: any; + let alice: TestUser; + let bob: TestUser; + let eve: TestUser; + const document: any = loadDocument(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + ajv.addSchema(document, CONTRACT_ID); + const covered = new Set(); + + const call = async ( + method: 'get' | 'post' | 'delete', + template: string, + values: Record, + expected: number, + { + user, + auth, + query = '', + body, + raw, + type, + headers = {}, + }: { + user?: TestUser | null; + auth?: string; + query?: string; + body?: unknown; + raw?: Buffer | string; + type?: string; + headers?: Record; + } = {}, + ) => { + const path = template.replace(/\{(\w+)\}/g, (_, name) => values[name]); + let req = request(server)[method](path + query).buffer(true).parse(binaryParser); + if (user) { + req = req.set('Authorization', bearer(user)); + } + if (auth) { + req = req.set('Authorization', auth); + } + for (const [name, value] of Object.entries(headers)) { + req = req.set(name, value); + } + if (type) { + req = req.set('Content-Type', type); + } + const res = raw !== undefined ? await req.send(raw) : body !== undefined ? await req.send(body as object) : await req; + const operation = document.paths[template][method]; + const label = `${method.toUpperCase()} ${template} -> ${res.status}`; + expect({ label, status: res.status }).toEqual({ label, status: expected }); + expect({ label, declared: String(res.status) in operation.responses }).toEqual({ label, declared: true }); + expect({ label, requestId: Boolean(res.headers['x-request-id']) }).toEqual({ label, requestId: true }); + expect({ label, instanceId: Boolean(res.headers['x-instance-id']) }).toEqual({ label, instanceId: true }); + const declared = operation.responses[String(res.status)]; + const content = declared.content ?? {}; + const type_ = (res.headers['content-type'] ?? '').split(';')[0]; + if (res.status === 204) { + expect({ label, length: res.body.length }).toEqual({ label, length: 0 }); + } else if (content['application/json']) { + expect({ label, type: type_ }).toEqual({ label, type: 'application/json' }); + const json = JSON.parse(res.body.toString('utf8')); + const schema = content['application/json'].schema; + const validate = ajv.compile(schema.$ref ? { $ref: CONTRACT_ID + schema.$ref } : schema); + const valid = validate(json); + expect({ label, valid, errors: validate.errors }).toEqual({ label, valid: true, errors: null }); + if (json && typeof json === 'object' && 'error' in json) { + expect({ label, same: json.error.request_id === res.headers['x-request-id'] }).toEqual({ label, same: true }); + } + } else { + expect({ label, type: Object.keys(content).includes(type_) }).toEqual({ label, type: true }); + } + covered.add(label); + return res.status === 204 || !content['application/json'] ? res.body : JSON.parse(res.body.toString('utf8')); + }; + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + alice = await registerUser(server, 'ct_alice'); + bob = await registerUser(server, 'ct_bob'); + eve = await registerUser(server, 'ct_eve'); + }); + + afterAll(async () => { + await app.close(); + }); + + it('health, пользователи и сессии', async () => { + await call('get', '/health/live', {}, 200); + await call('get', '/health/ready', {}, 200); + const username = `ct_${randomUUID().slice(0, 8)}`; + await call('post', '/api/v1/users', {}, 201, { body: { username, display_name: 'C', password: PASSWORD } }); + await call('post', '/api/v1/users', {}, 409, { body: { username, display_name: 'C', password: PASSWORD } }); + await call('post', '/api/v1/users', {}, 400, { body: { username: 'BAD NAME', display_name: 'C', password: PASSWORD } }); + await call('post', '/api/v1/users', {}, 400, { raw: '{bad', type: 'application/json' }); + await call('post', '/api/v1/auth/sessions', {}, 201, { auth: basic(username, PASSWORD) }); + await call('post', '/api/v1/auth/sessions', {}, 401, { auth: basic(username, 'wrong-password-123') }); + await call('post', '/api/v1/auth/sessions', {}, 400, { + auth: basic(username, PASSWORD), + body: { username }, + }); + await call('get', '/api/v1/users/me', {}, 200, { user: alice }); + await call('get', '/api/v1/users/me', {}, 401); + await call('get', '/api/v1/users/me', {}, 401, { auth: basic(username, PASSWORD) }); + const temp = await registerUser(server, 'ct_tmp'); + await call('delete', '/api/v1/auth/sessions/current', {}, 204, { user: temp }); + await call('delete', '/api/v1/auth/sessions/current', {}, 401, { user: temp }); + }); + + it('чаты и сообщения', async () => { + const chat = await call('post', '/api/v1/chats', {}, 201, { + user: alice, + body: { title: 'Contract', member_ids: [alice.id, bob.id] }, + }); + await call('post', '/api/v1/chats', {}, 400, { user: alice, body: { title: 'x', member_ids: [bob.id] } }); + await call('post', '/api/v1/chats', {}, 401, { body: { title: 'x', member_ids: [] } }); + await call('get', '/api/v1/chats', {}, 200, { user: bob, query: '?limit=1' }); + await call('get', '/api/v1/chats', {}, 400, { user: bob, query: '?limit=0' }); + await call('get', '/api/v1/chats', {}, 400, { user: bob, query: '?cursor=garbage' }); + const ids = { chat_id: chat.id }; + await call('get', '/api/v1/chats/{chat_id}', ids, 200, { user: bob }); + await call('get', '/api/v1/chats/{chat_id}', ids, 404, { user: eve }); + await call('get', '/api/v1/chats/{chat_id}', { chat_id: 'nope' }, 400, { user: bob }); + const key = randomUUID(); + const send = (status: number, body: unknown, user: TestUser = alice, idem: string | null = randomUUID()) => + call('post', '/api/v1/chats/{chat_id}/messages', ids, status, { + user, + body, + headers: idem ? { 'Idempotency-Key': idem } : {}, + }); + await send(201, { text: 'привет' }, alice, key); + await send(201, { text: 'привет' }, alice, key); + await send(201, { text: 'второе' }, bob); + await send(409, { text: 'другое' }, alice, key); + await send(400, { text: 'без ключа' }, alice, null); + await send(400, { text: '' }); + await send(400, { text: 'x', sender_id: alice.id }); + await send(404, { text: 'x' }, eve); + await send(404, { text: 'x', attachment_ids: [randomUUID()] }); + const page = await call('get', '/api/v1/chats/{chat_id}/messages', ids, 200, { user: bob, query: '?limit=1' }); + await call('get', '/api/v1/chats/{chat_id}/messages', ids, 200, { + user: bob, + query: `?limit=1&cursor=${encodeURIComponent(page.next_cursor)}`, + }); + await call('get', '/api/v1/chats/{chat_id}/messages', ids, 400, { user: bob, query: '?limit=101' }); + await call('get', '/api/v1/chats/{chat_id}/messages', ids, 404, { user: eve }); + }); + + it('вложения во всех состояниях', async () => { + const chat = await call('post', '/api/v1/chats', {}, 201, { + user: alice, + body: { title: 'Files', member_ids: [alice.id, bob.id] }, + }); + const ids = { chat_id: chat.id }; + const upload = (status: number, body: Buffer, type = 'image/png', query = '?filename=a.png', user: TestUser | null = alice) => + call('post', '/api/v1/chats/{chat_id}/attachments', ids, status, { user, raw: body, type, query }); + const queued = await upload(202, SAMPLE_PNG); + expect(queued.status).toBe('queued'); + await upload(202, await jpeg(), 'image/jpeg'); + await upload(400, SAMPLE_PNG, 'image/png', '?filename=../a.png'); + await upload(415, SAMPLE_PNG, 'image/jpeg'); + await upload(415, Buffer.from('text'), 'text/plain'); + await upload(413, Buffer.alloc(10 * 1024 * 1024 + 1), 'image/png'); + await upload(404, SAMPLE_PNG, 'image/png', '?filename=a.png', eve); + await upload(401, SAMPLE_PNG, 'image/png', '?filename=a.png', null); + + const one = { attachment_id: queued.id }; + const meta = '/api/v1/attachments/{attachment_id}'; + const content = '/api/v1/attachments/{attachment_id}/content'; + expect((await call('get', meta, one, 200, { user: bob })).status).toBe('queued'); + await call('get', content, one, 409, { user: bob }); + await call('get', content, one, 409, { user: bob, query: '?variant=thumbnail' }); + await call('post', '/api/v1/chats/{chat_id}/messages', ids, 201, { + user: alice, + body: { text: '', attachment_ids: [queued.id] }, + headers: { 'Idempotency-Key': randomUUID() }, + }); + + expect(await processAttachment(app, queued.id)).toBe('ready'); + const ready = await call('get', meta, one, 200, { user: bob }); + expect(ready.variants.map((v: any) => v.name)).toEqual(['thumbnail', 'crop', 'optimized']); + for (const variant of ['', '?variant=original', '?variant=thumbnail', '?variant=crop', '?variant=optimized']) { + await call('get', content, one, 200, { user: bob, query: variant }); + } + await call('get', content, one, 400, { user: bob, query: '?variant=huge' }); + await call('get', content, one, 404, { user: eve }); + await call('get', meta, one, 404, { user: eve }); + await call('get', meta, { attachment_id: 'nope' }, 400, { user: bob }); + await call('get', meta, one, 401); + + const broken = await upload(202, SAMPLE_PNG); + const prisma = app.get(PrismaService); + await prisma.attachmentJob.updateMany({ where: { attachmentId: broken.id }, data: { maxAttempts: 1 } }); + await prisma.attachment.update({ where: { id: broken.id }, data: { sha256: 'f'.repeat(64) } }); + expect(await processAttachment(app, broken.id)).toBe('failed'); + const failed = await call('get', meta, { attachment_id: broken.id }, 200, { user: bob }); + expect(failed).toMatchObject({ status: 'failed', error_code: 'checksum_mismatch', variants: [] }); + await call('get', content, { attachment_id: broken.id }, 409, { user: bob }); + await call('post', '/api/v1/chats/{chat_id}/messages', ids, 409, { + user: alice, + body: { text: '', attachment_ids: [broken.id] }, + headers: { 'Idempotency-Key': randomUUID() }, + }); + }); + + it('каждая операция контракта вызвана хотя бы раз', () => { + const operations = Object.entries(document.paths).flatMap(([path, ops]: [string, any]) => + Object.keys(ops) + .filter((method) => ['get', 'post', 'delete'].includes(method)) + .map((method) => `${method.toUpperCase()} ${path}`), + ); + const called = new Set([...covered].map((label) => label.split(' -> ')[0])); + expect(operations.filter((operation) => !called.has(operation))).toEqual([]); + }); +}); + +function binaryParser(res: any, done: (error: Error | null, body: Buffer) => void): void { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => done(null, Buffer.concat(chunks))); +} diff --git a/test/docs.e2e-spec.ts b/test/docs.e2e-spec.ts new file mode 100644 index 0000000..3066219 --- /dev/null +++ b/test/docs.e2e-spec.ts @@ -0,0 +1,69 @@ +import { INestApplication } from '@nestjs/common'; +import Ajv2020 from 'ajv/dist/2020'; +import request from 'supertest'; +import { OPERATION_EXAMPLES } from '../src/docs/examples'; +import { loadDocument, setupSwagger } from '../src/docs/swagger'; +import { createTestApp } from './helpers'; + +const CONTRACT_ID = 'https://contract.local/openapi.json'; + +describe('Swagger UI и примеры (e2e)', () => { + let app: INestApplication; + let server: any; + + beforeAll(async () => { + ({ app, server } = await createTestApp({}, setupSwagger)); + }); + + afterAll(async () => { + await app.close(); + }); + + it('отдаёт Swagger UI и документ контракта со всеми путями', async () => { + await request(server).get('/docs').expect(200); + const res = await request(server).get('/docs-json').expect(200); + expect(res.body.openapi).toBe('3.1.0'); + expect(Object.keys(res.body.paths)).toEqual( + Object.keys(loadDocument().paths), + ); + expect(res.body.components.securitySchemes).toHaveProperty('basicAuth'); + expect(res.body.components.securitySchemes).toHaveProperty('bearerAuth'); + }); + + it('каждый пример запроса и ответа проходит JSON Schema контракта', () => { + const document: any = loadDocument(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + ajv.addSchema(document, CONTRACT_ID); + let checked = 0; + for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) { + const [method, path] = key.split(' '); + const operation = document.paths[path][method.toLowerCase()]; + const targets: [string, any, Record][] = []; + if (examples.request) { + targets.push([ + 'request', + operation.requestBody.content['application/json'].schema, + examples.request, + ]); + } + for (const [status, named] of Object.entries(examples.responses)) { + targets.push([ + status, + operation.responses[status].content['application/json'].schema, + named, + ]); + } + for (const [where, schema, named] of targets) { + const validate = ajv.compile({ $ref: CONTRACT_ID + schema.$ref }); + for (const [name, example] of Object.entries(named)) { + const valid = validate(example.value); + expect({ key, where, name, valid, errors: validate.errors }).toEqual( + { key, where, name, valid: true, errors: null }, + ); + checked++; + } + } + } + expect(checked).toBeGreaterThan(40); + }); +}); diff --git a/test/failures.e2e-spec.ts b/test/failures.e2e-spec.ts new file mode 100644 index 0000000..41013f4 --- /dev/null +++ b/test/failures.e2e-spec.ts @@ -0,0 +1,166 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { randomUUID } from 'crypto'; +import Redis from 'ioredis'; +import { CacheService } from '../src/cache/cache.service'; +import { ChatsService } from '../src/chats/chats.service'; +import { PrismaService } from '../src/db/prisma.service'; +import { bearer, createTestApp, registerUser } from './helpers'; + +const UNREACHABLE_REDIS = 'redis://127.0.0.1:1/0'; +const UNREACHABLE_DB = 'postgresql://test:test@127.0.0.1:1/none?connect_timeout=1'; + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +describe('Уровень 4: expiry, отказы зависимостей, rollback (e2e)', () => { + const apps: INestApplication[] = []; + + async function start(env: Record = {}) { + const started = await createTestApp(env); + apps.push(started.app); + return started; + } + + afterAll(async () => { + await Promise.all(apps.map((app) => app.close())); + }); + + it('сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша', async () => { + const { server } = await start({ SESSION_TTL_SECONDS: '2' }); + const user = await registerUser(server, 'ttl'); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + await sleep(2500); + const res = await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(401); + expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"'); + }); + + it('без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва', async () => { + const { server } = await start({ CACHE_URL: UNREACHABLE_REDIS }); + const user = await registerUser(server, 'noredis'); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + const res = await request(server) + .delete('/api/v1/auth/sessions/current') + .set('Authorization', bearer(user)) + .expect(503); + expect(res.body.error.code).toBe('unavailable'); + await request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + await request(server).get('/api/v1/users/me').expect(401); + }); + + it('logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше', async () => { + const a = await start(); + const b = await start(); + const user = await registerUser(a.server, 'partition'); + const me = (server: any, status: number) => + request(server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(status); + const logout = (status: number) => + request(a.server) + .delete('/api/v1/auth/sessions/current') + .set('Authorization', bearer(user)) + .expect(status); + const cache = a.app.get(CacheService) as any; + const redis = cache.client as Redis; + + await me(b.server, 200); + redis.disconnect(); + await logout(503); + await me(b.server, 200); + await me(a.server, 200); + + await redis.connect(); + await sleep(200); + expect(cache.trusted).toBe(true); + await me(b.server, 200); + expect((await redis.keys('session:v1:*')).length).toBeGreaterThan(0); + await logout(204); + await me(b.server, 401); + await me(a.server, 401); + }); + + it('без PostgreSQL отвечает ограниченным 503 и не пускает анонима', async () => { + const healthy = await start(); + const user = await registerUser(healthy.server, 'nodb'); + await request(healthy.server) + .get('/api/v1/users/me') + .set('Authorization', bearer(user)) + .expect(200); + + const { server } = await start({ DATABASE_URL: UNREACHABLE_DB }); + const ready = await request(server).get('/health/ready').expect(503); + expect(ready.body.error.code).toBe('unavailable'); + expect(JSON.stringify(ready.body)).not.toMatch(/127\.0\.0\.1|postgresql:|prisma/i); + + await request(server).get('/api/v1/chats').expect(401); + await request(server) + .get('/api/v1/chats') + .set('X-User-Id', user.id) + .expect(401); + await request(server) + .get('/api/v1/chats') + .set('Authorization', 'Bearer unknown-token-value') + .expect(503); + const res = await request(server) + .get('/api/v1/chats') + .set('Authorization', bearer(user)) + .expect(503); + expect(res.body.error.code).toBe('unavailable'); + await request(server) + .post('/api/v1/users') + .send({ + username: `nodb_${randomUUID().slice(0, 8)}`, + display_name: 'X', + password: 'Long-enough-pass-1', + }) + .expect(503); + }); + + it('неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id', async () => { + const { app, server } = await start(); + const user = await registerUser(server, 'boom'); + jest + .spyOn(app.get(ChatsService), 'listForMember') + .mockRejectedValueOnce(new Error('secret internal details')); + const res = await request(server) + .get('/api/v1/chats') + .set('Authorization', bearer(user)) + .expect(500); + expect(res.body.error.code).toBe('internal_error'); + expect(JSON.stringify(res.body)).not.toMatch(/secret/); + expect(res.body.error.request_id).toBe(res.headers['x-request-id']); + expect(res.headers['x-instance-id']).toBeTruthy(); + }); + + it('откатывает создание чата целиком, если один из участников не существует', async () => { + const { app, server } = await start(); + const alice = await registerUser(server, 'rollback'); + const title = `rollback ${randomUUID()}`; + const res = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title, member_ids: [alice.id, randomUUID()] }) + .expect(400); + expect(res.body.error.code).toBe('invalid_request'); + const prisma = app.get(PrismaService); + expect(await prisma.chat.count({ where: { title } })).toBe(0); + expect( + await prisma.chatMember.count({ where: { userId: alice.id } }), + ).toBe(0); + }); +}); diff --git a/test/global-setup.ts b/test/global-setup.ts new file mode 100644 index 0000000..223e475 --- /dev/null +++ b/test/global-setup.ts @@ -0,0 +1,28 @@ +import { + BucketAlreadyOwnedByYou, + CreateBucketCommand, + S3Client, +} from '@aws-sdk/client-s3'; +import { execSync } from 'child_process'; + +export default async function globalSetup(): Promise { + execSync('npx prisma migrate deploy', { stdio: 'inherit' }); + const client = new S3Client({ + endpoint: process.env.S3_ENDPOINT, + region: 'us-east-1', + forcePathStyle: true, + credentials: { + accessKeyId: process.env.S3_ACCESS_KEY_ID!, + secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!, + }, + }); + try { + await client.send(new CreateBucketCommand({ Bucket: process.env.S3_BUCKET! })); + } catch (error) { + if (!(error instanceof BucketAlreadyOwnedByYou)) { + throw error; + } + } finally { + client.destroy(); + } +} diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..2d08381 --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,110 @@ +import { INestApplication } from '@nestjs/common'; +import { + FastifyAdapter, + NestFastifyApplication, +} from '@nestjs/platform-fastify'; +import { Test } from '@nestjs/testing'; +import { randomUUID } from 'crypto'; +import request from 'supertest'; +import { AppModule } from '../src/app.module'; +import { configureApp } from '../src/configure-app'; +import { PrismaService } from '../src/db/prisma.service'; +import { parseJobMessage } from '../src/jobs/job-message'; +import { + JobProcessor, + Outcome, + ProcessorHooks, + ProcessorOptions, + processorOptions, +} from '../src/jobs/processor'; +import { S3Service } from '../src/storage/s3.service'; + +export const PASSWORD = 'Correct-Horse-Battery-42'; + +export interface TestUser { + id: string; + username: string; + token: string; +} + +export async function createTestApp( + env: Record = {}, + setup: (app: NestFastifyApplication) => void = () => undefined, +): Promise<{ + app: INestApplication; + server: any; +}> { + const saved = { ...process.env }; + Object.assign(process.env, env); + let app: NestFastifyApplication; + try { + const moduleRef = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + app = moduleRef.createNestApplication( + new FastifyAdapter(), + ); + } finally { + process.env = saved; + } + configureApp(app); + setup(app); + await app.listen(0, '127.0.0.1'); + return { app, server: app.getHttpServer() }; +} + +export async function processAttachment( + app: INestApplication, + attachmentId: string, + hooks: ProcessorHooks = {}, + options: Partial = {}, +): Promise { + const prisma = app.get(PrismaService); + const entry = await prisma.outboxEntry.findFirstOrThrow({ + where: { job: { attachmentId } }, + orderBy: { id: 'desc' }, + }); + const message = parseJobMessage(Buffer.from(JSON.stringify(entry.payload))); + if (!message) { + throw new Error('outbox payload does not match jobs.schema.json'); + } + const processor = new JobProcessor( + prisma, + app.get(S3Service), + { ...processorOptions(), ...options }, + hooks, + ); + return processor.handle(message); +} + +export function basic(username: string, password: string): string { + return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`; +} + +export function bearer(user: TestUser): string { + return `Bearer ${user.token}`; +} + +export async function login( + server: any, + username: string, + password = PASSWORD, +): Promise { + const res = await request(server) + .post('/api/v1/auth/sessions') + .set('Authorization', basic(username, password)) + .expect(201); + return res.body.token; +} + +export async function registerUser( + server: any, + label: string, +): Promise { + const username = `u_${label}_${randomUUID().slice(0, 8)}`; + const res = await request(server) + .post('/api/v1/users') + .send({ username, display_name: `User ${label}`, password: PASSWORD }) + .expect(201); + return { id: res.body.id, username, token: await login(server, username) }; +} diff --git a/test/idempotency.e2e-spec.ts b/test/idempotency.e2e-spec.ts new file mode 100644 index 0000000..a8cecc0 --- /dev/null +++ b/test/idempotency.e2e-spec.ts @@ -0,0 +1,139 @@ +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { randomUUID } from 'crypto'; +import { PrismaService } from '../src/db/prisma.service'; +import { bearer, createTestApp, registerUser, TestUser } from './helpers'; + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +describe('Идемпотентность отправки и X-Instance-Id (e2e)', () => { + const apps: INestApplication[] = []; + let server: any; + let replica: any; + let prisma: PrismaService; + + beforeAll(async () => { + const first = await createTestApp(); + const second = await createTestApp(); + apps.push(first.app, second.app); + server = first.server; + replica = second.server; + prisma = first.app.get(PrismaService); + }); + + afterAll(async () => { + await Promise.all(apps.map((app) => app.close())); + }); + + async function setup(label: string) { + const alice = await registerUser(server, label); + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Idem', member_ids: [alice.id] }) + .expect(201); + return { alice, path: `/api/v1/chats/${chat.body.id}/messages` }; + } + + function send(target: any, user: TestUser, path: string, key: string | null, body: object) { + const req = request(target).post(path).set('Authorization', bearer(user)); + return (key === null ? req : req.set('Idempotency-Key', key)).send(body); + } + + async function countMessages(path: string, user: TestUser): Promise { + const res = await request(server) + .get(`${path}?limit=100`) + .set('Authorization', bearer(user)) + .expect(200); + return res.body.items.length; + } + + it('требует Idempotency-Key правильного формата', async () => { + const { alice, path } = await setup('keyfmt'); + for (const key of [null, '', 'has space', 'semi;colon', 'slash/key', 'x'.repeat(129)]) { + const res = await send(server, alice, path, key, { text: 'x' }); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('invalid_request'); + } + await send(server, alice, path, 'A-z_0.9:' + 'k'.repeat(120), { text: 'x' }).expect(201); + }); + + it('повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение', async () => { + const { alice, path } = await setup('replay'); + const key = randomUUID(); + const first = await send(server, alice, path, key, { text: 'Привет 👋' }).expect(201); + const again = await send(replica, alice, path, key, { text: 'Привет 👋' }).expect(201); + expect(again.body).toEqual(first.body); + expect(await countMessages(path, alice)).toBe(1); + }); + + it('тот же ключ с другим телом — 409, сообщение не создаётся', async () => { + const { alice, path } = await setup('conflict'); + const key = randomUUID(); + await send(server, alice, path, key, { text: 'первое' }).expect(201); + const res = await send(server, alice, path, key, { text: 'другое' }).expect(409); + expect(res.body.error.code).toBe('conflict'); + expect(await countMessages(path, alice)).toBe(1); + }); + + it('20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение', async () => { + const { alice, path } = await setup('parallel'); + const key = randomUUID(); + const responses = await Promise.all( + Array.from({ length: 20 }, (_, i) => + send(i % 2 ? replica : server, alice, path, key, { text: 'одно' }), + ), + ); + expect(responses.map((r) => r.status)).toEqual(Array(20).fill(201)); + expect(new Set(responses.map((r) => r.body.id)).size).toBe(1); + expect(await countMessages(path, alice)).toBe(1); + }); + + it('область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим', async () => { + const a = await setup('scopea'); + const b = await setup('scopeb'); + const key = randomUUID(); + const one = await send(server, a.alice, a.path, key, { text: 'x' }).expect(201); + const two = await send(server, b.alice, b.path, key, { text: 'x' }).expect(201); + expect(one.body.id).not.toBe(two.body.id); + }); + + it('повтор заново проверяет сессию', async () => { + const { alice, path } = await setup('recheck'); + const key = randomUUID(); + await send(server, alice, path, key, { text: 'x' }).expect(201); + await request(server) + .delete('/api/v1/auth/sessions/current') + .set('Authorization', bearer(alice)) + .expect(204); + await send(server, alice, path, key, { text: 'x' }).expect(401); + }); + + it('после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново', async () => { + const { app, server: short } = await createTestApp({ IDEMPOTENCY_TTL_SECONDS: '1' }); + apps.push(app); + const { alice, path } = await setup('ttl'); + const key = randomUUID(); + const first = await send(short, alice, path, key, { text: 'x' }).expect(201); + await sleep(1500); + const second = await send(short, alice, path, key, { text: 'y' }).expect(201); + expect(second.body.id).not.toBe(first.body.id); + expect(await prisma.idempotencyKey.count({ where: { key } })).toBe(1); + }); + + it('X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе', async () => { + const ids = new Set(); + for (const res of [ + await request(server).get('/health/live').expect(200), + await request(server).get('/health/ready').expect(200), + await request(server).get('/api/v1/users/me').expect(401), + await request(server).post('/api/v1/users').send('{bad').set('Content-Type', 'application/json').expect(400), + ]) { + expect(res.headers['x-instance-id']).toBeTruthy(); + ids.add(res.headers['x-instance-id']); + } + expect(ids.size).toBe(1); + }); +}); diff --git a/test/images.ts b/test/images.ts new file mode 100644 index 0000000..c8a3c68 --- /dev/null +++ b/test/images.ts @@ -0,0 +1,150 @@ +import { readFileSync } from 'fs'; +import { join } from 'path'; +import sharp from 'sharp'; +import { deflateSync } from 'zlib'; + +const CRC_TABLE = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + return c >>> 0; +}); + +function crc32(data: Buffer): number { + let c = 0xffffffff; + for (const byte of data) { + c = CRC_TABLE[(c ^ byte) & 255] ^ (c >>> 8); + } + return (c ^ 0xffffffff) >>> 0; +} + +export function pngChunk(type: string, data: Buffer): Buffer { + const name = Buffer.from(type, 'latin1'); + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(Buffer.concat([name, data]))); + return Buffer.concat([length, name, data, crc]); +} + +const SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex'); +const END = pngChunk('IEND', Buffer.alloc(0)); + +function header(width: number, height: number, colorType = 2): Buffer { + const data = Buffer.alloc(13); + data.writeUInt32BE(width, 0); + data.writeUInt32BE(height, 4); + data[8] = 8; + data[9] = colorType; + return pngChunk('IHDR', data); +} + +function rows(width: number, height: number, filter = 0): Buffer { + const stride = width * 3 + 1; + const raw = Buffer.alloc(stride * height, 7); + for (let y = 0; y < height; y++) { + raw[y * stride] = filter; + } + return raw; +} + +export function png(width: number, height: number, extra: Buffer[] = []): Buffer { + return Buffer.concat([ + SIGNATURE, + header(width, height), + ...extra, + pngChunk('IDAT', deflateSync(rows(width, height))), + END, + ]); +} + +export function pngOfExactSize(size: number): Buffer { + const base = png(4, 4); + const padding = size - base.length - 12; + return png(4, 4, [pngChunk('abCd', Buffer.alloc(padding))]); +} + +export function pngHeaderOnly(width: number, height: number): Buffer { + return Buffer.concat([ + SIGNATURE, + header(width, height), + pngChunk('IDAT', deflateSync(Buffer.alloc(16))), + END, + ]); +} + +export const SAMPLE_PNG = readFileSync( + join(__dirname, '..', 'tests', 'fixtures', 'sample.png'), +); + +export const JPEG_WITHOUT_DATA = Buffer.from( + 'ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9', + 'hex', +); + +export async function jpeg(): Promise { + const noise = Buffer.alloc(320 * 200 * 3); + for (let i = 0; i < noise.length; i++) { + noise[i] = (i * 7919) & 255; + } + return sharp(noise, { raw: { width: 320, height: 200, channels: 3 } }) + .jpeg() + .toBuffer(); +} + +export function corruptedPngs(): Record { + const lastRowFilter = rows(64, 64); + lastRowFilter[63 * (64 * 3 + 1)] = 5; + const flipped = Buffer.from(SAMPLE_PNG); + flipped[100] ^= 255; + return { + 'первые 33 байта sample.png': SAMPLE_PNG.subarray(0, 33), + 'половина файла': SAMPLE_PNG.subarray(0, SAMPLE_PNG.length >> 1), + 'без последних 20 байт': SAMPLE_PNG.subarray(0, SAMPLE_PNG.length - 20), + 'без IEND': SAMPLE_PNG.subarray(0, SAMPLE_PNG.length - 12), + 'неверный CRC': flipped, + 'фильтр строки 5': pngFromRaw(1, 1, rows(1, 1, 5)), + 'фильтр строки 255': pngFromRaw(1, 1, rows(1, 1, 255)), + 'неверный фильтр в последней строке': pngFromRaw(64, 64, lastRowFilter), + 'мусор в IDAT с верным CRC': Buffer.concat([ + SIGNATURE, + header(64, 64), + pngChunk('IDAT', Buffer.alloc(40, 0xab)), + END, + ]), + 'данных меньше, чем строк': pngFromRaw(64, 64, rows(64, 10)), + 'палитра на 257 записей': Buffer.concat([ + SIGNATURE, + header(1, 1, 3), + pngChunk('PLTE', Buffer.alloc(771)), + pngChunk('IDAT', deflateSync(Buffer.from([0, 0]))), + END, + ]), + }; +} + +export function corruptedJpegs(valid: Buffer): Record { + const garbled = Buffer.from(valid); + for (let i = 800; i < garbled.length - 2; i += 3) { + garbled[i] = 0x55; + } + const foreignComponent = Buffer.from(valid); + foreignComponent[foreignComponent.indexOf(Buffer.from([0xff, 0xda])) + 5] = 250; + return { + 'компонент SOS отсутствует в SOF': foreignComponent, + '27 байт без таблиц и данных': JPEG_WITHOUT_DATA, + 'половина файла': valid.subarray(0, valid.length >> 1), + 'без последних 20 байт': valid.subarray(0, valid.length - 20), + 'испорченные данные скана': garbled, + }; +} + +function pngFromRaw(width: number, height: number, raw: Buffer): Buffer { + return Buffer.concat([ + SIGNATURE, + header(width, height), + pngChunk('IDAT', deflateSync(raw)), + END, + ]); +} diff --git a/test/jest-e2e.json b/test/jest-e2e.json new file mode 100644 index 0000000..f12a160 --- /dev/null +++ b/test/jest-e2e.json @@ -0,0 +1,11 @@ +{ + "testTimeout": 30000, + "moduleFileExtensions": ["js", "json", "ts"], + "rootDir": ".", + "testEnvironment": "node", + "testRegex": ".e2e-spec.ts$", + "globalSetup": "/global-setup.ts", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + } +} diff --git a/test/jobs.e2e-spec.ts b/test/jobs.e2e-spec.ts new file mode 100644 index 0000000..a5c08bc --- /dev/null +++ b/test/jobs.e2e-spec.ts @@ -0,0 +1,513 @@ +import { INestApplication } from '@nestjs/common'; +import { createHash, randomUUID } from 'crypto'; +import sharp from 'sharp'; +import request from 'supertest'; +import { reconcile } from '../src/attachments/reconciler'; +import { ApiError } from '../src/common/filters/api-error'; +import { PrismaService } from '../src/db/prisma.service'; +import { jobMessage, parseJobMessage } from '../src/jobs/job-message'; +import { backoffMs, recoverExpiredLeases, replayJob, republishStale } from '../src/jobs/job-store'; +import { JobProcessor, processorOptions } from '../src/jobs/processor'; +import { fitInside, InvalidImageError, renderVariants } from '../src/jobs/variants'; +import { S3Service } from '../src/storage/s3.service'; +import { + bearer, + createTestApp, + processAttachment, + registerUser, + TestUser, +} from './helpers'; +import { SAMPLE_PNG } from './images'; + +const MAX_BYTES = 10 * 1024 * 1024; + +describe('Фоновая обработка вложений (e2e)', () => { + let app: INestApplication; + let server: any; + let prisma: PrismaService; + let s3: S3Service; + let alice: TestUser; + let eve: TestUser; + let chatId: string; + + const upload = async (body: Buffer = SAMPLE_PNG, type = 'image/png') => { + const res = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', type) + .send(body) + .expect(202); + return res.body.id as string; + }; + + const metadata = async (id: string) => + (await request(server).get(`/api/v1/attachments/${id}`).set('Authorization', bearer(alice)).expect(200)).body; + + const content = (id: string, variant = 'original', user = alice) => + request(server) + .get(`/api/v1/attachments/${id}/content?variant=${variant}`) + .set('Authorization', bearer(user)) + .buffer(true) + .parse(binaryParser); + + const job = (attachmentId: string) => + prisma.attachmentJob.findFirstOrThrow({ where: { attachmentId } }); + + const makeDue = (attachmentId: string) => + prisma.attachmentJob.updateMany({ where: { attachmentId }, data: { nextAttemptAt: new Date() } }); + + const events = async (attachmentId: string) => + ( + await prisma.jobEvent.findMany({ + where: { job: { attachmentId } }, + orderBy: { id: 'asc' }, + }) + ).map((event) => event.event); + + const sendMessage = (attachmentIds: string[]) => + request(server) + .post(`/api/v1/chats/${chatId}/messages`) + .set('Authorization', bearer(alice)) + .set('Idempotency-Key', randomUUID()) + .send({ text: '', attachment_ids: attachmentIds }); + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + prisma = app.get(PrismaService); + s3 = app.get(S3Service); + alice = await registerUser(server, 'job_alice'); + eve = await registerUser(server, 'job_eve'); + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Jobs', member_ids: [alice.id] }) + .expect(201); + chatId = chat.body.id; + }); + + afterAll(async () => { + await app.close(); + }); + + describe('до обработки', () => { + it('queued: метаданные доступны, content любого варианта — 409, сообщение с вложением создаётся', async () => { + const id = await upload(); + expect(await metadata(id)).toMatchObject({ status: 'queued', variants: [], error_code: null }); + for (const variant of ['original', 'thumbnail', 'crop', 'optimized']) { + const res = await content(id, variant).expect(409); + expect(JSON.parse(res.body.toString()).error.code).toBe('conflict'); + } + await content(id, 'original', eve).expect(404); + await content(id, 'nonsense').expect(400); + const message = await sendMessage([id]).expect(201); + expect(message.body.attachment_ids).toEqual([id]); + }); + }); + + describe('результат worker', () => { + it('ready: оригинал неизменен, thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP без увеличения', async () => { + const id = await upload(); + expect(await processAttachment(app, id)).toBe('ready'); + const meta = await metadata(id); + expect(meta.status).toBe('ready'); + expect(meta.error_code).toBeNull(); + expect(meta.variants.map((v: any) => [v.name, v.content_type, v.width, v.height])).toEqual([ + ['thumbnail', 'image/jpeg', 256, 160], + ['crop', 'image/jpeg', 128, 128], + ['optimized', 'image/webp', 320, 200], + ]); + const original = await content(id).expect(200); + expect(Buffer.compare(original.body, SAMPLE_PNG)).toBe(0); + for (const variant of meta.variants) { + const res = await content(id, variant.name).expect(200); + expect(res.headers['content-type']).toBe(variant.content_type); + expect(res.body.length).toBe(variant.size_bytes); + expect(createHash('sha256').update(res.body).digest('hex')).toBe(variant.sha256); + const actual = await sharp(res.body).metadata(); + expect([actual.format, actual.width, actual.height, actual.exif]).toEqual([ + variant.content_type.split('/')[1], + variant.width, + variant.height, + undefined, + ]); + } + const row = await prisma.attachment.findUniqueOrThrow({ where: { id } }); + expect(row.stagingKey).toBeNull(); + await expect(s3.getBuffer(`staging/${id}`, MAX_BYTES)).rejects.toThrow('missing'); + expect(await events(id)).toEqual(['enqueued', 'processing', 'ready']); + }); + + it('маленький исходник не увеличивается в thumbnail/optimized, crop — увеличивается', async () => { + const small = await sharp({ create: { width: 100, height: 50, channels: 3, background: '#123456' } }) + .png() + .toBuffer(); + const id = await upload(small); + expect(await processAttachment(app, id)).toBe('ready'); + const sizes = (await metadata(id)).variants.map((v: any) => [v.name, v.width, v.height]); + expect(sizes).toEqual([ + ['thumbnail', 100, 50], + ['crop', 128, 128], + ['optimized', 100, 50], + ]); + }); + + it('прозрачность компонуется на белый, EXIF orientation применяется', async () => { + const transparent = await sharp({ + create: { width: 40, height: 20, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } }, + }) + .png() + .toBuffer(); + const alphaId = await upload(transparent); + expect(await processAttachment(app, alphaId)).toBe('ready'); + const thumb = await content(alphaId, 'thumbnail').expect(200); + const { data } = await sharp(thumb.body).raw().toBuffer({ resolveWithObject: true }); + expect(Math.min(...data)).toBeGreaterThanOrEqual(250); + + const rotated = await sharp({ create: { width: 320, height: 200, channels: 3, background: '#808080' } }) + .jpeg() + .withMetadata({ orientation: 6 }) + .toBuffer(); + const rotatedId = await upload(rotated, 'image/jpeg'); + expect(await processAttachment(app, rotatedId)).toBe('ready'); + const thumbnail = (await metadata(rotatedId)).variants.find((v: any) => v.name === 'thumbnail'); + expect([thumbnail.width, thumbnail.height]).toEqual([160, 256]); + }); + + it('worker ограничивает пиксели до распаковки: превышение — InvalidImageError', async () => { + const image = await sharp({ create: { width: 300, height: 200, channels: 3, background: '#000' } }) + .png() + .toBuffer(); + await expect(renderVariants(image, 300 * 200 - 1)).rejects.toBeInstanceOf(InvalidImageError); + await expect(renderVariants(image, 300 * 200)).resolves.toHaveLength(3); + }); + + it('размеры считаются целочисленно: 319×200 → 256×160, перебор совпадает с точной формулой', () => { + expect(fitInside(319, 200, 256)).toEqual({ width: 256, height: 160 }); + for (let width = 1; width <= 3000; width++) { + for (const height of [1, 7, 100, 199, 200, 256, 257, 333, 1000, 2999]) { + const longest = BigInt(Math.max(width, height)); + const expected = + width <= 256 && height <= 256 + ? { width, height } + : width >= height + ? { width: 256, height: Math.max(1, Number((BigInt(height) * 256n) / longest)) } + : { width: Math.max(1, Number((BigInt(width) * 256n) / longest)), height: 256 }; + expect(fitInside(width, height, 256)).toEqual(expected); + } + } + }); + + it('размеры округляются вниз, минимум 1 px', () => { + expect(fitInside(320, 200, 256)).toEqual({ width: 256, height: 160 }); + expect(fitInside(1000, 3, 256)).toEqual({ width: 256, height: 1 }); + expect(fitInside(333, 1000, 256)).toEqual({ width: 85, height: 256 }); + expect(fitInside(10, 10, 256)).toEqual({ width: 10, height: 10 }); + }); + }); + + describe('идемпотентность и повторная доставка', () => { + it('повтор уже ready-задания — no-op: второго набора вариантов нет, объекты не меняются', async () => { + const id = await upload(); + expect(await processAttachment(app, id)).toBe('ready'); + const before = await prisma.attachmentVariant.findMany({ where: { attachmentId: id } }); + const put = jest.spyOn(s3, 'putBuffer'); + try { + expect(await processAttachment(app, id)).toBe('skipped'); + expect(put).not.toHaveBeenCalled(); + } finally { + put.mockRestore(); + } + const after = await prisma.attachmentVariant.findMany({ where: { attachmentId: id } }); + expect(after).toEqual(before); + expect(after).toHaveLength(3); + }); + + it('пока lease действует, второй обработчик того же job не запускается', async () => { + const id = await upload(); + let concurrent: string | undefined; + const outcome = await processAttachment(app, id, { + afterStore: async () => { + concurrent = await processAttachment(app, id); + }, + }); + expect([outcome, concurrent]).toEqual(['ready', 'skipped']); + }); + + it('worker упал после записи объектов, до COMMIT/ack: lease истекает, повтор завершает тот же результат', async () => { + const id = await upload(); + await expect( + processAttachment(app, id, { + afterStore: async () => { + throw new Error('worker crashed'); + }, + }), + ).rejects.toThrow('worker crashed'); + expect(await job(id)).toMatchObject({ status: 'processing', attempt: 1 }); + expect((await metadata(id)).status).toBe('processing'); + const stored = await s3.getBuffer(`attachments/${id}/v1/thumbnail.jpg`, MAX_BYTES); + + expect(await recoverExpiredLeases(prisma)).toBe(0); + const future = new Date(Date.now() + 10 * 60 * 1000); + expect(await recoverExpiredLeases(prisma, future)).toBeGreaterThanOrEqual(1); + expect(await job(id)).toMatchObject({ status: 'queued', attempt: 2 }); + await makeDue(id); + expect(await processAttachment(app, id)).toBe('ready'); + + const variants = await prisma.attachmentVariant.findMany({ where: { attachmentId: id } }); + expect(variants).toHaveLength(3); + const thumbnail = variants.find((v) => v.name === 'thumbnail')!; + expect(thumbnail.sha256).toBe(createHash('sha256').update(stored).digest('hex')); + expect(await events(id)).toEqual(['enqueued', 'processing', 'lease_expired', 'processing', 'ready']); + }); + + it('worker упал после COMMIT, до ack: повтор — no-op, staging убирается при повторной доставке', async () => { + const id = await upload(); + await expect( + processAttachment(app, id, { + afterCommit: async () => { + throw new Error('worker crashed'); + }, + }), + ).rejects.toThrow('worker crashed'); + expect((await metadata(id)).status).toBe('ready'); + expect((await prisma.attachment.findUniqueOrThrow({ where: { id } })).stagingKey).toBe(`staging/${id}`); + const put = jest.spyOn(s3, 'putBuffer'); + try { + expect(await processAttachment(app, id)).toBe('skipped'); + expect(put).not.toHaveBeenCalled(); + } finally { + put.mockRestore(); + } + expect((await prisma.attachment.findUniqueOrThrow({ where: { id } })).stagingKey).toBeNull(); + expect(await prisma.attachmentVariant.count({ where: { attachmentId: id } })).toBe(3); + expect(await events(id)).toEqual(['enqueued', 'processing', 'ready']); + }); + + it('сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз', async () => { + const id = await upload(); + const row = await job(id); + const later = new Date(Date.now() + 10 * 60 * 1000); + expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBe(0); + await prisma.outboxEntry.updateMany({ + where: { jobId: row.id }, + data: { publishedAt: new Date() }, + }); + expect(await republishStale(prisma, 5 * 60 * 1000, new Date())).toBe(0); + expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBeGreaterThanOrEqual(1); + expect(await prisma.outboxEntry.count({ where: { jobId: row.id } })).toBe(2); + expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBe(0); + expect(await prisma.outboxEntry.count({ where: { jobId: row.id } })).toBe(2); + expect(await processAttachment(app, id)).toBe('ready'); + expect(await events(id)).toEqual(['enqueued', 'republished', 'processing', 'ready']); + }); + + it('устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются', async () => { + const id = await upload(); + const row = await job(id); + const processor = new JobProcessor(prisma, s3, processorOptions()); + const base = jobMessage(row, new Date()); + expect(await processor.handle({ ...base, attachment_id: randomUUID() })).toBe('skipped'); + expect(await processor.handle({ ...base, pipeline_version: 2 })).toBe('skipped'); + expect(await processor.handle({ ...base, job_id: randomUUID() })).toBe('skipped'); + expect((await job(id)).status).toBe('queued'); + }); + }); + + describe('ошибки, повторы и replay', () => { + it('временная ошибка S3: повтор с backoff, до срока задание не берётся, затем ready', async () => { + const id = await upload(); + const put = jest + .spyOn(s3, 'putBuffer') + .mockRejectedValueOnce(new ApiError('unavailable', 'object storage unavailable')); + try { + expect(await processAttachment(app, id)).toBe('retry'); + } finally { + put.mockRestore(); + } + const retried = await job(id); + expect(retried).toMatchObject({ status: 'queued', attempt: 2, lastError: 'temporary failure: ApiError' }); + expect(retried.nextAttemptAt.getTime()).toBeGreaterThan(Date.now()); + expect((await metadata(id)).status).toBe('queued'); + const outbox = await prisma.outboxEntry.findMany({ where: { jobId: retried.id }, orderBy: { id: 'asc' } }); + expect(outbox).toHaveLength(2); + expect(outbox[1].availableAt).toEqual(retried.nextAttemptAt); + expect((outbox[1].payload as any).attempt).toBe(2); + expect((outbox[1].payload as any).job_id).toBe(retried.id); + + expect(await processAttachment(app, id)).toBe('skipped'); + await makeDue(id); + expect(await processAttachment(app, id)).toBe('ready'); + expect(await events(id)).toEqual(['enqueued', 'processing', 'retry_scheduled', 'processing', 'ready']); + }); + + it('попытки исчерпаны — failed retry_exhausted; replay явно возвращает в очередь и доводит до ready', async () => { + const id = await upload(); + await prisma.attachmentJob.updateMany({ where: { attachmentId: id }, data: { maxAttempts: 2 } }); + const put = jest + .spyOn(s3, 'putBuffer') + .mockRejectedValue(new ApiError('unavailable', 'object storage unavailable')); + try { + expect(await processAttachment(app, id)).toBe('retry'); + await makeDue(id); + expect(await processAttachment(app, id)).toBe('failed'); + } finally { + put.mockRestore(); + } + expect(await metadata(id)).toMatchObject({ status: 'failed', error_code: 'retry_exhausted', variants: [] }); + const failed = await job(id); + expect(failed).toMatchObject({ status: 'failed', errorCode: 'retry_exhausted', attempt: 2 }); + await sendMessage([id]).expect(409); + + expect(await replayJob(prisma, failed.id, 'test-operator')).toBe('replayed'); + expect(await job(id)).toMatchObject({ status: 'queued', attempt: 1, errorCode: null }); + expect(await metadata(id)).toMatchObject({ status: 'queued', error_code: null }); + expect(await processAttachment(app, id)).toBe('ready'); + + const outboxBefore = await prisma.outboxEntry.count({ where: { jobId: failed.id } }); + expect(await replayJob(prisma, failed.id, 'test-operator')).toBe('already_ready'); + expect(await prisma.outboxEntry.count({ where: { jobId: failed.id } })).toBe(outboxBefore); + expect(await replayJob(prisma, randomUUID(), 'test-operator')).toBe('not_found'); + const replayed = await prisma.jobEvent.findFirstOrThrow({ where: { jobId: failed.id, event: 'replayed' } }); + expect(replayed.detail).toBe('by test-operator; previous retry_exhausted after attempt 2'); + }); + + it('lease истёк на последней попытке — failed retry_exhausted, а не вечный processing', async () => { + const id = await upload(); + await prisma.attachmentJob.updateMany({ where: { attachmentId: id }, data: { maxAttempts: 1 } }); + await expect( + processAttachment(app, id, { + afterStore: async () => { + throw new Error('worker crashed'); + }, + }), + ).rejects.toThrow('worker crashed'); + await recoverExpiredLeases(prisma, new Date(Date.now() + 10 * 60 * 1000)); + expect(await job(id)).toMatchObject({ status: 'failed', errorCode: 'retry_exhausted', leaseOwner: null }); + expect(await metadata(id)).toMatchObject({ status: 'failed', error_code: 'retry_exhausted' }); + }); + + it('replay и очистка staging не теряют исходник ни при каком порядке', async () => { + const fail = async () => { + const id = await upload(); + await prisma.attachmentJob.updateMany({ + where: { attachmentId: id }, + data: { status: 'failed', errorCode: 'retry_exhausted' }, + }); + await prisma.attachment.update({ + where: { id }, + data: { status: 'failed', errorCode: 'retry_exhausted' }, + }); + return id; + }; + const expire = (id: string) => + reconcile(prisma, s3, { + apply: true, + graceMs: 0, + prefix: `staging/${id}`, + stagingRetentionMs: 0, + now: new Date(Date.now() + 1000), + }); + + const replayedFirst = await fail(); + expect(await replayJob(prisma, (await job(replayedFirst)).id, 'test-operator')).toBe('replayed'); + await expire(replayedFirst); + expect(await s3.getBuffer(`staging/${replayedFirst}`, MAX_BYTES)).toHaveLength(SAMPLE_PNG.length); + expect(await processAttachment(app, replayedFirst)).toBe('ready'); + + const expiredFirst = await fail(); + await expire(expiredFirst); + await expect(s3.getBuffer(`staging/${expiredFirst}`, MAX_BYTES)).rejects.toThrow('missing'); + expect(await replayJob(prisma, (await job(expiredFirst)).id, 'test-operator')).toBe('source_missing'); + expect(await job(expiredFirst)).toMatchObject({ status: 'failed' }); + expect(await metadata(expiredFirst)).toMatchObject({ status: 'failed' }); + }); + + it('replay задания в очереди не создаёт дубль', async () => { + const id = await upload(); + expect(await replayJob(prisma, (await job(id)).id, 'test-operator')).toBe('not_failed'); + expect(await prisma.outboxEntry.count({ where: { job: { attachmentId: id } } })).toBe(1); + }); + + it('нераспаковываемое изображение — постоянная ошибка: сразу failed invalid_image без повторов', async () => { + const id = await upload(); + const garbage = Buffer.concat([SAMPLE_PNG.subarray(0, 64), Buffer.alloc(512, 7)]); + const sha256 = createHash('sha256').update(garbage).digest('hex'); + await s3.putBuffer(`staging/${id}`, garbage, 'image/png', sha256); + await prisma.attachment.update({ where: { id }, data: { sizeBytes: garbage.length, sha256 } }); + expect(await processAttachment(app, id)).toBe('failed'); + expect(await metadata(id)).toMatchObject({ status: 'failed', error_code: 'invalid_image', variants: [] }); + expect(await job(id)).toMatchObject({ status: 'failed', attempt: 1, errorCode: 'invalid_image' }); + await content(id).expect(409); + await sendMessage([id]).expect(409); + expect(await prisma.attachment.findUniqueOrThrow({ where: { id } })).toMatchObject({ + stagingKey: `staging/${id}`, + }); + }); + + it('staging подменён — failed checksum_mismatch; staging пропал — failed staging_missing', async () => { + const changed = await upload(); + const other = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#ff0000' } }) + .png() + .toBuffer(); + await s3.putBuffer(`staging/${changed}`, other, 'image/png', createHash('sha256').update(other).digest('hex')); + expect(await processAttachment(app, changed)).toBe('failed'); + expect((await metadata(changed)).error_code).toBe('checksum_mismatch'); + + const missing = await upload(); + await s3.delete(`staging/${missing}`); + expect(await processAttachment(app, missing)).toBe('failed'); + expect((await metadata(missing)).error_code).toBe('staging_missing'); + }); + + it('превышение времени обработки — временная ошибка с повтором', async () => { + const id = await upload(); + const slow = jest + .spyOn(s3, 'getBuffer') + .mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve(SAMPLE_PNG), 500))); + try { + expect(await processAttachment(app, id, {}, { timeoutMs: 50 })).toBe('retry'); + } finally { + slow.mockRestore(); + } + expect((await job(id)).lastError).toBe('processing timed out'); + }); + }); + + describe('формат сообщения и backoff', () => { + it('сообщение соответствует jobs.schema.json, лишние/неверные поля отклоняются', () => { + const valid = jobMessage( + { id: randomUUID(), attachmentId: randomUUID(), pipelineVersion: 1, attempt: 1 }, + new Date(), + ); + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)); + expect(parseJobMessage(encode(valid))).toEqual(valid); + for (const bad of [ + { ...valid, url: 'http://evil' }, + { ...valid, job_id: 'nope' }, + { ...valid, type: 'other' }, + { ...valid, attempt: 0 }, + { ...valid, schema_version: 2 }, + { ...valid, created_at: 'yesterday' }, + [valid], + ]) { + expect(parseJobMessage(encode(bad))).toBeNull(); + } + expect(parseJobMessage(Buffer.from('{bad'))).toBeNull(); + }); + + it('backoff растёт экспоненциально с jitter и ограничен сверху', () => { + expect(backoffMs(1, () => 0)).toBe(500); + expect(backoffMs(1, () => 1)).toBe(1000); + expect(backoffMs(3, () => 0)).toBe(2000); + expect(backoffMs(3, () => 1)).toBe(4000); + expect(backoffMs(20, () => 1)).toBe(30000); + expect(backoffMs(20, () => 0)).toBe(15000); + }); + }); +}); + +function binaryParser(res: any, done: (error: Error | null, body: Buffer) => void): void { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => done(null, Buffer.concat(chunks))); +} diff --git a/test/reconciler.e2e-spec.ts b/test/reconciler.e2e-spec.ts new file mode 100644 index 0000000..307608c --- /dev/null +++ b/test/reconciler.e2e-spec.ts @@ -0,0 +1,343 @@ +import { INestApplication } from '@nestjs/common'; +import { createHash, randomUUID } from 'crypto'; +import { mkdtempSync, rmSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import request from 'supertest'; +import { reconcile } from '../src/attachments/reconciler'; +import { PrismaService } from '../src/db/prisma.service'; +import { replayJob } from '../src/jobs/job-store'; +import { S3Service } from '../src/storage/s3.service'; +import { + bearer, + createTestApp, + processAttachment, + registerUser, + TestUser, +} from './helpers'; +import { SAMPLE_PNG } from './images'; + +const HOUR_MS = 60 * 60 * 1000; + +describe('Сверка объектов S3 с метаданными (e2e)', () => { + let app: INestApplication; + let server: any; + let prisma: PrismaService; + let s3: S3Service; + let alice: TestUser; + let chatId: string; + let dir: string; + + const putObject = async (key: string): Promise => { + const path = join(dir, randomUUID()); + writeFileSync(path, SAMPLE_PNG); + await s3.putFile({ + key, + path, + size: SAMPLE_PNG.length, + contentType: 'image/png', + sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'), + }); + }; + + const exists = async (key: string): Promise => { + const page = await s3.listObjects(key, 1); + return page.objects.some((object) => object.key === key); + }; + + const scope = () => `reconcile-test/${randomUUID()}/`; + const later = () => new Date(Date.now() + 2 * HOUR_MS); + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + prisma = app.get(PrismaService); + s3 = app.get(S3Service); + dir = mkdtempSync(join(tmpdir(), 'reconcile-test-')); + alice = await registerUser(server, 'rec_alice'); + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Reconcile', member_ids: [alice.id] }) + .expect(201); + chatId = chat.body.id; + }); + + afterAll(async () => { + rmSync(dir, { recursive: true, force: true }); + await app.close(); + }); + + it('dry-run сообщает о сироте и ничего не удаляет, apply удаляет, повторный запуск ничего не делает', async () => { + const prefix = scope(); + const key = `${prefix}orphan`; + await putObject(key); + const options = { graceMs: HOUR_MS, prefix, now: later() }; + + const dry = await reconcile(prisma, s3, { ...options, apply: false }); + expect(dry).toMatchObject({ mode: 'dry-run', scanned: 1, orphans: 1, deleted: 0, orphan_keys: [key] }); + expect(await exists(key)).toBe(true); + + const applied = await reconcile(prisma, s3, { ...options, apply: true }); + expect(applied).toMatchObject({ mode: 'apply', orphans: 1, deleted: 1, failed: 0 }); + expect(await exists(key)).toBe(false); + + const again = await reconcile(prisma, s3, { ...options, apply: true }); + expect(again).toMatchObject({ scanned: 0, orphans: 0, deleted: 0 }); + }); + + it('не трогает свежий объект внутри grace period', async () => { + const prefix = scope(); + const key = `${prefix}fresh`; + await putObject(key); + const report = await reconcile(prisma, s3, { apply: true, graceMs: HOUR_MS, prefix }); + expect(report).toMatchObject({ scanned: 1, fresh_skipped: 1, orphans: 0, deleted: 0 }); + expect(await exists(key)).toBe(true); + }); + + it('не трогает старый объект, на который есть метаданные', async () => { + const prefix = scope(); + const key = `${prefix}referenced`; + await putObject(key); + await prisma.attachment.create({ + data: { + chatId, + ownerId: alice.id, + filename: 'a.png', + contentType: 'image/png', + sizeBytes: SAMPLE_PNG.length, + sha256: createHash('sha256').update(SAMPLE_PNG).digest('hex'), + objectKey: key, + status: 'ready', + }, + }); + const report = await reconcile(prisma, s3, { + apply: true, + graceMs: HOUR_MS, + prefix, + now: later(), + }); + expect(report).toMatchObject({ scanned: 1, referenced: 1, orphans: 0, deleted: 0 }); + expect(await exists(key)).toBe(true); + }); + + it('при отказе PostgreSQL проход прерывается и ничего не удаляет', async () => { + const prefix = scope(); + const key = `${prefix}orphan`; + await putObject(key); + const broken = { + attachment: { + findMany: jest.fn().mockRejectedValue(new Error('database down')), + }, + } as unknown as PrismaService; + await expect( + reconcile(broken, s3, { apply: true, graceMs: HOUR_MS, prefix, now: later() }), + ).rejects.toThrow('database down'); + expect(await exists(key)).toBe(true); + }); + + it('сбой удаления считается и повторяется на следующем проходе', async () => { + const prefix = scope(); + const key = `${prefix}orphan`; + await putObject(key); + const options = { apply: true, graceMs: HOUR_MS, prefix, now: later() }; + const remove = jest.spyOn(s3, 'delete').mockRejectedValueOnce(new Error('s3 down')); + try { + const failed = await reconcile(prisma, s3, options); + expect(failed).toMatchObject({ orphans: 1, deleted: 0, failed: 1 }); + expect(await exists(key)).toBe(true); + } finally { + remove.mockRestore(); + } + const retried = await reconcile(prisma, s3, options); + expect(retried).toMatchObject({ orphans: 1, deleted: 1, failed: 0 }); + expect(await exists(key)).toBe(false); + }); + + it('обходит все страницы листинга', async () => { + const prefix = scope(); + await Promise.all([1, 2, 3].map((n) => putObject(`${prefix}${n}`))); + const report = await reconcile(prisma, s3, { + apply: true, + graceMs: HOUR_MS, + prefix, + now: later(), + pageSize: 1, + }); + expect(report).toMatchObject({ scanned: 3, orphans: 3, deleted: 3 }); + }); + + it('реальная загрузка остаётся доступной после сверки всего bucket префикса вложений', async () => { + const upload = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + expect(await processAttachment(app, upload.body.id)).toBe('ready'); + const report = await reconcile(prisma, s3, { apply: true, graceMs: HOUR_MS }); + expect(report.fresh_skipped).toBeGreaterThanOrEqual(4); + for (const variant of ['original', 'thumbnail', 'crop', 'optimized']) { + await request(server) + .get(`/api/v1/attachments/${upload.body.id}/content?variant=${variant}`) + .set('Authorization', bearer(alice)) + .expect(200); + } + }); + + it('после grace period объекты вложения и staging в очереди не считаются сиротами', async () => { + const queued = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + const ready = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=b.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + expect(await processAttachment(app, ready.body.id)).toBe('ready'); + for (const id of [queued.body.id, ready.body.id]) { + for (const prefix of [`attachments/${id}/`, `staging/${id}`]) { + const report = await reconcile(prisma, s3, { + apply: true, + graceMs: HOUR_MS, + prefix, + now: later(), + }); + expect(report).toMatchObject({ orphans: 0, deleted: 0 }); + } + } + expect(await exists(`staging/${queued.body.id}`)).toBe(true); + expect(await exists(`staging/${ready.body.id}`)).toBe(false); + }); + + it('staging failed-вложения удаляется после срока хранения', async () => { + const res = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + await prisma.attachment.update({ + where: { id: res.body.id }, + data: { status: 'failed', errorCode: 'invalid_image' }, + }); + const options = { graceMs: HOUR_MS, prefix: `staging/${res.body.id}`, now: later() }; + const kept = await reconcile(prisma, s3, { + ...options, + apply: true, + stagingRetentionMs: 3 * HOUR_MS, + }); + expect(kept.staging_expired).toBe(0); + expect(await exists(`staging/${res.body.id}`)).toBe(true); + const expired = await reconcile(prisma, s3, { + ...options, + apply: true, + stagingRetentionMs: HOUR_MS, + }); + expect(expired.staging_expired).toBeGreaterThanOrEqual(1); + expect(await exists(`staging/${res.body.id}`)).toBe(false); + const row = await prisma.attachment.findUniqueOrThrow({ where: { id: res.body.id } }); + expect(row.stagingKey).toBeNull(); + }); + + it('объекты вариантов без строк у существующего вложения не удаляются: replay после сверки доводит до ready', async () => { + const res = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + const id = res.body.id; + await expect( + processAttachment(app, id, { + afterStore: async () => { + throw new Error('worker crashed'); + }, + }), + ).rejects.toThrow('worker crashed'); + const job = await prisma.attachmentJob.findFirstOrThrow({ where: { attachmentId: id } }); + await prisma.attachmentJob.update({ + where: { id: job.id }, + data: { status: 'failed', errorCode: 'retry_exhausted', leaseOwner: null, leaseUntil: null }, + }); + await prisma.attachment.update({ + where: { id }, + data: { status: 'failed', errorCode: 'retry_exhausted' }, + }); + expect(await prisma.attachmentVariant.count({ where: { attachmentId: id } })).toBe(0); + const report = await reconcile(prisma, s3, { + apply: true, + graceMs: HOUR_MS, + prefix: `attachments/${id}/`, + now: later(), + }); + expect(report).toMatchObject({ scanned: 4, referenced: 4, orphans: 0, deleted: 0 }); + expect(await replayJob(prisma, job.id, 'test-operator')).toBe('replayed'); + expect(await processAttachment(app, id)).toBe('ready'); + for (const variant of ['original', 'thumbnail', 'crop', 'optimized']) { + await request(server) + .get(`/api/v1/attachments/${id}/content?variant=${variant}`) + .set('Authorization', bearer(alice)) + .expect(200); + } + }); + + it('staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения', async () => { + const res = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + await expect( + processAttachment(app, res.body.id, { + afterCommit: async () => { + throw new Error('worker crashed'); + }, + }), + ).rejects.toThrow('worker crashed'); + expect(await exists(`staging/${res.body.id}`)).toBe(true); + const report = await reconcile(prisma, s3, { + apply: true, + graceMs: HOUR_MS, + prefix: `staging/${res.body.id}`, + stagingRetentionMs: 24 * HOUR_MS, + }); + expect(report.staging_expired).toBeGreaterThanOrEqual(1); + expect(await exists(`staging/${res.body.id}`)).toBe(false); + await request(server) + .get(`/api/v1/attachments/${res.body.id}/content`) + .set('Authorization', bearer(alice)) + .expect(200); + }); +}); + +describe('Готовность при отказе S3 (e2e)', () => { + it('ready — 503 с заголовками за короткое время, live и core — 200', async () => { + const { app, server } = await createTestApp({ S3_ENDPOINT: 'http://127.0.0.1:9' }); + try { + const started = Date.now(); + const res = await request(server).get('/health/ready').expect(503); + expect(Date.now() - started).toBeLessThan(2000); + expect(res.body.error.code).toBe('unavailable'); + expect(res.body.error.request_id).toBe(res.headers['x-request-id']); + expect(res.headers['x-instance-id']).toBeTruthy(); + await request(server).get('/health/live').expect(200); + await request(server).get('/health/core').expect(200); + } finally { + await app.close(); + } + }); + + it('при рабочем S3 ready — 200', async () => { + const { app, server } = await createTestApp(); + try { + await request(server).get('/health/ready').expect(200); + } finally { + await app.close(); + } + }); +}); diff --git a/test/request-constraints.e2e-spec.ts b/test/request-constraints.e2e-spec.ts new file mode 100644 index 0000000..5e88fd0 --- /dev/null +++ b/test/request-constraints.e2e-spec.ts @@ -0,0 +1,206 @@ +import { INestApplication } from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import request from 'supertest'; +import { bearer, createTestApp, PASSWORD, registerUser, TestUser } from './helpers'; +import { SAMPLE_PNG } from './images'; + +type Case = [label: string, run: () => request.Test, expected: number]; + +describe('Каждое ограничение запроса из контракта отклоняется 400, граница принимается (e2e)', () => { + let app: INestApplication; + let server: any; + let alice: TestUser; + let bob: TestUser; + let chatId: string; + let attachmentId: string; + + beforeAll(async () => { + ({ app, server } = await createTestApp()); + alice = await registerUser(server, 'rc_alice'); + bob = await registerUser(server, 'rc_bob'); + const chat = await request(server) + .post('/api/v1/chats') + .set('Authorization', bearer(alice)) + .send({ title: 'Constraints', member_ids: [alice.id, bob.id] }) + .expect(201); + chatId = chat.body.id; + const upload = await request(server) + .post(`/api/v1/chats/${chatId}/attachments?filename=a.png`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG) + .expect(202); + attachmentId = upload.body.id; + }); + + afterAll(async () => { + await app.close(); + }); + + const check = async (cases: Case[]) => { + const mismatches: string[] = []; + for (const [label, run, expected] of cases) { + const res = await run(); + const okHeaders = Boolean(res.headers['x-request-id'] && res.headers['x-instance-id']); + const okBody = expected >= 400 ? res.body?.error?.code === 'invalid_request' : true; + if (res.status !== expected || !okHeaders || !okBody) { + mismatches.push(`${label}: expected ${expected}, got ${res.status} ${JSON.stringify(res.body).slice(0, 120)}`); + } + } + expect(mismatches).toEqual([]); + }; + + const emoji = (n: number) => '😀'.repeat(n); + const user = (body: unknown) => () => request(server).post('/api/v1/users').send(body as object); + const name = () => `rc_${randomUUID().slice(0, 8)}`; + const valid = () => ({ username: name(), display_name: 'R', password: PASSWORD }); + + it('POST /users', async () => { + const drop = (field: string) => { + const body: any = valid(); + delete body[field]; + return body; + }; + await check([ + ['без username', user(drop('username')), 400], + ['без display_name', user(drop('display_name')), 400], + ['без password', user(drop('password')), 400], + ['username число', user({ ...valid(), username: 123 }), 400], + ['username null', user({ ...valid(), username: null }), 400], + ['display_name массив', user({ ...valid(), display_name: ['a'] }), 400], + ['password число', user({ ...valid(), password: 123456789012 }), 400], + ['лишнее поле', user({ ...valid(), role: 'admin' }), 400], + ['лишнее поле в другом регистре', user({ ...valid(), Username: 'x' }), 400], + ['username 2 символа', user({ ...valid(), username: 'ab' }), 400], + ['username 33 символа', user({ ...valid(), username: 'a'.repeat(33) }), 400], + ['username заглавные', user({ ...valid(), username: 'Alice_' + randomUUID().slice(0, 4) }), 400], + ['username пробел', user({ ...valid(), username: 'al ice' }), 400], + ['username кириллица', user({ ...valid(), username: 'алиса' }), 400], + ['username дефис', user({ ...valid(), username: 'al-ice' }), 400], + ['username 3 символа', user({ ...valid(), username: randomUUID().slice(0, 3).replace(/-/g, '_') }), 201], + ['username 32 символа', user({ ...valid(), username: (name() + '_'.repeat(32)).slice(0, 32) }), 201], + ['display_name пустой', user({ ...valid(), display_name: '' }), 400], + ['display_name пробелы', user({ ...valid(), display_name: ' ' }), 400], + ['display_name 101 code point', user({ ...valid(), display_name: emoji(101) }), 400], + ['display_name 100 code points', user({ ...valid(), display_name: emoji(100) }), 201], + ['password 11', user({ ...valid(), password: 'x'.repeat(11) }), 400], + ['password 129 code points', user({ ...valid(), password: emoji(129) }), 400], + ['password пробелы', user({ ...valid(), password: ' '.repeat(12) }), 400], + ['password 12', user({ ...valid(), password: 'x'.repeat(12) }), 201], + ['password 128 code points', user({ ...valid(), password: emoji(128) }), 201], + ['тело массив', user([valid()]), 400], + ['тело строка', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send('"x"'), 400], + ['тело null', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send('null'), 400], + ['битый JSON', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send('{bad'), 400], + ['мусор после JSON', () => request(server).post('/api/v1/users').set('Content-Type', 'application/json').send(JSON.stringify(valid()) + 'x'), 400], + ['text/plain', () => request(server).post('/api/v1/users').set('Content-Type', 'text/plain').send(JSON.stringify(valid())), 400], + ['без тела', () => request(server).post('/api/v1/users'), 400], + ]); + }); + + it('POST /chats', async () => { + const chat = (body: unknown) => () => + request(server).post('/api/v1/chats').set('Authorization', bearer(alice)).send(body as object); + const members = (n: number) => [alice.id, ...Array.from({ length: n - 1 }, () => randomUUID())]; + await check([ + ['без title', chat({ member_ids: [alice.id] }), 400], + ['без member_ids', chat({ title: 'x' }), 400], + ['title число', chat({ title: 1, member_ids: [alice.id] }), 400], + ['title пустой', chat({ title: '', member_ids: [alice.id] }), 400], + ['title пробелы', chat({ title: ' ', member_ids: [alice.id] }), 400], + ['title 101 code point', chat({ title: emoji(101), member_ids: [alice.id] }), 400], + ['title 100 code points', chat({ title: emoji(100), member_ids: [alice.id] }), 201], + ['member_ids не массив', chat({ title: 'x', member_ids: alice.id }), 400], + ['member_ids пустой', chat({ title: 'x', member_ids: [] }), 400], + ['member_ids 101', chat({ title: 'x', member_ids: members(101) }), 400], + ['member_ids дубль', chat({ title: 'x', member_ids: [alice.id, alice.id] }), 400], + ['member_ids дубль в другом регистре', chat({ title: 'x', member_ids: [alice.id, alice.id.toUpperCase()] }), 400], + ['member_ids не UUID', chat({ title: 'x', member_ids: [alice.id, 'nope'] }), 400], + ['member_ids число', chat({ title: 'x', member_ids: [alice.id, 1] }), 400], + ['member_ids null', chat({ title: 'x', member_ids: null }), 400], + ['без вызывающего', chat({ title: 'x', member_ids: [bob.id] }), 400], + ['неизвестный участник', chat({ title: 'x', member_ids: [alice.id, randomUUID()] }), 400], + ['лишнее поле', chat({ title: 'x', member_ids: [alice.id], owner_id: alice.id }), 400], + ]); + }); + + it('POST /chats/{chat_id}/messages', async () => { + const send = (body: unknown, key: string | null = randomUUID(), chat = chatId) => () => { + const req = request(server).post(`/api/v1/chats/${chat}/messages`).set('Authorization', bearer(alice)); + if (key !== null) { + req.set('Idempotency-Key', key); + } + return req.send(body as object); + }; + await check([ + ['без text', send({ attachment_ids: [attachmentId] }), 400], + ['text число', send({ text: 1 }), 400], + ['text null', send({ text: null }), 400], + ['text 4001 code point', send({ text: emoji(4001) }), 400], + ['text 4000 code points', send({ text: emoji(4000) }), 201], + ['text пустой без вложений', send({ text: '' }), 400], + ['text пробелы без вложений', send({ text: ' ' }), 400], + ['text пустой с []', send({ text: '', attachment_ids: [] }), 400], + ['text пустой с вложением', send({ text: '', attachment_ids: [attachmentId] }), 201], + ['attachment_ids не массив', send({ text: 'x', attachment_ids: attachmentId }), 400], + ['attachment_ids null', send({ text: 'x', attachment_ids: null }), 400], + ['attachment_ids 11', send({ text: 'x', attachment_ids: Array.from({ length: 11 }, () => randomUUID()) }), 400], + ['attachment_ids дубль', send({ text: 'x', attachment_ids: [attachmentId, attachmentId] }), 400], + ['attachment_ids не UUID', send({ text: 'x', attachment_ids: ['nope'] }), 400], + ['sender_id в теле', send({ text: 'x', sender_id: alice.id }), 400], + ['лишнее поле', send({ text: 'x', extra: 1 }), 400], + ['тело массив', send([{ text: 'x' }]), 400], + ['без Idempotency-Key', send({ text: 'x' }, null), 400], + ['Idempotency-Key пустой', send({ text: 'x' }, ''), 400], + ['Idempotency-Key 129', send({ text: 'x' }, 'k'.repeat(129)), 400], + ['Idempotency-Key пробел', send({ text: 'x' }, 'a b'), 400], + ['Idempotency-Key слэш', send({ text: 'x' }, 'a/b'), 400], + ['Idempotency-Key 128 из всех допустимых символов', send({ text: 'x' }, ('Az09._:-' + randomUUID().replace(/-/g, '')).padEnd(128, 'k')), 201], + ['chat_id не UUID', send({ text: 'x' }, randomUUID(), 'nope'), 400], + ]); + }); + + it('query и path параметры', async () => { + const get = (path: string) => () => request(server).get(path).set('Authorization', bearer(alice)); + const lists = ['/api/v1/chats', `/api/v1/chats/${chatId}/messages`]; + const cases: Case[] = []; + for (const base of lists) { + for (const limit of ['0', '101', '-1', 'abc', '1.5', '', ' ', '1e1', '0x10', '10abc']) { + cases.push([`${base} limit=${JSON.stringify(limit)}`, get(`${base}?limit=${encodeURIComponent(limit)}`), 400]); + } + cases.push([`${base} limit дважды`, get(`${base}?limit=1&limit=2`), 400]); + cases.push([`${base} limit=1`, get(`${base}?limit=1`), 200]); + cases.push([`${base} limit=100`, get(`${base}?limit=100`), 200]); + cases.push([`${base} cursor пустой`, get(`${base}?cursor=`), 400]); + cases.push([`${base} cursor мусор`, get(`${base}?cursor=garbage`), 400]); + cases.push([`${base} cursor base64 числа`, get(`${base}?cursor=${Buffer.from('123').toString('base64url')}`), 400]); + cases.push([`${base} cursor base64 null`, get(`${base}?cursor=${Buffer.from('null').toString('base64url')}`), 400]); + } + cases.push(['chat_id не UUID', get('/api/v1/chats/nope'), 400]); + cases.push(['chat_id почти UUID', get(`/api/v1/chats/${chatId}0`), 400]); + cases.push(['attachment_id не UUID', get('/api/v1/attachments/nope'), 400]); + cases.push(['content attachment_id не UUID', get('/api/v1/attachments/nope/content'), 400]); + for (const variant of ['', 'Original', 'THUMBNAIL', 'big']) { + cases.push([`variant=${JSON.stringify(variant)}`, get(`/api/v1/attachments/${attachmentId}/content?variant=${variant}`), 400]); + } + cases.push(['variant дважды', get(`/api/v1/attachments/${attachmentId}/content?variant=crop&variant=crop`), 400]); + await check(cases); + }); + + it('POST /chats/{chat_id}/attachments: filename и chat_id', async () => { + const upload = (query: string, chat = chatId) => () => + request(server) + .post(`/api/v1/chats/${chat}/attachments${query}`) + .set('Authorization', bearer(alice)) + .set('Content-Type', 'image/png') + .send(SAMPLE_PNG); + await check([ + ['без filename', upload(''), 400], + ['filename пустой', upload('?filename='), 400], + ['filename 256 code points', upload(`?filename=${encodeURIComponent(emoji(256))}`), 400], + ['filename 255 code points', upload(`?filename=${encodeURIComponent(emoji(255))}`), 202], + ['filename дважды', upload('?filename=a.png&filename=b.png'), 400], + ['chat_id не UUID', upload('?filename=a.png', 'nope'), 400], + ]); + }); +}); diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..3478c4e --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "test", "dist", "experiments", "**/*spec.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..1a82cb3 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "declaration": false, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "target": "ES2021", + "sourceMap": true, + "outDir": "./dist", + "baseUrl": "./", + "incremental": true, + "skipLibCheck": true, + "strict": true, + "strictNullChecks": true, + "noImplicitAny": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true, + "types": ["node", "jest"] + } +} -- 2.54.0 From 9ed32e2d15fcbfec571ecab801910ae1c1b9b175 Mon Sep 17 00:00:00 2001 From: aegor Date: Wed, 18 Nov 2026 19:23:20 +0300 Subject: [PATCH 2/8] feat: add otel collector, prometheus, loki, tempo and grafana --- compose.yaml | 109 +++++++++++++++++- .../provisioning/dashboards/dashboards.yaml | 10 ++ .../provisioning/datasources/datasources.yaml | 45 ++++++++ infra/loki/loki.yaml | 43 +++++++ infra/otel/collector.yaml | 85 ++++++++++++++ infra/prometheus/prometheus.yml | 23 ++++ infra/tempo/tempo.yaml | 31 +++++ 7 files changed, 343 insertions(+), 3 deletions(-) create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/loki/loki.yaml create mode 100644 infra/otel/collector.yaml create mode 100644 infra/prometheus/prometheus.yml create mode 100644 infra/tempo/tempo.yaml diff --git a/compose.yaml b/compose.yaml index dcce9f8..7e95960 100644 --- a/compose.yaml +++ b/compose.yaml @@ -10,8 +10,8 @@ services: - -ec - | cd /secrets - mkdir -p postgres redis api migrate s3 s3-init reconciler broker rabbitmq relay worker - for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20 broker_password:broker:24; do + mkdir -p postgres redis api migrate s3 s3-init reconciler broker rabbitmq relay worker grafana + for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20 broker_password:broker:24 admin_password:grafana:16; do file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:} [ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file" done @@ -28,7 +28,7 @@ services: printf 'default_user = messenger\ndefault_pass = %s\nloopback_users = none\nlog.console = true\nlisteners.tcp.default = 5672\n' "$$(cat broker/broker_password)" > rabbitmq/10-messenger.conf cp api/database_url api/s3_access_key_id api/s3_secret_access_key reconciler/ cp api/s3_access_key_id api/s3_secret_access_key worker/ - chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/* broker/* rabbitmq/* relay/* worker/* + chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/* broker/* rabbitmq/* relay/* worker/* grafana/* deploy: resources: limits: { cpus: "0.1", memory: 32M } @@ -310,6 +310,101 @@ services: condition: service_healthy restart: unless-stopped + otel-collector: + image: otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8 + command: ["--config=/etc/otelcol/collector.yaml"] + volumes: + - ./infra/otel/collector.yaml:/etc/otelcol/collector.yaml:ro + networks: [default, telemetry] + deploy: + resources: + limits: { cpus: "0.5", memory: 256M } + restart: unless-stopped + + prometheus: + image: prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + - --storage.tsdb.retention.size=1GB + - --web.enable-otlp-receiver + volumes: + - ./infra/prometheus:/etc/prometheus:ro + - prometheusdata:/prometheus + networks: [telemetry] + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"] + interval: 5s + timeout: 3s + retries: 20 + restart: unless-stopped + + loki: + image: grafana/loki:3.3.2@sha256:8af2de1abbdd7aa92b27c9bcc96f0f4140c9096b507c77921ffddf1c6ad6c48f + command: ["-config.file=/etc/loki/loki.yaml"] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro + - lokidata:/loki + networks: [telemetry] + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + restart: unless-stopped + + tempo: + image: grafana/tempo:2.6.1@sha256:ef4384fce6e8ad22b95b243d8fc165628cda655376fd50e7850536ad89d71d50 + command: ["-config.file=/etc/tempo/tempo.yaml"] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro + - tempodata:/var/tempo + networks: [telemetry] + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + restart: unless-stopped + + grafana: + image: grafana/grafana:11.4.0@sha256:d8ea37798ccc41061a62ab080f2676dda6bf7815558499f901bdb0f533a456fb + ports: + - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/admin_password + GF_AUTH_ANONYMOUS_ENABLED: "true" + GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer + GF_USERS_VIEWERS_CAN_EDIT: "true" + GF_ANALYTICS_REPORTING_ENABLED: "false" + GF_ANALYTICS_CHECK_FOR_UPDATES: "false" + GF_NEWS_NEWS_FEED_ENABLED: "false" + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafanadata:/var/lib/grafana + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: grafana } } + networks: [default, telemetry] + deploy: + resources: + limits: { cpus: "0.5", memory: 256M } + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:3000/api/health"] + interval: 5s + timeout: 3s + retries: 20 + depends_on: + secrets-init: + condition: service_completed_successfully + prometheus: + condition: service_healthy + loki: + condition: service_started + tempo: + condition: service_started + restart: unless-stopped + tools: profiles: [tools] build: @@ -331,4 +426,12 @@ volumes: pgdata: s3data: rabbitmqdata: + prometheusdata: + lokidata: + tempodata: + grafanadata: secrets: + +networks: + telemetry: + internal: true diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..a9d058c --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,10 @@ +apiVersion: 1 + +providers: + - name: messenger + folder: Messenger + type: file + disableDeletion: true + allowUiUpdates: false + options: + path: /var/lib/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..1abcca9 --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,45 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + jsonData: + httpMethod: POST + exemplarTraceIdDestinations: + - name: trace_id + datasourceUid: tempo + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + jsonData: + derivedFields: + - name: trace_id + matcherType: label + matcherRegex: trace_id + url: "$${__value.raw}" + datasourceUid: tempo + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: -5m + spanEndTimeShift: 5m + filterByTraceID: false + customQuery: true + query: '{service_name=~".+"} | trace_id="$${__span.traceId}"' + tracesToMetrics: + datasourceUid: prometheus + serviceMap: + datasourceUid: prometheus + nodeGraph: + enabled: true diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 0000000..fe0639f --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,43 @@ +auth_enabled: false + +server: + http_listen_address: 0.0.0.0 + http_listen_port: 3100 + grpc_listen_port: 9096 + log_level: warn + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + replication_factor: 1 + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2026-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + retention_period: 168h + ingestion_rate_mb: 8 + ingestion_burst_size_mb: 16 + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem + +analytics: + reporting_enabled: false diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..30c8ccd --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,85 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + max_request_body_size: 4194304 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 160 + spike_limit_mib: 40 + batch: + send_batch_size: 512 + send_batch_max_size: 1024 + timeout: 2s + +exporters: + otlphttp/prometheus: + endpoint: http://prometheus:9090/api/v1/otlp + timeout: 5s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 60s + otlphttp/loki: + endpoint: http://loki:3100/otlp + timeout: 5s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 60s + otlphttp/tempo: + endpoint: http://tempo:4318 + timeout: 5s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 10s + max_elapsed_time: 60s + +service: + extensions: [health_check] + telemetry: + logs: + level: warn + metrics: + level: normal + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 0000000..28f48eb --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,23 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + +otlp: + promote_resource_attributes: + - deployment.environment.name + - service.version + +storage: + tsdb: + out_of_order_time_window: 30m + +rule_files: + - /etc/prometheus/rules/*.yml + +scrape_configs: + - job_name: otel-collector + static_configs: + - targets: ["otel-collector:8888"] + - job_name: prometheus + static_configs: + - targets: ["localhost:9090"] diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 0000000..4ae59a9 --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,31 @@ +stream_over_http_enabled: true + +server: + http_listen_address: 0.0.0.0 + http_listen_port: 3200 + log_level: warn + +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +ingester: + max_block_duration: 5m + +compactor: + compaction: + block_retention: 168h + +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks + +usage_report: + reporting_enabled: false -- 2.54.0 From 307b658bfb5049bcb29c30a770097fa397a74475 Mon Sep 17 00:00:00 2001 From: aegor Date: Fri, 20 Nov 2026 12:55:53 +0300 Subject: [PATCH 3/8] feat: instrument api, relay and worker with opentelemetry --- compose.yaml | 11 + infra/grafana/dashboards/messenger.json | 235 ++++++ package-lock.json | 820 +++++++++++++++++++- package.json | 15 + scripts/dashboard-check.py | 57 ++ scripts/latency-compare.py | 52 ++ scripts/trace-check.py | 134 ++++ src/common/filters/http-exception.filter.ts | 12 +- src/health/shutdown.ts | 15 +- src/jobs/job-message.ts | 33 +- src/jobs/processor.ts | 23 +- src/main.ts | 5 + src/relay.ts | 45 +- src/telemetry/http.ts | 66 ++ src/telemetry/json-logger.ts | 99 +++ src/telemetry/register.ts | 3 + src/telemetry/sdk.ts | 157 ++++ src/worker.ts | 110 ++- 18 files changed, 1843 insertions(+), 49 deletions(-) create mode 100644 infra/grafana/dashboards/messenger.json create mode 100755 scripts/dashboard-check.py create mode 100755 scripts/latency-compare.py create mode 100755 scripts/trace-check.py create mode 100644 src/telemetry/http.ts create mode 100644 src/telemetry/json-logger.ts create mode 100644 src/telemetry/register.ts create mode 100644 src/telemetry/sdk.ts diff --git a/compose.yaml b/compose.yaml index 7e95960..c5087a0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,5 +1,10 @@ name: messenger-lab6 +x-otel: &otel + OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} + services: secrets-init: image: alpine:3.20.3 @@ -168,6 +173,8 @@ services: MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + <<: *otel + OTEL_SERVICE_NAME: messenger-api volumes: - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } } deploy: @@ -244,6 +251,8 @@ services: BROKER_URL_FILE: /run/secrets/broker_url JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} RELAY_FAULT: ${RELAY_FAULT:-} + <<: *otel + OTEL_SERVICE_NAME: messenger-relay volumes: - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: relay } } deploy: @@ -279,6 +288,8 @@ services: JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-90} WORKER_FAULT: ${WORKER_FAULT:-} + <<: *otel + OTEL_SERVICE_NAME: messenger-worker volumes: - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: worker } } deploy: diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..d935127 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,235 @@ +{ + "uid": "messenger-overview", + "title": "Messenger overview", + "tags": ["messenger", "lab6"], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "editable": false, + "graphTooltip": 1, + "refresh": "10s", + "time": { "from": "now-30m", "to": "now" }, + "templating": { "list": [] }, + "annotations": { "list": [] }, + "panels": [ + { + "type": "row", + "title": "API", + "id": 100, + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 } + }, + { + "type": "timeseries", + "title": "RPS по маршрутам (без health)", + "id": 1, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 12, "x": 0, "y": 1 }, + "fieldConfig": { "defaults": { "unit": "reqps" }, "overrides": [] }, + "options": { "legend": { "displayMode": "table", "placement": "right", "calcs": ["lastNotNull"] } }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "sum by (http_request_method, http_route) (rate(http_server_requests_total{job=\"messenger-api\", http_route!~\"/health.*\"}[$__rate_interval]))", + "legendFormat": "{{http_request_method}} {{http_route}}" + } + ] + }, + { + "type": "timeseries", + "title": "Ответы по классам статуса (без health)", + "id": 2, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 12, "x": 12, "y": 1 }, + "fieldConfig": { "defaults": { "unit": "reqps" }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "sum by (http_response_status_class) (rate(http_server_requests_total{job=\"messenger-api\", http_route!~\"/health.*\"}[$__rate_interval]))", + "legendFormat": "{{http_response_status_class}}" + } + ] + }, + { + "type": "timeseries", + "title": "Доля 5xx среди бизнес-запросов (окно 5m)", + "id": 3, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 9 }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "min": 0, + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "red", "value": 0.05 }] }, + "custom": { "thresholdsStyle": { "mode": "line" } } + }, + "overrides": [] + }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "(sum(rate(http_server_requests_total{job=\"messenger-api\", http_route!~\"/health.*\", http_response_status_class=\"5xx\"}[5m])) or vector(0)) / sum(rate(http_server_requests_total{job=\"messenger-api\", http_route!~\"/health.*\"}[5m]))", + "legendFormat": "5xx ratio" + } + ] + }, + { + "type": "timeseries", + "title": "Длительность API p50 / p95 / p99 (все реплики, без health)", + "id": 4, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 9 }, + "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\", http_route!~\"/health.*\"}[$__rate_interval])))", + "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.*\"}[$__rate_interval])))", + "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.*\"}[$__rate_interval])))", + "legendFormat": "p99" + } + ] + }, + { + "type": "timeseries", + "title": "p95 по маршрутам", + "id": 5, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 9 }, + "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.95, sum by (le, http_request_method, http_route) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\", http_route!~\"/health.*\"}[$__rate_interval])))", + "legendFormat": "{{http_request_method}} {{http_route}}" + } + ] + }, + { + "type": "row", + "title": "Worker", + "id": 101, + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 17 } + }, + { + "type": "timeseries", + "title": "Задания по исходу (в секунду)", + "id": 6, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 12, "x": 0, "y": 18 }, + "fieldConfig": { "defaults": { "unit": "ops" }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "sum by (job_type, outcome) (rate(jobs_processed_total{job=\"messenger-worker\"}[$__rate_interval]))", + "legendFormat": "{{job_type}} {{outcome}}" + } + ] + }, + { + "type": "timeseries", + "title": "Длительность обработки задания p50 / p95 / p99", + "id": 7, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 12, "x": 12, "y": 18 }, + "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(jobs_duration_seconds_bucket{job=\"messenger-worker\", outcome=\"success\"}[$__rate_interval])))", + "legendFormat": "p50 success" + }, + { + "refId": "B", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(jobs_duration_seconds_bucket{job=\"messenger-worker\", outcome=\"success\"}[$__rate_interval])))", + "legendFormat": "p95 success" + }, + { + "refId": "C", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(jobs_duration_seconds_bucket{job=\"messenger-worker\", outcome=\"success\"}[$__rate_interval])))", + "legendFormat": "p99 success" + }, + { + "refId": "D", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(jobs_duration_seconds_bucket{job=\"messenger-worker\", outcome!=\"success\"}[$__rate_interval])))", + "legendFormat": "p95 retry/failed" + } + ] + }, + { + "type": "row", + "title": "Логи и трассы", + "id": 102, + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 26 } + }, + { + "type": "logs", + "title": "Логи API и worker (WARN и выше)", + "id": 8, + "datasource": { "type": "loki", "uid": "loki" }, + "gridPos": { "h": 10, "w": 12, "x": 0, "y": 27 }, + "options": { "showTime": true, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "loki", "uid": "loki" }, + "expr": "{service_name=~\"messenger-.+\"} | severity_text=~\"WARN|ERROR|FATAL\"" + } + ] + }, + { + "type": "logs", + "title": "Все логи (http.request, job.handled, …)", + "id": 9, + "datasource": { "type": "loki", "uid": "loki" }, + "gridPos": { "h": 10, "w": 12, "x": 12, "y": 27 }, + "options": { "showTime": true, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "loki", "uid": "loki" }, + "expr": "{service_name=~\"messenger-.+\"}" + } + ] + }, + { + "type": "table", + "title": "Последние трассы (HTTP server и consumer spans)", + "id": 10, + "datasource": { "type": "tempo", "uid": "tempo" }, + "gridPos": { "h": 10, "w": 24, "x": 0, "y": 37 }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "tempo", "uid": "tempo" }, + "queryType": "traceql", + "query": "{resource.service.name=~\"messenger-.+\" && (kind=server || kind=consumer)}", + "limit": 20, + "tableType": "traces" + } + ] + } + ] +} diff --git a/package-lock.json b/package-lock.json index d306d52..d7834ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,22 @@ "@nestjs/core": "^10.4.15", "@nestjs/platform-fastify": "^10.4.15", "@nestjs/swagger": "7.4.2", + "@opentelemetry/api": "1.9.0", + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/exporter-logs-otlp-proto": "0.57.2", + "@opentelemetry/exporter-metrics-otlp-proto": "0.57.2", + "@opentelemetry/exporter-trace-otlp-proto": "0.57.2", + "@opentelemetry/instrumentation-aws-sdk": "0.49.1", + "@opentelemetry/instrumentation-http": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-logs": "0.57.2", + "@opentelemetry/sdk-metrics": "1.30.1", + "@opentelemetry/sdk-node": "0.57.2", + "@opentelemetry/sdk-trace-base": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0", "@prisma/client": "6.1.0", + "@prisma/instrumentation": "6.1.0", "amqplib": "0.10.5", "argon2": "0.41.1", "class-transformer": "^0.5.1", @@ -1961,6 +1976,37 @@ "glob": "^10.3.4" } }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.7", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.7.tgz", + "integrity": "sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.1.tgz", + "integrity": "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", @@ -3016,6 +3062,16 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, "node_modules/@ljharb/through": { "version": "2.3.14", "resolved": "https://registry.npmjs.org/@ljharb/through/-/through-2.3.14.tgz", @@ -3484,6 +3540,556 @@ "npm": ">=5.0.0" } }, + "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.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.57.2.tgz", + "integrity": "sha512-uIX52NnTM0iBh84MShlpouI7UKqkZ7MrUszTmaypHBu4r7NofznSnQRfJ+uUeDtQDj6w8eFGg5KBLDAwAPz1+A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@opentelemetry/context-async-hooks": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-1.30.1.tgz", + "integrity": "sha512-s5vvxXPVdjqS3kTLKMeBMvop9hbWkwzBpu+mUO2M7sZtlkyDJGwFe33wRKnbaYDo8ExRVBIIdwIGrqpxHuKttA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.30.1.tgz", + "integrity": "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-grpc": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.57.2.tgz", + "integrity": "sha512-eovEy10n3umjKJl2Ey6TLzikPE+W4cUQ4gCwgGP1RqzTGtgDra0WjIqdy29ohiUKfvmbiL3MndZww58xfIvyFw==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-grpc-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/sdk-logs": "0.57.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-http": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.57.2.tgz", + "integrity": "sha512-0rygmvLcehBRp56NQVLSleJ5ITTduq/QfU7obOkyWgPpFHulwpw2LYTqNIz5TczKZuy5YY+5D3SDnXZL1tXImg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/sdk-logs": "0.57.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-logs-otlp-proto": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.57.2.tgz", + "integrity": "sha512-ta0ithCin0F8lu9eOf4lEz9YAScecezCHkMMyDkvd9S7AnZNX5ikUmC5EQOQADU+oCcgo/qkQIaKcZvQ0TYKDw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-logs": "0.57.2", + "@opentelemetry/sdk-trace-base": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-grpc": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.57.2.tgz", + "integrity": "sha512-r70B8yKR41F0EC443b5CGB4rUaOMm99I5N75QQt6sHKxYDzSEc6gm48Diz1CI1biwa5tDPznpylTrywO/pT7qw==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.57.2", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-grpc-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-metrics": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-http": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.57.2.tgz", + "integrity": "sha512-ttb9+4iKw04IMubjm3t0EZsYRNWr3kg44uUuzfo9CaccYlOh8cDooe4QObDUkvx9d5qQUrbEckhrWKfJnKhemA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-metrics": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-metrics-otlp-proto": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.57.2.tgz", + "integrity": "sha512-HX068Q2eNs38uf7RIkNN9Hl4Ynl+3lP0++KELkXMCpsCbFO03+0XNNZ1SkwxPlP9jrhQahsMPMkzNXpq3fKsnw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/exporter-metrics-otlp-http": "0.57.2", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-metrics": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-prometheus": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.57.2.tgz", + "integrity": "sha512-VqIqXnuxWMWE/1NatAGtB1PvsQipwxDcdG4RwA/umdBcW3/iOHp0uejvFHTRN2O78ZPged87ErJajyUBPUhlDQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-metrics": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-grpc": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.57.2.tgz", + "integrity": "sha512-gHU1vA3JnHbNxEXg5iysqCWxN9j83d7/epTYBZflqQnTyCC4N7yZXn/dMM+bEmyhQPGjhCkNZLx4vZuChH1PYw==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-grpc-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-http": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.57.2.tgz", + "integrity": "sha512-sB/gkSYFu+0w2dVQ0PWY9fAMl172PKMZ/JrHkkW8dmjCL0CYkmXeE+ssqIL/yBUTPOvpLIpenX5T9RwXRBW/3g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-trace-otlp-proto": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.57.2.tgz", + "integrity": "sha512-awDdNRMIwDvUtoRYxRhja5QYH6+McBLtoz1q9BeEsskhZcrGmH/V1fWpGx8n+Rc+542e8pJA6y+aullbIzQmlw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/exporter-zipkin": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-1.30.1.tgz", + "integrity": "sha512-6S2QIMJahIquvFaaxmcwpvQQRD/YFaMTNoIxrfPIPOeITN+a8lfEcPDxNxn8JDAaxkg+4EnXhz8upVDYenoQjA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0" + } + }, + "node_modules/@opentelemetry/instrumentation": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.57.2.tgz", + "integrity": "sha512-BdBGhQBh8IjZ2oIIX6F2/Q3LKm/FDDKi6ccYKcBTeilh6SNdNKveDOLk73BkSJjQLJk6qe4Yh+hHw1UPhCDdrg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@types/shimmer": "^1.2.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1", + "semver": "^7.5.2", + "shimmer": "^1.2.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-aws-sdk": { + "version": "0.49.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-aws-sdk/-/instrumentation-aws-sdk-0.49.1.tgz", + "integrity": "sha512-Vbj4BYeV/1K4Pbbfk+gQ8gwYL0w+tBeUwG88cOxnF7CLPO1XnskGV8Q3Gzut2Ah/6Dg17dBtlzEqL3UiFP2Z6A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "^1.8.0", + "@opentelemetry/instrumentation": "^0.57.1", + "@opentelemetry/propagation-utils": "^0.30.16", + "@opentelemetry/semantic-conventions": "^1.27.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/instrumentation-http": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.57.2.tgz", + "integrity": "sha512-1Uz5iJ9ZAlFOiPuwYg29Bf7bJJc/GeoeJIFKJYQf67nTVKFe8RHbEtxgkOmK4UGZNHKXcpW4P8cWBYzBn1USpg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/instrumentation": "0.57.2", + "@opentelemetry/semantic-conventions": "1.28.0", + "forwarded-parse": "2.1.2", + "semver": "^7.5.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-exporter-base": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.57.2.tgz", + "integrity": "sha512-XdxEzL23Urhidyebg5E6jZoaiW5ygP/mRjxLHixogbqwDy2Faduzb5N0o/Oi+XTIJu+iyxXdVORjXax+Qgfxag==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-transformer": "0.57.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-grpc-exporter-base": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.57.2.tgz", + "integrity": "sha512-USn173KTWy0saqqRB5yU9xUZ2xdgb1Rdu5IosJnm9aV4hMTuFFRTUsQxbgc24QxpCHeoKzzCSnS/JzdV0oM2iQ==", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.7.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/otlp-exporter-base": "0.57.2", + "@opentelemetry/otlp-transformer": "0.57.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/otlp-transformer": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.57.2.tgz", + "integrity": "sha512-48IIRj49gbQVK52jYsw70+Jv+JbahT8BqT2Th7C4H7RCM9d0gZ5sgNPoMpWldmfjvIsSgiGJtjfk9MeZvjhoig==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-logs": "0.57.2", + "@opentelemetry/sdk-metrics": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "protobufjs": "^7.3.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/propagation-utils": { + "version": "0.30.16", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagation-utils/-/propagation-utils-0.30.16.tgz", + "integrity": "sha512-ZVQ3Z/PQ+2GQlrBfbMMMT0U7MzvYZLCPP800+ooyaBqm4hMvuQHfP028gB9/db0mwkmyEAMad9houukUVxhwcw==", + "deprecated": "The use of process spans has been removed from Messaging Semantic Conventions. It is now recommended to connect pub/sub spans via Span Links. See https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ for details.", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0" + } + }, + "node_modules/@opentelemetry/propagator-b3": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-1.30.1.tgz", + "integrity": "sha512-oATwWWDIJzybAZ4pO76ATN5N6FFbOA1otibAVlS8v90B4S1wClnhRUk7K+2CHAwN1JKYuj4jh/lpCEG5BAqFuQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/propagator-jaeger": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-1.30.1.tgz", + "integrity": "sha512-Pj/BfnYEKIOImirH76M4hDaBSx6HyZ2CXUqk+Kj02m6BB80c/yo4BdWkn/1gDFfU+YPY+bPR2U0DKBfdxCKwmg==", + "deprecated": "Package no longer supported. See https://github.com/open-telemetry/opentelemetry-js/pull/7077", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.30.1.tgz", + "integrity": "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-logs": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.57.2.tgz", + "integrity": "sha512-TXFHJ5c+BKggWbdEQ/inpgIzEmS2BGQowLE9UhsMd7YYlUfBQJ4uax0VF/B5NYigdM/75OoJGhAV3upEhK+3gg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.4.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-metrics": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.30.1.tgz", + "integrity": "sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-node": { + "version": "0.57.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.57.2.tgz", + "integrity": "sha512-8BaeqZyN5sTuPBtAoY+UtKwXBdqyuRKmekN5bFzAO40CgbGzAxfTpiL3PBerT7rhZ7p2nBdq7FaMv/tBQgHE4A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/exporter-logs-otlp-grpc": "0.57.2", + "@opentelemetry/exporter-logs-otlp-http": "0.57.2", + "@opentelemetry/exporter-logs-otlp-proto": "0.57.2", + "@opentelemetry/exporter-metrics-otlp-grpc": "0.57.2", + "@opentelemetry/exporter-metrics-otlp-http": "0.57.2", + "@opentelemetry/exporter-metrics-otlp-proto": "0.57.2", + "@opentelemetry/exporter-prometheus": "0.57.2", + "@opentelemetry/exporter-trace-otlp-grpc": "0.57.2", + "@opentelemetry/exporter-trace-otlp-http": "0.57.2", + "@opentelemetry/exporter-trace-otlp-proto": "0.57.2", + "@opentelemetry/exporter-zipkin": "1.30.1", + "@opentelemetry/instrumentation": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-logs": "0.57.2", + "@opentelemetry/sdk-metrics": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "@opentelemetry/sdk-trace-node": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.30.1.tgz", + "integrity": "sha512-jVPgBbH1gCy2Lb7X0AVQ8XAfgg0pJ4nvl8/IiQA6nxOsPvS+0zMJaFSs2ltXe0J6C8dqjcnpyqINDJmU30+uOg==", + "deprecated": "Use @opentelemetry/sdk-trace package", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-node": { + "version": "1.30.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-1.30.1.tgz", + "integrity": "sha512-cBjYOINt1JxXdpw1e5MlHmFRc5fgj4GW/86vsKFxJCJ8AL4PdVtYH41gWwl4qd4uQjqEL1oJVrXkSy5cnduAnQ==", + "deprecated": "Use @opentelemetry/sdk-trace package", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "1.30.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/propagator-b3": "1.30.1", + "@opentelemetry/propagator-jaeger": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "semver": "^7.5.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", + "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, "node_modules/@paralleldrive/cuid2": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", @@ -3587,6 +4193,107 @@ "@prisma/debug": "6.1.0" } }, + "node_modules/@prisma/instrumentation": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@prisma/instrumentation/-/instrumentation-6.1.0.tgz", + "integrity": "sha512-mNdBeKOvKeXWFmowPNVEciGzpWjd7o3hkTVZmbjuMhA1ZHQksS3Am4HposiAmvqpuYnCJ2h79sJsv2kW0CqlDg==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.8" + } + }, + "node_modules/@prisma/instrumentation/node_modules/@opentelemetry/api-logs": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.56.0.tgz", + "integrity": "sha512-Wr39+94UNNG3Ei9nv3pHd4AJ63gq5nSemMRpCd8fPwDL9rN3vK26lzxfH27mw16XzOSO+TpyQwBAMaLxaPWG0g==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@prisma/instrumentation/node_modules/@opentelemetry/instrumentation": { + "version": "0.56.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.56.0.tgz", + "integrity": "sha512-2KkGBKE+FPXU1F0zKww+stnlUxUTlBvLCiWdP63Z9sqXYeNI/ziNzsxAp4LAdUcTQmXjw1IWgvm5CAb/BHy99w==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.56.0", + "@types/shimmer": "^1.2.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1", + "semver": "^7.5.2", + "shimmer": "^1.2.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "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/@sinclair/typebox": { "version": "0.27.12", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz", @@ -4513,12 +5220,17 @@ "version": "20.19.43", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", - "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, + "node_modules/@types/shimmer": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz", + "integrity": "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg==", + "license": "MIT" + }, "node_modules/@types/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", @@ -4998,7 +5710,6 @@ "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", - "dev": true, "license": "MIT", "bin": { "acorn": "bin/acorn" @@ -5007,6 +5718,15 @@ "node": ">=0.4.0" } }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -5749,7 +6469,6 @@ "version": "1.4.3", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", - "dev": true, "license": "MIT" }, "node_modules/class-transformer": { @@ -5825,7 +6544,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, "license": "ISC", "dependencies": { "string-width": "^4.2.0", @@ -5840,7 +6558,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", @@ -6377,7 +7094,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -6424,7 +7140,6 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -7227,6 +7942,12 @@ "node": ">= 0.6" } }, + "node_modules/forwarded-parse": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/forwarded-parse/-/forwarded-parse-2.1.2.tgz", + "integrity": "sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==", + "license": "MIT" + }, "node_modules/fs-extra": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", @@ -7275,7 +7996,6 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7295,7 +8015,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" @@ -7574,7 +8293,6 @@ "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==", - "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -7676,6 +8394,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/import-in-the-middle": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.15.0.tgz", + "integrity": "sha512-bpQy+CrsRmYmoPMAE/0G33iwRqwW4ouqdRg8jgbH3aKuCtOc8lxgmYXg2dMM92CRiGP660EtBcymH/eVUpCSaA==", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^8.14.0", + "acorn-import-attributes": "^1.9.5", + "cjs-module-lexer": "^1.2.2", + "module-details-from-path": "^1.0.3" + } + }, "node_modules/import-local": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", @@ -7808,7 +8538,6 @@ "version": "2.17.0", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", - "dev": true, "license": "MIT", "dependencies": { "hasown": "^2.0.4" @@ -8985,6 +9714,12 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" + }, "node_modules/lodash.defaults": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", @@ -9028,6 +9763,12 @@ "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/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -9424,6 +10165,12 @@ "obliterator": "^2.0.1" } }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==", + "license": "MIT" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -9767,7 +10514,6 @@ "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, "license": "MIT" }, "node_modules/path-scurry": { @@ -10048,6 +10794,29 @@ "node": ">= 6" } }, + "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", @@ -10239,7 +11008,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -10254,6 +11022,20 @@ "node": ">=0.10.0" } }, + "node_modules/require-in-the-middle": { + "version": "7.5.2", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz", + "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", @@ -10264,7 +11046,6 @@ "version": "1.22.12", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -10690,6 +11471,12 @@ "node": ">=8" } }, + "node_modules/shimmer": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", + "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==", + "license": "BSD-2-Clause" + }, "node_modules/side-channel": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", @@ -11095,7 +11882,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -11817,7 +12603,6 @@ "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, "license": "MIT" }, "node_modules/universalify": { @@ -12227,7 +13012,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "license": "ISC", "engines": { "node": ">=10" @@ -12244,7 +13028,6 @@ "version": "17.7.3", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", - "dev": true, "license": "MIT", "dependencies": { "cliui": "^8.0.1", @@ -12263,7 +13046,6 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, "license": "ISC", "engines": { "node": ">=12" diff --git a/package.json b/package.json index b392238..dc58a83 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,22 @@ "@nestjs/core": "^10.4.15", "@nestjs/platform-fastify": "^10.4.15", "@nestjs/swagger": "7.4.2", + "@opentelemetry/api": "1.9.0", + "@opentelemetry/api-logs": "0.57.2", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/exporter-logs-otlp-proto": "0.57.2", + "@opentelemetry/exporter-metrics-otlp-proto": "0.57.2", + "@opentelemetry/exporter-trace-otlp-proto": "0.57.2", + "@opentelemetry/instrumentation-aws-sdk": "0.49.1", + "@opentelemetry/instrumentation-http": "0.57.2", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-logs": "0.57.2", + "@opentelemetry/sdk-metrics": "1.30.1", + "@opentelemetry/sdk-node": "0.57.2", + "@opentelemetry/sdk-trace-base": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0", "@prisma/client": "6.1.0", + "@prisma/instrumentation": "6.1.0", "amqplib": "0.10.5", "argon2": "0.41.1", "class-transformer": "^0.5.1", diff --git a/scripts/dashboard-check.py b/scripts/dashboard-check.py new file mode 100755 index 0000000..c5c1f5e --- /dev/null +++ b/scripts/dashboard-check.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Runs every query of the provisioned dashboard through Grafana datasource proxies and reports empty panels. + +Run inside the tools container: docker compose run --rm tools python3 scripts/dashboard-check.py +""" +import json +import os +import sys +import time +import urllib.parse +import urllib.request + +GRAFANA = os.environ.get('GRAFANA_URL', 'http://grafana:3000') +DASHBOARD = os.path.join(os.path.dirname(__file__), '..', 'infra', 'grafana', 'dashboards', 'messenger.json') + + +def get(path, **params): + url = GRAFANA + path + ('?' + urllib.parse.urlencode(params) if params else '') + with urllib.request.urlopen(url, timeout=15) as response: + return json.loads(response.read()) + + +def run(target): + uid = target['datasource']['uid'] + now = int(time.time()) + if uid == 'prometheus': + expr = target['expr'].replace('$__rate_interval', '1m') + body = get('/api/datasources/proxy/uid/prometheus/api/v1/query_range', query=expr, start=now - 1800, end=now, step=30) + series = body['data']['result'] + last = [s['values'][-1][1] for s in series if s['values']] + return len(series), ', '.join('%s=%s' % (s['metric'].get('outcome') or s['metric'].get('http_response_status_class') or '', v) + for s, v in zip(series[:4], last[:4])) + if uid == 'loki': + body = get('/api/datasources/proxy/uid/loki/loki/api/v1/query_range', query=target['expr'], limit=20, since='30m') + return sum(len(s['values']) for s in body['data']['result']), '' + if uid == 'tempo': + body = get('/api/datasources/proxy/uid/tempo/api/search', q=target['query'], limit=target.get('limit', 20), start=now - 1800, end=now) + return len(body.get('traces', [])), '' + return 0, 'unknown datasource' + + +def main(): + grafana = get('/api/dashboards/uid/messenger-overview') + print('Grafana dashboard:', grafana['dashboard']['title'], 'folder:', grafana['meta'].get('folderTitle')) + dashboard = json.load(open(DASHBOARD, encoding='utf-8')) + empty = 0 + for panel in dashboard['panels']: + for target in panel.get('targets', []): + count, sample = run(target) + empty += count == 0 + print('%-4s %-62s %-3s %4d %s' % ('OK' if count else 'EMPTY', panel['title'][:62], target['refId'], count, sample[:70])) + print('\n%s: %d empty queries' % ('PASS' if empty == 0 else 'WARN', empty)) + sys.exit(0 if empty == 0 else 1) + + +if __name__ == '__main__': + main() diff --git a/scripts/latency-compare.py b/scripts/latency-compare.py new file mode 100755 index 0000000..edf7914 --- /dev/null +++ b/scripts/latency-compare.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Compares client-side percentiles of tests/load.py with histogram_quantile over the same window in Prometheus. + +Run inside the tools container: docker compose run --rm tools python3 scripts/latency-compare.py [--duration 30] +""" +import json +import os +import subprocess +import sys +import tempfile +import time +import urllib.parse +import urllib.request + +GRAFANA = os.environ.get('GRAFANA_URL', 'http://grafana:3000') +BASE = os.environ.get('BASE_URL', 'http://lb:8080') +SERIES = 'http_server_request_duration_seconds_bucket{job="messenger-api",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/messages"}' + + +def prom(expr, at): + params = urllib.parse.urlencode({'query': expr, 'time': at}) + with urllib.request.urlopen(GRAFANA + '/api/datasources/proxy/uid/prometheus/api/v1/query?' + params, timeout=15) as r: + result = json.loads(r.read())['data']['result'] + return float(result[0]['value'][1]) if result else None + + +def main(): + duration = sys.argv[sys.argv.index('--duration') + 1] if '--duration' in sys.argv else '30' + output = os.path.join(tempfile.mkdtemp(), 'load.json') + started = time.time() + subprocess.run([sys.executable, 'tests/load.py', '--base-url', BASE, '--duration', duration, '--output', output], + check=True, stdout=subprocess.DEVNULL) + report = json.load(open(output)) + print('waiting 25 s for the metric export interval') + time.sleep(25) + at = time.time() + window = int(at - started) + 5 + print('client (tests/load.py): %d requests, %.1f rps, errors %d' % ( + report['successful_requests'], report['successful_rps'], report['failed_requests'])) + count = prom('sum(increase(%s[%ds]))' % (SERIES.replace('_bucket{', '_count{'), window), at) + print('prometheus: %.0f requests in POST /api/v1/chats/{chat_id}/messages over %d s' % (count or 0, window)) + print('%-5s %12s %16s' % ('', 'client, ms', 'prometheus, ms')) + for p in ('p50', 'p95', 'p99'): + q = int(p[1:]) / 100 + server = prom('histogram_quantile(%s, sum by (le) (increase(%s[%ds])))' % (q, SERIES, window), at) + print('%-5s %12.2f %16.2f' % (p, report['successful_latency_ms'][p], (server or 0) * 1000)) + print('server-side histogram excludes network/client overhead; values are interpolated inside buckets ' + '(…, 5, 10, 25, 50, 100 ms, …).') + + +if __name__ == '__main__': + main() diff --git a/scripts/trace-check.py b/scripts/trace-check.py new file mode 100755 index 0000000..68f6a97 --- /dev/null +++ b/scripts/trace-check.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Control request for lab6: upload with a client traceparent, then find its trace in Tempo and logs in Loki. + +Run inside the tools container: docker compose run --rm tools python3 scripts/trace-check.py +""" +import base64 +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid + +BASE = os.environ.get('BASE_URL', 'http://localhost:8080') +GRAFANA = os.environ.get('GRAFANA_URL', 'http://grafana:3000') +SAMPLE = open(os.path.join(os.path.dirname(__file__), '..', 'tests', 'fixtures', 'sample.png'), 'rb').read() + + +def call(method, url, body=None, headers=None, raw=None): + data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) + all_headers = dict(headers or {}) + if body is not None: + all_headers['Content-Type'] = 'application/json' + request = urllib.request.Request(url, data=data, method=method, headers=all_headers) + try: + with urllib.request.urlopen(request, timeout=15) as response: + return response.status, json.loads(response.read() or b'null') + except urllib.error.HTTPError as error: + return error.code, None + + +def session(): + username = 'trace_' + uuid.uuid4().hex[:8] + password = 'Trace-check-' + uuid.uuid4().hex + _, user = call('POST', BASE + '/api/v1/users', {'username': username, 'display_name': 'Trace check', 'password': password}) + credential = base64.b64encode((username + ':' + password).encode()).decode() + _, login = call('POST', BASE + '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential}) + auth = {'Authorization': 'Bearer ' + login['token']} + _, chat = call('POST', BASE + '/api/v1/chats', {'title': 'Trace check', 'member_ids': [user['id']]}, auth) + return auth, chat['id'] + + +def wait_trace(trace_id, services, timeout=60): + deadline = time.monotonic() + timeout + spans = [] + while time.monotonic() < deadline: + code, body = call('GET', GRAFANA + '/api/datasources/proxy/uid/tempo/api/traces/' + trace_id) + if code == 200 and body: + spans = [] + for batch in body.get('batches', []): + attrs = {a['key']: a['value'] for a in batch['resource']['attributes']} + service = attrs['service.name']['stringValue'] + for scope in batch.get('scopeSpans', []): + for span in scope.get('spans', []): + spans.append((service, span)) + if services <= {service for service, _ in spans}: + return spans + time.sleep(3) + return spans + + +def b64hex(value): + return base64.b64decode(value).hex() if value else '' + + +def main(): + trace_id = os.urandom(16).hex() + client_span = os.urandom(8).hex() + traceparent = '00-%s-%s-01' % (trace_id, client_span) + auth, chat = session() + started = time.monotonic() + code, attachment = call( + 'POST', BASE + '/api/v1/chats/%s/attachments?filename=sample.png' % chat, + headers={**auth, 'Content-Type': 'image/png', 'traceparent': traceparent}, raw=SAMPLE, + ) + print('upload ->', code, attachment and attachment['status'], 'traceparent', traceparent) + status = None + while time.monotonic() - started < 60: + _, body = call('GET', BASE + '/api/v1/attachments/' + attachment['id'], headers=auth) + status = body['status'] + if status in ('ready', 'failed'): + break + time.sleep(0.5) + print('attachment', attachment['id'], 'status', status, 'after %.2f s' % (time.monotonic() - started)) + + spans = wait_trace(trace_id, {'messenger-api', 'messenger-relay', 'messenger-worker'}) + by_id = {b64hex(s['spanId']): (svc, s) for svc, s in spans} + print('\ntrace %s: %d spans (prisma:* internals except db_query omitted below)' % (trace_id, len(spans))) + for service, span in sorted(spans, key=lambda item: int(item[1]['startTimeUnixNano'])): + if span['name'].startswith('prisma:') and span['name'] not in ('prisma:engine:db_query', 'prisma:client:transaction'): + continue + parent = b64hex(span.get('parentSpanId')) + parent_name = 'client' if parent == client_span else by_id.get(parent, ('', {'name': '-'}))[1]['name'] + duration = (int(span['endTimeUnixNano']) - int(span['startTimeUnixNano'])) / 1e6 + print(' %-17s %-22s %-48s %8.2f ms parent=%s' % ( + service, span.get('kind', ''), span['name'][:48], duration, parent_name)) + + query = '{service_name=~"messenger-.+"} | trace_id="%s"' % trace_id + params = urllib.parse.urlencode({'query': query, 'limit': 50, 'since': '15m'}) + streams = [] + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + _, logs = call('GET', GRAFANA + '/api/datasources/proxy/uid/loki/loki/api/v1/query_range?' + params) + streams = (logs or {}).get('data', {}).get('result', []) + if {'messenger-api', 'messenger-worker'} <= {s['stream'].get('service_name') for s in streams}: + break + time.sleep(3) + print('\nLoki %s' % query) + lines = 0 + for stream in streams: + labels = stream['stream'] + for _, line in stream['values']: + lines += 1 + print(' %-17s %-8s %-13s span_id=%s %s' % ( + labels.get('service_name'), labels.get('severity_text', ''), labels.get('event', ''), + labels.get('span_id', ''), line[:60])) + + kinds = {(service, span.get('kind')) for service, span in spans} + ok = ( + status == 'ready' + and ('messenger-api', 'SPAN_KIND_SERVER') in kinds + and ('messenger-relay', 'SPAN_KIND_PRODUCER') in kinds + and ('messenger-worker', 'SPAN_KIND_CONSUMER') in kinds + and any(b64hex(s.get('parentSpanId')) == client_span for _, s in spans) + and {'messenger-api', 'messenger-worker'} <= {s['stream'].get('service_name') for s in streams} + ) + print('\n%s: client trace continued through api -> relay -> worker, logs linked by trace_id' % ('PASS' if ok else 'FAIL')) + sys.exit(0 if ok else 1) + + +if __name__ == '__main__': + main() diff --git a/src/common/filters/http-exception.filter.ts b/src/common/filters/http-exception.filter.ts index 0a79a1b..911e3aa 100644 --- a/src/common/filters/http-exception.filter.ts +++ b/src/common/filters/http-exception.filter.ts @@ -8,6 +8,7 @@ import { } from '@nestjs/common'; import { FastifyReply, FastifyRequest } from 'fastify'; import { isDatabaseUnavailable } from '../../db/prisma.service'; +import { routeTemplate } from '../../telemetry/http'; import { ApiError, ErrorCode } from './api-error'; const CODE_BY_STATUS: Partial> = { @@ -39,9 +40,14 @@ export class HttpExceptionFilter implements ExceptionFilter { const { status, code, message } = this.resolve(exception); if (status >= 500) { - this.logger.error( - `${request.method} ${request.url} -> ${status}: ${message}`, - ); + this.logger.error({ + event: 'http.error', + message, + method: request.method, + route: routeTemplate(request), + status, + request_id: requestId, + }); } if (exception instanceof ApiError) { diff --git a/src/health/shutdown.ts b/src/health/shutdown.ts index 329f27d..90c28c1 100644 --- a/src/health/shutdown.ts +++ b/src/health/shutdown.ts @@ -1,4 +1,5 @@ import { INestApplication, Logger } from '@nestjs/common'; +import { shutdownTelemetry } from '../telemetry/sdk'; let draining = false; @@ -15,10 +16,16 @@ export function enableGracefulShutdown(app: INestApplication): void { draining = true; Logger.log(`${signal}: readiness → 503, closing in ${delayMs} ms`, 'Shutdown'); setTimeout(() => { - app.close().then( - () => process.exit(0), - () => process.exit(1), - ); + app + .close() + .then( + () => 0, + () => 1, + ) + .then(async (code) => { + await shutdownTelemetry(); + process.exit(code); + }); }, delayMs); }; process.once('SIGTERM', () => shutdown('SIGTERM')); diff --git a/src/jobs/job-message.ts b/src/jobs/job-message.ts index 3fbeeb4..93ea6d7 100644 --- a/src/jobs/job-message.ts +++ b/src/jobs/job-message.ts @@ -1,9 +1,18 @@ +import { context, propagation } from '@opentelemetry/api'; import { validate as isUuid } from '../common/uuid'; export const PIPELINE_VERSION = 1; export const JOB_TYPE = 'attachment.process.v1'; -export interface JobMessage { +const TRACEPARENT = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/; +const TRACESTATE_MAX = 512; + +export interface TraceCarrier { + traceparent?: string; + tracestate?: string; +} + +export interface JobMessage extends TraceCarrier { schema_version: 1; job_id: string; type: typeof JOB_TYPE; @@ -21,6 +30,8 @@ const FIELDS = [ 'pipeline_version', 'attempt', 'created_at', + 'traceparent', + 'tracestate', ]; export function jobMessage( @@ -35,9 +46,23 @@ export function jobMessage( pipeline_version: job.pipelineVersion, attempt: job.attempt, created_at: createdAt.toISOString(), + ...currentTraceCarrier(), }; } +export function currentTraceCarrier(): TraceCarrier { + const carrier: Record = {}; + propagation.inject(context.active(), carrier); + const result: TraceCarrier = {}; + if (TRACEPARENT.test(carrier.traceparent ?? '')) { + result.traceparent = carrier.traceparent; + if (carrier.tracestate && carrier.tracestate.length <= TRACESTATE_MAX) { + result.tracestate = carrier.tracestate; + } + } + return result; +} + export function parseJobMessage(raw: Buffer): JobMessage | null { let value: any; try { @@ -61,7 +86,11 @@ export function parseJobMessage(raw: Buffer): JobMessage | null { !Number.isInteger(value.attempt) || value.attempt < 1 || typeof value.created_at !== 'string' || - Number.isNaN(Date.parse(value.created_at)) + Number.isNaN(Date.parse(value.created_at)) || + (value.traceparent !== undefined && + (typeof value.traceparent !== 'string' || !TRACEPARENT.test(value.traceparent))) || + (value.tracestate !== undefined && + (typeof value.tracestate !== 'string' || value.tracestate.length > TRACESTATE_MAX)) ) { return null; } diff --git a/src/jobs/processor.ts b/src/jobs/processor.ts index a1f1a1b..9491ee5 100644 --- a/src/jobs/processor.ts +++ b/src/jobs/processor.ts @@ -1,4 +1,5 @@ import { Logger } from '@nestjs/common'; +import { SpanStatusCode, trace } from '@opentelemetry/api'; import { Attachment, AttachmentJob, PrismaClient } from '@prisma/client'; import { createHash, randomUUID } from 'crypto'; import { @@ -50,6 +51,8 @@ class PermanentError extends Error { class TimeoutError extends Error {} +const tracer = trace.getTracer('messenger-worker'); + export class JobProcessor { private readonly logger = new Logger('JobProcessor'); @@ -141,11 +144,21 @@ export class JobProcessor { } let variants: RenderedVariant[]; try { - variants = await renderVariants( - original, - this.options.maxPixels, - Math.ceil(this.options.timeoutMs / 1000), - ); + variants = await tracer.startActiveSpan('attachment.render_variants', async (span) => { + span.setAttribute('messenger.image.bytes', original.length); + try { + return await renderVariants( + original, + this.options.maxPixels, + Math.ceil(this.options.timeoutMs / 1000), + ); + } catch (error) { + span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.name : 'error' }); + throw error; + } finally { + span.end(); + } + }); } catch (error) { if (error instanceof InvalidImageError) { throw new PermanentError('invalid_image', 'image cannot be decoded'); diff --git a/src/main.ts b/src/main.ts index 4e6043c..68982df 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,3 +1,4 @@ +import './telemetry/register'; import { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { @@ -8,6 +9,8 @@ import { AppModule } from './app.module'; import { configureApp } from './configure-app'; import { setupSwagger } from './docs/swagger'; import { enableGracefulShutdown } from './health/shutdown'; +import { registerHttpTelemetry } from './telemetry/http'; +import { JsonLogger } from './telemetry/json-logger'; async function bootstrap(): Promise { const app = await NestFactory.create( @@ -15,10 +18,12 @@ async function bootstrap(): Promise { new FastifyAdapter(), { bufferLogs: true, + logger: new JsonLogger(), }, ); configureApp(app); + registerHttpTelemetry(app.getHttpAdapter().getInstance()); setupSwagger(app); enableGracefulShutdown(app); diff --git a/src/relay.ts b/src/relay.ts index 5f54987..bcc43d6 100644 --- a/src/relay.ts +++ b/src/relay.ts @@ -1,9 +1,15 @@ +import './telemetry/register'; import { Logger } from '@nestjs/common'; +import { propagation, ROOT_CONTEXT, Span, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; import { ConfirmChannel } from 'amqplib'; import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; import { PrismaService } from './db/prisma.service'; import { JobMessage } from './jobs/job-message'; import { recoverExpiredLeases, republishStale } from './jobs/job-store'; +import { JsonLogger } from './telemetry/json-logger'; +import { shutdownTelemetry } from './telemetry/sdk'; + +Logger.overrideLogger(new JsonLogger()); const BATCH_SIZE = 100; const POLL_MS = Number(process.env.RELAY_POLL_MS ?? 500); @@ -13,8 +19,29 @@ const FAULT = process.env.RELAY_FAULT; const logger = new Logger('OutboxRelay'); const prisma = new PrismaService(); +const tracer = trace.getTracer('messenger-relay'); let stopping = false; +function startPublishSpan(payload: JobMessage, headers: Record): Span { + const parent = propagation.extract(ROOT_CONTEXT, payload); + const span = tracer.startSpan( + `${JOB_QUEUE} publish`, + { + kind: SpanKind.PRODUCER, + attributes: { + 'messaging.system': 'rabbitmq', + 'messaging.operation.type': 'publish', + 'messaging.destination.name': JOB_QUEUE, + 'messaging.message.id': payload.job_id, + 'messaging.job.attempt': payload.attempt, + }, + }, + parent, + ); + propagation.inject(trace.setSpan(parent, span), headers); + return span; +} + async function publishBatch(channel: ConfirmChannel): Promise { return prisma.$transaction( async (tx) => { @@ -27,15 +54,30 @@ async function publishBatch(channel: ConfirmChannel): Promise { if (rows.length === 0) { return 0; } + const spans: Span[] = []; for (const { payload } of rows) { + const headers: Record = {}; + spans.push(startPublishSpan(payload, headers)); channel.sendToQueue(JOB_QUEUE, Buffer.from(JSON.stringify(payload)), { persistent: true, contentType: 'application/json', messageId: payload.job_id, type: payload.type, + headers, }); } - await channel.waitForConfirms(); + try { + await channel.waitForConfirms(); + } catch (error) { + for (const span of spans) { + span.setStatus({ code: SpanStatusCode.ERROR, message: 'broker did not confirm' }); + span.end(); + } + throw error; + } + for (const span of spans) { + span.end(); + } logger.log(`published ${rows.length} job message(s), broker confirmed`); if (FAULT === 'exit-after-confirm') { logger.warn('fault injection: exit after broker confirm, before outbox is marked'); @@ -121,6 +163,7 @@ run() .then(async () => { await prisma.$disconnect(); logger.log('stopped'); + await shutdownTelemetry(); process.exit(0); }) .catch((error) => { diff --git a/src/telemetry/http.ts b/src/telemetry/http.ts new file mode 100644 index 0000000..9f8e406 --- /dev/null +++ b/src/telemetry/http.ts @@ -0,0 +1,66 @@ +import { Logger } from '@nestjs/common'; +import { metrics, trace } from '@opentelemetry/api'; +import { FastifyInstance, FastifyRequest } from 'fastify'; + +export const LATENCY_BUCKETS = [ + 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 2.5, 5, 10, +]; + +const METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']); + +const meter = metrics.getMeter('messenger-api'); +const requests = meter.createCounter('http.server.requests', { + description: 'HTTP requests by method, route template and status class', +}); +const duration = meter.createHistogram('http.server.request.duration', { + description: 'HTTP request duration', + unit: 's', + advice: { explicitBucketBoundaries: LATENCY_BUCKETS }, +}); +const logger = new Logger('Http'); + +export function routeTemplate(request: FastifyRequest): string { + const url = request.routeOptions?.url; + return url + ? url.replace(/:([A-Za-z0-9_]+)/g, (_, name: string) => `{${name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)}}`) + : 'unmatched'; +} + +export function registerHttpTelemetry(instance: FastifyInstance): void { + instance.addHook('onRequest', (request, _reply, done) => { + const span = trace.getActiveSpan(); + if (span) { + const route = routeTemplate(request); + span.updateName(`${methodOf(request)} ${route}`); + span.setAttribute('http.route', route); + span.setAttribute('messenger.request_id', request.requestId); + } + done(); + }); + instance.addHook('onResponse', (request, reply, done) => { + const route = routeTemplate(request); + const method = methodOf(request); + const attributes = { + 'http.request.method': method, + 'http.route': route, + 'http.response.status_class': `${Math.floor(reply.statusCode / 100)}xx`, + }; + requests.add(1, attributes); + duration.record(reply.elapsedTime / 1000, attributes); + if (!route.startsWith('/health')) { + logger.log({ + event: 'http.request', + method, + route, + status: reply.statusCode, + duration_ms: Math.round(reply.elapsedTime * 100) / 100, + request_id: request.requestId, + }); + } + done(); + }); +} + +function methodOf(request: FastifyRequest): string { + return METHODS.has(request.method) ? request.method : '_OTHER'; +} diff --git a/src/telemetry/json-logger.ts b/src/telemetry/json-logger.ts new file mode 100644 index 0000000..181492e --- /dev/null +++ b/src/telemetry/json-logger.ts @@ -0,0 +1,99 @@ +import { LoggerService } from '@nestjs/common'; +import { trace, TraceFlags } from '@opentelemetry/api'; +import { AnyValueMap, logs, SeverityNumber } from '@opentelemetry/api-logs'; + +type Level = 'fatal' | 'error' | 'warn' | 'log' | 'debug' | 'verbose'; + +const SEVERITY: Record = { + fatal: [SeverityNumber.FATAL, 'FATAL'], + error: [SeverityNumber.ERROR, 'ERROR'], + warn: [SeverityNumber.WARN, 'WARN'], + log: [SeverityNumber.INFO, 'INFO'], + debug: [SeverityNumber.DEBUG, 'DEBUG'], + verbose: [SeverityNumber.TRACE, 'TRACE'], +}; + +type Field = string | number | boolean; + +export class JsonLogger implements LoggerService { + private readonly otel = logs.getLogger('messenger'); + + constructor(private readonly service = process.env.OTEL_SERVICE_NAME ?? 'messenger') {} + + fatal(message: unknown, ...params: unknown[]): void { + this.write('fatal', message, params); + } + + error(message: unknown, ...params: unknown[]): void { + this.write('error', message, params); + } + + warn(message: unknown, ...params: unknown[]): void { + this.write('warn', message, params); + } + + log(message: unknown, ...params: unknown[]): void { + this.write('log', message, params); + } + + debug(message: unknown, ...params: unknown[]): void { + this.write('debug', message, params); + } + + verbose(message: unknown, ...params: unknown[]): void { + this.write('verbose', message, params); + } + + private write(level: Level, message: unknown, params: unknown[]): void { + const last = params[params.length - 1]; + const logger = typeof last === 'string' ? last : 'app'; + const fields = toFields(message); + const event = typeof fields.event === 'string' ? fields.event : eventName(logger); + delete fields.event; + const [severityNumber, severityText] = SEVERITY[level]; + const active = trace.getActiveSpan()?.spanContext(); + const span = active && active.traceFlags & TraceFlags.SAMPLED ? active : undefined; + const line = JSON.stringify({ + timestamp: new Date().toISOString(), + severity: severityText, + 'service.name': this.service, + event, + logger, + ...fields, + trace_id: span?.traceId, + span_id: span?.spanId, + }); + process.stdout.write(line + '\n'); + const attributes: AnyValueMap = { event, logger }; + for (const [key, value] of Object.entries(fields)) { + if (key !== 'message') { + attributes[key] = value; + } + } + this.otel.emit({ + severityNumber, + severityText, + body: line, + attributes, + }); + } +} + +function toFields(message: unknown): Record { + if (typeof message === 'object' && message !== null && !(message instanceof Error)) { + const fields: Record = {}; + for (const [key, value] of Object.entries(message)) { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + fields[key] = value; + } + } + return fields; + } + return { message: message instanceof Error ? message.message : String(message) }; +} + +function eventName(logger: string): string { + return logger + .replace(/([a-z0-9])([A-Z])/g, '$1_$2') + .toLowerCase(); +} diff --git a/src/telemetry/register.ts b/src/telemetry/register.ts new file mode 100644 index 0000000..571273b --- /dev/null +++ b/src/telemetry/register.ts @@ -0,0 +1,3 @@ +import { startTelemetry } from './sdk'; + +startTelemetry(); diff --git a/src/telemetry/sdk.ts b/src/telemetry/sdk.ts new file mode 100644 index 0000000..96cebbc --- /dev/null +++ b/src/telemetry/sdk.ts @@ -0,0 +1,157 @@ +import { Attributes, Context, Link, SpanKind } from '@opentelemetry/api'; +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 { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk'; +import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; +import { envDetectorSync, Resource } from '@opentelemetry/resources'; +import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'; +import { + DropAggregation, + PeriodicExportingMetricReader, + View, +} from '@opentelemetry/sdk-metrics'; +import { NodeSDK } from '@opentelemetry/sdk-node'; +import { + BatchSpanProcessor, + ParentBasedSampler, + Sampler, + SamplingDecision, + SamplingResult, +} from '@opentelemetry/sdk-trace-base'; +import { PrismaInstrumentation } from '@prisma/instrumentation'; +import { readFileSync } from 'fs'; +import { IncomingMessage } from 'http'; +import { hostname } from 'os'; +import { join } from 'path'; + +const EXPORT_TIMEOUT_MS = 5000; + +const NOISY_LEAF_SPANS = new Set([ + 'prisma:client:serialize', + 'prisma:engine:serialize', + 'prisma:engine:response_json_serialization', + 'prisma:engine:connection', +]); + +const NOT_RECORDED: SamplingResult = { decision: SamplingDecision.NOT_RECORD }; + +class SkipRootDatabaseSpans implements Sampler { + shouldSample( + _context: Context, + _traceId: string, + name: string, + ): SamplingResult { + return name.startsWith('prisma:') + ? NOT_RECORDED + : { decision: SamplingDecision.RECORD_AND_SAMPLED }; + } + + toString(): string { + return 'SkipRootDatabaseSpans'; + } +} + +class MessengerSampler implements Sampler { + private readonly parentBased = new ParentBasedSampler({ root: new SkipRootDatabaseSpans() }); + + shouldSample( + context: Context, + traceId: string, + name: string, + kind: SpanKind, + attributes: Attributes, + links: Link[], + ): SamplingResult { + if (NOISY_LEAF_SPANS.has(name)) { + return NOT_RECORDED; + } + return this.parentBased.shouldSample(context, traceId, name, kind, attributes, links); + } + + toString(): string { + return 'MessengerSampler'; + } +} + +let sdk: NodeSDK | null = null; + +export function telemetryEnabled(): boolean { + return Boolean(process.env.OTEL_EXPORTER_OTLP_ENDPOINT) && process.env.OTEL_SDK_DISABLED !== 'true'; +} + +export function startTelemetry(): void { + if (!telemetryEnabled() || sdk) { + return; + } + sdk = new NodeSDK({ + resource: new Resource({ + 'service.version': serviceVersion(), + 'service.instance.id': process.env.INSTANCE_ID ?? hostname(), + }), + resourceDetectors: [envDetectorSync], + sampler: new MessengerSampler(), + spanProcessors: [ + new BatchSpanProcessor(new OTLPTraceExporter({ timeoutMillis: EXPORT_TIMEOUT_MS }), { + maxQueueSize: 2048, + maxExportBatchSize: 512, + exportTimeoutMillis: EXPORT_TIMEOUT_MS, + }), + ], + logRecordProcessors: [ + new BatchLogRecordProcessor(new OTLPLogExporter({ timeoutMillis: EXPORT_TIMEOUT_MS }), { + maxQueueSize: 2048, + maxExportBatchSize: 512, + exportTimeoutMillis: EXPORT_TIMEOUT_MS, + }), + ], + metricReader: new PeriodicExportingMetricReader({ + exporter: new OTLPMetricExporter({ timeoutMillis: EXPORT_TIMEOUT_MS }), + exportIntervalMillis: 10000, + exportTimeoutMillis: EXPORT_TIMEOUT_MS, + }), + views: [ + new View({ + meterName: '@opentelemetry/instrumentation-http', + aggregation: new DropAggregation(), + }), + ], + instrumentations: [ + new HttpInstrumentation({ + ignoreIncomingRequestHook: (request) => (request.url ?? '').startsWith('/health'), + ignoreOutgoingRequestHook: () => true, + requestHook: (span, request) => { + if (request instanceof IncomingMessage) { + const path = (request.url ?? '/').split('?')[0]; + span.setAttribute('http.target', path); + span.setAttribute('http.url', path); + } + }, + }), + new AwsInstrumentation({ suppressInternalInstrumentation: true }), + new PrismaInstrumentation(), + ], + }); + sdk.start(); +} + +export async function shutdownTelemetry(): Promise { + if (!sdk) { + return; + } + const current = sdk; + sdk = null; + await Promise.race([ + current.shutdown().catch(() => undefined), + new Promise((resolve) => setTimeout(resolve, EXPORT_TIMEOUT_MS)), + ]); +} + +function serviceVersion(): string { + try { + const raw = readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'); + return String(JSON.parse(raw).version); + } catch { + return 'unknown'; + } +} diff --git a/src/worker.ts b/src/worker.ts index cec9146..9dab179 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,10 +1,25 @@ +import './telemetry/register'; import { Logger } from '@nestjs/common'; +import { + context, + Context, + metrics, + propagation, + ROOT_CONTEXT, + SpanKind, + SpanStatusCode, + trace, +} from '@opentelemetry/api'; import { Channel, ConsumeMessage } from 'amqplib'; import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; import { PrismaService } from './db/prisma.service'; -import { parseJobMessage } from './jobs/job-message'; +import { JOB_TYPE, JobMessage, parseJobMessage } from './jobs/job-message'; import { JobProcessor, ProcessorHooks, processorOptions } from './jobs/processor'; import { S3Service } from './storage/s3.service'; +import { JsonLogger } from './telemetry/json-logger'; +import { shutdownTelemetry } from './telemetry/sdk'; + +Logger.overrideLogger(new JsonLogger()); const CONCURRENCY = Number(process.env.WORKER_CONCURRENCY ?? 2); const INFRA_RETRY_MS = Number(process.env.WORKER_INFRA_RETRY_MS ?? 5000); @@ -18,6 +33,27 @@ const processor = new JobProcessor(prisma, s3, processorOptions(), faultHooks()) let stopping = false; let inFlight = 0; +const JOB_BUCKETS = [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 2.5, 5, 10, 30, 60, 120]; + +const tracer = trace.getTracer('messenger-worker'); +const meter = metrics.getMeter('messenger-worker'); +const jobsProcessed = meter.createCounter('jobs.processed', { + description: 'Job deliveries handled by the worker, by job type and outcome', +}); +const jobDuration = meter.createHistogram('jobs.duration', { + description: 'Job delivery handling duration', + unit: 's', + advice: { explicitBucketBoundaries: JOB_BUCKETS }, +}); + +function parentContext(delivery: ConsumeMessage, message: JobMessage | null): Context { + const headers = delivery.properties.headers ?? {}; + if (typeof headers.traceparent === 'string') { + return propagation.extract(ROOT_CONTEXT, headers); + } + return message ? propagation.extract(ROOT_CONTEXT, message) : ROOT_CONTEXT; +} + function faultHooks(): ProcessorHooks { const crash = (point: string) => async () => { logger.warn(`fault injection: worker killed ${point}`); @@ -34,31 +70,74 @@ function faultHooks(): ProcessorHooks { async function handle(channel: Channel, delivery: ConsumeMessage): Promise { inFlight++; + const started = performance.now(); + const message = parseJobMessage(delivery.content); + const span = tracer.startSpan( + `${JOB_QUEUE} process`, + { + kind: SpanKind.CONSUMER, + attributes: { + 'messaging.system': 'rabbitmq', + 'messaging.operation.type': 'process', + 'messaging.destination.name': JOB_QUEUE, + 'messaging.message.id': message?.job_id ?? 'malformed', + 'messaging.rabbitmq.redelivered': delivery.fields.redelivered, + 'messaging.job.attempt': message?.attempt ?? 0, + }, + }, + parentContext(delivery, message), + ); + const active = trace.setSpan(context.active(), span); + let outcome = 'interrupted'; + let requeue = false; try { - const message = parseJobMessage(delivery.content); - if (!message) { - logger.warn('malformed job message moved to dead letter queue'); - channel.nack(delivery, false, false); - return; + await context.with(active, async () => { + if (!message) { + outcome = 'malformed'; + logger.warn('malformed job message moved to dead letter queue'); + channel.nack(delivery, false, false); + return; + } + const result = await processor.handle(message); + outcome = result === 'ready' ? 'success' : result; + logger.log({ + event: 'job.handled', + job_id: message.job_id, + attachment_id: message.attachment_id, + attempt: message.attempt, + redelivered: delivery.fields.redelivered, + outcome, + duration_ms: Math.round(performance.now() - started), + }); + channel.ack(delivery); + }); + span.setAttribute('messenger.job.outcome', outcome); + if (outcome === 'failed' || outcome === 'malformed') { + span.setStatus({ code: SpanStatusCode.ERROR, message: outcome }); } - const outcome = await processor.handle(message); - logger.log( - `job ${message.job_id} attempt ${message.attempt}` + - `${delivery.fields.redelivered ? ' (redelivered)' : ''}: ${outcome}`, - ); - channel.ack(delivery); } catch (error) { const reason = error instanceof Error ? error.name : 'unknown error'; - logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`); + span.setAttribute('messenger.job.outcome', outcome); + span.setStatus({ code: SpanStatusCode.ERROR, message: reason }); + context.with(active, () => + logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`), + ); + requeue = true; + } finally { + span.end(); + const attributes = { 'job.type': JOB_TYPE, outcome }; + jobsProcessed.add(1, attributes); + jobDuration.record((performance.now() - started) / 1000, attributes); + } + if (requeue) { await sleep(INFRA_RETRY_MS); try { channel.nack(delivery, false, true); } catch { logger.warn('channel closed, broker will redeliver unacked message'); } - } finally { - inFlight--; } + inFlight--; } async function run(): Promise { @@ -129,6 +208,7 @@ run() await prisma.$disconnect(); s3.onModuleDestroy(); logger.log('stopped'); + await shutdownTelemetry(); process.exit(0); }) .catch((error) => { -- 2.54.0 From 3171835fff27bf766c0cff6bd204d03bd2e31e76 Mon Sep 17 00:00:00 2001 From: aegor Date: Fri, 20 Nov 2026 13:24:31 +0300 Subject: [PATCH 4/8] feat: add queue, pool, saturation metrics, slo and alert rules --- docs/runbooks.md | 63 +++++ infra/grafana/dashboards/messenger.json | 291 ++++++++++++++++++++---- infra/prometheus/rules/messenger.yml | 68 ++++++ prisma/schema.prisma | 3 +- src/db/prisma.service.ts | 5 +- src/jobs/processor.ts | 14 +- src/relay.ts | 44 +++- src/telemetry/db-pool.ts | 52 +++++ src/telemetry/sdk.ts | 20 +- src/worker.ts | 6 + 10 files changed, 511 insertions(+), 55 deletions(-) create mode 100644 docs/runbooks.md create mode 100644 infra/prometheus/rules/messenger.yml create mode 100644 src/telemetry/db-pool.ts diff --git a/docs/runbooks.md b/docs/runbooks.md new file mode 100644 index 0000000..36de540 --- /dev/null +++ b/docs/runbooks.md @@ -0,0 +1,63 @@ +# Runbooks + +Alert rules: [infra/prometheus/rules/messenger.yml](../infra/prometheus/rules/messenger.yml). Состояние: Grafana → dashboard «Messenger overview» → панель «Alerts»; или Prometheus API `GET /api/v1/alerts` (из контейнера `tools`: `wget -qO- http://grafana:3000/api/datasources/proxy/uid/prometheus/api/v1/alerts`). Уведомления наружу не отправляются. + +## SLO + +| SLI | Формула | SLO | Окно | +| --- | --- | --- | --- | +| Доступность API | 1 − 5xx / все бизнес-запросы (без `/health/*`) | ≥ 99% | 1 ч (учебный стенд; в эксплуатации — 30 дней) | +| Задержка API | доля бизнес-запросов с длительностью ≤ 0,5 с (bucket `le="0.5"`) | ≥ 95% | 1 ч | +| Готовность вложений | доля вложений, ставших `ready` за ≤ 10 с от принятия upload (bucket `le="10"`) | ≥ 95% | 1 ч | + +## MessengerHighErrorRate + +**Условие:** доля 5xx среди бизнес-запросов за 5 минут > 5% при трафике > 0,05 rps, держится 1 минуту. При SLO 99% это сжигание бюджета ошибок в 5 раз быстрее допустимого. + +**Проверить:** +1. Панель «Ответы по классам статуса» и «p95 по маршрутам»: какой маршрут даёт 5xx. +2. Loki: `{service_name="messenger-api"} | event="http.error"` — поле `message` (`database unavailable`, `object storage unavailable`, `Internal server error`), `route`, `request_id`. По `trace_id` записи — trace в Tempo. +3. В trace: на каком span ошибка — `prisma:engine:db_query`, `S3.PutObject` или код обработчика. +4. `docker compose ps` — живы ли postgres, s3, redis; `/health/ready` реплик. + +**Действия:** восстановить зависимость (`docker compose start postgres` и т. п.); при ошибке кода — откат образа. Readiness исключает реплику без БД из HAProxy автоматически. + +**Resolved:** доля 5xx за 5 минут снова ниже 5%. + +## MessengerJobQueueLag + +**Условие:** старейшее задание в состоянии `queued` с наступившим `next_attempt_at` ждёт дольше 60 с, держится 1 минуту. Источник — таблица `attachment_jobs` (метрика `jobs_queue_oldest_age_seconds` от relay), а не брокер: она показывает и задания, сообщения которых ещё не опубликованы. + +**Проверить:** +1. Панель «Worker: занято / ёмкость». `busy = capacity` — worker насыщен (медленная обработка); метрик worker нет совсем — процесс остановлен; `busy = 0` при растущей очереди — worker не получает сообщения (брокер, relay). +2. «Задания по исходу»: много `retry` — зависимость worker (S3/БД) отвечает ошибками. +3. `docker compose ps worker relay rabbitmq`; логи worker в Loki: `{service_name="messenger-worker"}`. +4. Возраст отдельных заданий: `SELECT id, status, attempt, next_attempt_at FROM attachment_jobs WHERE status='queued' ORDER BY next_attempt_at LIMIT 10;` + +**Действия:** запустить worker (`docker compose start worker`) или добавить реплик/увеличить `WORKER_CONCURRENCY` при насыщении. Задания не теряются: при старте worker обрабатывает backlog. + +**Resolved:** backlog разобран, возраст старейшего задания < 60 с. + +## MessengerSlowApi + +**Условие:** p95 бизнес-запросов за 5 минут > 1 с при трафике > 0,05 rps, держится 2 минуты. + +**Как отличить медленную БД от медленного обработчика:** +- медленная/недоступная БД: растёт `db_client_connection_pending_requests` (ожидание пула) и/или в trace медленного запроса основное время — spans `prisma:engine:db_query`; ошибки `database unavailable` (503); +- медленный обработчик: пул свободен, spans БД короткие, время приходится на сам SERVER span или S3/рендеринг; растёт CPU API. + +**Действия:** для БД — проверить postgres (`pg_stat_activity`, блокировки, ресурсы контейнера); для обработчика — профилировать маршрут, найденный в «p95 по маршрутам». + +**Resolved:** p95 за 5 минут < 1 с. + +## TelemetryExportFailing + +**Условие:** Collector получает ошибки при отправке в Loki/Tempo/Prometheus или очередь exporter заполнена больше чем наполовину, держится 1 минуту. + +**Что происходит:** API и worker продолжают работать: SDK отправляет телеметрию асинхронно с таймаутом 5 с и ограниченными очередями (2048 записей), Collector держит ограниченную очередь (`queue_size: 200` batch на exporter), повторяет отправку до 60 с и затем отбрасывает данные. `memory_limiter` (160 MiB) отказывает в приёме при нехватке памяти. Потери видны в `otelcol_exporter_send_failed_*` и `otelcol_receiver_refused_*`. + +**Проверить:** панель «Конвейер телеметрии»; `docker compose ps loki tempo prometheus`; логи Collector `docker compose logs otel-collector`. + +**Действия:** запустить хранилище (`docker compose start loki tempo`). Данные, отброшенные за время недоступности, не восстанавливаются; логи остаются в stdout контейнеров (`docker compose logs`). + +**Resolved:** отказов отправки нет, очередь exporter опустела. diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json index d935127..5cb751d 100644 --- a/infra/grafana/dashboards/messenger.json +++ b/infra/grafana/dashboards/messenger.json @@ -4,7 +4,7 @@ "tags": ["messenger", "lab6"], "timezone": "browser", "schemaVersion": 39, - "version": 1, + "version": 2, "editable": false, "graphTooltip": 1, "refresh": "10s", @@ -12,19 +12,87 @@ "templating": { "list": [] }, "annotations": { "list": [] }, "panels": [ + { "type": "row", "title": "SLO и alerts", "id": 100, "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 } }, { - "type": "row", - "title": "API", - "id": 100, - "collapsed": false, - "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 } + "type": "stat", + "title": "Доступность API, 1 ч (SLO ≥ 99% без 5xx)", + "id": 20, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 5, "w": 6, "x": 0, "y": 1 }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", "decimals": 2, + "thresholds": { "mode": "absolute", "steps": [{ "color": "red", "value": null }, { "color": "green", "value": 0.99 }] } + }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background" }, + "targets": [{ "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "1 - messenger:http_error_ratio:rate1h" }] }, + { + "type": "stat", + "title": "Запросы быстрее 500 мс, 1 ч (SLO ≥ 95%)", + "id": 21, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 5, "w": 6, "x": 6, "y": 1 }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", "decimals": 2, + "thresholds": { "mode": "absolute", "steps": [{ "color": "red", "value": null }, { "color": "green", "value": 0.95 }] } + }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background" }, + "targets": [{ "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "messenger:http_fast_ratio:rate1h" }] + }, + { + "type": "stat", + "title": "Вложения готовы за ≤ 10 с, 1 ч (SLO ≥ 95%)", + "id": 22, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 5, "w": 6, "x": 12, "y": 1 }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", "decimals": 2, + "thresholds": { "mode": "absolute", "steps": [{ "color": "red", "value": null }, { "color": "green", "value": 0.95 }] } + }, + "overrides": [] + }, + "options": { "reduceOptions": { "calcs": ["lastNotNull"] }, "colorMode": "background" }, + "targets": [{ "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "messenger:time_to_ready_fast_ratio:rate1h" }] + }, + { + "type": "state-timeline", + "title": "Alerts (pending / firing)", + "id": 23, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 5, "w": 6, "x": 18, "y": 1 }, + "fieldConfig": { + "defaults": { + "color": { "mode": "thresholds" }, + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "orange", "value": 1 }, { "color": "red", "value": 2 }] }, + "mappings": [{ "type": "value", "options": { "1": { "text": "pending" }, "2": { "text": "firing" } } }] + }, + "overrides": [] + }, + "options": { "showValue": "never", "mergeValues": true, "legend": { "showLegend": false } }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "max by (alertname) (ALERTS{alertstate=\"firing\"}) * 2 or max by (alertname) (ALERTS{alertstate=\"pending\"})", + "legendFormat": "{{alertname}}" + } + ] + }, + + { "type": "row", "title": "API", "id": 101, "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 6 } }, { "type": "timeseries", "title": "RPS по маршрутам (без health)", "id": 1, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 12, "x": 0, "y": 1 }, + "gridPos": { "h": 8, "w": 12, "x": 0, "y": 7 }, "fieldConfig": { "defaults": { "unit": "reqps" }, "overrides": [] }, "options": { "legend": { "displayMode": "table", "placement": "right", "calcs": ["lastNotNull"] } }, "targets": [ @@ -41,7 +109,7 @@ "title": "Ответы по классам статуса (без health)", "id": 2, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 12, "x": 12, "y": 1 }, + "gridPos": { "h": 8, "w": 12, "x": 12, "y": 7 }, "fieldConfig": { "defaults": { "unit": "reqps" }, "overrides": [] }, "targets": [ { @@ -54,10 +122,10 @@ }, { "type": "timeseries", - "title": "Доля 5xx среди бизнес-запросов (окно 5m)", + "title": "Доля 5xx среди бизнес-запросов (окно 5m, порог alert 5%)", "id": 3, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 8, "x": 0, "y": 9 }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 15 }, "fieldConfig": { "defaults": { "unit": "percentunit", @@ -68,12 +136,7 @@ "overrides": [] }, "targets": [ - { - "refId": "A", - "datasource": { "type": "prometheus", "uid": "prometheus" }, - "expr": "(sum(rate(http_server_requests_total{job=\"messenger-api\", http_route!~\"/health.*\", http_response_status_class=\"5xx\"}[5m])) or vector(0)) / sum(rate(http_server_requests_total{job=\"messenger-api\", http_route!~\"/health.*\"}[5m]))", - "legendFormat": "5xx ratio" - } + { "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "messenger:http_error_ratio:rate5m", "legendFormat": "5xx ratio" } ] }, { @@ -81,7 +144,7 @@ "title": "Длительность API p50 / p95 / p99 (все реплики, без health)", "id": 4, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 8, "x": 8, "y": 9 }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 15 }, "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, "targets": [ { @@ -109,7 +172,7 @@ "title": "p95 по маршрутам", "id": 5, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 8, "x": 16, "y": 9 }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 15 }, "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, "targets": [ { @@ -120,19 +183,61 @@ } ] }, + + { "type": "row", "title": "Очередь и worker", "id": 102, "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 23 } }, { - "type": "row", - "title": "Worker", - "id": 101, - "collapsed": false, - "gridPos": { "h": 1, "w": 24, "x": 0, "y": 17 } + "type": "timeseries", + "title": "Глубина очереди attachment.jobs (из attachment_jobs)", + "id": 30, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 24 }, + "fieldConfig": { "defaults": { "unit": "short", "min": 0 }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "max by (state) (jobs_queue_depth{job=\"messenger-relay\"})", + "legendFormat": "{{state}}" + } + ] + }, + { + "type": "timeseries", + "title": "Возраст старейшего готового задания (порог alert 60 s)", + "id": 31, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 24 }, + "fieldConfig": { + "defaults": { + "unit": "s", "min": 0, + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "red", "value": 60 }] }, + "custom": { "thresholdsStyle": { "mode": "line" } } + }, + "overrides": [] + }, + "targets": [ + { "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "messenger:jobs_queue_oldest_age:max", "legendFormat": "oldest due job age" } + ] + }, + { + "type": "timeseries", + "title": "Worker: занято / ёмкость", + "id": 32, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 24 }, + "fieldConfig": { "defaults": { "unit": "short", "min": 0 }, "overrides": [] }, + "targets": [ + { "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(worker_jobs_busy{job=\"messenger-worker\"})", "legendFormat": "busy" }, + { "refId": "B", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(worker_jobs_capacity{job=\"messenger-worker\"})", "legendFormat": "capacity" }, + { "refId": "C", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(avg_over_time(worker_jobs_busy{job=\"messenger-worker\"}[5m])) / sum(worker_jobs_capacity{job=\"messenger-worker\"})", "legendFormat": "saturation 5m" } + ] }, { "type": "timeseries", "title": "Задания по исходу (в секунду)", "id": 6, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 12, "x": 0, "y": 18 }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 32 }, "fieldConfig": { "defaults": { "unit": "ops" }, "overrides": [] }, "targets": [ { @@ -148,7 +253,7 @@ "title": "Длительность обработки задания p50 / p95 / p99", "id": 7, "datasource": { "type": "prometheus", "uid": "prometheus" }, - "gridPos": { "h": 8, "w": 12, "x": 12, "y": 18 }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 32 }, "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, "targets": [ { @@ -168,35 +273,127 @@ "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "histogram_quantile(0.99, sum by (le) (rate(jobs_duration_seconds_bucket{job=\"messenger-worker\", outcome=\"success\"}[$__rate_interval])))", "legendFormat": "p99 success" - }, - { - "refId": "D", - "datasource": { "type": "prometheus", "uid": "prometheus" }, - "expr": "histogram_quantile(0.95, sum by (le) (rate(jobs_duration_seconds_bucket{job=\"messenger-worker\", outcome!=\"success\"}[$__rate_interval])))", - "legendFormat": "p95 retry/failed" } ] }, { - "type": "row", - "title": "Логи и трассы", - "id": 102, - "collapsed": false, - "gridPos": { "h": 1, "w": 24, "x": 0, "y": 26 } + "type": "timeseries", + "title": "Время от upload до ready p50 / p95 / p99", + "id": 33, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 32 }, + "fieldConfig": { "defaults": { "unit": "s", "min": 0 }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(attachments_time_to_ready_seconds_bucket{job=\"messenger-worker\"}[$__rate_interval])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(attachments_time_to_ready_seconds_bucket{job=\"messenger-worker\"}[$__rate_interval])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(attachments_time_to_ready_seconds_bucket{job=\"messenger-worker\"}[$__rate_interval])))", + "legendFormat": "p99" + } + ] }, + + { "type": "row", "title": "БД и ресурсы", "id": 103, "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 40 } }, + { + "type": "timeseries", + "title": "Пул БД: занято / ожидают соединения", + "id": 40, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 0, "y": 41 }, + "fieldConfig": { "defaults": { "unit": "short", "min": 0 }, "overrides": [] }, + "targets": [ + { "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "legendFormat": "{{job}} used" }, + { "refId": "B", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum by (job) (db_client_connection_pending_requests)", "legendFormat": "{{job}} waiting" }, + { "refId": "C", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum by (job) (db_client_connection_max)", "legendFormat": "{{job}} max" } + ] + }, + { + "type": "timeseries", + "title": "CPU процессов (доля ядра)", + "id": 41, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 8, "y": 41 }, + "fieldConfig": { "defaults": { "unit": "percentunit", "min": 0 }, "overrides": [] }, + "targets": [ + { + "refId": "A", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "sum by (job, instance) (rate(process_cpu_time_seconds_total{job=~\"messenger-.+\"}[$__rate_interval]))", + "legendFormat": "{{job}} {{instance}}" + }, + { + "refId": "B", + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "expr": "rate(otelcol_process_cpu_seconds{job=\"otel-collector\"}[$__rate_interval])", + "legendFormat": "otel-collector" + } + ] + }, + { + "type": "timeseries", + "title": "RAM процессов (RSS)", + "id": 42, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 8, "x": 16, "y": 41 }, + "fieldConfig": { "defaults": { "unit": "bytes", "min": 0 }, "overrides": [] }, + "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": "otelcol_process_memory_rss{job=\"otel-collector\"}", "legendFormat": "otel-collector" } + ] + }, + + { "type": "row", "title": "Конвейер телеметрии (Collector)", "id": 104, "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 49 } }, + { + "type": "timeseries", + "title": "Принято / отправлено / ошибки отправки (в секунду)", + "id": 50, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 12, "x": 0, "y": 50 }, + "fieldConfig": { "defaults": { "unit": "short", "min": 0 }, "overrides": [] }, + "targets": [ + { "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "legendFormat": "spans accepted" }, + { "refId": "B", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "legendFormat": "spans sent" }, + { "refId": "C", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval])) or vector(0)", "legendFormat": "spans failed" }, + { "refId": "D", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(rate(otelcol_exporter_sent_log_records[$__rate_interval]))", "legendFormat": "logs sent" }, + { "refId": "E", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval])) or vector(0)", "legendFormat": "logs failed" }, + { "refId": "F", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "sum(rate(otelcol_receiver_refused_spans[$__rate_interval])) + sum(rate(otelcol_receiver_refused_log_records[$__rate_interval])) or vector(0)", "legendFormat": "refused (memory_limiter)" } + ] + }, + { + "type": "timeseries", + "title": "Очередь exporter (ограничена queue_size)", + "id": 51, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "gridPos": { "h": 8, "w": 12, "x": 12, "y": 50 }, + "fieldConfig": { "defaults": { "unit": "short", "min": 0 }, "overrides": [] }, + "targets": [ + { "refId": "A", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "max by (exporter) (otelcol_exporter_queue_size)", "legendFormat": "{{exporter}} size" }, + { "refId": "B", "datasource": { "type": "prometheus", "uid": "prometheus" }, "expr": "max(otelcol_exporter_queue_capacity)", "legendFormat": "capacity" } + ] + }, + + { "type": "row", "title": "Логи и трассы", "id": 105, "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 58 } }, { "type": "logs", "title": "Логи API и worker (WARN и выше)", "id": 8, "datasource": { "type": "loki", "uid": "loki" }, - "gridPos": { "h": 10, "w": 12, "x": 0, "y": 27 }, + "gridPos": { "h": 10, "w": 12, "x": 0, "y": 59 }, "options": { "showTime": true, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true }, "targets": [ - { - "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, - "expr": "{service_name=~\"messenger-.+\"} | severity_text=~\"WARN|ERROR|FATAL\"" - } + { "refId": "A", "datasource": { "type": "loki", "uid": "loki" }, "expr": "{service_name=~\"messenger-.+\"} | severity_text=~\"WARN|ERROR|FATAL\"" } ] }, { @@ -204,14 +401,10 @@ "title": "Все логи (http.request, job.handled, …)", "id": 9, "datasource": { "type": "loki", "uid": "loki" }, - "gridPos": { "h": 10, "w": 12, "x": 12, "y": 27 }, + "gridPos": { "h": 10, "w": 12, "x": 12, "y": 59 }, "options": { "showTime": true, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true }, "targets": [ - { - "refId": "A", - "datasource": { "type": "loki", "uid": "loki" }, - "expr": "{service_name=~\"messenger-.+\"}" - } + { "refId": "A", "datasource": { "type": "loki", "uid": "loki" }, "expr": "{service_name=~\"messenger-.+\"}" } ] }, { @@ -219,7 +412,7 @@ "title": "Последние трассы (HTTP server и consumer spans)", "id": 10, "datasource": { "type": "tempo", "uid": "tempo" }, - "gridPos": { "h": 10, "w": 24, "x": 0, "y": 37 }, + "gridPos": { "h": 10, "w": 24, "x": 0, "y": 69 }, "targets": [ { "refId": "A", diff --git a/infra/prometheus/rules/messenger.yml b/infra/prometheus/rules/messenger.yml new file mode 100644 index 0000000..6025dfb --- /dev/null +++ b/infra/prometheus/rules/messenger.yml @@ -0,0 +1,68 @@ +groups: + - name: messenger-sli + interval: 15s + rules: + - record: messenger:http_requests:rate5m + expr: sum(rate(http_server_requests_total{job="messenger-api", http_route!~"/health.*"}[5m])) + - record: messenger:http_errors:rate5m + expr: sum(rate(http_server_requests_total{job="messenger-api", http_route!~"/health.*", http_response_status_class="5xx"}[5m])) or vector(0) + - record: messenger:http_error_ratio:rate5m + expr: messenger:http_errors:rate5m / messenger:http_requests:rate5m + - record: messenger:http_error_ratio:rate1h + expr: | + (sum(rate(http_server_requests_total{job="messenger-api", http_route!~"/health.*", http_response_status_class="5xx"}[1h])) or vector(0)) + / sum(rate(http_server_requests_total{job="messenger-api", http_route!~"/health.*"}[1h])) + - record: messenger:http_latency_p95:rate5m + expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health.*"}[5m]))) + - record: messenger:http_fast_ratio:rate1h + expr: | + sum(rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health.*", le="0.5"}[1h])) + / sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health.*"}[1h])) + - record: messenger:time_to_ready_fast_ratio:rate1h + expr: | + sum(rate(attachments_time_to_ready_seconds_bucket{job="messenger-worker", le="10"}[1h])) + / sum(rate(attachments_time_to_ready_seconds_count{job="messenger-worker"}[1h])) + - record: messenger:jobs_queue_oldest_age:max + expr: max(jobs_queue_oldest_age_seconds{job="messenger-relay"}) + + - name: messenger-alerts + rules: + - alert: MessengerHighErrorRate + expr: messenger:http_error_ratio:rate5m > 0.05 and messenger:http_requests:rate5m > 0.05 + for: 1m + labels: + severity: critical + annotations: + summary: "Доля 5xx бизнес-запросов API {{ $value | humanizePercentage }} за 5 минут (порог 5%)" + description: "SLO доступности 99% за 1 ч: при 5% ошибок бюджет сгорает в 5 раз быстрее допустимого. Health-запросы не учитываются." + runbook: "docs/runbooks.md#messengerhigherrorrate" + - alert: MessengerJobQueueLag + expr: messenger:jobs_queue_oldest_age:max > 60 + for: 1m + labels: + severity: warning + annotations: + summary: "Старейшее готовое к обработке задание ждёт {{ $value | humanizeDuration }} (порог 60 s)" + description: "Задания принимаются, но не обрабатываются: worker остановлен, не справляется или не получает сообщения из брокера." + runbook: "docs/runbooks.md#messengerjobqueuelag" + - alert: MessengerSlowApi + expr: messenger:http_latency_p95:rate5m > 1 and messenger:http_requests:rate5m > 0.05 + for: 2m + labels: + severity: warning + annotations: + summary: "p95 бизнес-запросов API {{ $value | humanizeDuration }} за 5 минут (порог 1 s)" + description: "Проверьте ожидание пула БД (db_client_connection_pending_requests) и spans prisma:engine:db_query в трассах медленных запросов." + runbook: "docs/runbooks.md#messengerslowapi" + - alert: TelemetryExportFailing + expr: | + sum(rate(otelcol_exporter_send_failed_spans[2m])) + sum(rate(otelcol_exporter_send_failed_log_records[2m])) + + sum(rate(otelcol_exporter_send_failed_metric_points[2m])) > 0 + or max(otelcol_exporter_queue_size / otelcol_exporter_queue_capacity) > 0.5 + for: 1m + labels: + severity: warning + annotations: + summary: "Collector не может доставить телеметрию в хранилище" + description: "Растёт очередь exporter или есть отказы отправки. Мессенджер работает, но часть трасс/логов теряется после заполнения ограниченной очереди." + runbook: "docs/runbooks.md#telemetryexportfailing" diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 2942712..03d6fb8 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -1,5 +1,6 @@ generator client { - provider = "prisma-client-js" + provider = "prisma-client-js" + previewFeatures = ["metrics"] } datasource db { diff --git a/src/db/prisma.service.ts b/src/db/prisma.service.ts index e391433..bcca5b9 100644 --- a/src/db/prisma.service.ts +++ b/src/db/prisma.service.ts @@ -1,13 +1,16 @@ import { Injectable, OnModuleDestroy } from '@nestjs/common'; import { Prisma, PrismaClient } from '@prisma/client'; import { readFileSync } from 'fs'; +import { registerDbPool } from '../telemetry/db-pool'; const UNAVAILABLE_CODES = new Set(['P1001', 'P1002', 'P1008', 'P1017', 'P2024']); @Injectable() export class PrismaService extends PrismaClient implements OnModuleDestroy { constructor() { - super({ datasourceUrl: readDatabaseUrl() }); + const url = readDatabaseUrl(); + super({ datasourceUrl: url }); + registerDbPool(this, url); } async onModuleDestroy(): Promise { diff --git a/src/jobs/processor.ts b/src/jobs/processor.ts index 9491ee5..79576da 100644 --- a/src/jobs/processor.ts +++ b/src/jobs/processor.ts @@ -1,5 +1,5 @@ import { Logger } from '@nestjs/common'; -import { SpanStatusCode, trace } from '@opentelemetry/api'; +import { metrics, SpanStatusCode, trace } from '@opentelemetry/api'; import { Attachment, AttachmentJob, PrismaClient } from '@prisma/client'; import { createHash, randomUUID } from 'crypto'; import { @@ -7,7 +7,7 @@ import { ObjectTooLargeError, S3Service, } from '../storage/s3.service'; -import { JobMessage, PIPELINE_VERSION } from './job-message'; +import { JOB_TYPE, JobMessage, PIPELINE_VERSION } from './job-message'; import { markFailed, retryOrFail } from './job-store'; import { InvalidImageError, @@ -52,6 +52,13 @@ class PermanentError extends Error { class TimeoutError extends Error {} const tracer = trace.getTracer('messenger-worker'); +const timeToReady = metrics.getMeter('messenger-worker').createHistogram('attachments.time_to_ready', { + description: 'From durable upload acceptance to the committed ready state', + unit: 's', + advice: { + explicitBucketBoundaries: [0.1, 0.25, 0.5, 1, 2, 3, 5, 10, 20, 30, 60, 120, 300, 600], + }, +}); export class JobProcessor { private readonly logger = new Logger('JobProcessor'); @@ -225,6 +232,9 @@ export class JobProcessor { this.logger.warn(`job ${lease.id}: lease lost before commit, result left to owner`); return 'skipped'; } + timeToReady.record((now.getTime() - attachment.createdAt.getTime()) / 1000, { + 'job.type': JOB_TYPE, + }); await this.hooks.afterCommit?.(); await this.removeStaging(attachment); return 'ready'; diff --git a/src/relay.ts b/src/relay.ts index bcc43d6..c7467f8 100644 --- a/src/relay.ts +++ b/src/relay.ts @@ -1,6 +1,14 @@ import './telemetry/register'; import { Logger } from '@nestjs/common'; -import { propagation, ROOT_CONTEXT, Span, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; +import { + metrics, + propagation, + ROOT_CONTEXT, + Span, + SpanKind, + SpanStatusCode, + trace, +} from '@opentelemetry/api'; import { ConfirmChannel } from 'amqplib'; import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; import { PrismaService } from './db/prisma.service'; @@ -22,6 +30,40 @@ const prisma = new PrismaService(); const tracer = trace.getTracer('messenger-relay'); let stopping = false; +const meter = metrics.getMeter('messenger-relay'); +const queueDepth = meter.createObservableGauge('jobs.queue.depth', { + description: 'Attachment jobs by state (source of truth: attachment_jobs)', +}); +const oldestAge = meter.createObservableGauge('jobs.queue.oldest_age', { + description: 'Age of the oldest due queued job (since accepted or retry became due)', + unit: 's', +}); + +meter.addBatchObservableCallback( + async (result) => { + const [row] = await prisma.$queryRaw< + { queued: number; due: number; processing: number; oldest: number }[] + >` + SELECT + count(*) FILTER (WHERE status = 'queued')::int AS queued, + count(*) FILTER (WHERE status = 'queued' AND next_attempt_at <= now())::int AS due, + count(*) FILTER (WHERE status = 'processing')::int AS processing, + COALESCE(EXTRACT(EPOCH FROM now() - min(next_attempt_at) + FILTER (WHERE status = 'queued' AND next_attempt_at <= now())), 0)::float8 AS oldest + FROM attachment_jobs + WHERE status IN ('queued', 'processing')`.catch(() => []); + if (!row) { + return; + } + const queue = { 'messaging.destination.name': JOB_QUEUE }; + result.observe(queueDepth, row.queued, { ...queue, state: 'queued' }); + result.observe(queueDepth, row.due, { ...queue, state: 'due' }); + result.observe(queueDepth, row.processing, { ...queue, state: 'processing' }); + result.observe(oldestAge, row.oldest, queue); + }, + [queueDepth, oldestAge], +); + function startPublishSpan(payload: JobMessage, headers: Record): Span { const parent = propagation.extract(ROOT_CONTEXT, payload); const span = tracer.startSpan( diff --git a/src/telemetry/db-pool.ts b/src/telemetry/db-pool.ts new file mode 100644 index 0000000..6d280fa --- /dev/null +++ b/src/telemetry/db-pool.ts @@ -0,0 +1,52 @@ +import { metrics } from '@opentelemetry/api'; +import { PrismaClient } from '@prisma/client'; + +interface Pool { + client: PrismaClient; + max: number; +} + +const pools: Pool[] = []; +const meter = metrics.getMeter('messenger-db'); +const connections = meter.createObservableGauge('db.client.connection.count', { + description: 'Prisma pool connections by state', +}); +const pending = meter.createObservableGauge('db.client.connection.pending_requests', { + description: 'Queries waiting for a free pool connection', +}); +const max = meter.createObservableGauge('db.client.connection.max', { + description: 'Configured pool size (connection_limit)', +}); + +meter.addBatchObservableCallback( + async (result) => { + for (const pool of pools) { + let gauges: Record; + try { + const snapshot = await pool.client.$metrics.json(); + gauges = Object.fromEntries(snapshot.gauges.map((gauge) => [gauge.key, gauge.value])); + } catch { + continue; + } + result.observe(connections, gauges.prisma_pool_connections_busy ?? 0, { + 'db.client.connection.state': 'used', + }); + result.observe(connections, gauges.prisma_pool_connections_idle ?? 0, { + 'db.client.connection.state': 'idle', + }); + result.observe(pending, gauges.prisma_client_queries_wait ?? 0); + result.observe(max, pool.max); + } + }, + [connections, pending, max], +); + +export function registerDbPool(client: PrismaClient, url: string): void { + let limit = 0; + try { + limit = Number(new URL(url).searchParams.get('connection_limit') ?? 0); + } catch { + limit = 0; + } + pools.push({ client, max: limit }); +} diff --git a/src/telemetry/sdk.ts b/src/telemetry/sdk.ts index 96cebbc..46a2e32 100644 --- a/src/telemetry/sdk.ts +++ b/src/telemetry/sdk.ts @@ -1,4 +1,4 @@ -import { Attributes, Context, Link, SpanKind } from '@opentelemetry/api'; +import { Attributes, Context, Link, metrics, SpanKind } from '@opentelemetry/api'; import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'; import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'; @@ -133,6 +133,24 @@ export function startTelemetry(): void { ], }); sdk.start(); + registerProcessMetrics(); +} + +function registerProcessMetrics(): void { + const meter = metrics.getMeter('messenger-process'); + meter + .createObservableCounter('process.cpu.time', { description: 'Process CPU time', unit: 's' }) + .addCallback((result) => { + const usage = process.cpuUsage(); + result.observe(usage.user / 1e6, { 'cpu.mode': 'user' }); + result.observe(usage.system / 1e6, { 'cpu.mode': 'system' }); + }); + meter + .createObservableGauge('process.memory.usage', { description: 'Resident set size', unit: 'By' }) + .addCallback((result) => result.observe(process.memoryUsage.rss())); + meter + .createObservableGauge('process.memory.heap_used', { description: 'V8 heap used', unit: 'By' }) + .addCallback((result) => result.observe(process.memoryUsage().heapUsed)); } export async function shutdownTelemetry(): Promise { diff --git a/src/worker.ts b/src/worker.ts index 9dab179..600f681 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -45,6 +45,12 @@ const jobDuration = meter.createHistogram('jobs.duration', { unit: 's', advice: { explicitBucketBoundaries: JOB_BUCKETS }, }); +meter + .createObservableGauge('worker.jobs.busy', { description: 'Deliveries being handled now' }) + .addCallback((result) => result.observe(inFlight)); +meter + .createObservableGauge('worker.jobs.capacity', { description: 'Concurrent deliveries allowed (prefetch)' }) + .addCallback((result) => result.observe(CONCURRENCY)); function parentContext(delivery: ConsumeMessage, message: JobMessage | null): Context { const headers = delivery.properties.headers ?? {}; -- 2.54.0 From 5f870e4fb09eac7b1a2602166a2b4b95fe3ff2f8 Mon Sep 17 00:00:00 2001 From: aegor Date: Fri, 20 Nov 2026 16:39:45 +0300 Subject: [PATCH 5/8] feat: add incident scenarios, privacy check and lab6 evidence collection --- docs/runbooks.md | 12 + infra/prometheus/rules/messenger.yml | 9 + scripts/collect-evidence.sh | 40 ++- scripts/incidents.py | 386 +++++++++++++++++++++++++++ scripts/telemetry-privacy.py | 102 +++++++ src/jobs/processor.ts | 4 +- src/telemetry/sdk.ts | 1 - 7 files changed, 550 insertions(+), 4 deletions(-) create mode 100755 scripts/incidents.py create mode 100755 scripts/telemetry-privacy.py diff --git a/docs/runbooks.md b/docs/runbooks.md index 36de540..baed5a1 100644 --- a/docs/runbooks.md +++ b/docs/runbooks.md @@ -24,6 +24,18 @@ Alert rules: [infra/prometheus/rules/messenger.yml](../infra/prometheus/rules/me **Resolved:** доля 5xx за 5 минут снова ниже 5%. +## MessengerApiNotReady + +**Условие:** больше 10 ответов 5xx на `/health/core` (проверка HAProxy раз в секунду, `SELECT 1` в PostgreSQL) за минуту, держится 30 с. Штатная остановка реплики даёт 3–4 таких ответа (3 с drain) и alert не вызывает; недоступная БД — около 140 в минуту на две реплики. + +**Почему отдельный alert:** когда все реплики не готовы, HAProxy сам отвечает клиентам `503 no API replica available`; эти ответы не проходят через API и не входят в `http_server_requests_total`, поэтому доля 5xx бизнес-запросов может оставаться нулевой. + +**Проверить:** Loki `{service_name="messenger-api"} | event="http.error"` — `route=/health/core`, `message` (`database unavailable` или `shutting down`); `docker compose ps postgres`; панель «Пул БД» (рост `waiting`). + +**Действия:** восстановить PostgreSQL (`docker compose start postgres` / `docker compose unpause postgres`). После первых успешных проверок (`rise 2`) HAProxy возвращает реплики. + +**Resolved:** проверки готовности снова 200 в течение минуты. + ## MessengerJobQueueLag **Условие:** старейшее задание в состоянии `queued` с наступившим `next_attempt_at` ждёт дольше 60 с, держится 1 минуту. Источник — таблица `attachment_jobs` (метрика `jobs_queue_oldest_age_seconds` от relay), а не брокер: она показывает и задания, сообщения которых ещё не опубликованы. diff --git a/infra/prometheus/rules/messenger.yml b/infra/prometheus/rules/messenger.yml index 6025dfb..a8254f4 100644 --- a/infra/prometheus/rules/messenger.yml +++ b/infra/prometheus/rules/messenger.yml @@ -36,6 +36,15 @@ groups: summary: "Доля 5xx бизнес-запросов API {{ $value | humanizePercentage }} за 5 минут (порог 5%)" description: "SLO доступности 99% за 1 ч: при 5% ошибок бюджет сгорает в 5 раз быстрее допустимого. Health-запросы не учитываются." runbook: "docs/runbooks.md#messengerhigherrorrate" + - alert: MessengerApiNotReady + expr: sum(increase(http_server_requests_total{job="messenger-api", http_route="/health/core", http_response_status_class="5xx"}[1m])) > 10 + for: 30s + labels: + severity: critical + annotations: + summary: "Реплики API отвечают 503 на /health/core — HAProxy выводит их из балансировки" + description: "Обычно недоступна БД или реплика останавливается. Пока все реплики не готовы, клиенты получают 503 от LB, и такие ответы не попадают в метрики API (MessengerHighErrorRate их не видит)." + runbook: "docs/runbooks.md#messengerapinotready" - alert: MessengerJobQueueLag expr: messenger:jobs_queue_oldest_age:max > 60 for: 1m diff --git a/scripts/collect-evidence.sh b/scripts/collect-evidence.sh index 20da164..daacfd0 100755 --- a/scripts/collect-evidence.sh +++ b/scripts/collect-evidence.sh @@ -37,8 +37,13 @@ echo 'container.txt' run docker compose ps -a --format 'table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' echo '## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах)' run sh -c "docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' \$(docker compose ps -aq)" + echo '## Опубликованные порты: только LB и Grafana на 127.0.0.1; OTLP, Prometheus, Loki, Tempo наружу не открыты' + run sh -c "docker compose ps --format '{{.Service}} {{.Ports}}' | grep -v '^\\S* *$' || true" + echo '## Сети телеметрии: хранилища только во внутренней сети telemetry' + run sh -c "for s in otel-collector prometheus loki tempo grafana api worker; do printf '%s: ' \$s; docker inspect -f '{{range \$k, \$v := .NetworkSettings.Networks}}{{\$k}} {{end}}' \$(docker compose ps -q \$s | head -1); done" + run docker network inspect -f '{{.Name}} internal={{.Internal}}' messenger-lab6_telemetry echo '## Секреты: каждый сервис видит только свои файлы (содержимое не выводится)' - for service in postgres redis s3 api reconciler relay worker; do + for service in postgres redis s3 api reconciler relay worker grafana; do run docker compose exec -T "$service" ls /run/secrets done run docker compose exec -T rabbitmq ls /etc/rabbitmq/conf.d @@ -49,6 +54,7 @@ echo 'container.txt' run docker compose exec -T redis redis-server --version run docker compose exec -T s3 minio --version run docker compose exec -T rabbitmq rabbitmqctl -q version + run sh -c "docker compose images otel-collector prometheus loki tempo grafana" echo '## Топология брокера: durable quorum-очереди, delivery-limit и DLQ' run docker compose exec -T rabbitmq rabbitmqctl -q list_queues name type durable arguments messages run docker compose exec -T rabbitmq rabbitmqctl -q list_consumers queue_name prefetch_count ack_required @@ -62,10 +68,12 @@ echo 'container.txt' echo 'tests.txt' { - header 'Собственные e2e-тесты (PostgreSQL + Redis + MinIO из compose.test.yaml)' + header 'Собственные e2e-тесты (PostgreSQL + Redis + MinIO из compose.test.yaml); основной стенд на время тестов остановлен ради памяти Docker' + docker compose stop lb api worker relay reconciler otel-collector prometheus loki tempo grafana rabbitmq s3 redis postgres >/dev/null 2>&1 docker compose -f compose.test.yaml build -q tests run docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose docker compose -f compose.test.yaml down -v >/dev/null 2>&1 + docker compose up -d --wait >/dev/null 2>&1 } > evidence/tests.txt echo 'smoke.txt' @@ -120,4 +128,32 @@ echo 'jobs.txt' docker compose logs --no-log-prefix --tail 1 reconciler 2>&1 } > evidence/jobs.txt +echo 'telemetry.txt' +{ + header 'Наблюдаемость: контрольный запрос (trace + логи), dashboard, перцентили, приватность, правила' + echo '## Prometheus: правила загружены (promtool и /api/v1/rules)' + run docker compose exec -T prometheus promtool check rules /etc/prometheus/rules/messenger.yml + run sh -c "wget -qO- http://grafana:3000/api/datasources/proxy/uid/prometheus/api/v1/rules | python3 -c 'import json,sys; [print(r[\"type\"], r[\"name\"], r[\"health\"]) for g in json.load(sys.stdin)[\"data\"][\"groups\"] for r in g[\"rules\"]]'" + echo '## Grafana: datasources с фиксированными UID, dashboard из provisioning' + run sh -c "for uid in prometheus loki tempo; do wget -qO- http://grafana:3000/api/datasources/uid/\$uid | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d[\"uid\"], d[\"type\"], d[\"url\"])'; done" + echo '## Контрольный upload с клиентским traceparent: trace в Tempo и логи в Loki' + run python3 scripts/trace-check.py + echo '## Секреты и содержимое не попадают в telemetry; в labels метрик нет ID' + run python3 scripts/telemetry-privacy.py + echo '## Перцентили dashboard против клиентского замера tests/load.py' + run python3 scripts/latency-compare.py --duration 30 + echo '## Все запросы dashboard (пустые панели alerts/WARN-логов допустимы без инцидентов)' + run python3 scripts/dashboard-check.py + echo '## Пример структурного лога (stdout API)' + docker compose logs --no-log-prefix --tail 200 api 2>&1 | grep '"event":"http.request"' | tail -2 +} > evidence/telemetry.txt + +for scenario in retry-trace worker-stop db telemetry; do + echo "incident-$scenario.txt" + { + header "Инцидент: scripts/incidents.py $scenario" + run python3 scripts/incidents.py "$scenario" + } > "evidence/incident-$scenario.txt" +done + echo 'done' diff --git a/scripts/incidents.py b/scripts/incidents.py new file mode 100755 index 0000000..7106dd0 --- /dev/null +++ b/scripts/incidents.py @@ -0,0 +1,386 @@ +#!/usr/bin/env python3 +"""Controlled incidents for lab6 observability; run inside the tools container. + + docker compose run --rm tools python3 scripts/incidents.py worker-stop|db|telemetry|retry-trace + +Every scenario injects a fault, keeps synthetic traffic going, samples Prometheus/Tempo/Loki through Grafana +and waits for the related alert to become firing and then resolved after recovery. +""" +import base64 +import importlib.util +import json +import os +import statistics +import struct +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +import uuid +import zlib + +spec = importlib.util.spec_from_file_location('job_scenario', os.path.join(os.path.dirname(__file__), 'job-scenario.py')) +js = importlib.util.module_from_spec(spec) +spec.loader.exec_module(js) +log = js.log + +GRAFANA = os.environ.get('GRAFANA_URL', 'http://grafana:3000') +PROM = GRAFANA + '/api/datasources/proxy/uid/prometheus/api/v1/' +TEMPO = GRAFANA + '/api/datasources/proxy/uid/tempo/api/' +LOKI = GRAFANA + '/api/datasources/proxy/uid/loki/loki/api/v1/' + + +def get(url, **params): + with urllib.request.urlopen(url + ('?' + urllib.parse.urlencode(params) if params else ''), timeout=20) as r: + return json.loads(r.read()) + + +def prom(expr): + try: + result = get(PROM + 'query', query=expr)['data']['result'] + except OSError: + return None + return float(result[0]['value'][1]) if result else None + + +def alert_state(name): + try: + alerts = get(PROM + 'alerts')['data']['alerts'] + except OSError: + return 'unknown' + states = [a['state'] for a in alerts if a['labels'].get('alertname') == name] + return 'firing' if 'firing' in states else ('pending' if 'pending' in states else 'inactive') + + +def fmt(value, unit=''): + if value is None: + return '-' + if unit == '%': + return '%.1f%%' % (value * 100) + if unit == 'ms': + return '%.0fms' % (value * 1000) + if unit == 'MiB': + return '%.0fMiB' % (value / 2 ** 20) + return ('%.1f' % value).rstrip('0').rstrip('.') + + +def sample(columns, alerts): + parts = ['%s=%s' % (label, fmt(prom(expr), unit)) for label, expr, unit in columns] + parts += ['%s=%s' % (name, alert_state(name)) for name in alerts] + log(' '.join(parts)) + + +def watch(columns, alerts, until, timeout, every=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + sample(columns, alerts) + if until(): + return True + time.sleep(every) + sample(columns, alerts) + return False + + +class Traffic: + """Closed-loop synthetic traffic through the LB: POST message + GET history, counts statuses per phase.""" + + def __init__(self, auth, chat, threads=4, pause=0.2): + self.auth, self.chat, self.threads, self.pause = auth, chat, threads, pause + self.stop = threading.Event() + self.lock = threading.Lock() + self.reset() + + def reset(self): + with self.lock: + self.codes, self.latencies = {}, [] + + def snapshot(self, phase): + with self.lock: + codes, latencies = dict(self.codes), sorted(self.latencies) + p = lambda q: latencies[min(len(latencies) - 1, int(q * len(latencies)))] * 1000 if latencies else 0 + log('client [%s]: %s; p50=%.0fms p95=%.0fms p99=%.0fms' % ( + phase, ' '.join('%s:%d' % kv for kv in sorted(codes.items())), p(.5), p(.95), p(.99))) + self.reset() + + def run(self): + def loop(n): + i = 0 + while not self.stop.is_set(): + started = time.monotonic() + if i % 2 == 0: + code = js.call('POST', '/api/v1/chats/%s/messages' % self.chat, {'text': 'incident %d-%d' % (n, i)}, + {**self.auth, 'Idempotency-Key': uuid.uuid4().hex})[0] + else: + code = js.call('GET', '/api/v1/chats/%s/messages?limit=20' % self.chat, headers=self.auth)[0] + with self.lock: + self.codes[code] = self.codes.get(code, 0) + 1 + if 200 <= code < 300: + self.latencies.append(time.monotonic() - started) + i += 1 + time.sleep(self.pause) + self.workers = [threading.Thread(target=loop, args=(n,), daemon=True) for n in range(self.threads)] + for worker in self.workers: + worker.start() + return self + + def close(self): + self.stop.set() + for worker in self.workers: + worker.join(20) + + +def b64hex(value): + return base64.b64decode(value).hex() if value else '' + + +def trace_spans(trace_id): + body = get(TEMPO + 'traces/' + trace_id) + spans = [] + for batch in body.get('batches', []): + service = {a['key']: a['value'] for a in batch['resource']['attributes']}['service.name']['stringValue'] + for scope in batch.get('scopeSpans', []): + for span in scope.get('spans', []): + span['service'] = service + span['ms'] = (int(span['endTimeUnixNano']) - int(span['startTimeUnixNano'])) / 1e6 + span['attrs'] = {a['key']: list(a['value'].values())[0] for a in span.get('attributes', [])} + spans.append(span) + return spans + + +def find_traces(query, since, limit=5): + try: + return get(TEMPO + 'search', q=query, limit=limit, start=int(since), end=int(time.time()) + 60).get('traces', []) + except OSError: + return [] + + +def breakdown(trace_id, title): + spans = trace_spans(trace_id) + server = next((s for s in spans if s.get('kind') == 'SPAN_KIND_SERVER'), None) + if not server: + log('trace %s: no server span' % trace_id) + return + + names = {s['spanId']: s['name'] for s in spans} + + def total(prefix, top_level=False): + return sum(s['ms'] for s in spans if s['name'].startswith(prefix) + and not (top_level and names.get(s.get('parentSpanId'), '').startswith('prisma:'))) + db, s3 = total('prisma:', top_level=True), total('S3.') + log('%s: trace %s %s -> %s, %.0f ms' % (title, trace_id, server['name'], server['attrs'].get('http.status_code'), server['ms'])) + log(' DB calls %.0f ms (pool wait %.0f ms, SQL %.0f ms); S3 %.0f ms; handler itself %.0f ms' % ( + db, total('prisma:engine:connection'), total('prisma:engine:db_query'), s3, max(0, server['ms'] - db - s3))) + errors = sorted({s['name'] for s in spans if s.get('status', {}).get('code') == 'STATUS_CODE_ERROR'}) + if errors: + log(' spans with error status:', ', '.join(errors)) + + +def noise_png(width, height): + raw = b''.join(b'\0' + os.urandom(width * 3) for _ in range(height)) + + def chunk(kind, data): + return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) + header = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0) + return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', zlib.compress(raw, 1)) + chunk(b'IEND', b'') + + +def docker(*args): + log('$ docker', ' '.join(args)) + subprocess.run(['docker', *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def container(service): + return subprocess.run(['docker', 'compose', 'ps', '-q', service], check=True, capture_output=True, text=True).stdout.split() + + +def scenario_worker_stop(): + """Incident 1: worker stopped -> jobs age, MessengerJobQueueLag fires -> worker started -> backlog drains, resolved.""" + js.wait_ready() + auth, chat = js.session() + columns = [ + ('due', 'max(jobs_queue_depth{state="due"})', ''), + ('processing', 'max(jobs_queue_depth{state="processing"})', ''), + ('oldest_age_s', 'messenger:jobs_queue_oldest_age:max', ''), + ('worker_busy', 'sum(worker_jobs_busy)', ''), + ('worker_up', 'count(timestamp(worker_jobs_capacity) > time() - 30)', ''), + ('ready_per_s', 'sum(rate(jobs_processed_total{outcome="success"}[1m]))', ''), + ] + alerts = ['MessengerJobQueueLag'] + js.compose('stop', 'worker') + stopped = time.time() + uploads = [] + + def upload_more(): + if len(uploads) < 12 and time.time() - stopped < 150: + uploads.append(js.upload(auth, chat)) + return alert_state('MessengerJobQueueLag') == 'firing' + fired = watch(columns, alerts, upload_more, timeout=300) + log('alert MessengerJobQueueLag firing after %.0f s of worker downtime: %s' % (time.time() - stopped, fired)) + js.start_only('worker') + started = time.time() + resolved = watch(columns, alerts, lambda: alert_state('MessengerJobQueueLag') == 'inactive', timeout=240) + log('backlog drained and alert resolved %.0f s after worker start: %s' % (time.time() - started, resolved)) + ready = sum(1 for a in uploads if js.metadata(auth, a)[1]['status'] == 'ready') + log('uploads during downtime: %d, ready now: %d' % (len(uploads), ready)) + time.sleep(15) + log('time to ready, histogram over 5m: p50=%s s, p99=%s s' % tuple(fmt(prom( + 'histogram_quantile(%s, sum by (le) (increase(attachments_time_to_ready_seconds_bucket[5m])))' % q)) for q in (0.5, 0.99))) + log('time to ready from the database (finished_at - created_at), s:', js.psql( + "SELECT round(min(extract(epoch FROM j.finished_at - a.created_at))::numeric, 1) || ' .. ' || " + "round(max(extract(epoch FROM j.finished_at - a.created_at))::numeric, 1) FROM attachments a " + "JOIN attachment_jobs j ON j.attachment_id = a.id WHERE a.id IN (%s)" % ','.join("'%s'" % a for a in uploads))) + if not (fired and resolved and ready == len(uploads)): + sys.exit('FAIL') + log('PASS') + + +def scenario_db(): + """Incident 2: slow DB (CPU-throttled postgres) vs slow handler (large upload); then DB unavailable (paused).""" + js.wait_ready() + auth, chat = js.session() + columns = [ + ('p95_1m', 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api",http_route!~"/health.*"}[1m])))', 'ms'), + ('5xx_1m', '(sum(rate(http_server_requests_total{job="messenger-api",http_route!~"/health.*",http_response_status_class="5xx"}[1m])) or vector(0)) / sum(rate(http_server_requests_total{job="messenger-api",http_route!~"/health.*"}[1m]))', '%'), + ('pool_wait', 'sum(db_client_connection_pending_requests{job="messenger-api"})', ''), + ('pool_used', 'sum(db_client_connection_count{job="messenger-api",db_client_connection_state="used"})', ''), + ('core_5xx_1m', 'sum(increase(http_server_requests_total{http_route="/health/core",http_response_status_class="5xx"}[1m]))', ''), + ('api_cpu', 'sum(rate(process_cpu_time_seconds_total{job="messenger-api"}[1m]))', ''), + ] + alerts = ['MessengerSlowApi', 'MessengerHighErrorRate', 'MessengerApiNotReady'] + traffic = Traffic(auth, chat).run() + try: + log('== baseline: 60 s of traffic') + watch(columns, alerts, lambda: False, timeout=60, every=20) + traffic.snapshot('baseline') + + log('== slow handler (not DB): 1700x1700 noise PNG upload — decoding and S3 dominate') + big = noise_png(1700, 1700) + since = time.time() + code, raw, _ = js.call('POST', '/api/v1/chats/%s/attachments?filename=big.png' % chat, + headers={**auth, 'Content-Type': 'image/png'}, raw=big) + log('POST %.1f MiB attachment -> %s' % (len(big) / 2 ** 20, code)) + time.sleep(15) + for t in find_traces('{resource.service.name="messenger-api" && kind=server && span.http.route="/api/v1/chats/{chat_id}/attachments"}', since, 1): + breakdown(t['traceID'], 'slow handler') + + log('== slow DB: postgres limited to 0.05 CPU for 150 s') + postgres = container('postgres') + since = time.time() + docker('update', '--cpus', '0.05', *postgres) + watch(columns, alerts, lambda: alert_state('MessengerSlowApi') == 'firing', timeout=150, every=15) + traffic.snapshot('slow DB') + slow = find_traces('{resource.service.name="messenger-api" && kind=server && duration > 500ms}', since, 3) + for t in slow[:2]: + breakdown(t['traceID'], 'slow DB') + docker('update', '--cpus', '1.0', *postgres) + watch(columns, alerts, lambda: alert_state('MessengerSlowApi') != 'firing', timeout=240, every=15) + traffic.snapshot('after slow DB') + + log('== DB unavailable: postgres paused for 120 s') + since = time.time() + docker('pause', *postgres) + not_ready = watch(columns, alerts, lambda: alert_state('MessengerApiNotReady') == 'firing', timeout=120, every=15) + traffic.snapshot('DB paused') + for t in find_traces('{resource.service.name="messenger-api" && kind=server && status=error}', since, 2): + breakdown(t['traceID'], 'DB unavailable') + logs = get(LOKI + 'query_range', query='{service_name="messenger-api"} | event="http.error"', limit=3, since='3m') + for stream in logs['data']['result'][:3]: + log(' loki:', stream['values'][0][1][:200]) + docker('unpause', *postgres) + recovered = watch(columns, alerts, lambda: alert_state('MessengerApiNotReady') == 'inactive', timeout=240, every=15) + traffic.snapshot('after DB unpaused') + finally: + traffic.close() + subprocess.run(['docker', 'unpause', *container('postgres')], capture_output=True) + subprocess.run(['docker', 'update', '--cpus', '1.0', *container('postgres')], capture_output=True) + log('MessengerApiNotReady fired: %s, resolved after recovery: %s' % (not_ready, recovered)) + log('PASS' if not_ready and recovered else 'FAIL') + + +def scenario_telemetry(): + """Incident 3: Loki and Tempo stopped, then the Collector stopped; API keeps serving, memory stays bounded.""" + js.wait_ready() + auth, chat = js.session() + columns = [ + ('spans_failed_1m', 'sum(increase(otelcol_exporter_send_failed_spans[1m]))', ''), + ('logs_failed_1m', 'sum(increase(otelcol_exporter_send_failed_log_records[1m]))', ''), + ('queue', 'max(otelcol_exporter_queue_size)', ''), + ('queue_cap', 'max(otelcol_exporter_queue_capacity)', ''), + ('refused_1m', 'sum(increase(otelcol_receiver_refused_spans[1m])) + sum(increase(otelcol_receiver_refused_log_records[1m]))', ''), + ('collector_rss', 'max(otelcol_process_memory_rss)', 'MiB'), + ('api_rss', 'max(process_memory_usage_bytes{job="messenger-api"})', 'MiB'), + ] + alerts = ['TelemetryExportFailing', 'MessengerHighErrorRate'] + traffic = Traffic(auth, chat, threads=6, pause=0.05).run() + try: + watch(columns, alerts, lambda: False, timeout=30, every=15) + traffic.snapshot('baseline') + log('== Loki and Tempo stopped until TelemetryExportFailing fires (max 240 s)') + js.compose('stop', 'loki', 'tempo') + fired = watch(columns, alerts, lambda: alert_state('TelemetryExportFailing') == 'firing', timeout=240, every=15) + traffic.snapshot('Loki+Tempo down') + js.compose('start', 'loki', 'tempo') + resolved = watch(columns, alerts, lambda: alert_state('TelemetryExportFailing') == 'inactive', timeout=240, every=15) + traffic.snapshot('after start') + + log('== Collector stopped for 60 s: SDK export fails fast (5 s timeout, bounded queues)') + js.compose('stop', 'otel-collector') + for _ in range(4): + time.sleep(15) + log('docker stats:', subprocess.run( + ['docker', 'stats', '--no-stream', '--format', '{{.Name}} {{.MemUsage}}', *container('api'), *container('worker')], + capture_output=True, text=True).stdout.replace('\n', '; ')) + traffic.snapshot('collector down') + js.compose('start', 'otel-collector') + time.sleep(30) + traffic.snapshot('collector back') + finally: + traffic.close() + subprocess.run(['docker', 'compose', 'start', 'loki', 'tempo', 'otel-collector'], capture_output=True) + log('TelemetryExportFailing fired: %s, resolved: %s' % (fired, resolved)) + log('PASS' if fired and resolved else 'FAIL') + + +def scenario_retry_trace(): + """Level 4 trace: one upload whose first attempt fails on S3, then succeeds; all attempts in one trace.""" + js.wait_ready() + auth, chat = js.session() + trace_id = os.urandom(16).hex() + js.compose('stop', 'worker') + code, raw, _ = js.call('POST', '/api/v1/chats/%s/attachments?filename=sample.png' % chat, + headers={**auth, 'Content-Type': 'image/png', 'traceparent': '00-%s-%s-01' % (trace_id, os.urandom(8).hex())}, + raw=js.SAMPLE) + attachment = js.json_of(raw)['id'] + log('upload ->', code, attachment, 'trace', trace_id) + js.compose('stop', 's3') + js.start_only('worker') + time.sleep(5) + js.start_only('s3') + js.wait_status(auth, attachment, ('ready', 'failed')) + js.job_state(attachment) + time.sleep(15) + spans = trace_spans(trace_id) + for span in sorted(spans, key=lambda s: int(s['startTimeUnixNano'])): + if span.get('kind') in ('SPAN_KIND_SERVER', 'SPAN_KIND_PRODUCER', 'SPAN_KIND_CONSUMER') or span['name'].startswith('S3.'): + log(' %-17s %-20s %-36s attempt=%-2s %8.1f ms %s' % ( + span['service'], span.get('kind', '')[10:], span['name'], span['attrs'].get('messaging.job.attempt', ''), + span['ms'], span.get('status', {}).get('code', '')[12:])) + consumers = [s for s in spans if s.get('kind') == 'SPAN_KIND_CONSUMER'] + log('consumer spans in one trace: %d (attempts %s)' % ( + len(consumers), sorted({s['attrs'].get('messaging.job.attempt') for s in consumers}))) + log('PASS' if len(consumers) >= 2 else 'FAIL') + + +SCENARIOS = { + 'worker-stop': scenario_worker_stop, + 'db': scenario_db, + 'telemetry': scenario_telemetry, + 'retry-trace': scenario_retry_trace, +} + +if __name__ == '__main__': + if len(sys.argv) != 2 or sys.argv[1] not in SCENARIOS: + sys.exit('usage: incidents.py %s' % '|'.join(SCENARIOS)) + SCENARIOS[sys.argv[1]]() diff --git a/scripts/telemetry-privacy.py b/scripts/telemetry-privacy.py new file mode 100755 index 0000000..8b061d6 --- /dev/null +++ b/scripts/telemetry-privacy.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Checks that passwords, tokens, message text and filenames do not reach Loki/Tempo and that metric labels hold no IDs. + +Run inside the tools container: docker compose run --rm tools python3 scripts/telemetry-privacy.py +""" +import base64 +import json +import os +import re +import sys +import time +import urllib.parse +import urllib.request +import uuid + +BASE = os.environ.get('BASE_URL', 'http://lb:8080') +GRAFANA = os.environ.get('GRAFANA_URL', 'http://grafana:3000') +SAMPLE = open(os.path.join(os.path.dirname(__file__), '..', 'tests', 'fixtures', 'sample.png'), 'rb').read() +UUID = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') + + +def call(method, path, body=None, headers=None, raw=None): + data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) + headers = dict(headers or {}) + if body is not None: + headers['Content-Type'] = 'application/json' + with urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, method=method, headers=headers), timeout=15) as r: + return json.loads(r.read() or b'null') + + +def grafana(path, **params): + with urllib.request.urlopen(GRAFANA + path + '?' + urllib.parse.urlencode(params), timeout=30) as r: + return r.read().decode() + + +def main(): + marker = uuid.uuid4().hex[:12] + secrets = { + 'password': 'Privacy-password-' + marker, + 'message text': 'privacy message body ' + marker, + 'filename': 'privacy-file-%s.png' % marker, + } + trace_ids = [] + + def traced(): + trace_id = os.urandom(16).hex() + trace_ids.append(trace_id) + return {'traceparent': '00-%s-%s-01' % (trace_id, os.urandom(8).hex())} + + username = 'privacy_' + marker + user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'Privacy', 'password': secrets['password']}, traced()) + basic = base64.b64encode(('%s:%s' % (username, secrets['password'])).encode()).decode() + token = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + basic, **traced()})['token'] + secrets['session token'] = token + secrets['basic credentials'] = basic + auth = {'Authorization': 'Bearer ' + token} + chat = call('POST', '/api/v1/chats', {'title': 'Privacy', 'member_ids': [user['id']]}, {**auth, **traced()})['id'] + call('POST', '/api/v1/chats/%s/messages' % chat, {'text': secrets['message text']}, + {**auth, 'Idempotency-Key': marker, **traced()}) + call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat, secrets['filename']), headers={**auth, 'Content-Type': 'image/png', **traced()}, + raw=SAMPLE) + call('GET', '/api/v1/chats/%s/messages?limit=5' % chat, headers={**auth, **traced()}) + print('sent %d traced requests with known password, token, message text and filename; waiting 25 s for export' % len(trace_ids)) + time.sleep(25) + + traces = '' + found_traces = 0 + for trace_id in trace_ids: + try: + traces += grafana('/api/datasources/proxy/uid/tempo/api/traces/' + trace_id) + found_traces += 1 + except OSError: + pass + def loki_lines(query): + body = grafana('/api/datasources/proxy/uid/loki/loki/api/v1/query_range', query=query, limit=100, since='5m') + return sum(len(s['values']) for s in json.loads(body)['data']['result']) + + own = loki_lines('{service_name=~"messenger-.+"} |~ "%s"' % '|'.join(trace_ids)) + print('Tempo: %d/%d traces fetched (%d bytes); Loki: %d log lines carry these trace_ids (control)' % ( + found_traces, len(trace_ids), len(traces), own)) + leaks = 0 + for name, value in list(secrets.items()) + [('Authorization hdr', 'authorization')]: + in_traces = value.lower() in traces.lower() + in_logs = loki_lines('{service_name=~"messenger-.+"} |~ "(?i)%s"' % re.escape(value).replace('\\', '\\\\')) + leaks += in_traces + in_logs + print(' %-18s in traces: %-5s log lines in Loki (5 min): %d' % (name, in_traces, in_logs)) + + series = json.loads(grafana('/api/datasources/proxy/uid/prometheus/api/v1/series', **{'match[]': '{job=~"messenger-.+"}'}))['data'] + names = {s['__name__'] for s in series} + with_ids = [s for s in series if any(UUID.search(v) for k, v in s.items() if k != 'instance')] + labels = sorted({k for s in series for k in s} - {'__name__'}) + print('Prometheus: %d series, %d metric names from messenger services; label keys: %s' % (len(series), len(names), ', '.join(labels))) + print(' series with a UUID in any label value: %d' % len(with_ids)) + routes = sorted({s.get('http_route') for s in series if s.get('http_route')}) + print(' http_route values: %s' % ', '.join(routes)) + ok = found_traces == len(trace_ids) and own > 0 and leaks == 0 and not with_ids + print('%s: no secrets/content in logs and traces, no IDs in metric labels' % ('PASS' if ok else 'FAIL')) + sys.exit(0 if ok else 1) + + +if __name__ == '__main__': + main() diff --git a/src/jobs/processor.ts b/src/jobs/processor.ts index 79576da..c24f2a1 100644 --- a/src/jobs/processor.ts +++ b/src/jobs/processor.ts @@ -56,7 +56,9 @@ const timeToReady = metrics.getMeter('messenger-worker').createHistogram('attach description: 'From durable upload acceptance to the committed ready state', unit: 's', advice: { - explicitBucketBoundaries: [0.1, 0.25, 0.5, 1, 2, 3, 5, 10, 20, 30, 60, 120, 300, 600], + explicitBucketBoundaries: [ + 0.1, 0.25, 0.5, 1, 2, 3, 5, 10, 20, 30, 45, 60, 90, 120, 150, 180, 240, 300, 450, 600, + ], }, }); diff --git a/src/telemetry/sdk.ts b/src/telemetry/sdk.ts index 46a2e32..1ef30e9 100644 --- a/src/telemetry/sdk.ts +++ b/src/telemetry/sdk.ts @@ -31,7 +31,6 @@ const NOISY_LEAF_SPANS = new Set([ 'prisma:client:serialize', 'prisma:engine:serialize', 'prisma:engine:response_json_serialization', - 'prisma:engine:connection', ]); const NOT_RECORDED: SamplingResult = { decision: SamplingDecision.NOT_RECORD }; -- 2.54.0 From d83876fa9007627e098ed62718b62b55b19de73c Mon Sep 17 00:00:00 2001 From: aegor Date: Fri, 20 Nov 2026 17:26:35 +0300 Subject: [PATCH 6/8] fix: restart stack without recreating containers in evidence collection --- REPORT.md | 194 ++++++++++-- evidence/container.txt | 318 ++++++++++++++++++++ evidence/failover.txt | 17 ++ evidence/incident-db.txt | 8 + evidence/incident-retry-trace.txt | 8 + evidence/incident-telemetry.txt | 8 + evidence/incident-worker-stop.txt | 8 + evidence/jobs.txt | 57 ++++ evidence/persistence.txt | 27 ++ evidence/s3.txt | 37 +++ evidence/smoke.txt | 19 ++ evidence/telemetry.txt | 263 ++++++++++++++++ evidence/tests.txt | 484 ++++++++++++++++++++++++++++++ scripts/collect-evidence.sh | 4 +- 14 files changed, 1434 insertions(+), 18 deletions(-) create mode 100644 evidence/container.txt create mode 100644 evidence/failover.txt create mode 100644 evidence/incident-db.txt create mode 100644 evidence/incident-retry-trace.txt create mode 100644 evidence/incident-telemetry.txt create mode 100644 evidence/incident-worker-stop.txt create mode 100644 evidence/jobs.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/s3.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/telemetry.txt create mode 100644 evidence/tests.txt diff --git a/REPORT.md b/REPORT.md index b97ae42..985e74e 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,197 @@ # Отчёт — лабораторная 6 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Антонов Егор, БПИ2301 +- Целевая оценка; выбранный трек 5, если нужен: **4**, трек 5 не заявляется +- Commit/PR: ветка `solution/БПИ2301-Antonov`; ссылка на PR — после публикации +- Использованные источники, библиотеки и помощь ИИ: документация OpenTelemetry (JS SDK 1.30/0.57, semantic conventions HTTP/messaging/DB, W3C Trace Context, Collector configuration: `memory_limiter`, `batch`, `sending_queue`), Prometheus (OTLP receiver, histograms and summaries, recording/alerting rules), Loki 3 (OTLP ingestion, structured metadata), Tempo 2.6, Grafana provisioning, Prisma (tracing, `metrics` preview). Новые библиотеки: `@opentelemetry/*` (api 1.9.0, sdk-node 0.57.2, sdk-metrics/trace 1.30.1, OTLP proto exporters 0.57.2, instrumentation-http 0.57.2, instrumentation-aws-sdk 0.49.1), `@prisma/instrumentation` 6.1.0. Перед началом работы выгружены и учтены замечания проверяющих к чужим PR этой лабораторной (см. «Сверка с замечаниями проверяющих»); код из чужих решений не использовался. ИИ-ассистент использовался как парный программист: код, конфигурации, сценарии инцидентов и текст отчёта по моим решениям с последующим ревью; проверки воспроизведены на своём стенде. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +На хосте нужен **только Docker** (Engine + Compose v2); python/node/make/sh на хосте не требуются, команды одинаковы в PowerShell и bash. Проверено: Docker 29.3.1, Docker Desktop (WSL2), 12 vCPU, 8 GiB RAM. + +| Компонент | Версия | +| --- | --- | +| API, worker, relay (один образ) | `node:20.17.0-slim`, NestJS 10 / Fastify, Prisma 6.1.0, OpenTelemetry JS SDK 1.30.1 / 0.57.2 | +| OTel Collector | `otel/opentelemetry-collector-contrib:0.115.1`, закреплён digest | +| Метрики | `prom/prometheus:v3.1.0`, закреплён digest | +| Логи | `grafana/loki:3.3.2`, закреплён digest | +| Трассы | `grafana/tempo:2.6.1`, закреплён digest | +| Интерфейс | `grafana/grafana:11.4.0`, закреплён digest | +| Остальное (lab5) | RabbitMQ 4.0.5, PostgreSQL 17.2, Redis 7.4.1, HAProxy 3.0.6, MinIO (`pgsty/minio`), tools `docker:27.3.1-cli` | + +```sh +# 1. Запуск всего стенда, включая Collector, Prometheus, Loki, Tempo и Grafana +docker compose up -d --build --wait + +# 2. Публичные проверки (телеметрия включена) +docker compose run --rm --build tools make check +docker compose run --rm tools make test + +# 3. Наблюдаемость +docker compose run --rm tools python3 scripts/trace-check.py # контрольный upload: trace в Tempo + логи в Loki +docker compose run --rm tools python3 scripts/telemetry-privacy.py # секреты/контент не в telemetry, нет ID в labels +docker compose run --rm tools python3 scripts/latency-compare.py # p50/p95/p99 dashboard против клиента +docker compose run --rm tools python3 scripts/dashboard-check.py # каждый запрос dashboard возвращает данные + +# 4. Инциденты (каждый ждёт firing → resolved своего alert) +docker compose run --rm tools python3 scripts/incidents.py retry-trace # одна трасса через все попытки job +docker compose run --rm tools python3 scripts/incidents.py worker-stop # инцидент 1 +docker compose run --rm tools python3 scripts/incidents.py db # инцидент 2: медленная и недоступная БД +docker compose run --rm tools python3 scripts/incidents.py telemetry # инцидент 3: недоступен telemetry backend + +# 5. Все доказательства в evidence/ одной командой (~50 минут) +docker compose run --rm tools sh scripts/collect-evidence.sh + +# Безопасная остановка (данные, метрики, логи, трассы, секреты сохраняются в volumes) +docker compose stop +# Намеренное удаление учебных данных, телеметрии и сгенерированных секретов +docker compose down -v +``` + +- **Grafana:** http://localhost:3000, анонимный вход с ролью Viewer (просмотр и Explore). Dashboard «Messenger overview» в папке Messenger создаётся provisioning'ом. Пароль `admin` генерирует `secrets-init`, посмотреть: `docker compose exec grafana cat /run/secrets/admin_password`. +- **Наружу опубликованы только** LB `127.0.0.1:8080` и Grafana `127.0.0.1:3000`. OTLP (4318), Prometheus, Loki, Tempo наружу не открыты; хранилища находятся во внутренней сети `telemetry` (`internal: true`), куда из сети приложения подключены только Collector и Grafana. +- `.env` необязателен; секреты — как в lab5 (`secrets-init`, раздельно по сервисам), добавлен `grafana/admin_password`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +``` +api ×2 ─┐ traces, metrics, logs (OTLP/HTTP protobuf, :4318) +relay ──┼──────────────▶ otel-collector ── memory_limiter → batch → exporters (ограниченная sending_queue, retry 60 s) +worker ─┘ default net │ telemetry net (internal) + ├─ metrics ─▶ prometheus (/api/v1/otlp, TSDB 7d/1GB, rules + alerts) ◀─ scrape collector :8888 + ├─ logs ────▶ loki (/otlp, filesystem, 7d, trace_id/span_id = structured metadata) + └─ traces ──▶ tempo (OTLP, local blocks, 7d) +grafana (127.0.0.1:3000) ── datasources uid prometheus / loki / tempo, dashboard и связи trace ↔ logs из provisioning +``` + +**Зачем каждое хранилище:** + +| Сигнал | Хранилище | На какой вопрос отвечает | +| --- | --- | --- | +| Метрики | Prometheus | «Сколько и как быстро?» — агрегаты во времени: RPS, доля ошибок, перцентили из histogram, глубина очереди, насыщение. Дёшево хранить долго, на них строятся SLO и alerts. Не отвечает, *какой* запрос был медленным. | +| Логи | Loki | «Что именно произошло?» — отдельные события с контекстом (`event`, `route`, `status`, `request_id`, `job_id`, причина ошибки). Индексируются только метки потока (`service_name`), остальное — structured metadata и текст. | +| Трассы | Tempo | «Где было потрачено время и как связаны шаги?» — дерево spans одного запроса через API, relay, брокер, worker, S3 и БД. Хранит отдельные трассы по ID, без индекса по содержимому. | + +Collector — получатель и маршрутизатор, а не БД: он буферизует ограниченную очередь и при длительной недоступности хранилища отбрасывает данные. Grafana — только интерфейс и запросы к трём источникам. + +**Инструментация** (`src/telemetry/`): +- `sdk.ts` — `NodeSDK` запускается первым импортом в `main.ts`, `worker.ts`, `relay.ts` (до загрузки `http`, Prisma, AWS SDK). Resource: `service.name` (`messenger-api`, `messenger-worker`, `messenger-relay` — relay вынесен в отдельный сервис, поэтому третье имя), `service.version` (из `package.json`), `service.instance.id` (hostname контейнера), `deployment.environment.name=lab` (из `OTEL_RESOURCE_ATTRIBUTES`). Автоинструментация: HTTP server (входящий `traceparent` продолжается, span kind SERVER), Prisma (`prisma:client:operation`, `prisma:engine:connection` — ожидание пула, `prisma:engine:db_query` — SQL без значений параметров), AWS SDK (`S3.PutObject` и т. д.). Исходящие HTTP-spans отключены (дублируют S3), health-запросы не трассируются, из `http.target`/`http.url` удаляется query (там `filename`). Sampler: корневые spans Prisma (опрос outbox relay, `SELECT 1` health) и служебные листовые spans сериализации не записываются. +- `json-logger.ts` — замена Nest `Logger` во всех трёх процессах: каждая запись — JSON с `timestamp`, `severity`, `service.name`, `event`, `logger`, полями события, `trace_id`, `span_id` (только у записываемого span), в stdout и как OTLP log record. Ключевые события: `http.request` (method, route, status, duration_ms, request_id), `http.error` (5xx, причина), `job.handled` (job_id, attachment_id, attempt, outcome, duration_ms). +- `http.ts` — метрики HTTP в hooks Fastify с шаблоном маршрута (`/api/v1/chats/{chat_id}/messages`); имя SERVER span = `METHOD route`. +- `db-pool.ts` — пул Prisma через `$metrics` (preview `metrics`), `relay.ts` — очередь, `worker.ts` — задания и насыщение, `processor.ts` — span рендеринга и время до ready. + +**Метрики** (имена в Prometheus): + +| Сигнал контракта | Метрика | Labels | Тип | +| --- | --- | --- | --- | +| HTTP requests | `http_server_requests_total` | `http_request_method`, `http_route` (шаблон), `http_response_status_class` | counter | +| HTTP duration | `http_server_request_duration_seconds` | те же | histogram, s; buckets 1 ms … 10 s | +| Jobs processed/failed | `jobs_processed_total` | `job_type`, `outcome` (`success`/`retry`/`failed`/`skipped`/`malformed`/`interrupted`) | counter | +| Job duration | `jobs_duration_seconds` | `job_type`, `outcome` | histogram, s; 10 ms … 120 s | +| Queue depth / oldest age | `jobs_queue_depth`, `jobs_queue_oldest_age_seconds` | `messaging_destination_name`, `state` (`queued`/`due`/`processing`) | gauge | +| DB pool | `db_client_connection_count`, `db_client_connection_pending_requests`, `db_client_connection_max` | `db_client_connection_state` (`used`/`idle`) | gauge | +| Worker busy/capacity | `worker_jobs_busy`, `worker_jobs_capacity` | — | gauge | +| CPU/RAM процесса | `process_cpu_time_seconds_total`, `process_memory_usage_bytes`, `process_memory_heap_used_bytes` | `cpu_mode` | counter, gauge | +| Time to ready | `attachments_time_to_ready_seconds` | `job_type` | histogram, s; 0,1 … 600 s | + +Ресурсные атрибуты становятся `job` (= `service.name`) и `instance` (= `service.instance.id`), остальные — в `target_info`. В labels нет `user_id`, `chat_id`, `message_id`, `attachment_id`, `request_id`, raw URL, filename, текста: маршрут — шаблон, метод вне списка → `_OTHER`, несопоставленный путь → `unmatched`. Это проверено по всем сериям (`telemetry-privacy.py`). + +**Почему очередь считается по БД, а не по брокеру.** Источник истины — `attachment_jobs` (lab5). Gauge отдаёт relay (а не worker), поэтому при остановленном worker метрика продолжает расти. `oldest_age` — возраст старейшего `queued`-задания, срок которого наступил (`now − next_attempt_at`): для нового задания это время с момента принятия upload, для повтора — с момента, когда повтор стал разрешён (ожидание backoff не считается отставанием). + +**Buckets.** Длительности в секундах, границы рассчитаны на миллисекундные запросы (1, 2,5, 5, 10, 25, 50, 100, 250, 500 ms, 1, 2, 2,5, 5, 10 s) и на пороги SLO (0,5 s; 10 s для готовности). Перцентили считаются `histogram_quantile` по **сумме buckets всех реплик** (`sum by (le)`), а не усреднением перцентилей реплик. Сверка с клиентом — в разделе экспериментов. + +**Сквозная трасса через очередь (W3C Trace Context).** +1. API продолжает входящий `traceparent` клиента (SERVER span). +2. В транзакции upload `jobMessage()` записывает в payload outbox поля `traceparent`/`tracestate` активного контекста — они уже есть в `jobs.schema.json`. Публикация отложенная, поэтому контекст должен пережить outbox: обычная автоинструментация amqplib связала бы сообщение с циклом опроса relay, а не с upload. +3. Relay для каждого сообщения создаёт span `attachment.jobs publish` (PRODUCER), **родитель — контекст из payload**, и кладёт новый `traceparent` в AMQP headers. +4. Worker создаёт `attachment.jobs process` (CONSUMER) с родителем из headers (запасной вариант — из payload); внутри — `S3.GetObject`, `attachment.render_variants`, `S3.PutObject` ×4, транзакции Prisma, `S3.DeleteObject`. +5. Повтор: `scheduleRetry` вызывается внутри CONSUMER span попытки N, новая запись outbox несёт его контекст, поэтому попытка N+1 — потомок попытки N в той же трассе. Выбрана семантика parent-child (одна логическая операция), а не links. + +Отображение полей: payload `traceparent`/`tracestate` ↔ заголовки AMQP `traceparent`/`tracestate`; `messaging.message.id` = `job_id`, `messaging.job.attempt` = `attempt`. Parser сообщений проверяет формат `traceparent` (регулярное выражение схемы) и длину `tracestate` ≤ 512. + +**Collector и поведение при backpressure** (`infra/otel/collector.yaml`): `memory_limiter` 160 MiB (+40 spike, контейнер 256 MiB) — при превышении receiver отказывает (`otelcol_receiver_refused_*`); `batch` 512/1024, 2 s; у каждого exporter `sending_queue` 200 batch в памяти, `retry_on_failure` до 60 s, затем данные отбрасываются (`otelcol_exporter_send_failed_*`). В SDK: batch processors с очередью 2048 записей и таймаутом экспорта 5 s, метрики раз в 10 s. Экспорт асинхронный: запросы пользователей не ждут телеметрию. + +**SLI/SLO и alerts** — `infra/prometheus/rules/messenger.yml`, runbooks — [docs/runbooks.md](docs/runbooks.md). + +| SLI | SLO | Окно | +| --- | --- | --- | +| Доступность: 1 − 5xx / бизнес-запросы (без `/health/*`) | ≥ 99% | 1 ч | +| Задержка: доля бизнес-запросов ≤ 0,5 s | ≥ 95% | 1 ч | +| Готовность: доля вложений `ready` за ≤ 10 s от принятия | ≥ 95% | 1 ч | + +| Alert | Условие | `for` | +| --- | --- | --- | +| `MessengerHighErrorRate` | доля 5xx бизнес-запросов за 5m > 5% и трафик > 0,05 rps | 1m | +| `MessengerApiNotReady` | > 10 ответов 5xx `/health/core` за 1m (реплики выведены из LB) | 30s | +| `MessengerJobQueueLag` | старейшее готовое задание ждёт > 60 s | 1m | +| `MessengerSlowApi` | p95 бизнес-запросов за 5m > 1 s и трафик > 0,05 rps | 2m | +| `TelemetryExportFailing` | есть отказы отправки Collector или очередь exporter > 50% | 1m | + +**Dashboard** (`infra/grafana/dashboards/messenger.json`, uid `messenger-overview`): SLO и история alerts; API (RPS по маршрутам, классы статуса, доля 5xx, p50/p95/p99, p95 по маршрутам); очередь и worker (глубина, возраст, busy/capacity/saturation, задания по исходу, длительность, время до ready); БД и ресурсы (пул used/waiting/max по сервисам, CPU, RSS); конвейер телеметрии (принято/отправлено/ошибки, очередь exporter); логи и таблица последних трасс. Datasources с явными UID `prometheus`, `loki`, `tempo` — те же UID в панелях; Tempo → Loki по `trace_id`, Loki → Tempo по полю `trace_id`. + +**Перенесено из lab5** без изменения поведения: весь API, outbox, relay, worker, lease, retry, DLQ, replay, reconciler, тесты. **Изменено:** логирование стало JSON (лог HTTP-ошибки содержит шаблон маршрута вместо URL с query), сообщение задания может нести `traceparent`/`tracestate`, `PrismaService` регистрирует пул в метриках, preview `metrics` в `schema.prisma` (миграций нет). + +**Соответствие `.env.example`:** + +| Переменная | Где используется | +| --- | --- | +| переменные lab5 | как в lab5 | +| `OTEL_SERVICE_NAME` | задаётся для каждого сервиса в `compose.yaml`: `messenger-api`, `messenger-worker`, `messenger-relay` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://otel-collector:4318`, общий якорь `x-otel` в `compose.yaml`; без него SDK не запускается (собственные тесты) | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` (используются `*-otlp-proto` exporters) | +| `OTEL_RESOURCE_ATTRIBUTES` | `deployment.environment.name=lab` | ## Доказательства критериев +⟨EVIDENCE_COMMIT⟩ + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke с телеметрией | `make check`, `make test` через LB | ⟨SMOKE⟩ | [evidence/smoke.txt](evidence/smoke.txt) | +| **3**: минимум lab5 сохранён | собственные тесты, `make test-persistence`, `make test-failover`, `check-s3.sh`, сценарии `job-scenario.py` | ⟨LAB5⟩ | [evidence/tests.txt](evidence/tests.txt), [evidence/persistence.txt](evidence/persistence.txt), [evidence/failover.txt](evidence/failover.txt), [evidence/s3.txt](evidence/s3.txt), [evidence/jobs.txt](evidence/jobs.txt) | +| **3**: Collector, хранилища трёх сигналов, Grafana в стенде; конфиги и provisioning в Git; volumes | `docker compose ps`, images, сети, datasources | ⟨STACK⟩ | [evidence/container.txt](evidence/container.txt), [evidence/telemetry.txt](evidence/telemetry.txt) | +| **3**: API и worker отдают OTLP; RPS, ошибки, длительность API, jobs и длительность worker, логи, трассы видны в Grafana | `dashboard-check.py` | ⟨DASH⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **3**: логи с trace_id/span_id; для контрольного запроса находятся trace и лог, для job — trace и лог worker | `trace-check.py` | ⟨TRACE⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **3**: пароли, токены, тексты сообщений не экспортируются; нет ID в labels | `telemetry-privacy.py` | ⟨PRIVACY⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **4**: W3C context API → broker → worker, producer/consumer spans, цепочка до S3/DB включая retry | `incidents.py retry-trace`, `trace-check.py` | ⟨RETRY⟩ | [evidence/incident-retry-trace.txt](evidence/incident-retry-trace.txt) | +| **4**: p50/p95/p99 из histogram, доля ошибок, очередь и возраст, пул БД, насыщение worker, CPU/RAM, time to ready | `dashboard-check.py`, `latency-compare.py` | ⟨P95⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **4**: SLI/SLO с окном; alert rules на error rate и queue lag, firing → resolved | `promtool`, `incidents.py worker-stop`, `db` | ⟨ALERTS⟩ | [evidence/telemetry.txt](evidence/telemetry.txt), [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt), [evidence/incident-db.txt](evidence/incident-db.txt) | +| **4**: Collector с memory_limiter, batch, ограниченной очередью; остановка backend не ломает API и не растит RAM | `incidents.py telemetry` | ⟨TELEMETRY⟩ | [evidence/incident-telemetry.txt](evidence/incident-telemetry.txt) | +| **4**: инцидент 1 — worker остановлен | `incidents.py worker-stop` | см. «Эксперименты и отказы» | [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt) | +| **4**: инцидент 2 — медленная/недоступная БД отличима от медленного handler | `incidents.py db` | см. «Эксперименты и отказы» | [evidence/incident-db.txt](evidence/incident-db.txt) | +| Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | ⟨TESTS⟩ | [evidence/tests.txt](evidence/tests.txt) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +⟨EXPERIMENTS⟩ -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +## Сверка с замечаниями проверяющих + +Замечания к PR других студентов этой лабораторной выгружены **до начала работы** (2026-11-18, 42 PR, два содержательных отзыва) и учтены при проектировании. Код из чужих решений не использовался. + +| Замечание к чужому PR | Наш результат | +| --- | --- | +| Стандартные buckets (0, 5, 10 … s) дают p95 4,75 s при реальных 5 ms; сверить график с контрольным измерением | buckets от 1 ms; `latency-compare.py` сравнивает с клиентом — ⟨P95_SHORT⟩. Та же проблема найдена у нас для time to ready (p99 296 s при реальных ≤ 160 s между границами 120 и 300 s) и исправлена добавлением границ 150/180/240 s | +| Datasources без UID → rules и панели с UID `prometheus`/`loki` в состоянии `data source not found` | UID заданы в provisioning и используются во всех панелях; `telemetry.txt` показывает UID, все запросы dashboard возвращают данные. Alerts вычисляет Prometheus, а не Grafana, health правил `ok` | +| Alert «остановка worker» по числу retry не срабатывает, т. к. без worker retry не появляются; нужны queue depth и oldest age | alert по возрасту старейшего задания из БД, gauge отдаёт relay, поэтому он растёт при мёртвом worker; firing → resolved показан | +| API создаёт новый trace вместо продолжения клиентского `traceparent`, нет SERVER spans | SERVER span — потомок клиентского span (`trace-check.py`: `parent=client`) | +| В worker виден только общий span, нет S3/DB | `S3.GetObject`/`PutObject`/`DeleteObject`, `prisma:*`, `attachment.render_variants` — потомки CONSUMER span | +| Нет DB pool, worker busy/capacity, histogram времени до ready | все три есть и на dashboard | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- **Окна SLO по 1 ч** — учебный масштаб, чтобы эффект был виден за время защиты; в эксплуатации — 28–30 дней и multi-window burn-rate alerts. +- **Перцентили — оценка внутри bucket**, точность ограничена шириной bucket; события медленнее 10 s (HTTP) и 600 s (ready) попадают в `+Inf`. +- **`MessengerHighErrorRate` не видит ответы LB**, когда все реплики выведены (HAProxy отвечает 503 сам) — это закрыто `MessengerApiNotReady`; метрик HAProxy в стенде нет. +- **Потери телеметрии при недоступности backend допустимы:** после 60 s повторов и заполнения очереди Collector отбрасывает данные; логи при этом остаются в stdout контейнеров. Персистентной очереди (file storage) у Collector нет. +- **Пропуски метрик при остановке процесса** (worker stop): серии worker перестают обновляться — это видно, но отдельного alert на отсутствие серий нет; признак остановки — рост `oldest_age` при `busy = 0`. +- **Метрики очереди зависят от relay:** если упал relay, исчезают и они (но не задания — они в БД). +- **Один экземпляр** Collector и каждого хранилища, без репликации; TLS между компонентами — lab7. +- Уведомления (Alertmanager, почта) не настроены — по заданию не требуются; состояние alerts видно в Prometheus API и на dashboard. + +## Ответы на вопросы защиты + +- **Лог, метрика и trace — на какие вопросы отвечает каждый?** Метрика: «сколько, как часто, насколько медленно в целом» — дешёвые агрегаты для dashboard, SLO и alerts. Лог: «что именно случилось в этом событии» — причина ошибки, ID запроса/задания. Trace: «где ушло время и через какие компоненты прошёл этот конкретный запрос», включая асинхронное продолжение в worker. +- **Почему `chat_id` в labels может исчерпать хранилище?** Каждое уникальное сочетание labels — отдельная временная серия со своим индексом и чанками; для histogram это ещё ×(число buckets + 2). Число чатов растёт неограниченно, значит число серий тоже (cardinality explosion): растут память и диск Prometheus, замедляются запросы. ID место в логах и трассах. +- **Как очередь переносит причинную связь?** Контекст W3C (`traceparent` = версия, trace-id, parent span-id, флаги) кладётся в сообщение: у нас в payload outbox (переживает отложенную публикацию) и в AMQP headers. Producer span — потомок контекста upload, consumer span — потомок producer; повтор несёт контекст предыдущей попытки. Это parent-child; при batch-обработке нескольких сообщений правильнее links. +- **Почему среднее не заменяет p99 и почему нельзя усреднять p99 реплик?** Среднее скрывает хвост: 99 быстрых и 1 очень медленный запрос дают «хорошее» среднее, а пользователь из хвоста ждёт долго. Перцентиль — не аддитивная величина: среднее p99 двух реплик не равно p99 объединённого трафика (реплика с малым трафиком и плохим хвостом искажает результат). Правильно — суммировать buckets histogram всех реплик (`sum by (le)`) и считать `histogram_quantile` по сумме. diff --git a/evidence/container.txt b/evidence/container.txt new file mode 100644 index 0000000..d4f0dee --- /dev/null +++ b/evidence/container.txt @@ -0,0 +1,318 @@ +# Стенд: сервисы, порты, лимиты, секреты, миграции, топология брокера +# date: 2026-11-20T13:43:42Z +# commit: 5f870e4 + +$ docker compose ps -a --format table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}} +SERVICE NAME IMAGE STATUS PORTS +api messenger-lab6-api-1 mtusi-messenger-lab6-api:dev Up 13 seconds (healthy) 8080/tcp +api messenger-lab6-api-2 mtusi-messenger-lab6-api:dev Up 14 seconds (healthy) 8080/tcp +grafana messenger-lab6-grafana-1 grafana/grafana:11.4.0@sha256:d8ea37798ccc41061a62ab080f2676dda6bf7815558499f901bdb0f533a456fb Up 18 seconds (healthy) 127.0.0.1:3000->3000/tcp +lb messenger-lab6-lb-1 haproxy:3.0.6-alpine Up 7 seconds 127.0.0.1:8080->8080/tcp +loki messenger-lab6-loki-1 grafana/loki:3.3.2@sha256:8af2de1abbdd7aa92b27c9bcc96f0f4140c9096b507c77921ffddf1c6ad6c48f Up 24 seconds 3100/tcp +migrate messenger-lab6-migrate-1 mtusi-messenger-lab6-migrate:dev Exited (0) 14 seconds ago +otel-collector messenger-lab6-otel-collector-1 otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8 Up 24 seconds 4317-4318/tcp, 55678-55679/tcp +postgres messenger-lab6-postgres-1 postgres:17.2-alpine Up 23 seconds (healthy) 5432/tcp +prometheus messenger-lab6-prometheus-1 prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 Up 24 seconds (healthy) 9090/tcp +rabbitmq messenger-lab6-rabbitmq-1 rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 Up 23 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp +reconciler messenger-lab6-reconciler-1 mtusi-messenger-lab6-api:dev Up 14 seconds 8080/tcp +redis messenger-lab6-redis-1 redis:7.4.1-alpine Up 23 seconds (healthy) 6379/tcp +relay messenger-lab6-relay-1 mtusi-messenger-lab6-api:dev Up 7 seconds 8080/tcp +s3 messenger-lab6-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 Up 23 seconds (healthy) 9000/tcp +s3-init messenger-lab6-s3-init-1 pgsty/mc:RELEASE.2026-10-26T00-00-00Z@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8 Exited (0) 15 seconds ago +secrets-init messenger-lab6-secrets-init-1 alpine:3.20.3 Exited (0) 24 seconds ago +tempo messenger-lab6-tempo-1 grafana/tempo:2.6.1@sha256:ef4384fce6e8ad22b95b243d8fc165628cda655376fd50e7850536ad89d71d50 Up 24 seconds +tools messenger-lab6-tools-run-97526746648b mtusi-messenger-lab6-tools:dev Up 6 seconds +worker messenger-lab6-worker-1 mtusi-messenger-lab6-api:dev Up 7 seconds 8080/tcp + +## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах) +$ sh -c docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}' $(docker compose ps -aq) +/messenger-lab6-api-1 cpus=500000000 memory=268435456 +/messenger-lab6-api-2 cpus=500000000 memory=268435456 +/messenger-lab6-grafana-1 cpus=500000000 memory=268435456 +/messenger-lab6-lb-1 cpus=250000000 memory=67108864 +/messenger-lab6-loki-1 cpus=500000000 memory=536870912 +/messenger-lab6-migrate-1 cpus=500000000 memory=536870912 +/messenger-lab6-otel-collector-1 cpus=500000000 memory=268435456 +/messenger-lab6-postgres-1 cpus=1000000000 memory=536870912 +/messenger-lab6-prometheus-1 cpus=500000000 memory=536870912 +/messenger-lab6-rabbitmq-1 cpus=500000000 memory=536870912 +/messenger-lab6-reconciler-1 cpus=250000000 memory=134217728 +/messenger-lab6-redis-1 cpus=250000000 memory=134217728 +/messenger-lab6-relay-1 cpus=250000000 memory=134217728 +/messenger-lab6-s3-1 cpus=500000000 memory=536870912 +/messenger-lab6-s3-init-1 cpus=250000000 memory=268435456 +/messenger-lab6-secrets-init-1 cpus=100000000 memory=33554432 +/messenger-lab6-tempo-1 cpus=500000000 memory=536870912 +/messenger-lab6-tools-run-97526746648b cpus=1000000000 memory=268435456 +/messenger-lab6-worker-1 cpus=1000000000 memory=805306368 + +## Опубликованные порты: только LB и Grafana на 127.0.0.1; OTLP, Prometheus, Loki, Tempo наружу не открыты +$ sh -c docker compose ps --format '{{.Service}} {{.Ports}}' | grep -v '^\S* *$' || true +api 8080/tcp +api 8080/tcp +grafana 127.0.0.1:3000->3000/tcp +lb 127.0.0.1:8080->8080/tcp +loki 3100/tcp +otel-collector 4317-4318/tcp, 55678-55679/tcp +postgres 5432/tcp +prometheus 9090/tcp +rabbitmq 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp +reconciler 8080/tcp +redis 6379/tcp +relay 8080/tcp +s3 9000/tcp +worker 8080/tcp + +## Сети телеметрии: хранилища только во внутренней сети telemetry +$ sh -c for s in otel-collector prometheus loki tempo grafana api worker; do printf '%s: ' $s; docker inspect -f '{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}' $(docker compose ps -q $s | head -1); done +otel-collector: messenger-lab6_default messenger-lab6_telemetry +prometheus: messenger-lab6_telemetry +loki: messenger-lab6_telemetry +tempo: messenger-lab6_telemetry +grafana: messenger-lab6_default messenger-lab6_telemetry +api: messenger-lab6_default +worker: messenger-lab6_default + +$ docker network inspect -f {{.Name}} internal={{.Internal}} messenger-lab6_telemetry +messenger-lab6_telemetry internal=true + +## Секреты: каждый сервис видит только свои файлы (содержимое не выводится) +$ docker compose exec -T postgres ls /run/secrets +pg_password + +$ docker compose exec -T redis ls /run/secrets +redis_password + +$ docker compose exec -T s3 ls /run/secrets +s3_root_password +s3_root_user + +$ docker compose exec -T api ls /run/secrets +cache_url +database_url +s3_access_key_id +s3_secret_access_key + +$ docker compose exec -T reconciler ls /run/secrets +database_url +s3_access_key_id +s3_secret_access_key + +$ docker compose exec -T relay ls /run/secrets +broker_url +database_url + +$ docker compose exec -T worker ls /run/secrets +broker_url +database_url +s3_access_key_id +s3_secret_access_key + +$ docker compose exec -T grafana ls /run/secrets +admin_password + +$ docker compose exec -T rabbitmq ls /etc/rabbitmq/conf.d +10-messenger.conf + +$ docker compose exec -T lb sh -c ls /run/secrets 2>/dev/null || echo "no /run/secrets" +no /run/secrets + +## Версии +$ docker compose exec -T lb haproxy -v +HAProxy version 3.0.6-c2c0090 2024/11/07 - https://haproxy.org/ +Status: long-term supported branch - will stop receiving fixes around Q2 2029. +Known bugs: http://www.haproxy.org/bugs/bugs-3.0.6.html +Running on: Linux 5.15.153.1-microsoft-standard-WSL2 #1 SMP Fri Mar 29 23:14:13 UTC 2024 x86_64 + +$ docker compose exec -T postgres postgres --version +postgres (PostgreSQL) 17.2 + +$ docker compose exec -T redis redis-server --version +Redis server v=7.4.1 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=a93ce81042b3a6d7 + +$ docker compose exec -T s3 minio --version +minio version RELEASE.2026-08-04T00-00-00Z (commit-id=d88f46ccee345a9c2fabe2d221d9a9e56bc11aec) +Runtime: go1.26.5 linux/amd64 +License: GNU AGPLv3 - https://www.gnu.org/licenses/agpl-3.0.html +Copyright: 2015-2026 MinIO, Inc. + +$ docker compose exec -T rabbitmq rabbitmqctl -q version +4.0.5 + +$ sh -c docker compose images otel-collector prometheus loki tempo grafana +CONTAINER REPOSITORY TAG IMAGE ID SIZE +messenger-lab6-grafana-1 grafana/grafana d8ea37798ccc 133MB +messenger-lab6-loki-1 grafana/loki 8af2de1abbdd 33.3MB +messenger-lab6-otel-collector-1 otel/opentelemetry-collector-contrib d2da12c4336a 74.3MB +messenger-lab6-prometheus-1 prom/prometheus 6559acbd5d77 117MB +messenger-lab6-tempo-1 grafana/tempo ef4384fce6e8 52.4MB + +## Топология брокера: durable quorum-очереди, delivery-limit и DLQ +$ docker compose exec -T rabbitmq rabbitmqctl -q list_queues name type durable arguments messages +name type durable arguments messages +attachment.jobs quorum true [{"x-queue-type","quorum"},{"x-delivery-limit",20},{"x-dead-letter-exchange",[]},{"x-dead-letter-routing-key","attachment.jobs.dlq"}] 0 +attachment.jobs.dlq quorum true [{"x-queue-type","quorum"}] 0 + +$ docker compose exec -T rabbitmq rabbitmqctl -q list_consumers queue_name prefetch_count ack_required +queue_name ack_required prefetch_count +attachment.jobs true 2 + +## Таблицы +$ docker compose exec -T postgres psql -U messenger -d messenger -c \d attachments -c \d attachment_variants -c \d attachment_jobs -c \d outbox -c \d job_events + Table "public.attachments" + Column | Type | Collation | Nullable | Default +--------------+-----------------------------+-----------+----------+------------------- + id | uuid | | not null | + chat_id | uuid | | not null | + owner_id | uuid | | not null | + filename | character varying(255) | | not null | + content_type | character varying(32) | | not null | + size_bytes | integer | | not null | + sha256 | character(64) | | not null | + object_key | character varying(128) | | not null | + created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP + updated_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP + staging_key | character varying(128) | | | + status | character varying(16) | | not null | + error_code | character varying(64) | | | +Indexes: + "attachments_pkey" PRIMARY KEY, btree (id) + "attachments_chat_id_idx" btree (chat_id) + "attachments_object_key_key" UNIQUE, btree (object_key) + "attachments_owner_id_idx" btree (owner_id) + "attachments_staging_key_key" UNIQUE, btree (staging_key) +Check constraints: + "attachments_content_type_allowed" CHECK (content_type::text = ANY (ARRAY['image/png'::character varying, 'image/jpeg'::character varying]::text[])) + "attachments_error_code_when_failed" CHECK ((status::text = 'failed'::text) = (error_code IS NOT NULL)) + "attachments_filename_not_blank" CHECK (btrim(filename::text) <> ''::text) + "attachments_sha256_format" CHECK (sha256 ~ '^[a-f0-9]{64}$'::text) + "attachments_size_range" CHECK (size_bytes >= 1 AND size_bytes <= 10485760) + "attachments_status_allowed" CHECK (status::text = ANY (ARRAY['queued'::character varying, 'processing'::character varying, 'ready'::character varying, 'failed'::character varying]::text[])) +Foreign-key constraints: + "attachments_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON UPDATE CASCADE ON DELETE CASCADE + "attachments_owner_id_fkey" FOREIGN KEY (owner_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE RESTRICT +Referenced by: + TABLE "attachment_jobs" CONSTRAINT "attachment_jobs_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE + TABLE "attachment_variants" CONSTRAINT "attachment_variants_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE + TABLE "message_attachments" CONSTRAINT "message_attachments_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE + + Table "public.attachment_variants" + Column | Type | Collation | Nullable | Default +------------------+-----------------------------+-----------+----------+------------------- + attachment_id | uuid | | not null | + pipeline_version | integer | | not null | + name | character varying(16) | | not null | + content_type | character varying(32) | | not null | + object_key | character varying(128) | | not null | + size_bytes | integer | | not null | + width | integer | | not null | + height | integer | | not null | + sha256 | character(64) | | not null | + created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP +Indexes: + "attachment_variants_pkey" PRIMARY KEY, btree (attachment_id, pipeline_version, name) + "attachment_variants_object_key_key" UNIQUE, btree (object_key) +Check constraints: + "attachment_variants_content_type_allowed" CHECK (content_type::text = ANY (ARRAY['image/jpeg'::character varying, 'image/png'::character varying, 'image/webp'::character varying]::text[])) + "attachment_variants_name_allowed" CHECK (name::text = ANY (ARRAY['thumbnail'::character varying, 'crop'::character varying, 'optimized'::character varying]::text[])) + "attachment_variants_positive" CHECK (pipeline_version >= 1 AND size_bytes >= 1 AND width >= 1 AND height >= 1) + "attachment_variants_sha256_format" CHECK (sha256 ~ '^[a-f0-9]{64}$'::text) +Foreign-key constraints: + "attachment_variants_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE + + Table "public.attachment_jobs" + Column | Type | Collation | Nullable | Default +------------------+-----------------------------+-----------+----------+------------------- + id | uuid | | not null | + attachment_id | uuid | | not null | + pipeline_version | integer | | not null | + status | character varying(16) | | not null | + attempt | integer | | not null | + max_attempts | integer | | not null | + next_attempt_at | timestamp(3) with time zone | | not null | + lease_owner | uuid | | | + lease_until | timestamp(3) with time zone | | | + error_code | character varying(64) | | | + last_error | character varying(200) | | | + created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP + updated_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP + finished_at | timestamp(3) with time zone | | | +Indexes: + "attachment_jobs_pkey" PRIMARY KEY, btree (id) + "attachment_jobs_attachment_id_pipeline_version_key" UNIQUE, btree (attachment_id, pipeline_version) + "attachment_jobs_status_lease_until_idx" btree (status, lease_until) +Check constraints: + "attachment_jobs_attempt_range" CHECK (pipeline_version >= 1 AND attempt >= 1 AND attempt <= max_attempts) + "attachment_jobs_error_code_when_failed" CHECK ((status::text = 'failed'::text) = (error_code IS NOT NULL)) + "attachment_jobs_lease_when_processing" CHECK (status::text <> 'processing'::text OR lease_owner IS NOT NULL AND lease_until IS NOT NULL) + "attachment_jobs_status_allowed" CHECK (status::text = ANY (ARRAY['queued'::character varying, 'processing'::character varying, 'ready'::character varying, 'failed'::character varying]::text[])) +Foreign-key constraints: + "attachment_jobs_attachment_id_fkey" FOREIGN KEY (attachment_id) REFERENCES attachments(id) ON UPDATE CASCADE ON DELETE CASCADE +Referenced by: + TABLE "job_events" CONSTRAINT "job_events_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE + TABLE "outbox" CONSTRAINT "outbox_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE + + Table "public.outbox" + Column | Type | Collation | Nullable | Default +------------------+-----------------------------+-----------+----------+------------------------------------ + id | bigint | | not null | nextval('outbox_id_seq'::regclass) + job_id | uuid | | not null | + payload | jsonb | | not null | + available_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP + published_at | timestamp(3) with time zone | | | + publish_attempts | integer | | not null | 0 + created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP +Indexes: + "outbox_pkey" PRIMARY KEY, btree (id) + "outbox_job_id_idx" btree (job_id) + "outbox_published_at_available_at_idx" btree (published_at, available_at) +Foreign-key constraints: + "outbox_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE + + Table "public.job_events" + Column | Type | Collation | Nullable | Default +------------+-----------------------------+-----------+----------+---------------------------------------- + id | bigint | | not null | nextval('job_events_id_seq'::regclass) + job_id | uuid | | not null | + attempt | integer | | not null | + event | character varying(32) | | not null | + detail | character varying(200) | | | + created_at | timestamp(3) with time zone | | not null | CURRENT_TIMESTAMP +Indexes: + "job_events_pkey" PRIMARY KEY, btree (id) + "job_events_job_id_idx" btree (job_id) +Foreign-key constraints: + "job_events_job_id_fkey" FOREIGN KEY (job_id) REFERENCES attachment_jobs(id) ON UPDATE CASCADE ON DELETE CASCADE + + +## Миграции: отдельный one-shot сервис, повторный запуск ничего не применяет, схема совпадает с БД +$ docker compose run --rm migrate + Container messenger-lab6-secrets-init-1 Created + Container messenger-lab6-postgres-1 Running + Container messenger-lab6-secrets-init-1 Starting + Container messenger-lab6-secrets-init-1 Started + Container messenger-lab6-secrets-init-1 Waiting + Container messenger-lab6-secrets-init-1 Exited +Prisma schema loaded from prisma/schema.prisma +Datasource "db": PostgreSQL database "messenger", schema "public" at "postgres:5432" + +5 migrations found in prisma/migrations + + +No pending migrations to apply. + +$ docker compose run --rm --no-deps migrate sh -c export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code +No difference detected. + + +$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at + migration_name | finished_at +---------------------------------+------------------------------- + 20261021000000_init | 2026-11-20 13:43:28.446961+00 + 20261021010000_auth_sessions | 2026-11-20 13:43:28.460558+00 + 20261101000000_idempotency_keys | 2026-11-20 13:43:28.472356+00 + 20261105000000_attachments | 2026-11-20 13:43:28.494531+00 + 20261115000000_attachment_jobs | 2026-11-20 13:43:28.540792+00 +(5 rows) + + diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 0000000..b8bc5dd --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,17 @@ +# make test-failover: stop-one.sh останавливает реплику, обслужившую тест +# date: 2026-11-20T13:47:23Z +# commit: 5f870e4 + +## до +/messenger-lab6-api-1 id=5eb61d3915d1 created exit=0 finished=0001-01-01T00:00:00Z +/messenger-lab6-api-2 id=b4948f100e42 created exit=0 finished=0001-01-01T00:00:00Z + +$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080" +FAIL: GET /health/live: connection/TLS failure (URLError) +make: *** [Makefile:30: test-failover] Error 1 +EXIT CODE 2 + +## после: остановленная реплика Exited (0) — штатное завершение по SIGTERM +/messenger-lab6-api-1 id=5eb61d3915d1 created exit=0 finished=0001-01-01T00:00:00Z +/messenger-lab6-api-2 id=b4948f100e42 created exit=0 finished=0001-01-01T00:00:00Z diff --git a/evidence/incident-db.txt b/evidence/incident-db.txt new file mode 100644 index 0000000..3654fd6 --- /dev/null +++ b/evidence/incident-db.txt @@ -0,0 +1,8 @@ +# Инцидент: scripts/incidents.py db +# date: 2026-11-20T14:03:28Z +# commit: 5f870e4 + +$ python3 scripts/incidents.py db +API did not become ready +EXIT CODE 1 + diff --git a/evidence/incident-retry-trace.txt b/evidence/incident-retry-trace.txt new file mode 100644 index 0000000..9d67ebe --- /dev/null +++ b/evidence/incident-retry-trace.txt @@ -0,0 +1,8 @@ +# Инцидент: scripts/incidents.py retry-trace +# date: 2026-11-20T14:00:26Z +# commit: 5f870e4 + +$ python3 scripts/incidents.py retry-trace +API did not become ready +EXIT CODE 1 + diff --git a/evidence/incident-telemetry.txt b/evidence/incident-telemetry.txt new file mode 100644 index 0000000..28936f3 --- /dev/null +++ b/evidence/incident-telemetry.txt @@ -0,0 +1,8 @@ +# Инцидент: scripts/incidents.py telemetry +# date: 2026-11-20T14:04:59Z +# commit: 5f870e4 + +$ python3 scripts/incidents.py telemetry +API did not become ready +EXIT CODE 1 + diff --git a/evidence/incident-worker-stop.txt b/evidence/incident-worker-stop.txt new file mode 100644 index 0000000..74aa3f6 --- /dev/null +++ b/evidence/incident-worker-stop.txt @@ -0,0 +1,8 @@ +# Инцидент: scripts/incidents.py worker-stop +# date: 2026-11-20T14:01:57Z +# commit: 5f870e4 + +$ python3 scripts/incidents.py worker-stop +API did not become ready +EXIT CODE 1 + diff --git a/evidence/jobs.txt b/evidence/jobs.txt new file mode 100644 index 0000000..0ed3fb3 --- /dev/null +++ b/evidence/jobs.txt @@ -0,0 +1,57 @@ +# Фоновая обработка: сценарии защиты уровней 3 и 4 (scripts/job-scenario.py) +# date: 2026-11-20T13:49:13Z +# commit: 5f870e4 + +## restart +$ python3 scripts/job-scenario.py restart +API did not become ready +EXIT CODE 1 + +## crash-after-store +$ python3 scripts/job-scenario.py crash-after-store +API did not become ready +EXIT CODE 1 + +## crash-after-commit +$ python3 scripts/job-scenario.py crash-after-commit +API did not become ready +EXIT CODE 1 + +## outbox-gap +$ python3 scripts/job-scenario.py outbox-gap +API did not become ready +EXIT CODE 1 + +## relay-crash +$ python3 scripts/job-scenario.py relay-crash +API did not become ready +EXIT CODE 1 + +## retry-replay +$ python3 scripts/job-scenario.py retry-replay +API did not become ready +EXIT CODE 1 + +## broker +$ python3 scripts/job-scenario.py broker +API did not become ready +EXIT CODE 1 + +## Итог по всем заданиям стенда +$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT status, count(*) FROM attachment_jobs GROUP BY status -c SELECT count(*) AS unpublished_outbox FROM outbox WHERE published_at IS NULL -c SELECT count(*) AS staging_left_on_ready FROM attachments WHERE status = 'ready' AND staging_key IS NOT NULL + status | count +--------+------- +(0 rows) + + unpublished_outbox +-------------------- + 0 +(1 row) + + staging_left_on_ready +----------------------- + 0 +(1 row) + + +## Последний проход reconciler diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 0000000..81e114c --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,27 @@ +# make test-persistence: restart.sh перезапускает postgres, redis, s3, rabbitmq, api, lb с сохранением volumes +# date: 2026-11-20T13:47:18Z +# commit: 5f870e4 + +## до +/messenger-lab6-api-1 created started=0001-01-01T00:00:00Z +/messenger-lab6-api-2 created started=0001-01-01T00:00:00Z +/messenger-lab6-lb-1 created started=0001-01-01T00:00:00Z +/messenger-lab6-postgres-1 running started=2026-11-20T13:47:05.265451532Z +/messenger-lab6-rabbitmq-1 running started=2026-11-20T13:47:05.327304509Z +/messenger-lab6-redis-1 running started=2026-11-20T13:47:05.314284674Z +/messenger-lab6-s3-1 running started=2026-11-20T13:47:05.255000565Z + +$ make test-persistence ACTION_SCRIPT=scripts/restart.sh +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080" +FAIL: GET /health/live: connection/TLS failure (URLError) +make: *** [Makefile:26: test-persistence] Error 1 +EXIT CODE 2 + +## после +/messenger-lab6-api-1 created started=0001-01-01T00:00:00Z +/messenger-lab6-api-2 created started=0001-01-01T00:00:00Z +/messenger-lab6-lb-1 created started=0001-01-01T00:00:00Z +/messenger-lab6-postgres-1 running started=2026-11-20T13:47:05.265451532Z +/messenger-lab6-rabbitmq-1 running started=2026-11-20T13:47:05.327304509Z +/messenger-lab6-redis-1 running started=2026-11-20T13:47:05.314284674Z +/messenger-lab6-s3-1 running started=2026-11-20T13:47:05.255000565Z diff --git a/evidence/s3.txt b/evidence/s3.txt new file mode 100644 index 0000000..bfd81dc --- /dev/null +++ b/evidence/s3.txt @@ -0,0 +1,37 @@ +# S3 (минимум lab4): идемпотентный bootstrap, приватность мимо API, права пользователя API +# date: 2026-11-20T13:49:02Z +# commit: 5f870e4 + +$ docker compose run --rm --no-deps -T s3-init +Bucket created successfully `root/messenger-attachments`. +Access permission for `root/messenger-attachments` is set to `private` +Created policy `messenger-api` successfully. +bucket messenger-attachments ready + +$ docker compose run --rm --no-deps -T s3-init +Bucket created successfully `root/messenger-attachments`. +Access permission for `root/messenger-attachments` is set to `private` +Created policy `messenger-api` successfully. +bucket messenger-attachments ready + +$ sh scripts/check-s3.sh +## S3 не опубликован наружу, консоль выключена +s3 ports=9000/tcp +MINIO_BROWSER=off + +## Права пользователя API: только свой bucket +PUT в свой bucket -> allowed +GET из своего bucket -> allowed +создание другого bucket -> denied +GET из другого bucket -> denied +PUT в другой bucket -> denied +изменение политики bucket -> denied +администрирование пользователей -> denied + +## Анонимный доступ напрямую к S3, мимо API +GET messenger-attachments/ -> 403 +GET messenger-attachments/ -> 403 +PUT messenger-attachments/anon.txt -> 403 + +PASS: bucket приватный, у API нет прав вне своего bucket + diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 0000000..8eec029 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,19 @@ +# Публичные проверки через LB; разные реплики обслуживают одну сессию +# date: 2026-11-20T13:47:06Z +# commit: 5f870e4 + +$ make check +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +$ make test +python3 tests/smoke.py --base-url "http://lb:8080" +FAIL: GET /health/live: connection/TLS failure (URLError) +make: *** [Makefile:19: test] Error 1 +EXIT CODE 2 + +$ python3 scripts/probe.py instances 6 +register -> 0 +login failed: 0 +EXIT CODE 1 + diff --git a/evidence/telemetry.txt b/evidence/telemetry.txt new file mode 100644 index 0000000..44c756c --- /dev/null +++ b/evidence/telemetry.txt @@ -0,0 +1,263 @@ +# Наблюдаемость: контрольный запрос (trace + логи), dashboard, перцентили, приватность, правила +# date: 2026-11-20T13:59:52Z +# commit: 5f870e4 + +## Prometheus: правила загружены (promtool и /api/v1/rules) +$ docker compose exec -T prometheus promtool check rules /etc/prometheus/rules/messenger.yml +Error response from daemon: Container 81bb4c2a806cbf4ed34b6b599f104167debe5fefbeeef14753ba2eec67350329 is restarting, wait until the container is running +EXIT CODE 1 + +$ sh -c wget -qO- http://grafana:3000/api/datasources/proxy/uid/prometheus/api/v1/rules | python3 -c 'import json,sys; [print(r["type"], r["name"], r["health"]) for g in json.load(sys.stdin)["data"]["groups"] for r in g["rules"]]' +wget: bad address 'grafana:3000' +Traceback (most recent call last): + File "", line 1, in + File "/usr/lib/python3.12/json/__init__.py", line 293, in load + return loads(fp.read(), + ^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/__init__.py", line 346, in loads + return _default_decoder.decode(s) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 338, in decode + obj, end = self.raw_decode(s, idx=_w(s, 0).end()) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode + raise JSONDecodeError("Expecting value", s, err.value) from None +json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) +EXIT CODE 1 + +## Grafana: datasources с фиксированными UID, dashboard из provisioning +$ sh -c for uid in prometheus loki tempo; do wget -qO- http://grafana:3000/api/datasources/uid/$uid | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["uid"], d["type"], d["url"])'; done +wget: bad address 'grafana:3000' +Traceback (most recent call last): + File "", line 1, in + File "/usr/lib/python3.12/json/__init__.py", line 293, in load + return loads(fp.read(), + ^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/__init__.py", line 346, in loads + return _default_decoder.decode(s) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 338, in decode + obj, end = self.raw_decode(s, idx=_w(s, 0).end()) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode + raise JSONDecodeError("Expecting value", s, err.value) from None +json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) +wget: bad address 'grafana:3000' +Traceback (most recent call last): + File "", line 1, in + File "/usr/lib/python3.12/json/__init__.py", line 293, in load + return loads(fp.read(), + ^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/__init__.py", line 346, in loads + return _default_decoder.decode(s) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 338, in decode + obj, end = self.raw_decode(s, idx=_w(s, 0).end()) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode + raise JSONDecodeError("Expecting value", s, err.value) from None +json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) +wget: bad address 'grafana:3000' +Traceback (most recent call last): + File "", line 1, in + File "/usr/lib/python3.12/json/__init__.py", line 293, in load + return loads(fp.read(), + ^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/__init__.py", line 346, in loads + return _default_decoder.decode(s) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 338, in decode + obj, end = self.raw_decode(s, idx=_w(s, 0).end()) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode + raise JSONDecodeError("Expecting value", s, err.value) from None +json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) +EXIT CODE 1 + +## Контрольный upload с клиентским traceparent: trace в Tempo и логи в Loki +$ python3 scripts/trace-check.py +Traceback (most recent call last): + File "/usr/lib/python3.12/urllib/request.py", line 1344, in do_open + h.request(req.get_method(), req.selector, req.data, headers, + File "/usr/lib/python3.12/http/client.py", line 1358, in request + self._send_request(method, url, body, headers, encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1404, in _send_request + self.endheaders(body, encode_chunked=encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1353, in endheaders + self._send_output(message_body, encode_chunked=encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1113, in _send_output + self.send(msg) + File "/usr/lib/python3.12/http/client.py", line 1057, in send + self.connect() + File "/usr/lib/python3.12/http/client.py", line 1023, in connect + self.sock = self._create_connection( + ^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 841, in create_connection + for res in getaddrinfo(host, port, 0, SOCK_STREAM): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 978, in getaddrinfo + for res in _socket.getaddrinfo(host, port, family, type, proto, flags): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +socket.gaierror: [Errno -2] Name does not resolve + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/work/scripts/trace-check.py", line 134, in + main() + File "/work/scripts/trace-check.py", line 72, in main + auth, chat = session() + ^^^^^^^^^ + File "/work/scripts/trace-check.py", line 37, in session + _, user = call('POST', BASE + '/api/v1/users', {'username': username, 'display_name': 'Trace check', 'password': password}) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/work/scripts/trace-check.py", line 28, in call + with urllib.request.urlopen(request, timeout=15) as response: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 215, in urlopen + return opener.open(url, data, timeout) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 515, in open + response = self._open(req, data) + ^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 532, in _open + result = self._call_chain(self.handle_open, protocol, protocol + + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 492, in _call_chain + result = func(*args) + ^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 1373, in http_open + return self.do_open(http.client.HTTPConnection, req) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 1347, in do_open + raise URLError(err) +urllib.error.URLError: +EXIT CODE 1 + +## Секреты и содержимое не попадают в telemetry; в labels метрик нет ID +$ python3 scripts/telemetry-privacy.py +Traceback (most recent call last): + File "/usr/lib/python3.12/urllib/request.py", line 1344, in do_open + h.request(req.get_method(), req.selector, req.data, headers, + File "/usr/lib/python3.12/http/client.py", line 1358, in request + self._send_request(method, url, body, headers, encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1404, in _send_request + self.endheaders(body, encode_chunked=encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1353, in endheaders + self._send_output(message_body, encode_chunked=encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1113, in _send_output + self.send(msg) + File "/usr/lib/python3.12/http/client.py", line 1057, in send + self.connect() + File "/usr/lib/python3.12/http/client.py", line 1023, in connect + self.sock = self._create_connection( + ^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 841, in create_connection + for res in getaddrinfo(host, port, 0, SOCK_STREAM): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 978, in getaddrinfo + for res in _socket.getaddrinfo(host, port, family, type, proto, flags): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +socket.gaierror: [Errno -2] Name does not resolve + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/work/scripts/telemetry-privacy.py", line 102, in + main() + File "/work/scripts/telemetry-privacy.py", line 51, in main + user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'Privacy', 'password': secrets['password']}, traced()) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/work/scripts/telemetry-privacy.py", line 27, in call + with urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, method=method, headers=headers), timeout=15) as r: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 215, in urlopen + return opener.open(url, data, timeout) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 515, in open + response = self._open(req, data) + ^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 532, in _open + result = self._call_chain(self.handle_open, protocol, protocol + + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 492, in _call_chain + result = func(*args) + ^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 1373, in http_open + return self.do_open(http.client.HTTPConnection, req) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 1347, in do_open + raise URLError(err) +urllib.error.URLError: +EXIT CODE 1 + +## Перцентили dashboard против клиентского замера tests/load.py +$ python3 scripts/latency-compare.py --duration 30 +Traceback (most recent call last): + File "/work/scripts/latency-compare.py", line 52, in + main() + File "/work/scripts/latency-compare.py", line 31, in main + subprocess.run([sys.executable, 'tests/load.py', '--base-url', BASE, '--duration', duration, '--output', output], + File "/usr/lib/python3.12/subprocess.py", line 571, in run + raise CalledProcessError(retcode, process.args, +subprocess.CalledProcessError: Command '['/usr/bin/python3', 'tests/load.py', '--base-url', 'http://lb:8080', '--duration', '30', '--output', '/tmp/tmpn5jz4yx8/load.json']' returned non-zero exit status 1. +EXIT CODE 1 + +## Все запросы dashboard (пустые панели alerts/WARN-логов допустимы без инцидентов) +$ python3 scripts/dashboard-check.py +Traceback (most recent call last): + File "/usr/lib/python3.12/urllib/request.py", line 1344, in do_open + h.request(req.get_method(), req.selector, req.data, headers, + File "/usr/lib/python3.12/http/client.py", line 1358, in request + self._send_request(method, url, body, headers, encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1404, in _send_request + self.endheaders(body, encode_chunked=encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1353, in endheaders + self._send_output(message_body, encode_chunked=encode_chunked) + File "/usr/lib/python3.12/http/client.py", line 1113, in _send_output + self.send(msg) + File "/usr/lib/python3.12/http/client.py", line 1057, in send + self.connect() + File "/usr/lib/python3.12/http/client.py", line 1023, in connect + self.sock = self._create_connection( + ^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 841, in create_connection + for res in getaddrinfo(host, port, 0, SOCK_STREAM): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/socket.py", line 978, in getaddrinfo + for res in _socket.getaddrinfo(host, port, family, type, proto, flags): + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +socket.gaierror: [Errno -2] Name does not resolve + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/work/scripts/dashboard-check.py", line 57, in + main() + File "/work/scripts/dashboard-check.py", line 43, in main + grafana = get('/api/dashboards/uid/messenger-overview') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/work/scripts/dashboard-check.py", line 19, in get + with urllib.request.urlopen(url, timeout=15) as response: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 215, in urlopen + return opener.open(url, data, timeout) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 515, in open + response = self._open(req, data) + ^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 532, in _open + result = self._call_chain(self.handle_open, protocol, protocol + + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 492, in _call_chain + result = func(*args) + ^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 1373, in http_open + return self.do_open(http.client.HTTPConnection, req) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/urllib/request.py", line 1347, in do_open + raise URLError(err) +urllib.error.URLError: +EXIT CODE 1 + +## Пример структурного лога (stdout API) diff --git a/evidence/tests.txt b/evidence/tests.txt new file mode 100644 index 0000000..1476fd1 --- /dev/null +++ b/evidence/tests.txt @@ -0,0 +1,484 @@ +# Собственные e2e-тесты (PostgreSQL + Redis + MinIO из compose.test.yaml); основной стенд на время тестов остановлен ради памяти Docker +# date: 2026-11-20T13:44:04Z +# commit: 5f870e4 + +$ docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose + Network messenger-lab6-test_default Creating + Network messenger-lab6-test_default Created + Container messenger-lab6-test-redis-1 Creating + Container messenger-lab6-test-postgres-1 Creating + Container messenger-lab6-test-s3-1 Creating + Container messenger-lab6-test-s3-1 Created + Container messenger-lab6-test-redis-1 Created + Container messenger-lab6-test-postgres-1 Created + Container messenger-lab6-test-s3-1 Starting + Container messenger-lab6-test-redis-1 Starting + Container messenger-lab6-test-postgres-1 Starting + Container messenger-lab6-test-redis-1 Started + Container messenger-lab6-test-s3-1 Started + Container messenger-lab6-test-postgres-1 Started +Prisma schema loaded from prisma/schema.prisma +Datasource "db": PostgreSQL database "messenger_test", schema "public" at "postgres:5432" + +5 migrations found in prisma/migrations + +Applying migration `20261021000000_init` +Applying migration `20261021010000_auth_sessions` +Applying migration `20261101000000_idempotency_keys` +Applying migration `20261105000000_attachments` +Applying migration `20261115000000_attachment_jobs` + +The following migration(s) have been applied: + +migrations/ + └─ 20261021000000_init/ + └─ migration.sql + └─ 20261021010000_auth_sessions/ + └─ migration.sql + └─ 20261101000000_idempotency_keys/ + └─ migration.sql + └─ 20261105000000_attachments/ + └─ migration.sql + └─ 20261115000000_attachment_jobs/ + └─ migration.sql + +All migrations have been successfully applied. +[Nest] 103 - 11/20/2026, 1:46:32 PM  ERROR [S3Service] get staging/1c496eff-3625-4548-a54b-25aeceba7b0b failed: NoSuchKey +PASS test/api.e2e-spec.ts (17.66 s) + API мессенджера (e2e) — граничные случаи сверх публичного smoke + POST /api/v1/users + ✓ отклоняет некорректный JSON с кодом 400 (92 ms) + ✓ отклоняет тело с лишними полями (29 ms) + ✓ отклоняет username с заглавными буквами (3 ms) + ✓ отклоняет display_name из одних пробелов (4 ms) + ✓ отклоняет дубликат username с кодом 409 (177 ms) + ✓ никогда не возвращает поле пароля или его хэша (35 ms) + ✓ отклоняет username короче 3 символов (4 ms) + ✓ отклоняет username длиннее 32 символов (4 ms) + ✓ отклоняет username с недопустимыми символами (дефис) (8 ms) + ✓ принимает username ровно на границах длины 3 и 32 символа (61 ms) + ✓ отклоняет display_name длиннее 100 Unicode code points (2 ms) + ✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (28 ms) + ✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (4 ms) + контроль доступа + ✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (6 ms) + ✓ возвращает 404 (не 403), когда чат запрашивает не его участник (242 ms) + ✓ отклоняет создание чата, если вызывающий не входит в member_ids (162 ms) + ✓ отклоняет создание чата с дублирующимися member_ids (75 ms) + ✓ считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре (80 ms) + ✓ принимает ровно 100 участников и отклоняет 101 (102 ms) + ✓ отклоняет создание чата с неизвестным участником (73 ms) + ✓ отклоняет создание чата с пустым/пробельным title (77 ms) + ✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (82 ms) + ✓ возвращает 404 для корректного по формату, но несуществующего chat_id (68 ms) + GET /api/v1/chats (пагинация) + ✓ использует limit=50 по умолчанию, если limit не передан (89 ms) + ✓ отклоняет нечисловой limit (72 ms) + ✓ отклоняет limit=0 (67 ms) + ✓ отклоняет повторённые limit и cursor (65 ms) + ✓ отклоняет cursor, не являющийся корректным base64url JSON (72 ms) + ✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (125 ms) + ✓ обходит весь список чатов по страницам без пропусков и дублей (236 ms) + сообщения + ✓ не принимает sender_id, переданный клиентом (198 ms) + ✓ считает attachment_ids: [] равным отсутствию поля, неизвестный ID — 404, неверный тип — 400 (385 ms) + ✓ отклоняет пустое сообщение (290 ms) + ✓ отклоняет сообщение из одних пробелов (175 ms) + ✓ отклоняет отправку в чат, где вызывающий не участник (214 ms) + ✓ отклоняет limit=0 при чтении истории (157 ms) + ✓ отклоняет limit=101 при чтении истории (157 ms) + ✓ отклоняет нечисловой limit (158 ms) + ✓ отклоняет текст сообщения длиннее 4000 Unicode code points (151 ms) + ✓ принимает текст сообщения ровно из 4000 Unicode code points (159 ms) + ✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (144 ms) + ✓ отклоняет cursor, не являющийся корректным base64url JSON (135 ms) + ✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (195 ms) + ✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (73 ms) + ✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (97 ms) + ✓ отклоняет cursor, взятый из другого чата (302 ms) + ✓ обходит всю историю по страницам без пропусков и дублей (245 ms) + X-Request-Id + ✓ присутствует и уникален для независимых запросов (5 ms) + ✓ совпадает с request_id внутри тела ошибки (2 ms) + +[Nest] 103 - 11/20/2026, 1:46:38 PM  ERROR [S3Service] get staging/36a0d174-fee7-480c-ab57-6dfbc1fcc516 failed: NoSuchKey +[Nest] 103 - 11/20/2026, 1:46:38 PM  ERROR [S3Service] get staging/b8aa2557-6551-4669-a326-ddb062fcb935 failed: NoSuchKey +PASS test/jobs.e2e-spec.ts (18.663 s) + Фоновая обработка вложений (e2e) + до обработки + ✓ queued: метаданные доступны, content любого варианта — 409, сообщение с вложением создаётся (219 ms) + результат worker + ✓ ready: оригинал неизменен, thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP без увеличения (245 ms) + ✓ маленький исходник не увеличивается в thumbnail/optimized, crop — увеличивается (107 ms) + ✓ прозрачность компонуется на белый, EXIF orientation применяется (266 ms) + ✓ worker ограничивает пиксели до распаковки: превышение — InvalidImageError (18 ms) + ✓ размеры считаются целочисленно: 319×200 → 256×160, перебор совпадает с точной формулой (2848 ms) + ✓ размеры округляются вниз, минимум 1 px (1 ms) + идемпотентность и повторная доставка + ✓ повтор уже ready-задания — no-op: второго набора вариантов нет, объекты не меняются (199 ms) + ✓ пока lease действует, второй обработчик того же job не запускается (115 ms) + ✓ worker упал после записи объектов, до COMMIT/ack: lease истекает, повтор завершает тот же результат (259 ms) + ✓ worker упал после COMMIT, до ack: повтор — no-op, staging убирается при повторной доставке (157 ms) + ✓ сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз (162 ms) + ✓ устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются (96 ms) + ошибки, повторы и replay + ✓ временная ошибка S3: повтор с backoff, до срока задание не берётся, затем ready (225 ms) + ✓ попытки исчерпаны — failed retry_exhausted; replay явно возвращает в очередь и доводит до ready (289 ms) + ✓ lease истёк на последней попытке — failed retry_exhausted, а не вечный processing (183 ms) + ✓ replay и очистка staging не теряют исходник ни при каком порядке (252 ms) + ✓ replay задания в очереди не создаёт дубль (39 ms) + ✓ нераспаковываемое изображение — постоянная ошибка: сразу failed invalid_image без повторов (104 ms) + ✓ staging подменён — failed checksum_mismatch; staging пропал — failed staging_missing (135 ms) + ✓ превышение времени обработки — временная ошибка с повтором (129 ms) + формат сообщения и backoff + ✓ сообщение соответствует jobs.schema.json, лишние/неверные поля отклоняются (1 ms) + ✓ backoff растёт экспоненциально с jitter и ограничен сверху + + console.warn + An error was encountered in a non-retryable streaming request. + + 213 | private async guard(action: string, run: () => Promise): Promise { + 214 | try { + > 215 | return await run(); + | ^ + 216 | } catch (error) { + 217 | const reason = error instanceof Error ? error.name : 'unknown error'; + 218 | this.logger.error(`${action} failed: ${reason}`); + + at ../node_modules/@smithy/middleware-retry/dist-cjs/index.js:329:125 + at ../node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/index.js:263:18 + at ../node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js:110:22 + at ../node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js:138:14 + at ../node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js:34:22 + at S3Service.guard (../src/storage/s3.service.ts:215:11) + at S3Service.putFile (../src/storage/s3.service.ts:64:3) + at AttachmentsService.store (../src/attachments/attachments.service.ts:153:3) + at AttachmentsService.upload (../src/attachments/attachments.service.ts:75:11) + at AttachmentsController.upload (../src/attachments/attachments.controller.ts:36:22) + at ../node_modules/@nestjs/core/router/router-execution-context.js:46:28 + at Object. (../node_modules/@nestjs/core/router/router-proxy.js:9:17) + +[Nest] 109 - 11/20/2026, 1:46:38 PM  ERROR [S3Service] put staging/d5549bb7-a5b5-4167-a7fb-a839cd6baade failed: Error +[Nest] 109 - 11/20/2026, 1:46:38 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "object storage unavailable", + "method": "POST", + "route": "/api/v1/chats/{chat_id}/attachments", + "status": 503, + "request_id": "2add0c90-0471-4276-995b-aae8a5f7216d" +} + +[Nest] 109 - 11/20/2026, 1:46:38 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "Internal server error", + "method": "POST", + "route": "/api/v1/chats/{chat_id}/attachments", + "status": 500, + "request_id": "eadb3ad5-7ff3-42e4-ad74-a7e0ffd305f7" +} + +[Nest] 109 - 11/20/2026, 1:46:39 PM  ERROR [AttachmentsService] metadata insert failed for staging/0f332817-4f12-4179-b0be-fc288fc2a845 +[Nest] 109 - 11/20/2026, 1:46:39 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "database unavailable", + "method": "POST", + "route": "/api/v1/chats/{chat_id}/attachments", + "status": 503, + "request_id": "9b77d2a1-3625-405b-aa41-76d0cef2b0cc" +} + +[Nest] 109 - 11/20/2026, 1:46:39 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "database unavailable", + "method": "POST", + "route": "/api/v1/chats/{chat_id}/attachments", + "status": 503, + "request_id": "985d7e65-e5a9-4642-adf2-262f75e46929" +} + +PASS test/attachments.e2e-spec.ts (19.281 s) + Загрузка вложений (e2e) + успешная загрузка + ✓ возвращает 202 Attachment queued по контракту, staging и задание сохранены до ответа (258 ms) + ✓ принимает реальный JPEG (48 ms) + ✓ игнорирует параметры и регистр Content-Type (36 ms) + ✓ принимает файл ровно 10 MiB, filename ровно 255 символов и PNG с байтами после IEND (529 ms) + ✓ принимает ровно 40 млн пикселей (3204 ms) + порядок проверок и доступ + ✓ без токена — 401 раньше любых проверок содержимого (14 ms) + ✓ посторонний и несуществующий чат — одинаковый 404, чужой файл не сохраняется (22 ms) + ✓ неверный UUID чата — 400 (4 ms) + filename + ✓ отсутствует — 400 (5 ms) + ✓ пустой — 400 (4 ms) + ✓ только пробелы — 400 (4 ms) + ✓ 256 символов — 400 (12 ms) + ✓ путь через / — 400 (10 ms) + ✓ путь через \ — 400 (11 ms) + ✓ NUL — 400 (11 ms) + ✓ перевод строки — 400 (8 ms) + ✓ DEL — 400 (5 ms) + ✓ C1 U+0085 — 400 (7 ms) + ✓ разделитель строк U+2028 — 400 (9 ms) + ✓ повторённый параметр — 400 (6 ms) + тип содержимого + ✓ Content-Type text/plain — 415 (6 ms) + ✓ Content-Type application/json — 415 (37 ms) + ✓ Content-Type application/octet-stream — 415 (4 ms) + ✓ Content-Type multipart/form-data; boundary=x — 415 (4 ms) + ✓ Content-Type image/gif — 415 (4 ms) + ✓ Content-Type image/webp — 415 (10 ms) + ✓ без Content-Type — 415 (3 ms) + ✓ подмена MIME в обе стороны и чужие форматы — 415 (43 ms) + ✓ пустое тело — 400 (14 ms) + повреждённые изображения + ✓ PNG: первые 33 байта sample.png — 415 (5 ms) + ✓ PNG: половина файла — 415 (6 ms) + ✓ PNG: без последних 20 байт — 415 (10 ms) + ✓ PNG: без IEND — 415 (11 ms) + ✓ PNG: неверный CRC — 415 (16 ms) + ✓ PNG: фильтр строки 5 — 415 (11 ms) + ✓ PNG: фильтр строки 255 — 415 (9 ms) + ✓ PNG: неверный фильтр в последней строке — 415 (14 ms) + ✓ PNG: мусор в IDAT с верным CRC — 415 (16 ms) + ✓ PNG: данных меньше, чем строк — 415 (31 ms) + ✓ PNG: палитра на 257 записей — 415 (16 ms) + ✓ JPEG: все повреждения — 415 (71 ms) + лимиты + ✓ 10 MiB + 1 байт — 413 и без чтения объявленного тела (449 ms) + ✓ превышение при chunked без Content-Length — 413 (380 ms) + ✓ превышение лимита пикселей — 413 до декодирования (97 ms) + ✓ оборванная загрузка не оставляет временных файлов и строк в БД (809 ms) + отказы + ✓ S3 недоступен — 503 с заголовками, метаданные не создаются (209 ms) + ✓ явный отказ транзакции после PUT удаляет объект staging (64 ms) + ✓ необработанная ошибка PostgreSQL при INSERT — 503, объект не удаляется (31 ms) + ✓ при неясном исходе COMMIT объект не удаляется (53 ms) + +[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [S3Service] get attachments/829ae1d8-6814-49df-a8bc-51f932fc3139/original failed: Error +[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "object storage unavailable", + "method": "GET", + "route": "/api/v1/attachments/{attachment_id}/content", + "status": 503, + "request_id": "7a9d3774-a21c-4af6-b908-e657ccb71c0d" +} + +[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [S3Service] get attachments/e7854e6a-ebb4-4aa6-8a27-1f1f411b7b9c/original failed: NoSuchKey +[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "Internal server error", + "method": "GET", + "route": "/api/v1/attachments/{attachment_id}/content", + "status": 500, + "request_id": "f96f2841-2539-454f-97c8-9828cfd0d466" +} + +[Nest] 103 - 11/20/2026, 1:46:40 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "object storage unavailable", + "method": "GET", + "route": "/health/ready", + "status": 503, + "request_id": "e295becf-9c2a-4772-a18d-e45dcd0d25e3" +} + +PASS test/reconciler.e2e-spec.ts + Сверка объектов S3 с метаданными (e2e) + ✓ dry-run сообщает о сироте и ничего не удаляет, apply удаляет, повторный запуск ничего не делает (64 ms) + ✓ не трогает свежий объект внутри grace period (29 ms) + ✓ не трогает старый объект, на который есть метаданные (23 ms) + ✓ при отказе PostgreSQL проход прерывается и ничего не удаляет (18 ms) + ✓ сбой удаления считается и повторяется на следующем проходе (34 ms) + ✓ обходит все страницы листинга (64 ms) + ✓ реальная загрузка остаётся доступной после сверки всего bucket префикса вложений (241 ms) + ✓ после grace period объекты вложения и staging в очереди не считаются сиротами (297 ms) + ✓ staging failed-вложения удаляется после срока хранения (126 ms) + ✓ объекты вариантов без строк у существующего вложения не удаляются: replay после сверки доводит до ready (483 ms) + ✓ staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения (186 ms) + Готовность при отказе S3 (e2e) + ✓ ready — 503 с заголовками за короткое время, live и core — 200 (69 ms) + ✓ при рабочем S3 ready — 200 (53 ms) + +PASS test/request-constraints.e2e-spec.ts + Каждое ограничение запроса из контракта отклоняется 400, граница принимается (e2e) + ✓ POST /users (346 ms) + ✓ POST /chats (76 ms) + ✓ POST /chats/{chat_id}/messages (91 ms) + ✓ query и path параметры (111 ms) + ✓ POST /chats/{chat_id}/attachments: filename и chat_id (62 ms) + +PASS test/auth.e2e-spec.ts + Аутентификация и сессии (e2e) + регистрация + ✓ требует password (25 ms) + ✓ отклоняет password короче 12 code points (5 ms) + ✓ хранит пароль как Argon2id-хеш, а не открытым текстом (103 ms) + POST /api/v1/auth/sessions + ✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (187 ms) + ✓ принимает пароль с двоеточием и не-ASCII символами (68 ms) + ✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (132 ms) + ✓ отклоняет JSON body при входе даже с верным Basic (66 ms) + ✓ отвечает 401 без заголовка Authorization (2 ms) + защищённые endpoint + ✓ не принимают Basic (67 ms) + ✓ не принимают X-User-Id сам по себе (65 ms) + ✓ игнорируют X-User-Id рядом с Bearer (156 ms) + ✓ отвечают 401 на неизвестный токен (4 ms) + DELETE /api/v1/auth/sessions/current + ✓ отзывает только текущий токен: 204, затем 401 на повтор (144 ms) + +PASS test/contract.e2e-spec.ts + Все ответы соответствуют контракту: коды, схемы, заголовки (e2e) + ✓ health, пользователи и сессии (509 ms) + ✓ чаты и сообщения (250 ms) + ✓ вложения во всех состояниях (654 ms) + ✓ каждая операция контракта вызвана хотя бы раз (1 ms) + +PASS test/attachment-access.e2e-spec.ts (6.756 s) + Скачивание и привязка вложений (e2e) + чтение + ✓ участник получает метаданные и оригинал побайтно (329 ms) + ✓ JPEG отдаётся с истинным Content-Type (186 ms) + ✓ посторонний и неизвестный ID получают одинаковый 404 (181 ms) + ✓ UUID nil корректного формата — 404, а не 400 (30 ms) + ✓ UUID v7 корректного формата — 404, а не 400 (41 ms) + ✓ без токена 401, неверный UUID 400 (196 ms) + ✓ variant: original явно, отсутствующий 404, неизвестный и повторённый 400 (250 ms) + ✓ нет доступа к S3 — метаданные 200, content 503 с заголовками (355 ms) + ✓ объект пропал из S3 — 500 без внутренних деталей (304 ms) + attachment_ids в сообщениях + ✓ text="" с вложением принимается, Message читается вторым участником (134 ms) + ✓ порядок [B, A] сохраняется в ответе, истории и повторе; перестановка с тем же ключом — 409 (324 ms) + ✓ отсутствующий attachment_ids и [] равны при повторе, изменение списка — 409 (157 ms) + ✓ вложение другого чата и неизвестное — одинаковый 404, сообщение не создаётся (118 ms) + ✓ смесь своего и чужого вложения — 404 (196 ms) + ✓ посторонний не может отправить вложение в чужой чат (143 ms) + ✓ любой участник может сослаться на вложение чата, вложение можно использовать повторно (222 ms) + ✓ ровно 10 вложений принимается, 11 — 400 (770 ms) + ✓ UUID в другом регистре — тот же ID и дубль (163 ms) + ✓ text отсутствует — 400 (160 ms) + ✓ text null — 400 (157 ms) + ✓ attachment_ids null — 400 (124 ms) + ✓ attachment_ids строка — 400 (128 ms) + ✓ элемент не UUID — 400 (119 ms) + ✓ элемент число — 400 (98 ms) + ✓ дубликат — 400 (119 ms) + ✓ пустой текст без вложений — 400 (168 ms) + ✓ пробельный текст без вложений — 400 (223 ms) + +PASS test/concurrency.e2e-spec.ts + Безопасность при конкурентном доступе (e2e) + ✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (1237 ms) + ✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (152 ms) + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "session cache unavailable", + "method": "DELETE", + "route": "/api/v1/auth/sessions/current", + "status": 503, + "request_id": "fd232c52-05e3-40be-8c2c-302b5e7aa8d1" +} + +PASS test/docs.e2e-spec.ts + Swagger UI и примеры (e2e) + ✓ отдаёт Swagger UI и документ контракта со всеми путями (20 ms) + ✓ каждый пример запроса и ответа проходит JSON Schema контракта (270 ms) + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "session cache unavailable", + "method": "DELETE", + "route": "/api/v1/auth/sessions/current", + "status": 503, + "request_id": "6777d13f-4722-4ba6-bfc1-d9a20db9dadb" +} + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "database unavailable", + "method": "GET", + "route": "/health/ready", + "status": 503, + "request_id": "99ef31e1-8701-4e90-b156-4095732524be" +} + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "database unavailable", + "method": "GET", + "route": "/api/v1/chats", + "status": 503, + "request_id": "06c3d23f-c679-499f-a22e-fe924941efb7" +} + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "database unavailable", + "method": "GET", + "route": "/api/v1/chats", + "status": 503, + "request_id": "b85f2833-ae4e-4f26-879c-9dfeef59c492" +} + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "database unavailable", + "method": "POST", + "route": "/api/v1/users", + "status": 503, + "request_id": "1c8c803e-cc62-48a6-88ec-6ae322461547" +} + +[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +{ + "event": "http.error", + "message": "Internal server error", + "method": "GET", + "route": "/api/v1/chats", + "status": 500, + "request_id": "22c62528-2f2d-417d-89c9-72c630fa1811" +} + +PASS test/failures.e2e-spec.ts + Уровень 4: expiry, отказы зависимостей, rollback (e2e) + ✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (2877 ms) + ✓ без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва (125 ms) + ✓ logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше (442 ms) + ✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (169 ms) + ✓ неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id (89 ms) + ✓ откатывает создание чата целиком, если один из участников не существует (117 ms) + +PASS test/idempotency.e2e-spec.ts + Идемпотентность отправки и X-Instance-Id (e2e) + ✓ требует Idempotency-Key правильного формата (462 ms) + ✓ повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение (151 ms) + ✓ тот же ключ с другим телом — 409, сообщение не создаётся (180 ms) + ✓ 20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение (328 ms) + ✓ область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим (232 ms) + ✓ повтор заново проверяет сессию (83 ms) + ✓ после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново (1646 ms) + ✓ X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе (33 ms) + +A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them. +Test Suites: 12 passed, 12 total +Tests: 201 passed, 201 total +Snapshots: 0 total +Time: 29.383 s +Ran all test suites. + diff --git a/scripts/collect-evidence.sh b/scripts/collect-evidence.sh index daacfd0..c213850 100755 --- a/scripts/collect-evidence.sh +++ b/scripts/collect-evidence.sh @@ -73,7 +73,9 @@ echo 'tests.txt' docker compose -f compose.test.yaml build -q tests run docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose docker compose -f compose.test.yaml down -v >/dev/null 2>&1 - docker compose up -d --wait >/dev/null 2>&1 + docker compose start postgres redis s3 rabbitmq api worker relay reconciler lb otel-collector prometheus loki tempo grafana >/dev/null 2>&1 + python3 scripts/probe.py ready >/dev/null + sleep 20 } > evidence/tests.txt echo 'smoke.txt' -- 2.54.0 From 2718c3b432cf86fea0abc0718b64a9eb142b32c4 Mon Sep 17 00:00:00 2001 From: aegor Date: Fri, 20 Nov 2026 18:11:19 +0300 Subject: [PATCH 7/8] test: extend collector outage to 300 s in telemetry incident --- REPORT.md | 39 ++- evidence/container.txt | 42 +-- evidence/failover.txt | 18 +- evidence/incident-db.txt | 64 +++- evidence/incident-retry-trace.txt | 36 ++- evidence/incident-telemetry.txt | 46 ++- evidence/incident-worker-stop.txt | 47 ++- evidence/jobs.txt | 191 ++++++++++-- evidence/persistence.txt | 37 ++- evidence/s3.txt | 4 +- evidence/smoke.txt | 19 +- evidence/telemetry.txt | 367 ++++++++-------------- evidence/tests.txt | 486 +++++++++++++++--------------- scripts/incidents.py | 9 +- 14 files changed, 818 insertions(+), 587 deletions(-) diff --git a/REPORT.md b/REPORT.md index 985e74e..ce41b13 100644 --- a/REPORT.md +++ b/REPORT.md @@ -143,27 +143,40 @@ Collector — получатель и маршрутизатор, а не БД: ## Доказательства критериев -⟨EVIDENCE_COMMIT⟩ +Файлы собраны `docker compose run --rm tools sh scripts/collect-evidence.sh` на commit `d83876f` с чистых volumes (`docker compose down -v`, затем `up`); в заголовке каждого файла — дата и commit. ⟨TELEMETRY_RERUN⟩ | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke с телеметрией | `make check`, `make test` через LB | ⟨SMOKE⟩ | [evidence/smoke.txt](evidence/smoke.txt) | -| **3**: минимум lab5 сохранён | собственные тесты, `make test-persistence`, `make test-failover`, `check-s3.sh`, сценарии `job-scenario.py` | ⟨LAB5⟩ | [evidence/tests.txt](evidence/tests.txt), [evidence/persistence.txt](evidence/persistence.txt), [evidence/failover.txt](evidence/failover.txt), [evidence/s3.txt](evidence/s3.txt), [evidence/jobs.txt](evidence/jobs.txt) | -| **3**: Collector, хранилища трёх сигналов, Grafana в стенде; конфиги и provisioning в Git; volumes | `docker compose ps`, images, сети, datasources | ⟨STACK⟩ | [evidence/container.txt](evidence/container.txt), [evidence/telemetry.txt](evidence/telemetry.txt) | -| **3**: API и worker отдают OTLP; RPS, ошибки, длительность API, jobs и длительность worker, логи, трассы видны в Grafana | `dashboard-check.py` | ⟨DASH⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | -| **3**: логи с trace_id/span_id; для контрольного запроса находятся trace и лог, для job — trace и лог worker | `trace-check.py` | ⟨TRACE⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | -| **3**: пароли, токены, тексты сообщений не экспортируются; нет ID в labels | `telemetry-privacy.py` | ⟨PRIVACY⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | -| **4**: W3C context API → broker → worker, producer/consumer spans, цепочка до S3/DB включая retry | `incidents.py retry-trace`, `trace-check.py` | ⟨RETRY⟩ | [evidence/incident-retry-trace.txt](evidence/incident-retry-trace.txt) | -| **4**: p50/p95/p99 из histogram, доля ошибок, очередь и возраст, пул БД, насыщение worker, CPU/RAM, time to ready | `dashboard-check.py`, `latency-compare.py` | ⟨P95⟩ | [evidence/telemetry.txt](evidence/telemetry.txt) | -| **4**: SLI/SLO с окном; alert rules на error rate и queue lag, firing → resolved | `promtool`, `incidents.py worker-stop`, `db` | ⟨ALERTS⟩ | [evidence/telemetry.txt](evidence/telemetry.txt), [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt), [evidence/incident-db.txt](evidence/incident-db.txt) | +| Публичный smoke с телеметрией | `make check`, `make test` через LB | `make check` PASS; `PASS: lab6 public API scenario` при включённой телеметрии; запросы одной сессии обслуживают обе реплики | [evidence/smoke.txt](evidence/smoke.txt) | +| **3**: минимум lab5 сохранён | собственные тесты, `make test-persistence`, `make test-failover`, `check-s3.sh`, сценарии `job-scenario.py` | 201/201 тест; persistence PASS; failover PASS (128 записей, 0 ошибок, восстановление 3,57 s); S3 PASS; все 7 сценариев lab5 (crash-after-store/commit, outbox-gap, relay-crash, retry-replay, broker) воспроизводятся с телеметрией | [evidence/tests.txt](evidence/tests.txt), [evidence/persistence.txt](evidence/persistence.txt), [evidence/failover.txt](evidence/failover.txt), [evidence/s3.txt](evidence/s3.txt), [evidence/jobs.txt](evidence/jobs.txt) | +| **3**: Collector, хранилища трёх сигналов, Grafana в стенде; конфиги и provisioning в Git; volumes | `docker compose ps`, images, сети, datasources | сервисы `otel-collector`, `prometheus`, `loki`, `tempo`, `grafana` работают, образы закреплены по digest; наружу только `127.0.0.1:8080` и `127.0.0.1:3000`; хранилища только в сети `telemetry` (`internal=true`); volumes `prometheusdata`, `lokidata`, `tempodata`, `grafanadata`; datasources с UID `prometheus`/`loki`/`tempo` | [evidence/container.txt](evidence/container.txt), [evidence/telemetry.txt](evidence/telemetry.txt) | +| **3**: API и worker отдают OTLP; RPS, ошибки, длительность API, jobs и длительность worker, логи, трассы видны в Grafana | `dashboard-check.py` | dashboard загружен из provisioning (папка Messenger); все запросы панелей возвращают данные, кроме истории alerts (в спокойном состоянии alerts нет); «время до ready» за последнюю минуту — NaN, т. к. новых готовых вложений в эту минуту не было | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **3**: логи с trace_id/span_id; для контрольного запроса находятся trace и лог, для job — trace и лог worker | `trace-check.py` | upload с клиентским `traceparent` → trace из 79 spans: SERVER API (родитель — span клиента) → PRODUCER relay → CONSUMER worker → S3 и SQL; в Loki по `trace_id` — `http.request` API и `job.handled` worker, у каждого свой `span_id` | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **3**: пароли, токены, тексты сообщений не экспортируются; нет ID в labels | `telemetry-privacy.py` | пароль, session token, Basic-учётка, заголовок Authorization, текст сообщения, filename — 0 вхождений в 6 трассах этих запросов и в Loki (контроль: 7 строк логов этих запросов найдены); 893 серии, 0 с UUID в значениях labels; `http_route` — только шаблоны | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **4**: W3C context API → broker → worker, producer/consumer spans, цепочка до S3/DB включая retry | `incidents.py retry-trace`, `trace-check.py` | одна загрузка — одна трасса: 3 пары PRODUCER → CONSUMER (`attempt` 1, 2, 3); в попытках 1–2 `S3.GetObject` с ошибкой (S3 остановлен), попытка 3 — S3 Put ×4, COMMIT, ready; события `enqueued → processing → retry_scheduled → processing → retry_scheduled → processing → ready` | [evidence/incident-retry-trace.txt](evidence/incident-retry-trace.txt) | +| **4**: p50/p95/p99 из histogram, доля ошибок, очередь и возраст, пул БД, насыщение worker, CPU/RAM, time to ready | `dashboard-check.py`, `latency-compare.py` | панели p50/p95/p99 (`sum by (le)`), доля 5xx, глубина/возраст очереди, пул used/waiting/max, busy/capacity, CPU, RSS, time to ready возвращают данные; клиент / histogram: p50 18,3 / 19,7 ms, p95 89,2 / 92,2 ms, p99 163,3 / 176,8 ms (3411 POST, 113 rps) | [evidence/telemetry.txt](evidence/telemetry.txt) | +| **4**: SLI/SLO с окном; alert rules на error rate и queue lag, firing → resolved | `promtool`, `incidents.py worker-stop`, `db` | `promtool`: 13 правил; все `health ok`; `MessengerJobQueueLag` и `MessengerApiNotReady` прошли pending → firing → inactive | [evidence/telemetry.txt](evidence/telemetry.txt), [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt), [evidence/incident-db.txt](evidence/incident-db.txt) | | **4**: Collector с memory_limiter, batch, ограниченной очередью; остановка backend не ломает API и не растит RAM | `incidents.py telemetry` | ⟨TELEMETRY⟩ | [evidence/incident-telemetry.txt](evidence/incident-telemetry.txt) | | **4**: инцидент 1 — worker остановлен | `incidents.py worker-stop` | см. «Эксперименты и отказы» | [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt) | | **4**: инцидент 2 — медленная/недоступная БД отличима от медленного handler | `incidents.py db` | см. «Эксперименты и отказы» | [evidence/incident-db.txt](evidence/incident-db.txt) | -| Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | ⟨TESTS⟩ | [evidence/tests.txt](evidence/tests.txt) | +| Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | `Tests: 201 passed, 201 total` | [evidence/tests.txt](evidence/tests.txt) | ## Эксперименты и отказы -⟨EXPERIMENTS⟩ +Стенд: Docker Desktop WSL2, 12 vCPU, 8 GiB; лимиты контейнеров — в `compose.yaml` и `evidence/container.txt` (API 0,5 CPU / 256M ×2, worker 1 CPU / 768M, Collector 0,5 CPU / 256M, хранилища по 0,5 CPU / 512M). Каждый сценарий выполнен один раз в составе `collect-evidence.sh`. Фоновая нагрузка в инцидентах — `Traffic` из `scripts/incidents.py`: 4–6 потоков closed loop через LB, POST сообщения и GET истории по очереди, пауза 0,05–0,2 s; файл для job — `sample.png` 320×200. Клиентские p50/p95/p99 считаются по успешным ответам фазы. + +**Сверка перцентилей** (`latency-compare.py`, 30 s, 4 потока, POST сообщений): клиент 3411 успешных запросов, 113 rps, 0 ошибок; p50 / p95 / p99 — 18,3 / 89,2 / 163,3 ms у клиента и 19,7 / 92,2 / 176,8 ms по `histogram_quantile` (`increase` за окно). Серверная гистограмма не включает сеть и клиент, значение интерполируется внутри bucket (50–100 ms и 100–250 ms), поэтому расхождение в пределах ширины bucket. Счётчик Prometheus за окно (3661) больше клиентского: `increase()` экстраполирует до границ окна. + +| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| --- | --- | --- | --- | +| **Инцидент 1:** `docker compose stop worker`, 12 загрузок по одной в 10 s | 202 продолжаются; растёт возраст старейшего задания; alert по lag; после старта backlog уменьшается | все загрузки 202; `jobs_queue_depth{state="due"}` до 12, `oldest_age` до 132,5 s (обновляется с шагом экспорта метрик), `worker_busy` 0, серии worker перестают обновляться; `MessengerJobQueueLag` pending → **firing через 151 s** простоя | после `start worker` очередь пуста через ≤ 20 s (12 → 2 → 0), alert **resolved через 30 s**; 12 из 12 `ready`; фактическое время до ready по БД 41,9–152,1 s, histogram p99 176 s (bucket 150–180 s); потерь нет | +| **Инцидент 2а — медленный handler (контроль):** upload PNG 1700×1700 шума, 8,3 MiB | время в обработчике и S3, БД быстрая | trace 525 ms: вызовы БД 40 ms (SQL 22 ms, ожидание пула 1 ms), S3 246 ms, сам обработчик (полное декодирование) 240 ms | — | +| **Инцидент 2б — медленная БД:** `docker update --cpus 0.05 postgres` на 150 s под нагрузкой | рост задержки, причина в SQL | 0 ошибок; клиент p95 23 → 196 ms, p99 49 → 637 ms; p95 в Prometheus (1m) до ~250 ms; trace 790 ms: БД 788 ms (SQL 781 ms, пул 0 ms), обработчик 1 ms; trace 505 ms: SQL 498 ms. `MessengerSlowApi` (порог p95 > 1 s) не сработал — деградация ниже порога | после `--cpus 1.0` p95 вернулся к ~24 ms за 1–2 мин | +| **Инцидент 2в — БД недоступна:** `docker pause postgres` на ~105 s | 503 вместо зависаний; alert | API: ожидание пула 5 s → `503 database unavailable` (trace 5005 ms: `prisma:engine:connection` 5000 ms); `/health/core` 503 → HAProxy выводит обе реплики, клиенты получают `503 no API replica available` (1910 ответов) и 3 × 504; доля 5xx в метриках API не растёт — запросы не доходят до API; `MessengerApiNotReady` **firing**; в Loki `http.error` / `database unavailable` | после `unpause` реплики вернулись в LB за секунды, 25 ответов 503 в хвосте; alert **resolved через ~60 s**; p95 23 ms; данных не потеряно (неподтверждённые записи получили 503) | +| **Инцидент 3а — Loki и Tempo остановлены** до срабатывания alert (150 s) под нагрузкой 6 потоков | API работает; Collector ограничивает очередь и память; потери считаются | клиент: 14 385 успешных, **0 ошибок**, p95 29 ms (до — 30 ms); очередь exporter 0 → **200 из 200**; `send_failed` ~1250 spans и ~930 log records в минуту; затем `memory_limiter` отказывает в приёме (`refused` до ~91 000 в минуту); RSS Collector 144 → **240 MiB** (лимит 256M, перезапусков и OOM нет); `TelemetryExportFailing` **firing** | после `start loki tempo` очередь опустела за ~15 s, RSS 155 MiB, alert **resolved** через ~105 s; трассы и логи за время простоя потеряны (посчитаны), логи остаются в `docker compose logs` | +| **Инцидент 3б — Collector остановлен** | API работает, RAM не растёт бесконечно | ⟨COLLECTOR⟩ | ⟨COLLECTOR_RECOVERY⟩ | +| S3 остановлен на время первых попыток job (`retry-trace`) | повторы в одной трассе | см. критерий W3C выше: 3 попытки в одной трассе | ready через ~9 s после upload | +| `restart.sh`, `stop-one.sh`, сценарии lab5 | как в lab5 | PASS; failover 128 записей, 0 ошибок, восстановление 3,57 s | потерь нет | ## Сверка с замечаниями проверяющих @@ -171,7 +184,7 @@ Collector — получатель и маршрутизатор, а не БД: | Замечание к чужому PR | Наш результат | | --- | --- | -| Стандартные buckets (0, 5, 10 … s) дают p95 4,75 s при реальных 5 ms; сверить график с контрольным измерением | buckets от 1 ms; `latency-compare.py` сравнивает с клиентом — ⟨P95_SHORT⟩. Та же проблема найдена у нас для time to ready (p99 296 s при реальных ≤ 160 s между границами 120 и 300 s) и исправлена добавлением границ 150/180/240 s | +| Стандартные buckets (0, 5, 10 … s) дают p95 4,75 s при реальных 5 ms; сверить график с контрольным измерением | buckets от 1 ms; `latency-compare.py` сравнивает с клиентом — p95 89 ms у клиента и 92 ms по histogram. Та же проблема найдена у нас для time to ready (p99 296 s при реальных ≤ 160 s между границами 120 и 300 s) и исправлена добавлением границ 150/180/240 s | | Datasources без UID → rules и панели с UID `prometheus`/`loki` в состоянии `data source not found` | UID заданы в provisioning и используются во всех панелях; `telemetry.txt` показывает UID, все запросы dashboard возвращают данные. Alerts вычисляет Prometheus, а не Grafana, health правил `ok` | | Alert «остановка worker» по числу retry не срабатывает, т. к. без worker retry не появляются; нужны queue depth и oldest age | alert по возрасту старейшего задания из БД, gauge отдаёт relay, поэтому он растёт при мёртвом worker; firing → resolved показан | | API создаёт новый trace вместо продолжения клиентского `traceparent`, нет SERVER spans | SERVER span — потомок клиентского span (`trace-check.py`: `parent=client`) | diff --git a/evidence/container.txt b/evidence/container.txt index d4f0dee..af35da3 100644 --- a/evidence/container.txt +++ b/evidence/container.txt @@ -1,27 +1,27 @@ # Стенд: сервисы, порты, лимиты, секреты, миграции, топология брокера -# date: 2026-11-20T13:43:42Z -# commit: 5f870e4 +# date: 2026-11-20T14:30:52Z +# commit: d83876f $ docker compose ps -a --format table {{.Service}}\t{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}} SERVICE NAME IMAGE STATUS PORTS api messenger-lab6-api-1 mtusi-messenger-lab6-api:dev Up 13 seconds (healthy) 8080/tcp -api messenger-lab6-api-2 mtusi-messenger-lab6-api:dev Up 14 seconds (healthy) 8080/tcp -grafana messenger-lab6-grafana-1 grafana/grafana:11.4.0@sha256:d8ea37798ccc41061a62ab080f2676dda6bf7815558499f901bdb0f533a456fb Up 18 seconds (healthy) 127.0.0.1:3000->3000/tcp +api messenger-lab6-api-2 mtusi-messenger-lab6-api:dev Up 13 seconds (healthy) 8080/tcp +grafana messenger-lab6-grafana-1 grafana/grafana:11.4.0@sha256:d8ea37798ccc41061a62ab080f2676dda6bf7815558499f901bdb0f533a456fb Up 19 seconds (healthy) 127.0.0.1:3000->3000/tcp lb messenger-lab6-lb-1 haproxy:3.0.6-alpine Up 7 seconds 127.0.0.1:8080->8080/tcp -loki messenger-lab6-loki-1 grafana/loki:3.3.2@sha256:8af2de1abbdd7aa92b27c9bcc96f0f4140c9096b507c77921ffddf1c6ad6c48f Up 24 seconds 3100/tcp +loki messenger-lab6-loki-1 grafana/loki:3.3.2@sha256:8af2de1abbdd7aa92b27c9bcc96f0f4140c9096b507c77921ffddf1c6ad6c48f Up 25 seconds 3100/tcp migrate messenger-lab6-migrate-1 mtusi-messenger-lab6-migrate:dev Exited (0) 14 seconds ago -otel-collector messenger-lab6-otel-collector-1 otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8 Up 24 seconds 4317-4318/tcp, 55678-55679/tcp -postgres messenger-lab6-postgres-1 postgres:17.2-alpine Up 23 seconds (healthy) 5432/tcp -prometheus messenger-lab6-prometheus-1 prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 Up 24 seconds (healthy) 9090/tcp -rabbitmq messenger-lab6-rabbitmq-1 rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 Up 23 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp -reconciler messenger-lab6-reconciler-1 mtusi-messenger-lab6-api:dev Up 14 seconds 8080/tcp -redis messenger-lab6-redis-1 redis:7.4.1-alpine Up 23 seconds (healthy) 6379/tcp +otel-collector messenger-lab6-otel-collector-1 otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8 Up 25 seconds 4317-4318/tcp, 55678-55679/tcp +postgres messenger-lab6-postgres-1 postgres:17.2-alpine Up 24 seconds (healthy) 5432/tcp +prometheus messenger-lab6-prometheus-1 prom/prometheus:v3.1.0@sha256:6559acbd5d770b15bb3c954629ce190ac3cbbdb2b7f1c30f0385c4e05104e218 Up 25 seconds (healthy) 9090/tcp +rabbitmq messenger-lab6-rabbitmq-1 rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 Up 24 seconds (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp +reconciler messenger-lab6-reconciler-1 mtusi-messenger-lab6-api:dev Up 13 seconds 8080/tcp +redis messenger-lab6-redis-1 redis:7.4.1-alpine Up 24 seconds (healthy) 6379/tcp relay messenger-lab6-relay-1 mtusi-messenger-lab6-api:dev Up 7 seconds 8080/tcp -s3 messenger-lab6-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 Up 23 seconds (healthy) 9000/tcp -s3-init messenger-lab6-s3-init-1 pgsty/mc:RELEASE.2026-10-26T00-00-00Z@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8 Exited (0) 15 seconds ago +s3 messenger-lab6-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372 Up 24 seconds (healthy) 9000/tcp +s3-init messenger-lab6-s3-init-1 pgsty/mc:RELEASE.2026-10-26T00-00-00Z@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8 Exited (0) 14 seconds ago secrets-init messenger-lab6-secrets-init-1 alpine:3.20.3 Exited (0) 24 seconds ago -tempo messenger-lab6-tempo-1 grafana/tempo:2.6.1@sha256:ef4384fce6e8ad22b95b243d8fc165628cda655376fd50e7850536ad89d71d50 Up 24 seconds -tools messenger-lab6-tools-run-97526746648b mtusi-messenger-lab6-tools:dev Up 6 seconds +tempo messenger-lab6-tempo-1 grafana/tempo:2.6.1@sha256:ef4384fce6e8ad22b95b243d8fc165628cda655376fd50e7850536ad89d71d50 Up 25 seconds +tools messenger-lab6-tools-run-68bd7ed38f92 mtusi-messenger-lab6-tools:dev Up 5 seconds worker messenger-lab6-worker-1 mtusi-messenger-lab6-api:dev Up 7 seconds 8080/tcp ## CPU/RAM-лимиты (NanoCpus: 1e9 = 1 CPU; Memory в байтах) @@ -43,7 +43,7 @@ $ sh -c docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.Hos /messenger-lab6-s3-init-1 cpus=250000000 memory=268435456 /messenger-lab6-secrets-init-1 cpus=100000000 memory=33554432 /messenger-lab6-tempo-1 cpus=500000000 memory=536870912 -/messenger-lab6-tools-run-97526746648b cpus=1000000000 memory=268435456 +/messenger-lab6-tools-run-68bd7ed38f92 cpus=1000000000 memory=268435456 /messenger-lab6-worker-1 cpus=1000000000 memory=805306368 ## Опубликованные порты: только LB и Grafana на 127.0.0.1; OTLP, Prometheus, Loki, Tempo наружу не открыты @@ -308,11 +308,11 @@ No difference detected. $ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at migration_name | finished_at ---------------------------------+------------------------------- - 20261021000000_init | 2026-11-20 13:43:28.446961+00 - 20261021010000_auth_sessions | 2026-11-20 13:43:28.460558+00 - 20261101000000_idempotency_keys | 2026-11-20 13:43:28.472356+00 - 20261105000000_attachments | 2026-11-20 13:43:28.494531+00 - 20261115000000_attachment_jobs | 2026-11-20 13:43:28.540792+00 + 20261021000000_init | 2026-11-20 14:30:37.860315+00 + 20261021010000_auth_sessions | 2026-11-20 14:30:37.880522+00 + 20261101000000_idempotency_keys | 2026-11-20 14:30:37.895909+00 + 20261105000000_attachments | 2026-11-20 14:30:37.918762+00 + 20261115000000_attachment_jobs | 2026-11-20 14:30:37.951618+00 (5 rows) diff --git a/evidence/failover.txt b/evidence/failover.txt index b8bc5dd..145c767 100644 --- a/evidence/failover.txt +++ b/evidence/failover.txt @@ -1,17 +1,17 @@ # make test-failover: stop-one.sh останавливает реплику, обслужившую тест -# date: 2026-11-20T13:47:23Z -# commit: 5f870e4 +# date: 2026-11-20T14:33:10Z +# commit: d83876f ## до -/messenger-lab6-api-1 id=5eb61d3915d1 created exit=0 finished=0001-01-01T00:00:00Z -/messenger-lab6-api-2 id=b4948f100e42 created exit=0 finished=0001-01-01T00:00:00Z +/messenger-lab6-api-1 id=64377e499417 running exit=0 finished=2026-11-20T14:33:08.109900069Z +/messenger-lab6-api-2 id=25ff01cef182 running exit=0 finished=2026-11-20T14:33:05.646476717Z $ make test-failover ACTION_SCRIPT=scripts/stop-one.sh python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080" -FAIL: GET /health/live: connection/TLS failure (URLError) -make: *** [Makefile:30: test-failover] Error 1 -EXIT CODE 2 +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 3.571} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. ## после: остановленная реплика Exited (0) — штатное завершение по SIGTERM -/messenger-lab6-api-1 id=5eb61d3915d1 created exit=0 finished=0001-01-01T00:00:00Z -/messenger-lab6-api-2 id=b4948f100e42 created exit=0 finished=0001-01-01T00:00:00Z +/messenger-lab6-api-1 id=64377e499417 running exit=0 finished=2026-11-20T14:33:08.109900069Z +/messenger-lab6-api-2 id=25ff01cef182 exited exit=0 finished=2026-11-20T14:33:19.073873959Z diff --git a/evidence/incident-db.txt b/evidence/incident-db.txt index 3654fd6..40964a3 100644 --- a/evidence/incident-db.txt +++ b/evidence/incident-db.txt @@ -1,8 +1,64 @@ # Инцидент: scripts/incidents.py db -# date: 2026-11-20T14:03:28Z -# commit: 5f870e4 +# date: 2026-11-20T14:41:32Z +# commit: d83876f $ python3 scripts/incidents.py db -API did not become ready -EXIT CODE 1 +[ 0.1s] user df6eb947-ae87-4aa5-9d75-0c0c8091ab4d chat e46df417-75d8-4eaa-bca3-e19e3a86da1a +[ 0.1s] == baseline: 60 s of traffic +[ 0.2s] p95_1m=16ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 20.2s] p95_1m=25ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 40.2s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 60.3s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 60.3s] client [baseline]: 200:567 201:568; p50=11ms p95=23ms p99=49ms +[ 60.3s] == slow handler (not DB): 1700x1700 noise PNG upload — decoding and S3 dominate +[ 61.1s] POST 8.3 MiB attachment -> 202 +[ 76.1s] slow handler: trace 7c5c169b5e229a27d34765e20c7dc102 POST /api/v1/chats/{chat_id}/attachments -> 202, 525 ms +[ 76.1s] DB calls 40 ms (pool wait 1 ms, SQL 22 ms); S3 246 ms; handler itself 240 ms +[ 76.1s] == slow DB: postgres limited to 0.05 CPU for 150 s +[ 76.3s] $ docker update --cpus 0.05 27a9b1f465438247ed81c48a9b572b24ab12ea5ffc7112d9817be18636e47310 +[ 76.3s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.2 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 91.4s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 106.4s] p95_1m=75ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 121.4s] p95_1m=102ms 5xx_1m=0.0% pool_wait=0 pool_used=1 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 136.5s] p95_1m=319ms 5xx_1m=0.0% pool_wait=0 pool_used=1 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 151.5s] p95_1m=309ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 166.5s] p95_1m=268ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 181.6s] p95_1m=282ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 196.6s] p95_1m=180ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 211.6s] p95_1m=187ms 5xx_1m=0.0% pool_wait=0 pool_used=1 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 226.7s] p95_1m=183ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 226.7s] client [slow DB]: 200:1391 201:1390; p50=12ms p95=196ms p99=637ms +[ 226.7s] slow DB: trace 4fa46b85e073eddb48c09bce00a7b150 POST /api/v1/chats/{chat_id}/messages -> 201, 790 ms +[ 226.7s] DB calls 788 ms (pool wait 0 ms, SQL 781 ms); S3 0 ms; handler itself 1 ms +[ 226.7s] slow DB: trace 20868735bb9111efc35f20b042032875 POST /api/v1/chats/{chat_id}/messages -> 201, 505 ms +[ 226.7s] DB calls 502 ms (pool wait 0 ms, SQL 498 ms); S3 0 ms; handler itself 3 ms +[ 226.7s] $ docker update --cpus 1.0 27a9b1f465438247ed81c48a9b572b24ab12ea5ffc7112d9817be18636e47310 +[ 226.8s] p95_1m=183ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 226.8s] client [after slow DB]: ; p50=0ms p95=0ms p99=0ms +[ 226.8s] == DB unavailable: postgres paused for 120 s +[ 226.8s] $ docker pause 27a9b1f465438247ed81c48a9b572b24ab12ea5ffc7112d9817be18636e47310 +[ 226.9s] p95_1m=183ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 242.0s] p95_1m=176ms 5xx_1m=0.0% pool_wait=5 pool_used=5 core_5xx_1m=- api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 257.0s] p95_1m=212ms 5xx_1m=0.0% pool_wait=6 pool_used=0 core_5xx_1m=8 api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 272.1s] p95_1m=197ms 5xx_1m=0.0% pool_wait=7 pool_used=0 core_5xx_1m=10.9 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 287.1s] p95_1m=nanms 5xx_1m=nan% pool_wait=7 pool_used=0 core_5xx_1m=15.7 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 302.1s] p95_1m=nanms 5xx_1m=nan% pool_wait=6 pool_used=0 core_5xx_1m=18 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=pending +[ 317.2s] p95_1m=nanms 5xx_1m=nan% pool_wait=7 pool_used=0 core_5xx_1m=16.8 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=pending +[ 332.2s] p95_1m=nanms 5xx_1m=nan% pool_wait=7 pool_used=0 core_5xx_1m=16.8 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=firing +[ 332.2s] client [DB paused]: 201:1 503:1910 504:3; p50=41ms p95=41ms p99=41ms +[ 332.3s] DB unavailable: trace 96521ffdb7e21480980d75738932c94d GET /api/v1/chats/{chat_id}/messages -> 503, 5005 ms +[ 332.3s] DB calls 5001 ms (pool wait 5000 ms, SQL 5000 ms); S3 0 ms; handler itself 3 ms +[ 332.3s] spans with error status: GET /api/v1/chats/{chat_id}/messages +[ 332.3s] loki: {"timestamp":"2026-11-20T14:47:01.051Z","severity":"ERROR","service.name":"messenger-api","event":"http.error","logger":"HttpExceptionFilter","message":"database unavailable","method":"GET","route":"/ +[ 332.3s] loki: {"timestamp":"2026-11-20T14:47:01.115Z","severity":"ERROR","service.name":"messenger-api","event":"http.error","logger":"HttpExceptionFilter","message":"database unavailable","method":"GET","route":"/ +[ 332.3s] loki: {"timestamp":"2026-11-20T14:47:03.054Z","severity":"ERROR","service.name":"messenger-api","event":"http.error","logger":"HttpExceptionFilter","message":"database unavailable","method":"GET","route":"/ +[ 332.3s] $ docker unpause 27a9b1f465438247ed81c48a9b572b24ab12ea5ffc7112d9817be18636e47310 +[ 332.4s] p95_1m=nanms 5xx_1m=nan% pool_wait=7 pool_used=0 core_5xx_1m=16.8 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=firing +[ 347.5s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=13.2 api_cpu=0 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=firing +[ 362.5s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=9.6 api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=firing +[ 377.5s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=3.6 api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=firing +[ 392.6s] p95_1m=24ms 5xx_1m=0.0% pool_wait=0 pool_used=0 core_5xx_1m=0 api_cpu=0.1 MessengerSlowApi=inactive MessengerHighErrorRate=inactive MessengerApiNotReady=inactive +[ 392.6s] client [after DB unpaused]: 200:556 201:556 503:25; p50=11ms p95=23ms p99=42ms +[ 393.1s] MessengerApiNotReady fired: True, resolved after recovery: True +[ 393.1s] PASS diff --git a/evidence/incident-retry-trace.txt b/evidence/incident-retry-trace.txt index 9d67ebe..659a5bb 100644 --- a/evidence/incident-retry-trace.txt +++ b/evidence/incident-retry-trace.txt @@ -1,8 +1,36 @@ # Инцидент: scripts/incidents.py retry-trace -# date: 2026-11-20T14:00:26Z -# commit: 5f870e4 +# date: 2026-11-20T14:37:50Z +# commit: d83876f $ python3 scripts/incidents.py retry-trace -API did not become ready -EXIT CODE 1 +[ 0.1s] user cd196c28-14b5-40a2-9c7d-c9a822ff9787 chat ef415dfb-4b85-421e-9e6f-45ecba61630e +[ 0.1s] $ docker compose stop worker +[ 0.8s] upload -> 202 b1a9f7a4-1eeb-4549-8fea-702494f5e4b7 trace d703294a338bfef3bf9f088ecc76f645 +[ 0.8s] $ docker compose stop s3 +[ 1.3s] $ docker start worker (without dependencies) +[ 6.8s] $ docker start s3 (without dependencies) +[ 7.2s] GET attachment -> status=queued error_code=None +[ 8.2s] GET attachment -> status=processing error_code=None +[ 9.2s] GET attachment -> status=ready error_code=None +[ 9.4s] job: d7ba0597-706c-4e41-bf88-353c21ab4e76 | ready | 3 | 5 | +[ 9.5s] variants rows: 3 +[ 9.7s] events: enqueued -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> ready +[ 24.7s] messenger-api SERVER POST /api/v1/chats/{chat_id}/attachments attempt= 57.8 ms +[ 24.7s] messenger-api CLIENT S3.PutObject attempt= 14.8 ms +[ 24.7s] messenger-relay PRODUCER attachment.jobs publish attempt=1 4.5 ms +[ 24.7s] messenger-worker CONSUMER attachment.jobs process attempt=1 1065.4 ms +[ 24.7s] messenger-worker CLIENT S3.GetObject attempt= 1013.7 ms ERROR +[ 24.7s] messenger-relay PRODUCER attachment.jobs publish attempt=2 10.5 ms +[ 24.7s] messenger-worker CONSUMER attachment.jobs process attempt=2 1028.0 ms +[ 24.7s] messenger-worker CLIENT S3.GetObject attempt= 1003.1 ms ERROR +[ 24.7s] messenger-relay PRODUCER attachment.jobs publish attempt=3 7.4 ms +[ 24.7s] messenger-worker CONSUMER attachment.jobs process attempt=3 1052.5 ms +[ 24.7s] messenger-worker CLIENT S3.GetObject attempt= 969.5 ms +[ 24.7s] messenger-worker CLIENT S3.PutObject attempt= 13.8 ms +[ 24.7s] messenger-worker CLIENT S3.PutObject attempt= 6.5 ms +[ 24.7s] messenger-worker CLIENT S3.PutObject attempt= 5.9 ms +[ 24.7s] messenger-worker CLIENT S3.PutObject attempt= 6.0 ms +[ 24.7s] messenger-worker CLIENT S3.DeleteObject attempt= 3.5 ms +[ 24.7s] consumer spans in one trace: 3 (attempts ['1', '2', '3']) +[ 24.7s] PASS diff --git a/evidence/incident-telemetry.txt b/evidence/incident-telemetry.txt index 28936f3..eb853cd 100644 --- a/evidence/incident-telemetry.txt +++ b/evidence/incident-telemetry.txt @@ -1,8 +1,46 @@ # Инцидент: scripts/incidents.py telemetry -# date: 2026-11-20T14:04:59Z -# commit: 5f870e4 +# date: 2026-11-20T14:48:05Z +# commit: d83876f $ python3 scripts/incidents.py telemetry -API did not become ready -EXIT CODE 1 +[ 0.1s] user b8211787-a380-40f3-b09b-107048ccafdf chat cb1f8ca9-090c-4f2b-b43b-35ad07360676 +[ 0.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=153MiB api_rss=227MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 15.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=151MiB api_rss=229MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 30.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=144MiB api_rss=228MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 30.2s] client [baseline]: 200:1427 201:1431; p50=11ms p95=30ms p99=66ms +[ 30.2s] == Loki and Tempo stopped until TelemetryExportFailing fires (max 240 s) +[ 30.2s] $ docker compose stop loki tempo +[ 32.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=144MiB api_rss=227MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 47.0s] spans_failed_1m=0 logs_failed_1m=0 queue=16 queue_cap=200 refused_1m=0 collector_rss=148MiB api_rss=227MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 62.0s] spans_failed_1m=0 logs_failed_1m=0 queue=58 queue_cap=200 refused_1m=0 collector_rss=150MiB api_rss=229MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 77.1s] spans_failed_1m=0 logs_failed_1m=0 queue=102 queue_cap=200 refused_1m=0 collector_rss=175MiB api_rss=229MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 92.1s] spans_failed_1m=0 logs_failed_1m=0 queue=145 queue_cap=200 refused_1m=0 collector_rss=181MiB api_rss=230MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 107.2s] spans_failed_1m=1251.9 logs_failed_1m=583.2 queue=186 queue_cap=200 refused_1m=0 collector_rss=188MiB api_rss=228MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 122.2s] spans_failed_1m=1252.6 logs_failed_1m=583.5 queue=200 queue_cap=200 refused_1m=14887.5 collector_rss=215MiB api_rss=229MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 137.2s] spans_failed_1m=1253.4 logs_failed_1m=583.9 queue=200 queue_cap=200 refused_1m=38541.8 collector_rss=230MiB api_rss=235MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 152.3s] spans_failed_1m=0 logs_failed_1m=0 queue=200 queue_cap=200 refused_1m=69789.2 collector_rss=231MiB api_rss=231MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 167.3s] spans_failed_1m=1365.5 logs_failed_1m=932.1 queue=198 queue_cap=200 refused_1m=87575.8 collector_rss=233MiB api_rss=234MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 182.3s] spans_failed_1m=1365.4 logs_failed_1m=932 queue=200 queue_cap=200 refused_1m=91415.4 collector_rss=237MiB api_rss=228MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 182.3s] client [Loki+Tempo down]: 200:7194 201:7191; p50=10ms p95=29ms p99=78ms +[ 182.3s] $ docker compose start loki tempo +[ 182.9s] spans_failed_1m=1365.4 logs_failed_1m=932 queue=200 queue_cap=200 refused_1m=91415.4 collector_rss=237MiB api_rss=228MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 197.9s] spans_failed_1m=1365.4 logs_failed_1m=932.1 queue=200 queue_cap=200 refused_1m=85848.4 collector_rss=238MiB api_rss=234MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 213.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=69153.5 collector_rss=240MiB api_rss=230MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 228.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=39560.8 collector_rss=155MiB api_rss=230MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 243.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=11155.2 collector_rss=155MiB api_rss=230MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 258.1s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=155MiB api_rss=229MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 273.1s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=155MiB api_rss=229MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 288.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=155MiB api_rss=230MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 288.2s] client [after start]: 200:4986 201:4987; p50=10ms p95=34ms p99=82ms +[ 288.2s] == Collector stopped for 60 s: SDK export fails fast (5 s timeout, bounded queues) +[ 288.2s] $ docker compose stop otel-collector +[ 306.8s] docker stats: messenger-lab6-api-1 171.3MiB / 256MiB; messenger-lab6-api-2 184.8MiB / 256MiB; messenger-lab6-worker-1 72.1MiB / 768MiB; +[ 323.9s] docker stats: messenger-lab6-api-1 178.6MiB / 256MiB; messenger-lab6-api-2 194.5MiB / 256MiB; messenger-lab6-worker-1 72.61MiB / 768MiB; +[ 341.8s] docker stats: messenger-lab6-api-1 187.5MiB / 256MiB; messenger-lab6-api-2 200.2MiB / 256MiB; messenger-lab6-worker-1 71.97MiB / 768MiB; +[ 359.6s] docker stats: messenger-lab6-api-1 191.7MiB / 256MiB; messenger-lab6-api-2 202.9MiB / 256MiB; messenger-lab6-worker-1 72.51MiB / 768MiB; +[ 359.6s] client [collector down]: 200:3307 201:3306; p50=11ms p95=30ms p99=111ms +[ 359.6s] $ docker compose start otel-collector +[ 390.3s] client [collector back]: 200:1429 201:1431; p50=11ms p95=32ms p99=91ms +[ 390.5s] TelemetryExportFailing fired: True, resolved: True +[ 390.5s] PASS diff --git a/evidence/incident-worker-stop.txt b/evidence/incident-worker-stop.txt index 74aa3f6..ec93dbd 100644 --- a/evidence/incident-worker-stop.txt +++ b/evidence/incident-worker-stop.txt @@ -1,8 +1,47 @@ # Инцидент: scripts/incidents.py worker-stop -# date: 2026-11-20T14:01:57Z -# commit: 5f870e4 +# date: 2026-11-20T14:38:15Z +# commit: d83876f $ python3 scripts/incidents.py worker-stop -API did not become ready -EXIT CODE 1 +[ 0.1s] user d494cd19-eea4-48ae-a471-64b35e821933 chat 0369989a-4572-4abd-8dd4-7aafb56e9d84 +[ 0.1s] $ docker compose stop worker +[ 0.7s] due=0 processing=0 oldest_age_s=0 worker_busy=0 worker_up=1 ready_per_s=0 MessengerJobQueueLag=inactive +[ 0.7s] POST attachment -> 202 status=queued id=2a8a08ff-2af0-47be-ac68-9404ea8c0f70 instance=25ff01cef182 +[ 10.7s] due=1 processing=0 oldest_age_s=0 worker_busy=0 worker_up=1 ready_per_s=0 MessengerJobQueueLag=inactive +[ 10.8s] POST attachment -> 202 status=queued id=90500e1c-2b31-45d7-b584-a3df08532497 instance=64377e499417 +[ 20.8s] due=2 processing=0 oldest_age_s=2.5 worker_busy=0 worker_up=1 ready_per_s=0 MessengerJobQueueLag=inactive +[ 20.8s] POST attachment -> 202 status=queued id=d388cce7-ef51-4bc6-a990-c9f7c25934cc instance=25ff01cef182 +[ 30.9s] due=3 processing=0 oldest_age_s=2.5 worker_busy=0 worker_up=- ready_per_s=0 MessengerJobQueueLag=inactive +[ 30.9s] POST attachment -> 202 status=queued id=93a3b0d8-3a39-47ac-8bc0-79fa17c5aed0 instance=64377e499417 +[ 40.9s] due=4 processing=0 oldest_age_s=12.5 worker_busy=0 worker_up=- ready_per_s=0 MessengerJobQueueLag=inactive +[ 41.0s] POST attachment -> 202 status=queued id=26b1886f-f54c-4fff-aea7-ebddbeba4662 instance=25ff01cef182 +[ 51.0s] due=5 processing=0 oldest_age_s=32.5 worker_busy=0 worker_up=- ready_per_s=0 MessengerJobQueueLag=inactive +[ 51.1s] POST attachment -> 202 status=queued id=43da824d-5d9f-4ecb-9621-58a1d0ff0f73 instance=64377e499417 +[ 61.1s] due=6 processing=0 oldest_age_s=32.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=inactive +[ 61.1s] POST attachment -> 202 status=queued id=1810e49b-e341-4820-8d01-40151a8ed795 instance=25ff01cef182 +[ 71.2s] due=7 processing=0 oldest_age_s=42.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=inactive +[ 71.2s] POST attachment -> 202 status=queued id=9884d9e1-6e5b-4e2b-953e-c08af021adfd instance=64377e499417 +[ 81.2s] due=8 processing=0 oldest_age_s=62.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=inactive +[ 81.3s] POST attachment -> 202 status=queued id=cb6af66e-bc34-41d8-ba90-1f5664611708 instance=25ff01cef182 +[ 91.3s] due=9 processing=0 oldest_age_s=62.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=pending +[ 91.3s] POST attachment -> 202 status=queued id=614d8080-709e-4574-96c5-8d5b2ebe66f8 instance=64377e499417 +[ 101.4s] due=10 processing=0 oldest_age_s=72.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=pending +[ 101.4s] POST attachment -> 202 status=queued id=5b201a4e-3f9e-4927-b282-10530a4c2be2 instance=25ff01cef182 +[ 111.4s] due=11 processing=0 oldest_age_s=92.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=pending +[ 111.5s] POST attachment -> 202 status=queued id=607a53d8-9583-4d79-93c4-c87f320ad7c6 instance=64377e499417 +[ 121.5s] due=12 processing=0 oldest_age_s=92.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=pending +[ 131.5s] due=12 processing=0 oldest_age_s=102.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=pending +[ 141.6s] due=12 processing=0 oldest_age_s=122.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=pending +[ 151.6s] due=12 processing=0 oldest_age_s=122.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=firing +[ 151.6s] alert MessengerJobQueueLag firing after 151 s of worker downtime: True +[ 151.6s] $ docker start worker (without dependencies) +[ 152.0s] due=12 processing=0 oldest_age_s=122.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=firing +[ 162.0s] due=2 processing=0 oldest_age_s=132.5 worker_busy=0 worker_up=- ready_per_s=- MessengerJobQueueLag=firing +[ 172.0s] due=0 processing=0 oldest_age_s=51.8 worker_busy=0 worker_up=1 ready_per_s=- MessengerJobQueueLag=firing +[ 182.0s] due=0 processing=0 oldest_age_s=51.8 worker_busy=0 worker_up=1 ready_per_s=0 MessengerJobQueueLag=inactive +[ 182.0s] backlog drained and alert resolved 30 s after worker start: True +[ 182.1s] uploads during downtime: 12, ready now: 12 +[ 197.1s] time to ready, histogram over 5m: p50=100 s, p99=176.4 s +[ 197.4s] time to ready from the database (finished_at - created_at), s: 41.9 .. 152.1 +[ 197.4s] PASS diff --git a/evidence/jobs.txt b/evidence/jobs.txt index 0ed3fb3..f887293 100644 --- a/evidence/jobs.txt +++ b/evidence/jobs.txt @@ -1,47 +1,203 @@ # Фоновая обработка: сценарии защиты уровней 3 и 4 (scripts/job-scenario.py) -# date: 2026-11-20T13:49:13Z -# commit: 5f870e4 +# date: 2026-11-20T14:33:45Z +# commit: d83876f ## restart $ python3 scripts/job-scenario.py restart -API did not become ready -EXIT CODE 1 +[ 0.2s] user 83a421c6-238a-430e-b23d-7065f92692ea chat 37e2da02-e39f-4a5b-bc3e-99e3072079ad +[ 0.2s] $ docker compose stop worker +[ 1.2s] POST attachment -> 202 status=queued id=b5032f63-71ca-4684-8071-8e546a2b1d38 instance=64377e499417 +[ 1.2s] content while queued -> 409 +[ 1.2s] POST message with 1 attachment(s) -> 201 id=3133055e-c217-4956-8b29-6c195ad7d832 +[ 1.2s] POST message with 0 attachment(s) -> 201 id=485a4b3d-e797-4cd8-8c3a-b6fbd22e51fa +[ 10.3s] queues: name type durable messages_ready messages_unacknowledged +attachment.jobs quorum true 1 0 +attachment.jobs.dlq quorum true 0 0 +[ 10.3s] $ docker compose restart api rabbitmq +[ 27.8s] queues after broker restart: name type durable messages_ready messages_unacknowledged +attachment.jobs quorum true 1 0 +attachment.jobs.dlq quorum true 0 0 +[ 27.8s] status after restarts: queued +[ 27.8s] $ docker compose start worker +[ 32.3s] GET attachment -> status=queued error_code=None +[ 33.3s] GET attachment -> status=ready error_code=None +[ 33.3s] original -> 200 sha256 matches upload: True +[ 33.4s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True +[ 33.4s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True +[ 33.4s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True +[ 33.6s] job: 4e569601-78cf-43c7-8e00-d11cb4929ef8 | ready | 1 | 5 | +[ 33.7s] variants rows: 3 +[ 33.9s] events: enqueued -> processing -> ready ## crash-after-store $ python3 scripts/job-scenario.py crash-after-store -API did not become ready -EXIT CODE 1 +[ 0.1s] user 00aee8d4-3de1-4190-ba59-145bbd9ab2e3 chat eb05fa1f-3a6f-412b-a924-23472af26d2b +[ 0.1s] $ docker compose stop worker +[ 0.7s] $ docker compose run --no-deps -e WORKER_FAULT=exit-after-store -e JOB_LEASE_SECONDS=15 worker +[ 2.7s] POST attachment -> 202 status=queued id=6c09adc1-6c17-43ad-a8ed-2fa6582fe5c5 instance=25ff01cef182 +[ 3.4s] one-off: {"timestamp":"2026-11-20T14:34:22.942Z","severity":"WARN","service.name":"messenger-worker","event":"worker","logger":"Worker","message":"fault injection: worker killed after storing objects, before commit and ack","trace_id":"0f573fa6f35061a106d47bf5eb093c3d","span_id":"39a42f14e6f1823b"} +[ 3.6s] one-off process exit code 137 (137 = killed without ack) +[ 3.6s] status after crash: processing +[ 3.9s] lease: processing | 1 | t +[ 11.7s] queues (unacked message returned): name type durable messages_ready messages_unacknowledged +attachment.jobs quorum true 1 0 +attachment.jobs.dlq quorum true 0 0 +[ 11.7s] $ docker compose start worker +[ 16.8s] GET attachment -> status=processing error_code=None +[ 19.8s] GET attachment -> status=queued error_code=None +[ 20.8s] GET attachment -> status=processing error_code=None +[ 21.9s] GET attachment -> status=ready error_code=None +[ 21.9s] original -> 200 sha256 matches upload: True +[ 21.9s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True +[ 21.9s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True +[ 21.9s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True +[ 22.0s] job: d619929c-d660-4311-bb5e-0d3fbc1813ef | ready | 2 | 5 | +[ 22.2s] variants rows: 3 +[ 22.3s] events: enqueued -> processing -> lease_expired -> processing -> ready +[ 22.6s] worker: {"timestamp":"2026-11-20T14:34:37.365Z","severity":"INFO","service.name":"messenger-worker","event":"job_processor","logger":"JobProcessor","message":"job d619929c-d660-4311-bb5e-0d3fbc1813ef: processing, not due or leased elsewhere, skipped","trace_id":"0f573fa6f35061a106d47bf5eb093c3d","span_id":"17a7f5d766544282"} +[ 22.6s] worker: {"timestamp":"2026-11-20T14:34:37.366Z","severity":"INFO","service.name":"messenger-worker","event":"job.handled","logger":"Worker","job_id":"d619929c-d660-4311-bb5e-0d3fbc1813ef","attachment_id":"6c09adc1-6c17-43ad-a8ed-2fa6582fe5c5","attempt":1,"redelivered":true,"outcome":"skipped","duration_ms":25,"trace_id":"0f573fa6f35061a106d47bf5eb093c3d","span_id":"17a7f5d766544282"} +[ 22.6s] worker: {"timestamp":"2026-11-20T14:34:40.735Z","severity":"INFO","service.name":"messenger-worker","event":"job.handled","logger":"Worker","job_id":"d619929c-d660-4311-bb5e-0d3fbc1813ef","attachment_id":"6c09adc1-6c17-43ad-a8ed-2fa6582fe5c5","attempt":2,"redelivered":false,"outcome":"success","duration_ms":159} +[ 22.7s] relay: {"timestamp":"2026-11-20T14:34:39.557Z","severity":"INFO","service.name":"messenger-relay","event":"outbox_relay","logger":"OutboxRelay","message":"lease expired: 1, stale queued republished: 0"} ## crash-after-commit $ python3 scripts/job-scenario.py crash-after-commit -API did not become ready -EXIT CODE 1 +[ 0.1s] user 34fae015-fbb7-48eb-ad9d-8f23ee67784c chat 801de767-107d-4eb7-92ff-b6aa38dc95cf +[ 0.1s] $ docker compose stop worker +[ 0.6s] $ docker compose run --no-deps -e WORKER_FAULT=exit-after-commit worker +[ 2.7s] POST attachment -> 202 status=queued id=e02d5568-ce5b-485d-9649-f9b4d7387d41 instance=25ff01cef182 +[ 3.4s] one-off: {"timestamp":"2026-11-20T14:34:45.757Z","severity":"WARN","service.name":"messenger-worker","event":"worker","logger":"Worker","message":"fault injection: worker killed after commit, before ack","trace_id":"e15e253daf15a01b76410070a68e7aff","span_id":"b5b5eb6d044c2f38"} +[ 3.5s] one-off process exit code 137 (137 = killed without ack) +[ 3.9s] status after crash: ready staging_key: staging/e02d5568-ce5b-485d-9649-f9b4d7387d41 +[ 11.7s] queues (unacked message returned): name type durable messages_ready messages_unacknowledged +attachment.jobs quorum true 1 0 +attachment.jobs.dlq quorum true 0 0 +[ 11.7s] $ docker compose start worker +[ 17.6s] staging_key after redelivery: NULL +[ 17.6s] original -> 200 sha256 matches upload: True +[ 17.6s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True +[ 17.6s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True +[ 17.6s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True +[ 17.8s] job: dbc6450f-1513-4fd0-9923-3c3339985866 | ready | 1 | 5 | +[ 18.0s] variants rows: 3 +[ 18.2s] events: enqueued -> processing -> ready +[ 18.5s] worker: {"timestamp":"2026-11-20T14:34:59.494Z","severity":"INFO","service.name":"messenger-worker","event":"job_processor","logger":"JobProcessor","message":"job dbc6450f-1513-4fd0-9923-3c3339985866: ready, not due or leased elsewhere, skipped","trace_id":"e15e253daf15a01b76410070a68e7aff","span_id":"db61235444dfbbbc"} +[ 18.5s] worker: {"timestamp":"2026-11-20T14:34:59.494Z","severity":"INFO","service.name":"messenger-worker","event":"job.handled","logger":"Worker","job_id":"dbc6450f-1513-4fd0-9923-3c3339985866","attachment_id":"e02d5568-ce5b-485d-9649-f9b4d7387d41","attempt":1,"redelivered":true,"outcome":"skipped","duration_ms":50,"trace_id":"e15e253daf15a01b76410070a68e7aff","span_id":"db61235444dfbbbc"} ## outbox-gap $ python3 scripts/job-scenario.py outbox-gap -API did not become ready -EXIT CODE 1 +[ 0.1s] user 8646554f-5ce9-4e60-951f-9403d8e951d1 chat 196660eb-f3fc-4117-96dd-9287c6c85681 +[ 0.1s] $ docker compose stop relay +[ 0.9s] POST attachment -> 202 status=queued id=14e198ac-f973-4692-9267-8dba3a1acbc0 instance=64377e499417 +[ 1.1s] outbox after COMMIT: 8 | NOT PUBLISHED | 0 +[ 8.8s] queues: name type durable messages_ready messages_unacknowledged +attachment.jobs quorum true 0 0 +attachment.jobs.dlq quorum true 0 0 +[ 8.8s] $ docker compose kill api +[ 9.4s] API killed (SIGKILL) after COMMIT, nothing was published +[ 9.4s] $ docker compose start api +[ 18.6s] status after API restart: queued +[ 18.6s] $ docker compose start relay +[ 22.9s] GET attachment -> status=queued error_code=None +[ 26.0s] GET attachment -> status=ready error_code=None +[ 26.2s] outbox after relay recovery: 8 | 2026-11-20 14:35:26.35+00 | 1 +[ 26.2s] original -> 200 sha256 matches upload: True +[ 26.2s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True +[ 26.2s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True +[ 26.3s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True +[ 26.4s] job: 29554704-45b1-4335-87fe-8bcb0621b000 | ready | 1 | 5 | +[ 26.6s] variants rows: 3 +[ 26.7s] events: enqueued -> processing -> ready ## relay-crash $ python3 scripts/job-scenario.py relay-crash -API did not become ready -EXIT CODE 1 +[ 0.1s] user da9df65a-2adb-4552-b09a-063e143f7e42 chat 59b25b73-439e-4eb9-abf5-51a8851b5dd5 +[ 0.1s] $ docker compose stop relay +[ 0.7s] $ docker compose run --no-deps -e RELAY_FAULT=exit-after-confirm relay +[ 3.7s] POST attachment -> 202 status=queued id=95f87871-7463-4cec-b73e-556b32ce1f57 instance=64377e499417 +[ 4.3s] one-off: {"timestamp":"2026-11-20T14:35:31.985Z","severity":"INFO","service.name":"messenger-relay","event":"outbox_relay","logger":"OutboxRelay","message":"published 1 job message(s), broker confirmed"} +[ 4.3s] one-off: {"timestamp":"2026-11-20T14:35:31.985Z","severity":"WARN","service.name":"messenger-relay","event":"outbox_relay","logger":"OutboxRelay","message":"fault injection: exit after broker confirm, before outbox is marked"} +[ 4.4s] one-off process exit code 137 (137 = killed without ack) +[ 4.8s] outbox after relay crash: 9 | NOT MARKED | 0 +[ 4.8s] $ docker compose start relay +[ 9.6s] GET attachment -> status=ready error_code=None +[ 12.8s] outbox after relay restart: 9 | 2026-11-20 14:35:39.707+00 | 1 +[ 12.8s] original -> 200 sha256 matches upload: True +[ 12.8s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True +[ 12.8s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True +[ 12.8s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True +[ 13.0s] job: 5449c7df-1ee6-435d-a8e4-60b0f672d65e | ready | 1 | 5 | +[ 13.1s] variants rows: 3 +[ 13.4s] events: enqueued -> processing -> ready +[ 13.6s] worker: {"timestamp":"2026-11-20T14:35:32.064Z","severity":"INFO","service.name":"messenger-worker","event":"job.handled","logger":"Worker","job_id":"5449c7df-1ee6-435d-a8e4-60b0f672d65e","attachment_id":"95f87871-7463-4cec-b73e-556b32ce1f57","attempt":1,"redelivered":false,"outcome":"success","duration_ms":79,"trace_id":"c24603daec760a57d467aff4b2a1d515","span_id":"99e7c21fe5d815b2"} +[ 13.6s] worker: {"timestamp":"2026-11-20T14:35:39.712Z","severity":"INFO","service.name":"messenger-worker","event":"job_processor","logger":"JobProcessor","message":"job 5449c7df-1ee6-435d-a8e4-60b0f672d65e: ready, not due or leased elsewhere, skipped","trace_id":"c24603daec760a57d467aff4b2a1d515","span_id":"ee8d2b5d22aac1b4"} +[ 13.6s] worker: {"timestamp":"2026-11-20T14:35:39.713Z","severity":"INFO","service.name":"messenger-worker","event":"job.handled","logger":"Worker","job_id":"5449c7df-1ee6-435d-a8e4-60b0f672d65e","attachment_id":"95f87871-7463-4cec-b73e-556b32ce1f57","attempt":1,"redelivered":false,"outcome":"skipped","duration_ms":6,"trace_id":"c24603daec760a57d467aff4b2a1d515","span_id":"ee8d2b5d22aac1b4"} ## retry-replay $ python3 scripts/job-scenario.py retry-replay -API did not become ready -EXIT CODE 1 +[ 0.1s] user beb0f294-3e65-411c-bda5-ce3f29e2c1d7 chat a253ff82-2c8c-457b-85cf-6b8c9beee260 +[ 0.1s] $ docker compose stop worker +[ 0.7s] POST attachment -> 202 status=queued id=9832fbf4-2f69-484e-87e4-463d3e8ef3a7 instance=64377e499417 +[ 0.7s] $ docker compose stop s3 +[ 1.2s] $ docker start worker (without dependencies) +[ 1.7s] GET attachment -> status=queued error_code=None +[ 2.7s] GET attachment -> status=processing error_code=None +[ 3.7s] GET attachment -> status=queued error_code=None +[ 4.8s] GET attachment -> status=processing error_code=None +[ 5.8s] GET attachment -> status=queued error_code=None +[ 7.8s] GET attachment -> status=processing error_code=None +[ 8.8s] GET attachment -> status=queued error_code=None +[ 12.8s] GET attachment -> status=processing error_code=None +[ 13.8s] GET attachment -> status=queued error_code=None +[ 19.9s] GET attachment -> status=processing error_code=None +[ 20.9s] GET attachment -> status=failed error_code=retry_exhausted +[ 20.9s] POST message with 1 attachment(s) -> 409 id=None +[ 20.9s] failed attachment in a new message -> 409 +[ 20.9s] retries: +[ 21.0s] 1 | enqueued | | 14:35:42.501 +[ 21.0s] 1 | processing | | 14:35:44.160 +[ 21.0s] 1 | retry_scheduled | temporary failure: ApiError; next attempt 2 in 860 ms | 14:35:45.201 +[ 21.0s] 2 | processing | | 14:35:46.335 +[ 21.0s] 2 | retry_scheduled | temporary failure: ApiError; next attempt 3 in 1537 ms | 14:35:47.349 +[ 21.0s] 3 | processing | | 14:35:49.390 +[ 21.0s] 3 | retry_scheduled | temporary failure: ApiError; next attempt 4 in 3959 ms | 14:35:50.403 +[ 21.0s] 4 | processing | | 14:35:54.463 +[ 21.0s] 4 | retry_scheduled | temporary failure: ApiError; next attempt 5 in 5443 ms | 14:35:55.491 +[ 21.0s] 5 | processing | | 14:36:01.035 +[ 21.0s] 5 | failed | retry_exhausted: temporary failure: ApiError | 14:36:02.047 +[ 21.0s] $ replay.js --list +[ 21.4s] replay: {"job_id":"b88d0626-5470-4148-83eb-cac17feb8b4c","attachment_id":"9832fbf4-2f69-484e-87e4-463d3e8ef3a7","error_code":"retry_exhausted","attempt":5,"last_error":"temporary failure: ApiError","finished_at":"2026-11-20T14:36:02.047Z"} +[ 21.4s] $ docker compose start s3 +[ 23.7s] $ replay.js 9832fbf4-2f69-484e-87e4-463d3e8ef3a7 +[ 24.0s] replay: {"id":"9832fbf4-2f69-484e-87e4-463d3e8ef3a7","job_id":"b88d0626-5470-4148-83eb-cac17feb8b4c","result":"replayed"} +[ 24.0s] GET attachment -> status=queued error_code=None +[ 25.1s] GET attachment -> status=ready error_code=None +[ 25.1s] original -> 200 sha256 matches upload: True +[ 25.1s] thumbnail -> 200 image/jpeg 256x160 sha256 matches metadata: True +[ 25.1s] crop -> 200 image/jpeg 128x128 sha256 matches metadata: True +[ 25.1s] optimized -> 200 image/webp 320x200 sha256 matches metadata: True +[ 25.1s] $ replay.js 9832fbf4-2f69-484e-87e4-463d3e8ef3a7 (already ready) +[ 25.4s] replay: {"id":"9832fbf4-2f69-484e-87e4-463d3e8ef3a7","job_id":"b88d0626-5470-4148-83eb-cac17feb8b4c","result":"already_ready"} +[ 25.6s] job: b88d0626-5470-4148-83eb-cac17feb8b4c | ready | 1 | 5 | +[ 25.7s] variants rows: 3 +[ 25.9s] events: enqueued -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> retry_scheduled -> processing -> failed -> replayed -> processing -> ready ## broker $ python3 scripts/job-scenario.py broker -API did not become ready -EXIT CODE 1 +[ 2.1s] consumers: queue_name ack_required prefetch_count +attachment.jobs true 2 +[ 2.2s] worker limits: cpus=1000000000 memory=805306368 +[ 2.5s] malformed message published +[ 10.3s] queues: name type durable messages_ready messages_unacknowledged +attachment.jobs quorum true 0 0 +attachment.jobs.dlq quorum true 1 0 +[ 10.4s] worker: {"timestamp":"2026-11-20T14:36:10.245Z","severity":"WARN","service.name":"messenger-worker","event":"worker","logger":"Worker","message":"malformed job message moved to dead letter queue","trace_id":"733415ad4bdbd66df930af833ef44f18","span_id":"abc299a80e5c1e42"} ## Итог по всем заданиям стенда $ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT status, count(*) FROM attachment_jobs GROUP BY status -c SELECT count(*) AS unpublished_outbox FROM outbox WHERE published_at IS NULL -c SELECT count(*) AS staging_left_on_ready FROM attachments WHERE status = 'ready' AND staging_key IS NOT NULL status | count --------+------- -(0 rows) + ready | 9 +(1 row) unpublished_outbox -------------------- @@ -55,3 +211,4 @@ $ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT statu ## Последний проход reconciler +{"mode":"apply","grace_seconds":3600,"staging_expired":0,"scanned":0,"fresh_skipped":0,"referenced":0,"orphans":0,"deleted":0,"failed":0,"orphan_keys":[],"duration_ms":351} diff --git a/evidence/persistence.txt b/evidence/persistence.txt index 81e114c..bdfa22b 100644 --- a/evidence/persistence.txt +++ b/evidence/persistence.txt @@ -1,27 +1,26 @@ # make test-persistence: restart.sh перезапускает postgres, redis, s3, rabbitmq, api, lb с сохранением volumes -# date: 2026-11-20T13:47:18Z -# commit: 5f870e4 +# date: 2026-11-20T14:33:01Z +# commit: d83876f ## до -/messenger-lab6-api-1 created started=0001-01-01T00:00:00Z -/messenger-lab6-api-2 created started=0001-01-01T00:00:00Z -/messenger-lab6-lb-1 created started=0001-01-01T00:00:00Z -/messenger-lab6-postgres-1 running started=2026-11-20T13:47:05.265451532Z -/messenger-lab6-rabbitmq-1 running started=2026-11-20T13:47:05.327304509Z -/messenger-lab6-redis-1 running started=2026-11-20T13:47:05.314284674Z -/messenger-lab6-s3-1 running started=2026-11-20T13:47:05.255000565Z +/messenger-lab6-api-1 running started=2026-11-20T14:32:32.185792399Z +/messenger-lab6-api-2 running started=2026-11-20T14:32:32.538220625Z +/messenger-lab6-lb-1 running started=2026-11-20T14:32:38.299124143Z +/messenger-lab6-postgres-1 running started=2026-11-20T14:32:22.796529774Z +/messenger-lab6-rabbitmq-1 running started=2026-11-20T14:32:22.722217174Z +/messenger-lab6-redis-1 running started=2026-11-20T14:32:22.787053855Z +/messenger-lab6-s3-1 running started=2026-11-20T14:32:22.813514565Z $ make test-persistence ACTION_SCRIPT=scripts/restart.sh python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080" -FAIL: GET /health/live: connection/TLS failure (URLError) -make: *** [Makefile:26: test-persistence] Error 1 -EXIT CODE 2 +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. ## после -/messenger-lab6-api-1 created started=0001-01-01T00:00:00Z -/messenger-lab6-api-2 created started=0001-01-01T00:00:00Z -/messenger-lab6-lb-1 created started=0001-01-01T00:00:00Z -/messenger-lab6-postgres-1 running started=2026-11-20T13:47:05.265451532Z -/messenger-lab6-rabbitmq-1 running started=2026-11-20T13:47:05.327304509Z -/messenger-lab6-redis-1 running started=2026-11-20T13:47:05.314284674Z -/messenger-lab6-s3-1 running started=2026-11-20T13:47:05.255000565Z +/messenger-lab6-api-1 running started=2026-11-20T14:33:08.406683646Z +/messenger-lab6-api-2 running started=2026-11-20T14:33:05.908734161Z +/messenger-lab6-lb-1 running started=2026-11-20T14:33:03.32738495Z +/messenger-lab6-postgres-1 running started=2026-11-20T14:33:03.697395758Z +/messenger-lab6-rabbitmq-1 running started=2026-11-20T14:33:04.196322444Z +/messenger-lab6-redis-1 running started=2026-11-20T14:33:03.432938355Z +/messenger-lab6-s3-1 running started=2026-11-20T14:33:03.540481157Z diff --git a/evidence/s3.txt b/evidence/s3.txt index bfd81dc..23bb478 100644 --- a/evidence/s3.txt +++ b/evidence/s3.txt @@ -1,6 +1,6 @@ # S3 (минимум lab4): идемпотентный bootstrap, приватность мимо API, права пользователя API -# date: 2026-11-20T13:49:02Z -# commit: 5f870e4 +# date: 2026-11-20T14:33:34Z +# commit: d83876f $ docker compose run --rm --no-deps -T s3-init Bucket created successfully `root/messenger-attachments`. diff --git a/evidence/smoke.txt b/evidence/smoke.txt index 8eec029..f207ebb 100644 --- a/evidence/smoke.txt +++ b/evidence/smoke.txt @@ -1,6 +1,6 @@ # Публичные проверки через LB; разные реплики обслуживают одну сессию -# date: 2026-11-20T13:47:06Z -# commit: 5f870e4 +# date: 2026-11-20T14:32:58Z +# commit: d83876f $ make check python3 scripts/check_contract.py @@ -8,12 +8,15 @@ PASS: offline skeleton structure, local refs and Python syntax; application NOT $ make test python3 tests/smoke.py --base-url "http://lb:8080" -FAIL: GET /health/live: connection/TLS failure (URLError) -make: *** [Makefile:19: test] Error 1 -EXIT CODE 2 +PASS: lab6 public API scenario; infrastructure and grading evidence remain separate. $ python3 scripts/probe.py instances 6 -register -> 0 -login failed: 0 -EXIT CODE 1 +register -> 201 +login -> 201 expires_at: 2026-11-20T15:33:01.208Z +GET /api/v1/users/me -> 200 X-Instance-Id: 64377e499417 +GET /api/v1/users/me -> 200 X-Instance-Id: 25ff01cef182 +GET /api/v1/users/me -> 200 X-Instance-Id: 64377e499417 +GET /api/v1/users/me -> 200 X-Instance-Id: 25ff01cef182 +GET /api/v1/users/me -> 200 X-Instance-Id: 64377e499417 +GET /api/v1/users/me -> 200 X-Instance-Id: 25ff01cef182 diff --git a/evidence/telemetry.txt b/evidence/telemetry.txt index 44c756c..2ddcab9 100644 --- a/evidence/telemetry.txt +++ b/evidence/telemetry.txt @@ -1,263 +1,158 @@ # Наблюдаемость: контрольный запрос (trace + логи), dashboard, перцентили, приватность, правила -# date: 2026-11-20T13:59:52Z -# commit: 5f870e4 +# date: 2026-11-20T14:36:18Z +# commit: d83876f ## Prometheus: правила загружены (promtool и /api/v1/rules) $ docker compose exec -T prometheus promtool check rules /etc/prometheus/rules/messenger.yml -Error response from daemon: Container 81bb4c2a806cbf4ed34b6b599f104167debe5fefbeeef14753ba2eec67350329 is restarting, wait until the container is running -EXIT CODE 1 +Checking /etc/prometheus/rules/messenger.yml + SUCCESS: 13 rules found + $ sh -c wget -qO- http://grafana:3000/api/datasources/proxy/uid/prometheus/api/v1/rules | python3 -c 'import json,sys; [print(r["type"], r["name"], r["health"]) for g in json.load(sys.stdin)["data"]["groups"] for r in g["rules"]]' -wget: bad address 'grafana:3000' -Traceback (most recent call last): - File "", line 1, in - File "/usr/lib/python3.12/json/__init__.py", line 293, in load - return loads(fp.read(), - ^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/__init__.py", line 346, in loads - return _default_decoder.decode(s) - ^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 338, in decode - obj, end = self.raw_decode(s, idx=_w(s, 0).end()) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode - raise JSONDecodeError("Expecting value", s, err.value) from None -json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -EXIT CODE 1 +alerting MessengerHighErrorRate ok +alerting MessengerApiNotReady ok +alerting MessengerJobQueueLag ok +alerting MessengerSlowApi ok +alerting TelemetryExportFailing ok +recording messenger:http_requests:rate5m ok +recording messenger:http_errors:rate5m ok +recording messenger:http_error_ratio:rate5m ok +recording messenger:http_error_ratio:rate1h ok +recording messenger:http_latency_p95:rate5m ok +recording messenger:http_fast_ratio:rate1h ok +recording messenger:time_to_ready_fast_ratio:rate1h ok +recording messenger:jobs_queue_oldest_age:max ok ## Grafana: datasources с фиксированными UID, dashboard из provisioning $ sh -c for uid in prometheus loki tempo; do wget -qO- http://grafana:3000/api/datasources/uid/$uid | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["uid"], d["type"], d["url"])'; done -wget: bad address 'grafana:3000' -Traceback (most recent call last): - File "", line 1, in - File "/usr/lib/python3.12/json/__init__.py", line 293, in load - return loads(fp.read(), - ^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/__init__.py", line 346, in loads - return _default_decoder.decode(s) - ^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 338, in decode - obj, end = self.raw_decode(s, idx=_w(s, 0).end()) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode - raise JSONDecodeError("Expecting value", s, err.value) from None -json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -wget: bad address 'grafana:3000' -Traceback (most recent call last): - File "", line 1, in - File "/usr/lib/python3.12/json/__init__.py", line 293, in load - return loads(fp.read(), - ^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/__init__.py", line 346, in loads - return _default_decoder.decode(s) - ^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 338, in decode - obj, end = self.raw_decode(s, idx=_w(s, 0).end()) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode - raise JSONDecodeError("Expecting value", s, err.value) from None -json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -wget: bad address 'grafana:3000' -Traceback (most recent call last): - File "", line 1, in - File "/usr/lib/python3.12/json/__init__.py", line 293, in load - return loads(fp.read(), - ^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/__init__.py", line 346, in loads - return _default_decoder.decode(s) - ^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 338, in decode - obj, end = self.raw_decode(s, idx=_w(s, 0).end()) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/json/decoder.py", line 356, in raw_decode - raise JSONDecodeError("Expecting value", s, err.value) from None -json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -EXIT CODE 1 +prometheus prometheus http://prometheus:9090 +loki loki http://loki:3100 +tempo tempo http://tempo:3200 ## Контрольный upload с клиентским traceparent: trace в Tempo и логи в Loki $ python3 scripts/trace-check.py -Traceback (most recent call last): - File "/usr/lib/python3.12/urllib/request.py", line 1344, in do_open - h.request(req.get_method(), req.selector, req.data, headers, - File "/usr/lib/python3.12/http/client.py", line 1358, in request - self._send_request(method, url, body, headers, encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1404, in _send_request - self.endheaders(body, encode_chunked=encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1353, in endheaders - self._send_output(message_body, encode_chunked=encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1113, in _send_output - self.send(msg) - File "/usr/lib/python3.12/http/client.py", line 1057, in send - self.connect() - File "/usr/lib/python3.12/http/client.py", line 1023, in connect - self.sock = self._create_connection( - ^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/socket.py", line 841, in create_connection - for res in getaddrinfo(host, port, 0, SOCK_STREAM): - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/socket.py", line 978, in getaddrinfo - for res in _socket.getaddrinfo(host, port, family, type, proto, flags): - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -socket.gaierror: [Errno -2] Name does not resolve +upload -> 202 queued traceparent 00-0a9700e372765e5f2774c2c5347f8c1b-0de651da523f691b-01 +attachment 0a91d4b0-0624-419a-824e-d4ae671e7d2b status ready after 0.57 s -During handling of the above exception, another exception occurred: +trace 0a9700e372765e5f2774c2c5347f8c1b: 79 spans (prisma:* internals except db_query omitted below) + messenger-api SPAN_KIND_SERVER POST /api/v1/chats/{chat_id}/attachments 50.36 ms parent=client + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 0.48 ms parent=prisma:engine:query + messenger-api SPAN_KIND_CLIENT S3.PutObject 25.34 ms parent=POST /api/v1/chats/{chat_id}/attachments + messenger-api SPAN_KIND_INTERNAL prisma:client:transaction 7.80 ms parent=POST /api/v1/chats/{chat_id}/attachments + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 0.15 ms parent=prisma:engine:start_transaction + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 0.81 ms parent=prisma:engine:query + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 0.51 ms parent=prisma:engine:query + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 0.27 ms parent=prisma:engine:query + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 0.31 ms parent=prisma:engine:query + messenger-api SPAN_KIND_CLIENT prisma:engine:db_query 1.33 ms parent=prisma:engine:commit_transaction + messenger-relay SPAN_KIND_PRODUCER attachment.jobs publish 5.71 ms parent=prisma:client:transaction + messenger-worker SPAN_KIND_CONSUMER attachment.jobs process 66.86 ms parent=attachment.jobs publish + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.25 ms parent=prisma:engine:connection + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.34 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.26 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_INTERNAL prisma:client:transaction 7.26 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.14 ms parent=prisma:engine:start_transaction + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.48 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.50 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.26 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.27 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 1.24 ms parent=prisma:engine:commit_transaction + messenger-worker SPAN_KIND_CLIENT S3.GetObject 3.00 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_INTERNAL attachment.render_variants 12.41 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT S3.PutObject 7.85 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT S3.PutObject 5.94 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT S3.PutObject 5.73 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT S3.PutObject 5.69 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_INTERNAL prisma:client:transaction 7.42 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.16 ms parent=prisma:engine:start_transaction + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.61 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.71 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.44 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 0.26 ms parent=prisma:engine:query + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 1.32 ms parent=prisma:engine:commit_transaction + messenger-worker SPAN_KIND_CLIENT S3.DeleteObject 3.23 ms parent=attachment.jobs process + messenger-worker SPAN_KIND_CLIENT prisma:engine:db_query 1.71 ms parent=prisma:engine:query -Traceback (most recent call last): - File "/work/scripts/trace-check.py", line 134, in - main() - File "/work/scripts/trace-check.py", line 72, in main - auth, chat = session() - ^^^^^^^^^ - File "/work/scripts/trace-check.py", line 37, in session - _, user = call('POST', BASE + '/api/v1/users', {'username': username, 'display_name': 'Trace check', 'password': password}) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/work/scripts/trace-check.py", line 28, in call - with urllib.request.urlopen(request, timeout=15) as response: - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 215, in urlopen - return opener.open(url, data, timeout) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 515, in open - response = self._open(req, data) - ^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 532, in _open - result = self._call_chain(self.handle_open, protocol, protocol + - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 492, in _call_chain - result = func(*args) - ^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 1373, in http_open - return self.do_open(http.client.HTTPConnection, req) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 1347, in do_open - raise URLError(err) -urllib.error.URLError: -EXIT CODE 1 +Loki {service_name=~"messenger-.+"} | trace_id="0a9700e372765e5f2774c2c5347f8c1b" + messenger-worker INFO job.handled span_id=8f3cc8917f60f19d {"timestamp":"2026-11-20T14:36:19.298Z","severity":"INFO","s + messenger-api INFO http.request span_id=70c807e8b4f94da9 {"timestamp":"2026-11-20T14:36:19.155Z","severity":"INFO","s + +PASS: client trace continued through api -> relay -> worker, logs linked by trace_id ## Секреты и содержимое не попадают в telemetry; в labels метрик нет ID $ python3 scripts/telemetry-privacy.py -Traceback (most recent call last): - File "/usr/lib/python3.12/urllib/request.py", line 1344, in do_open - h.request(req.get_method(), req.selector, req.data, headers, - File "/usr/lib/python3.12/http/client.py", line 1358, in request - self._send_request(method, url, body, headers, encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1404, in _send_request - self.endheaders(body, encode_chunked=encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1353, in endheaders - self._send_output(message_body, encode_chunked=encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1113, in _send_output - self.send(msg) - File "/usr/lib/python3.12/http/client.py", line 1057, in send - self.connect() - File "/usr/lib/python3.12/http/client.py", line 1023, in connect - self.sock = self._create_connection( - ^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/socket.py", line 841, in create_connection - for res in getaddrinfo(host, port, 0, SOCK_STREAM): - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/socket.py", line 978, in getaddrinfo - for res in _socket.getaddrinfo(host, port, family, type, proto, flags): - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -socket.gaierror: [Errno -2] Name does not resolve - -During handling of the above exception, another exception occurred: - -Traceback (most recent call last): - File "/work/scripts/telemetry-privacy.py", line 102, in - main() - File "/work/scripts/telemetry-privacy.py", line 51, in main - user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'Privacy', 'password': secrets['password']}, traced()) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/work/scripts/telemetry-privacy.py", line 27, in call - with urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, method=method, headers=headers), timeout=15) as r: - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 215, in urlopen - return opener.open(url, data, timeout) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 515, in open - response = self._open(req, data) - ^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 532, in _open - result = self._call_chain(self.handle_open, protocol, protocol + - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 492, in _call_chain - result = func(*args) - ^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 1373, in http_open - return self.do_open(http.client.HTTPConnection, req) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 1347, in do_open - raise URLError(err) -urllib.error.URLError: -EXIT CODE 1 +sent 6 traced requests with known password, token, message text and filename; waiting 25 s for export +Tempo: 6/6 traces fetched (79945 bytes); Loki: 7 log lines carry these trace_ids (control) + password in traces: False log lines in Loki (5 min): 0 + message text in traces: False log lines in Loki (5 min): 0 + filename in traces: False log lines in Loki (5 min): 0 + session token in traces: False log lines in Loki (5 min): 0 + basic credentials in traces: False log lines in Loki (5 min): 0 + Authorization hdr in traces: False log lines in Loki (5 min): 0 +Prometheus: 893 series, 22 metric names from messenger services; label keys: cpu_mode, db_client_connection_state, deployment_environment_name, http_request_method, http_response_status_class, http_route, instance, job, job_type, le, messaging_destination_name, outcome, service_version, state, telemetry_sdk_language, telemetry_sdk_name, telemetry_sdk_version + series with a UUID in any label value: 0 + http_route values: /api/v1/attachments/{attachment_id}, /api/v1/attachments/{attachment_id}/content, /api/v1/auth/sessions, /api/v1/auth/sessions/current, /api/v1/chats, /api/v1/chats/{chat_id}, /api/v1/chats/{chat_id}/attachments, /api/v1/chats/{chat_id}/messages, /api/v1/users, /api/v1/users/me, /health/core, /health/live, /health/ready +PASS: no secrets/content in logs and traces, no IDs in metric labels ## Перцентили dashboard против клиентского замера tests/load.py $ python3 scripts/latency-compare.py --duration 30 -Traceback (most recent call last): - File "/work/scripts/latency-compare.py", line 52, in - main() - File "/work/scripts/latency-compare.py", line 31, in main - subprocess.run([sys.executable, 'tests/load.py', '--base-url', BASE, '--duration', duration, '--output', output], - File "/usr/lib/python3.12/subprocess.py", line 571, in run - raise CalledProcessError(retcode, process.args, -subprocess.CalledProcessError: Command '['/usr/bin/python3', 'tests/load.py', '--base-url', 'http://lb:8080', '--duration', '30', '--output', '/tmp/tmpn5jz4yx8/load.json']' returned non-zero exit status 1. -EXIT CODE 1 +waiting 25 s for the metric export interval +client (tests/load.py): 3411 requests, 113.4 rps, errors 0 +prometheus: 3661 requests in POST /api/v1/chats/{chat_id}/messages over 60 s + client, ms prometheus, ms +p50 18.33 19.68 +p95 89.20 92.20 +p99 163.29 176.76 +server-side histogram excludes network/client overhead; values are interpolated inside buckets (…, 5, 10, 25, 50, 100 ms, …). ## Все запросы dashboard (пустые панели alerts/WARN-логов допустимы без инцидентов) $ python3 scripts/dashboard-check.py -Traceback (most recent call last): - File "/usr/lib/python3.12/urllib/request.py", line 1344, in do_open - h.request(req.get_method(), req.selector, req.data, headers, - File "/usr/lib/python3.12/http/client.py", line 1358, in request - self._send_request(method, url, body, headers, encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1404, in _send_request - self.endheaders(body, encode_chunked=encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1353, in endheaders - self._send_output(message_body, encode_chunked=encode_chunked) - File "/usr/lib/python3.12/http/client.py", line 1113, in _send_output - self.send(msg) - File "/usr/lib/python3.12/http/client.py", line 1057, in send - self.connect() - File "/usr/lib/python3.12/http/client.py", line 1023, in connect - self.sock = self._create_connection( - ^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/socket.py", line 841, in create_connection - for res in getaddrinfo(host, port, 0, SOCK_STREAM): - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/socket.py", line 978, in getaddrinfo - for res in _socket.getaddrinfo(host, port, family, type, proto, flags): - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -socket.gaierror: [Errno -2] Name does not resolve +Grafana dashboard: Messenger overview folder: Messenger +OK Доступность API, 1 ч (SLO ≥ 99% без 5xx) A 1 =1 +OK Запросы быстрее 500 мс, 1 ч (SLO ≥ 95%) A 1 =1 +OK Вложения готовы за ≤ 10 с, 1 ч (SLO ≥ 95%) A 1 =0.6666666666666667 +EMPTY Alerts (pending / firing) A 0 +OK RPS по маршрутам (без health) A 12 =0, =0, =0, =0 +OK Ответы по классам статуса (без health) A 2 2xx=61.1782202581422, 4xx=0 +OK Доля 5xx среди бизнес-запросов (окно 5m, порог alert 5%) A 1 =0 +OK Длительность API p50 / p95 / p99 (все реплики, без health) A 1 =0.019676691515573837 +OK Длительность API p50 / p95 / p99 (все реплики, без health) B 1 =0.09219914944691271 +OK Длительность API p50 / p95 / p99 (все реплики, без health) C 1 =0.17675359699995996 +OK p95 по маршрутам A 12 =NaN, =NaN, =NaN, =NaN +OK Глубина очереди attachment.jobs (из attachment_jobs) A 3 =0, =0, =0 +OK Возраст старейшего готового задания (порог alert 60 s) A 1 =0 +OK Worker: занято / ёмкость A 1 =0 +OK Worker: занято / ёмкость B 1 =2 +OK Worker: занято / ёмкость C 1 =0 +OK Задания по исходу (в секунду) A 5 failed=0, malformed=0, retry=0, skipped=0.025 +OK Длительность обработки задания p50 / p95 / p99 A 1 =NaN +OK Длительность обработки задания p50 / p95 / p99 B 1 =NaN +OK Длительность обработки задания p50 / p95 / p99 C 1 =NaN +OK Время от upload до ready p50 / p95 / p99 A 1 =NaN +OK Время от upload до ready p50 / p95 / p99 B 1 =NaN +OK Время от upload до ready p50 / p95 / p99 C 1 =NaN +OK Пул БД: занято / ожидают соединения A 3 =0, =0, =0 +OK Пул БД: занято / ожидают соединения B 3 =0, =0, =0 +OK Пул БД: занято / ожидают соединения C 3 =20, =3, =5 +OK CPU процессов (доля ядра) A 4 =0.2771702986118047, =0.2803168326733069, =0.006292157529451772, =0.00 +OK CPU процессов (доля ядра) B 2 =0.013556760600942309, =0.0006813251539196734 +OK RAM процессов (RSS) A 4 =207585280, =208904192, =90546176, =106270720 +OK RAM процессов (RSS) B 2 =210243584, =164040704 +OK Принято / отправлено / ошибки отправки (в секунду) A 1 =1512.6751237147007 +OK Принято / отправлено / ошибки отправки (в секунду) B 1 =1512.6751237147007 +OK Принято / отправлено / ошибки отправки (в секунду) C 1 =0 +OK Принято / отправлено / ошибки отправки (в секунду) D 1 =75.96230776068984 +OK Принято / отправлено / ошибки отправки (в секунду) E 1 =0 +OK Принято / отправлено / ошибки отправки (в секунду) F 1 =0 +OK Очередь exporter (ограничена queue_size) A 3 =0, =0, =0 +OK Очередь exporter (ограничена queue_size) B 1 =200 +OK Логи API и worker (WARN и выше) A 20 +OK Все логи (http.request, job.handled, …) A 20 +OK Последние трассы (HTTP server и consumer spans) A 20 -During handling of the above exception, another exception occurred: - -Traceback (most recent call last): - File "/work/scripts/dashboard-check.py", line 57, in - main() - File "/work/scripts/dashboard-check.py", line 43, in main - grafana = get('/api/dashboards/uid/messenger-overview') - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/work/scripts/dashboard-check.py", line 19, in get - with urllib.request.urlopen(url, timeout=15) as response: - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 215, in urlopen - return opener.open(url, data, timeout) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 515, in open - response = self._open(req, data) - ^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 532, in _open - result = self._call_chain(self.handle_open, protocol, protocol + - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 492, in _call_chain - result = func(*args) - ^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 1373, in http_open - return self.do_open(http.client.HTTPConnection, req) - ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - File "/usr/lib/python3.12/urllib/request.py", line 1347, in do_open - raise URLError(err) -urllib.error.URLError: +WARN: 1 empty queries EXIT CODE 1 ## Пример структурного лога (stdout API) +{"timestamp":"2026-11-20T14:37:24.827Z","severity":"INFO","service.name":"messenger-api","event":"http.request","logger":"Http","method":"POST","route":"/api/v1/chats/{chat_id}/messages","status":201,"duration_ms":23.22,"request_id":"078e6db3-d15e-4bdf-bac9-5fe5ea48bd35","trace_id":"67197c10f2dc44bc87840224dec07957","span_id":"a4e80137cbbf9edc"} +{"timestamp":"2026-11-20T14:37:24.838Z","severity":"INFO","service.name":"messenger-api","event":"http.request","logger":"Http","method":"POST","route":"/api/v1/chats/{chat_id}/messages","status":201,"duration_ms":20.5,"request_id":"5513c34d-64ea-4250-9cee-a9d9a4b12892","trace_id":"ec0813f680256f525febe0676221457b","span_id":"d20713fac541ea0b"} diff --git a/evidence/tests.txt b/evidence/tests.txt index 1476fd1..6a82021 100644 --- a/evidence/tests.txt +++ b/evidence/tests.txt @@ -1,22 +1,22 @@ # Собственные e2e-тесты (PostgreSQL + Redis + MinIO из compose.test.yaml); основной стенд на время тестов остановлен ради памяти Docker -# date: 2026-11-20T13:44:04Z -# commit: 5f870e4 +# date: 2026-11-20T14:31:15Z +# commit: d83876f $ docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose Network messenger-lab6-test_default Creating Network messenger-lab6-test_default Created Container messenger-lab6-test-redis-1 Creating - Container messenger-lab6-test-postgres-1 Creating Container messenger-lab6-test-s3-1 Creating + Container messenger-lab6-test-postgres-1 Creating Container messenger-lab6-test-s3-1 Created Container messenger-lab6-test-redis-1 Created Container messenger-lab6-test-postgres-1 Created Container messenger-lab6-test-s3-1 Starting Container messenger-lab6-test-redis-1 Starting Container messenger-lab6-test-postgres-1 Starting - Container messenger-lab6-test-redis-1 Started Container messenger-lab6-test-s3-1 Started Container messenger-lab6-test-postgres-1 Started + Container messenger-lab6-test-redis-1 Started Prisma schema loaded from prisma/schema.prisma Datasource "db": PostgreSQL database "messenger_test", schema "public" at "postgres:5432" @@ -43,96 +43,96 @@ migrations/ └─ migration.sql All migrations have been successfully applied. -[Nest] 103 - 11/20/2026, 1:46:32 PM  ERROR [S3Service] get staging/1c496eff-3625-4548-a54b-25aeceba7b0b failed: NoSuchKey -PASS test/api.e2e-spec.ts (17.66 s) +[Nest] 102 - 11/20/2026, 2:31:59 PM  ERROR [S3Service] get staging/a3987d2f-e0a6-4581-8caa-8670462a94fa failed: NoSuchKey +PASS test/api.e2e-spec.ts (17.729 s) API мессенджера (e2e) — граничные случаи сверх публичного smoke POST /api/v1/users - ✓ отклоняет некорректный JSON с кодом 400 (92 ms) - ✓ отклоняет тело с лишними полями (29 ms) - ✓ отклоняет username с заглавными буквами (3 ms) + ✓ отклоняет некорректный JSON с кодом 400 (112 ms) + ✓ отклоняет тело с лишними полями (39 ms) + ✓ отклоняет username с заглавными буквами (4 ms) ✓ отклоняет display_name из одних пробелов (4 ms) - ✓ отклоняет дубликат username с кодом 409 (177 ms) - ✓ никогда не возвращает поле пароля или его хэша (35 ms) - ✓ отклоняет username короче 3 символов (4 ms) + ✓ отклоняет дубликат username с кодом 409 (183 ms) + ✓ никогда не возвращает поле пароля или его хэша (32 ms) + ✓ отклоняет username короче 3 символов (3 ms) ✓ отклоняет username длиннее 32 символов (4 ms) - ✓ отклоняет username с недопустимыми символами (дефис) (8 ms) - ✓ принимает username ровно на границах длины 3 и 32 символа (61 ms) - ✓ отклоняет display_name длиннее 100 Unicode code points (2 ms) - ✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (28 ms) - ✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (4 ms) + ✓ отклоняет username с недопустимыми символами (дефис) (3 ms) + ✓ принимает username ровно на границах длины 3 и 32 символа (56 ms) + ✓ отклоняет display_name длиннее 100 Unicode code points (3 ms) + ✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (27 ms) + ✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (3 ms) контроль доступа - ✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (6 ms) - ✓ возвращает 404 (не 403), когда чат запрашивает не его участник (242 ms) - ✓ отклоняет создание чата, если вызывающий не входит в member_ids (162 ms) - ✓ отклоняет создание чата с дублирующимися member_ids (75 ms) - ✓ считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре (80 ms) - ✓ принимает ровно 100 участников и отклоняет 101 (102 ms) - ✓ отклоняет создание чата с неизвестным участником (73 ms) - ✓ отклоняет создание чата с пустым/пробельным title (77 ms) - ✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (82 ms) - ✓ возвращает 404 для корректного по формату, но несуществующего chat_id (68 ms) + ✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (5 ms) + ✓ возвращает 404 (не 403), когда чат запрашивает не его участник (254 ms) + ✓ отклоняет создание чата, если вызывающий не входит в member_ids (155 ms) + ✓ отклоняет создание чата с дублирующимися member_ids (83 ms) + ✓ считает один UUID в разном регистре дубликатом и узнаёт вызывающего в верхнем регистре (112 ms) + ✓ принимает ровно 100 участников и отклоняет 101 (104 ms) + ✓ отклоняет создание чата с неизвестным участником (79 ms) + ✓ отклоняет создание чата с пустым/пробельным title (75 ms) + ✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (74 ms) + ✓ возвращает 404 для корректного по формату, но несуществующего chat_id (75 ms) GET /api/v1/chats (пагинация) - ✓ использует limit=50 по умолчанию, если limit не передан (89 ms) - ✓ отклоняет нечисловой limit (72 ms) - ✓ отклоняет limit=0 (67 ms) - ✓ отклоняет повторённые limit и cursor (65 ms) - ✓ отклоняет cursor, не являющийся корректным base64url JSON (72 ms) - ✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (125 ms) - ✓ обходит весь список чатов по страницам без пропусков и дублей (236 ms) + ✓ использует limit=50 по умолчанию, если limit не передан (85 ms) + ✓ отклоняет нечисловой limit (75 ms) + ✓ отклоняет limit=0 (77 ms) + ✓ отклоняет повторённые limit и cursor (72 ms) + ✓ отклоняет cursor, не являющийся корректным base64url JSON (67 ms) + ✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (69 ms) + ✓ обходит весь список чатов по страницам без пропусков и дублей (114 ms) сообщения - ✓ не принимает sender_id, переданный клиентом (198 ms) - ✓ считает attachment_ids: [] равным отсутствию поля, неизвестный ID — 404, неверный тип — 400 (385 ms) - ✓ отклоняет пустое сообщение (290 ms) - ✓ отклоняет сообщение из одних пробелов (175 ms) - ✓ отклоняет отправку в чат, где вызывающий не участник (214 ms) - ✓ отклоняет limit=0 при чтении истории (157 ms) - ✓ отклоняет limit=101 при чтении истории (157 ms) - ✓ отклоняет нечисловой limit (158 ms) - ✓ отклоняет текст сообщения длиннее 4000 Unicode code points (151 ms) - ✓ принимает текст сообщения ровно из 4000 Unicode code points (159 ms) - ✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (144 ms) - ✓ отклоняет cursor, не являющийся корректным base64url JSON (135 ms) - ✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (195 ms) - ✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (73 ms) - ✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (97 ms) - ✓ отклоняет cursor, взятый из другого чата (302 ms) - ✓ обходит всю историю по страницам без пропусков и дублей (245 ms) + ✓ не принимает sender_id, переданный клиентом (144 ms) + ✓ считает attachment_ids: [] равным отсутствию поля, неизвестный ID — 404, неверный тип — 400 (241 ms) + ✓ отклоняет пустое сообщение (148 ms) + ✓ отклоняет сообщение из одних пробелов (132 ms) + ✓ отклоняет отправку в чат, где вызывающий не участник (199 ms) + ✓ отклоняет limit=0 при чтении истории (165 ms) + ✓ отклоняет limit=101 при чтении истории (148 ms) + ✓ отклоняет нечисловой limit (169 ms) + ✓ отклоняет текст сообщения длиннее 4000 Unicode code points (185 ms) + ✓ принимает текст сообщения ровно из 4000 Unicode code points (218 ms) + ✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (158 ms) + ✓ отклоняет cursor, не являющийся корректным base64url JSON (158 ms) + ✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (168 ms) + ✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (80 ms) + ✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (68 ms) + ✓ отклоняет cursor, взятый из другого чата (276 ms) + ✓ обходит всю историю по страницам без пропусков и дублей (277 ms) X-Request-Id - ✓ присутствует и уникален для независимых запросов (5 ms) + ✓ присутствует и уникален для независимых запросов (4 ms) ✓ совпадает с request_id внутри тела ошибки (2 ms) -[Nest] 103 - 11/20/2026, 1:46:38 PM  ERROR [S3Service] get staging/36a0d174-fee7-480c-ab57-6dfbc1fcc516 failed: NoSuchKey -[Nest] 103 - 11/20/2026, 1:46:38 PM  ERROR [S3Service] get staging/b8aa2557-6551-4669-a326-ddb062fcb935 failed: NoSuchKey -PASS test/jobs.e2e-spec.ts (18.663 s) +[Nest] 102 - 11/20/2026, 2:32:05 PM  ERROR [S3Service] get staging/02ca6856-dcd8-4bbd-9fe8-272649f2b87c failed: NoSuchKey +[Nest] 102 - 11/20/2026, 2:32:05 PM  ERROR [S3Service] get staging/8007bc99-ed6a-4a68-9ff7-1b65dcb1cd82 failed: NoSuchKey +PASS test/jobs.e2e-spec.ts (19.57 s) Фоновая обработка вложений (e2e) до обработки - ✓ queued: метаданные доступны, content любого варианта — 409, сообщение с вложением создаётся (219 ms) + ✓ queued: метаданные доступны, content любого варианта — 409, сообщение с вложением создаётся (250 ms) результат worker - ✓ ready: оригинал неизменен, thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP без увеличения (245 ms) - ✓ маленький исходник не увеличивается в thumbnail/optimized, crop — увеличивается (107 ms) - ✓ прозрачность компонуется на белый, EXIF orientation применяется (266 ms) + ✓ ready: оригинал неизменен, thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP без увеличения (253 ms) + ✓ маленький исходник не увеличивается в thumbnail/optimized, crop — увеличивается (148 ms) + ✓ прозрачность компонуется на белый, EXIF orientation применяется (322 ms) ✓ worker ограничивает пиксели до распаковки: превышение — InvalidImageError (18 ms) - ✓ размеры считаются целочисленно: 319×200 → 256×160, перебор совпадает с точной формулой (2848 ms) + ✓ размеры считаются целочисленно: 319×200 → 256×160, перебор совпадает с точной формулой (2289 ms) ✓ размеры округляются вниз, минимум 1 px (1 ms) идемпотентность и повторная доставка - ✓ повтор уже ready-задания — no-op: второго набора вариантов нет, объекты не меняются (199 ms) - ✓ пока lease действует, второй обработчик того же job не запускается (115 ms) - ✓ worker упал после записи объектов, до COMMIT/ack: lease истекает, повтор завершает тот же результат (259 ms) - ✓ worker упал после COMMIT, до ack: повтор — no-op, staging убирается при повторной доставке (157 ms) - ✓ сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз (162 ms) - ✓ устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются (96 ms) + ✓ повтор уже ready-задания — no-op: второго набора вариантов нет, объекты не меняются (249 ms) + ✓ пока lease действует, второй обработчик того же job не запускается (162 ms) + ✓ worker упал после записи объектов, до COMMIT/ack: lease истекает, повтор завершает тот же результат (293 ms) + ✓ worker упал после COMMIT, до ack: повтор — no-op, staging убирается при повторной доставке (210 ms) + ✓ сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз (233 ms) + ✓ устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются (62 ms) ошибки, повторы и replay - ✓ временная ошибка S3: повтор с backoff, до срока задание не берётся, затем ready (225 ms) - ✓ попытки исчерпаны — failed retry_exhausted; replay явно возвращает в очередь и доводит до ready (289 ms) - ✓ lease истёк на последней попытке — failed retry_exhausted, а не вечный processing (183 ms) - ✓ replay и очистка staging не теряют исходник ни при каком порядке (252 ms) - ✓ replay задания в очереди не создаёт дубль (39 ms) - ✓ нераспаковываемое изображение — постоянная ошибка: сразу failed invalid_image без повторов (104 ms) - ✓ staging подменён — failed checksum_mismatch; staging пропал — failed staging_missing (135 ms) - ✓ превышение времени обработки — временная ошибка с повтором (129 ms) + ✓ временная ошибка S3: повтор с backoff, до срока задание не берётся, затем ready (208 ms) + ✓ попытки исчерпаны — failed retry_exhausted; replay явно возвращает в очередь и доводит до ready (470 ms) + ✓ lease истёк на последней попытке — failed retry_exhausted, а не вечный processing (278 ms) + ✓ replay и очистка staging не теряют исходник ни при каком порядке (541 ms) + ✓ replay задания в очереди не создаёт дубль (76 ms) + ✓ нераспаковываемое изображение — постоянная ошибка: сразу failed invalid_image без повторов (165 ms) + ✓ staging подменён — failed checksum_mismatch; staging пропал — failed staging_missing (134 ms) + ✓ превышение времени обработки — временная ошибка с повтором (112 ms) формат сообщения и backoff ✓ сообщение соответствует jobs.schema.json, лишние/неверные поля отклоняются (1 ms) - ✓ backoff растёт экспоненциально с jitter и ограничен сверху + ✓ backoff растёт экспоненциально с jitter и ограничен сверху (1 ms) console.warn An error was encountered in a non-retryable streaming request. @@ -158,327 +158,327 @@ PASS test/jobs.e2e-spec.ts (18.663 s) at ../node_modules/@nestjs/core/router/router-execution-context.js:46:28 at Object. (../node_modules/@nestjs/core/router/router-proxy.js:9:17) -[Nest] 109 - 11/20/2026, 1:46:38 PM  ERROR [S3Service] put staging/d5549bb7-a5b5-4167-a7fb-a839cd6baade failed: Error -[Nest] 109 - 11/20/2026, 1:46:38 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 108 - 11/20/2026, 2:32:06 PM  ERROR [S3Service] put staging/1071fe6c-2f2f-4f80-a8b5-904ca05009a2 failed: Error +[Nest] 108 - 11/20/2026, 2:32:06 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "object storage unavailable", "method": "POST", "route": "/api/v1/chats/{chat_id}/attachments", "status": 503, - "request_id": "2add0c90-0471-4276-995b-aae8a5f7216d" + "request_id": "38769a67-411f-41a7-bca3-d3682a083471" } -[Nest] 109 - 11/20/2026, 1:46:38 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 108 - 11/20/2026, 2:32:06 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "Internal server error", "method": "POST", "route": "/api/v1/chats/{chat_id}/attachments", "status": 500, - "request_id": "eadb3ad5-7ff3-42e4-ad74-a7e0ffd305f7" + "request_id": "be749a43-6bee-4629-ac78-3f15b6f77eac" } -[Nest] 109 - 11/20/2026, 1:46:39 PM  ERROR [AttachmentsService] metadata insert failed for staging/0f332817-4f12-4179-b0be-fc288fc2a845 -[Nest] 109 - 11/20/2026, 1:46:39 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 108 - 11/20/2026, 2:32:06 PM  ERROR [AttachmentsService] metadata insert failed for staging/50082f9d-e8dd-4f01-9391-47bf371e52fb +[Nest] 108 - 11/20/2026, 2:32:06 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "database unavailable", "method": "POST", "route": "/api/v1/chats/{chat_id}/attachments", "status": 503, - "request_id": "9b77d2a1-3625-405b-aa41-76d0cef2b0cc" + "request_id": "2a4d5542-1230-4568-acb5-7eb6c4390cdf" } -[Nest] 109 - 11/20/2026, 1:46:39 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 108 - 11/20/2026, 2:32:06 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "database unavailable", "method": "POST", "route": "/api/v1/chats/{chat_id}/attachments", "status": 503, - "request_id": "985d7e65-e5a9-4642-adf2-262f75e46929" + "request_id": "41953d69-f89d-42ba-9f5c-61bd4fa2e40d" } -PASS test/attachments.e2e-spec.ts (19.281 s) +PASS test/attachments.e2e-spec.ts (20.033 s) Загрузка вложений (e2e) успешная загрузка - ✓ возвращает 202 Attachment queued по контракту, staging и задание сохранены до ответа (258 ms) + ✓ возвращает 202 Attachment queued по контракту, staging и задание сохранены до ответа (307 ms) ✓ принимает реальный JPEG (48 ms) - ✓ игнорирует параметры и регистр Content-Type (36 ms) - ✓ принимает файл ровно 10 MiB, filename ровно 255 символов и PNG с байтами после IEND (529 ms) - ✓ принимает ровно 40 млн пикселей (3204 ms) + ✓ игнорирует параметры и регистр Content-Type (41 ms) + ✓ принимает файл ровно 10 MiB, filename ровно 255 символов и PNG с байтами после IEND (724 ms) + ✓ принимает ровно 40 млн пикселей (2896 ms) порядок проверок и доступ - ✓ без токена — 401 раньше любых проверок содержимого (14 ms) - ✓ посторонний и несуществующий чат — одинаковый 404, чужой файл не сохраняется (22 ms) - ✓ неверный UUID чата — 400 (4 ms) + ✓ без токена — 401 раньше любых проверок содержимого (19 ms) + ✓ посторонний и несуществующий чат — одинаковый 404, чужой файл не сохраняется (17 ms) + ✓ неверный UUID чата — 400 (5 ms) filename - ✓ отсутствует — 400 (5 ms) + ✓ отсутствует — 400 (4 ms) ✓ пустой — 400 (4 ms) - ✓ только пробелы — 400 (4 ms) - ✓ 256 символов — 400 (12 ms) - ✓ путь через / — 400 (10 ms) - ✓ путь через \ — 400 (11 ms) - ✓ NUL — 400 (11 ms) - ✓ перевод строки — 400 (8 ms) + ✓ только пробелы — 400 (5 ms) + ✓ 256 символов — 400 (5 ms) + ✓ путь через / — 400 (5 ms) + ✓ путь через \ — 400 (5 ms) + ✓ NUL — 400 (8 ms) + ✓ перевод строки — 400 (5 ms) ✓ DEL — 400 (5 ms) - ✓ C1 U+0085 — 400 (7 ms) - ✓ разделитель строк U+2028 — 400 (9 ms) - ✓ повторённый параметр — 400 (6 ms) + ✓ C1 U+0085 — 400 (5 ms) + ✓ разделитель строк U+2028 — 400 (4 ms) + ✓ повторённый параметр — 400 (8 ms) тип содержимого - ✓ Content-Type text/plain — 415 (6 ms) - ✓ Content-Type application/json — 415 (37 ms) - ✓ Content-Type application/octet-stream — 415 (4 ms) - ✓ Content-Type multipart/form-data; boundary=x — 415 (4 ms) - ✓ Content-Type image/gif — 415 (4 ms) - ✓ Content-Type image/webp — 415 (10 ms) - ✓ без Content-Type — 415 (3 ms) - ✓ подмена MIME в обе стороны и чужие форматы — 415 (43 ms) - ✓ пустое тело — 400 (14 ms) + ✓ Content-Type text/plain — 415 (5 ms) + ✓ Content-Type application/json — 415 (35 ms) + ✓ Content-Type application/octet-stream — 415 (9 ms) + ✓ Content-Type multipart/form-data; boundary=x — 415 (13 ms) + ✓ Content-Type image/gif — 415 (13 ms) + ✓ Content-Type image/webp — 415 (9 ms) + ✓ без Content-Type — 415 (11 ms) + ✓ подмена MIME в обе стороны и чужие форматы — 415 (84 ms) + ✓ пустое тело — 400 (30 ms) повреждённые изображения - ✓ PNG: первые 33 байта sample.png — 415 (5 ms) - ✓ PNG: половина файла — 415 (6 ms) - ✓ PNG: без последних 20 байт — 415 (10 ms) - ✓ PNG: без IEND — 415 (11 ms) - ✓ PNG: неверный CRC — 415 (16 ms) - ✓ PNG: фильтр строки 5 — 415 (11 ms) - ✓ PNG: фильтр строки 255 — 415 (9 ms) - ✓ PNG: неверный фильтр в последней строке — 415 (14 ms) - ✓ PNG: мусор в IDAT с верным CRC — 415 (16 ms) - ✓ PNG: данных меньше, чем строк — 415 (31 ms) - ✓ PNG: палитра на 257 записей — 415 (16 ms) - ✓ JPEG: все повреждения — 415 (71 ms) + ✓ PNG: первые 33 байта sample.png — 415 (20 ms) + ✓ PNG: половина файла — 415 (17 ms) + ✓ PNG: без последних 20 байт — 415 (20 ms) + ✓ PNG: без IEND — 415 (24 ms) + ✓ PNG: неверный CRC — 415 (18 ms) + ✓ PNG: фильтр строки 5 — 415 (15 ms) + ✓ PNG: фильтр строки 255 — 415 (10 ms) + ✓ PNG: неверный фильтр в последней строке — 415 (11 ms) + ✓ PNG: мусор в IDAT с верным CRC — 415 (10 ms) + ✓ PNG: данных меньше, чем строк — 415 (8 ms) + ✓ PNG: палитра на 257 записей — 415 (11 ms) + ✓ JPEG: все повреждения — 415 (68 ms) лимиты - ✓ 10 MiB + 1 байт — 413 и без чтения объявленного тела (449 ms) - ✓ превышение при chunked без Content-Length — 413 (380 ms) - ✓ превышение лимита пикселей — 413 до декодирования (97 ms) - ✓ оборванная загрузка не оставляет временных файлов и строк в БД (809 ms) + ✓ 10 MiB + 1 байт — 413 и без чтения объявленного тела (220 ms) + ✓ превышение при chunked без Content-Length — 413 (944 ms) + ✓ превышение лимита пикселей — 413 до декодирования (92 ms) + ✓ оборванная загрузка не оставляет временных файлов и строк в БД (819 ms) отказы - ✓ S3 недоступен — 503 с заголовками, метаданные не создаются (209 ms) - ✓ явный отказ транзакции после PUT удаляет объект staging (64 ms) - ✓ необработанная ошибка PostgreSQL при INSERT — 503, объект не удаляется (31 ms) - ✓ при неясном исходе COMMIT объект не удаляется (53 ms) + ✓ S3 недоступен — 503 с заголовками, метаданные не создаются (185 ms) + ✓ явный отказ транзакции после PUT удаляет объект staging (56 ms) + ✓ необработанная ошибка PostgreSQL при INSERT — 503, объект не удаляется (34 ms) + ✓ при неясном исходе COMMIT объект не удаляется (31 ms) -[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [S3Service] get attachments/829ae1d8-6814-49df-a8bc-51f932fc3139/original failed: Error -[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 101 - 11/20/2026, 2:32:07 PM  ERROR [S3Service] get attachments/0b88f570-7a00-4713-bc1f-eb84c29804f1/original failed: Error +[Nest] 101 - 11/20/2026, 2:32:07 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "object storage unavailable", "method": "GET", "route": "/api/v1/attachments/{attachment_id}/content", "status": 503, - "request_id": "7a9d3774-a21c-4af6-b908-e657ccb71c0d" + "request_id": "c2f13d3f-5110-4cc7-83af-7137dd518fea" } -[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [S3Service] get attachments/e7854e6a-ebb4-4aa6-8a27-1f1f411b7b9c/original failed: NoSuchKey -[Nest] 102 - 11/20/2026, 1:46:40 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 101 - 11/20/2026, 2:32:07 PM  ERROR [S3Service] get attachments/6ea31e5f-9549-486c-8249-e3ffb6da6413/original failed: NoSuchKey +[Nest] 101 - 11/20/2026, 2:32:07 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "Internal server error", "method": "GET", "route": "/api/v1/attachments/{attachment_id}/content", "status": 500, - "request_id": "f96f2841-2539-454f-97c8-9828cfd0d466" + "request_id": "e2f0e5e7-e052-4972-8fcc-60b05ae4bb83" } -[Nest] 103 - 11/20/2026, 1:46:40 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:08 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "object storage unavailable", "method": "GET", "route": "/health/ready", "status": 503, - "request_id": "e295becf-9c2a-4772-a18d-e45dcd0d25e3" + "request_id": "fce039e2-3f6a-4a82-bcc9-516576969c72" } -PASS test/reconciler.e2e-spec.ts - Сверка объектов S3 с метаданными (e2e) - ✓ dry-run сообщает о сироте и ничего не удаляет, apply удаляет, повторный запуск ничего не делает (64 ms) - ✓ не трогает свежий объект внутри grace period (29 ms) - ✓ не трогает старый объект, на который есть метаданные (23 ms) - ✓ при отказе PostgreSQL проход прерывается и ничего не удаляет (18 ms) - ✓ сбой удаления считается и повторяется на следующем проходе (34 ms) - ✓ обходит все страницы листинга (64 ms) - ✓ реальная загрузка остаётся доступной после сверки всего bucket префикса вложений (241 ms) - ✓ после grace period объекты вложения и staging в очереди не считаются сиротами (297 ms) - ✓ staging failed-вложения удаляется после срока хранения (126 ms) - ✓ объекты вариантов без строк у существующего вложения не удаляются: replay после сверки доводит до ready (483 ms) - ✓ staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения (186 ms) - Готовность при отказе S3 (e2e) - ✓ ready — 503 с заголовками за короткое время, live и core — 200 (69 ms) - ✓ при рабочем S3 ready — 200 (53 ms) - PASS test/request-constraints.e2e-spec.ts Каждое ограничение запроса из контракта отклоняется 400, граница принимается (e2e) - ✓ POST /users (346 ms) - ✓ POST /chats (76 ms) - ✓ POST /chats/{chat_id}/messages (91 ms) - ✓ query и path параметры (111 ms) - ✓ POST /chats/{chat_id}/attachments: filename и chat_id (62 ms) + ✓ POST /users (263 ms) + ✓ POST /chats (91 ms) + ✓ POST /chats/{chat_id}/messages (157 ms) + ✓ query и path параметры (149 ms) + ✓ POST /chats/{chat_id}/attachments: filename и chat_id (91 ms) + +PASS test/reconciler.e2e-spec.ts + Сверка объектов S3 с метаданными (e2e) + ✓ dry-run сообщает о сироте и ничего не удаляет, apply удаляет, повторный запуск ничего не делает (67 ms) + ✓ не трогает свежий объект внутри grace period (24 ms) + ✓ не трогает старый объект, на который есть метаданные (19 ms) + ✓ при отказе PostgreSQL проход прерывается и ничего не удаляет (27 ms) + ✓ сбой удаления считается и повторяется на следующем проходе (50 ms) + ✓ обходит все страницы листинга (112 ms) + ✓ реальная загрузка остаётся доступной после сверки всего bucket префикса вложений (384 ms) + ✓ после grace period объекты вложения и staging в очереди не считаются сиротами (282 ms) + ✓ staging failed-вложения удаляется после срока хранения (88 ms) + ✓ объекты вариантов без строк у существующего вложения не удаляются: replay после сверки доводит до ready (301 ms) + ✓ staging ready-вложения, оставшийся после сбоя worker, удаляется без ожидания срока хранения (161 ms) + Готовность при отказе S3 (e2e) + ✓ ready — 503 с заголовками за короткое время, live и core — 200 (64 ms) + ✓ при рабочем S3 ready — 200 (61 ms) PASS test/auth.e2e-spec.ts Аутентификация и сессии (e2e) регистрация - ✓ требует password (25 ms) - ✓ отклоняет password короче 12 code points (5 ms) - ✓ хранит пароль как Argon2id-хеш, а не открытым текстом (103 ms) + ✓ требует password (22 ms) + ✓ отклоняет password короче 12 code points (3 ms) + ✓ хранит пароль как Argon2id-хеш, а не открытым текстом (147 ms) POST /api/v1/auth/sessions - ✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (187 ms) - ✓ принимает пароль с двоеточием и не-ASCII символами (68 ms) - ✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (132 ms) - ✓ отклоняет JSON body при входе даже с верным Basic (66 ms) - ✓ отвечает 401 без заголовка Authorization (2 ms) + ✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (117 ms) + ✓ принимает пароль с двоеточием и не-ASCII символами (85 ms) + ✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (141 ms) + ✓ отклоняет JSON body при входе даже с верным Basic (83 ms) + ✓ отвечает 401 без заголовка Authorization (3 ms) защищённые endpoint - ✓ не принимают Basic (67 ms) - ✓ не принимают X-User-Id сам по себе (65 ms) - ✓ игнорируют X-User-Id рядом с Bearer (156 ms) - ✓ отвечают 401 на неизвестный токен (4 ms) + ✓ не принимают Basic (68 ms) + ✓ не принимают X-User-Id сам по себе (89 ms) + ✓ игнорируют X-User-Id рядом с Bearer (150 ms) + ✓ отвечают 401 на неизвестный токен (7 ms) DELETE /api/v1/auth/sessions/current - ✓ отзывает только текущий токен: 204, затем 401 на повтор (144 ms) + ✓ отзывает только текущий токен: 204, затем 401 на повтор (195 ms) PASS test/contract.e2e-spec.ts Все ответы соответствуют контракту: коды, схемы, заголовки (e2e) - ✓ health, пользователи и сессии (509 ms) - ✓ чаты и сообщения (250 ms) - ✓ вложения во всех состояниях (654 ms) + ✓ health, пользователи и сессии (324 ms) + ✓ чаты и сообщения (471 ms) + ✓ вложения во всех состояниях (768 ms) ✓ каждая операция контракта вызвана хотя бы раз (1 ms) -PASS test/attachment-access.e2e-spec.ts (6.756 s) +PASS test/attachment-access.e2e-spec.ts (7.499 s) Скачивание и привязка вложений (e2e) чтение ✓ участник получает метаданные и оригинал побайтно (329 ms) - ✓ JPEG отдаётся с истинным Content-Type (186 ms) - ✓ посторонний и неизвестный ID получают одинаковый 404 (181 ms) - ✓ UUID nil корректного формата — 404, а не 400 (30 ms) - ✓ UUID v7 корректного формата — 404, а не 400 (41 ms) - ✓ без токена 401, неверный UUID 400 (196 ms) - ✓ variant: original явно, отсутствующий 404, неизвестный и повторённый 400 (250 ms) - ✓ нет доступа к S3 — метаданные 200, content 503 с заголовками (355 ms) - ✓ объект пропал из S3 — 500 без внутренних деталей (304 ms) + ✓ JPEG отдаётся с истинным Content-Type (210 ms) + ✓ посторонний и неизвестный ID получают одинаковый 404 (265 ms) + ✓ UUID nil корректного формата — 404, а не 400 (99 ms) + ✓ UUID v7 корректного формата — 404, а не 400 (46 ms) + ✓ без токена 401, неверный UUID 400 (193 ms) + ✓ variant: original явно, отсутствующий 404, неизвестный и повторённый 400 (218 ms) + ✓ нет доступа к S3 — метаданные 200, content 503 с заголовками (225 ms) + ✓ объект пропал из S3 — 500 без внутренних деталей (168 ms) attachment_ids в сообщениях - ✓ text="" с вложением принимается, Message читается вторым участником (134 ms) - ✓ порядок [B, A] сохраняется в ответе, истории и повторе; перестановка с тем же ключом — 409 (324 ms) - ✓ отсутствующий attachment_ids и [] равны при повторе, изменение списка — 409 (157 ms) - ✓ вложение другого чата и неизвестное — одинаковый 404, сообщение не создаётся (118 ms) - ✓ смесь своего и чужого вложения — 404 (196 ms) - ✓ посторонний не может отправить вложение в чужой чат (143 ms) - ✓ любой участник может сослаться на вложение чата, вложение можно использовать повторно (222 ms) - ✓ ровно 10 вложений принимается, 11 — 400 (770 ms) - ✓ UUID в другом регистре — тот же ID и дубль (163 ms) - ✓ text отсутствует — 400 (160 ms) - ✓ text null — 400 (157 ms) - ✓ attachment_ids null — 400 (124 ms) - ✓ attachment_ids строка — 400 (128 ms) - ✓ элемент не UUID — 400 (119 ms) - ✓ элемент число — 400 (98 ms) - ✓ дубликат — 400 (119 ms) - ✓ пустой текст без вложений — 400 (168 ms) - ✓ пробельный текст без вложений — 400 (223 ms) + ✓ text="" с вложением принимается, Message читается вторым участником (164 ms) + ✓ порядок [B, A] сохраняется в ответе, истории и повторе; перестановка с тем же ключом — 409 (430 ms) + ✓ отсутствующий attachment_ids и [] равны при повторе, изменение списка — 409 (179 ms) + ✓ вложение другого чата и неизвестное — одинаковый 404, сообщение не создаётся (159 ms) + ✓ смесь своего и чужого вложения — 404 (316 ms) + ✓ посторонний не может отправить вложение в чужой чат (131 ms) + ✓ любой участник может сослаться на вложение чата, вложение можно использовать повторно (165 ms) + ✓ ровно 10 вложений принимается, 11 — 400 (767 ms) + ✓ UUID в другом регистре — тот же ID и дубль (201 ms) + ✓ text отсутствует — 400 (152 ms) + ✓ text null — 400 (159 ms) + ✓ attachment_ids null — 400 (137 ms) + ✓ attachment_ids строка — 400 (149 ms) + ✓ элемент не UUID — 400 (122 ms) + ✓ элемент число — 400 (113 ms) + ✓ дубликат — 400 (128 ms) + ✓ пустой текст без вложений — 400 (115 ms) + ✓ пробельный текст без вложений — 400 (95 ms) PASS test/concurrency.e2e-spec.ts Безопасность при конкурентном доступе (e2e) - ✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (1237 ms) - ✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (152 ms) + ✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (1147 ms) + ✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (192 ms) -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:13 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "session cache unavailable", "method": "DELETE", "route": "/api/v1/auth/sessions/current", "status": 503, - "request_id": "fd232c52-05e3-40be-8c2c-302b5e7aa8d1" + "request_id": "f7de03bc-bdf0-42ee-a767-01a1c55c8900" } -PASS test/docs.e2e-spec.ts - Swagger UI и примеры (e2e) - ✓ отдаёт Swagger UI и документ контракта со всеми путями (20 ms) - ✓ каждый пример запроса и ответа проходит JSON Schema контракта (270 ms) - -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:13 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "session cache unavailable", "method": "DELETE", "route": "/api/v1/auth/sessions/current", "status": 503, - "request_id": "6777d13f-4722-4ba6-bfc1-d9a20db9dadb" + "request_id": "3cb57701-e14e-4d0c-95b1-74125f609d5f" } -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:14 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "database unavailable", "method": "GET", "route": "/health/ready", "status": 503, - "request_id": "99ef31e1-8701-4e90-b156-4095732524be" + "request_id": "c84cbd52-47cb-410d-ae40-7028a9bd486f" } -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:14 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "database unavailable", "method": "GET", "route": "/api/v1/chats", "status": 503, - "request_id": "06c3d23f-c679-499f-a22e-fe924941efb7" + "request_id": "0f917fec-5b5c-4001-9fad-02c9c41c29a6" } -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:14 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "database unavailable", "method": "GET", "route": "/api/v1/chats", "status": 503, - "request_id": "b85f2833-ae4e-4f26-879c-9dfeef59c492" + "request_id": "ce2feb99-927d-4095-971d-d4a91e5674d3" } -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +[Nest] 102 - 11/20/2026, 2:32:14 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "database unavailable", "method": "POST", "route": "/api/v1/users", "status": 503, - "request_id": "1c8c803e-cc62-48a6-88ec-6ae322461547" + "request_id": "2e2483c7-5f3d-4218-94f0-5dc4813905f4" } -[Nest] 109 - 11/20/2026, 1:46:47 PM  ERROR [HttpExceptionFilter] Object: +PASS test/idempotency.e2e-spec.ts + Идемпотентность отправки и X-Instance-Id (e2e) + ✓ требует Idempotency-Key правильного формата (147 ms) + ✓ повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение (107 ms) + ✓ тот же ключ с другим телом — 409, сообщение не создаётся (106 ms) + ✓ 20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение (312 ms) + ✓ область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим (238 ms) + ✓ повтор заново проверяет сессию (219 ms) + ✓ после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново (1832 ms) + ✓ X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе (58 ms) + +[Nest] 102 - 11/20/2026, 2:32:14 PM  ERROR [HttpExceptionFilter] Object: { "event": "http.error", "message": "Internal server error", "method": "GET", "route": "/api/v1/chats", "status": 500, - "request_id": "22c62528-2f2d-417d-89c9-72c630fa1811" + "request_id": "dd8bae40-6d02-4739-b4ac-194bb45a416c" } PASS test/failures.e2e-spec.ts Уровень 4: expiry, отказы зависимостей, rollback (e2e) - ✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (2877 ms) - ✓ без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва (125 ms) - ✓ logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше (442 ms) - ✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (169 ms) - ✓ неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id (89 ms) - ✓ откатывает создание чата целиком, если один из участников не существует (117 ms) + ✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (2882 ms) + ✓ без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва (160 ms) + ✓ logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше (424 ms) + ✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (263 ms) + ✓ неожиданное исключение — 500 internal_error без деталей, с X-Request-Id и X-Instance-Id (267 ms) + ✓ откатывает создание чата целиком, если один из участников не существует (226 ms) -PASS test/idempotency.e2e-spec.ts - Идемпотентность отправки и X-Instance-Id (e2e) - ✓ требует Idempotency-Key правильного формата (462 ms) - ✓ повтор с тем же ключом и телом возвращает тот же 201 и то же сообщение (151 ms) - ✓ тот же ключ с другим телом — 409, сообщение не создаётся (180 ms) - ✓ 20 параллельных запросов с одним ключом через два экземпляра создают ровно одно сообщение (328 ms) - ✓ область ключа — пользователь и чат: одинаковый ключ у разных пользователей и чатов независим (232 ms) - ✓ повтор заново проверяет сессию (83 ms) - ✓ после IDEMPOTENCY_TTL_SECONDS ключ можно использовать заново (1646 ms) - ✓ X-Instance-Id есть в успешных ответах, ошибках и health и стабилен в процессе (33 ms) +PASS test/docs.e2e-spec.ts + Swagger UI и примеры (e2e) + ✓ отдаёт Swagger UI и документ контракта со всеми путями (39 ms) + ✓ каждый пример запроса и ответа проходит JSON Schema контракта (407 ms) A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them. Test Suites: 12 passed, 12 total Tests: 201 passed, 201 total Snapshots: 0 total -Time: 29.383 s +Time: 30.222 s Ran all test suites. diff --git a/scripts/incidents.py b/scripts/incidents.py index 7106dd0..e77b31c 100755 --- a/scripts/incidents.py +++ b/scripts/incidents.py @@ -325,10 +325,10 @@ def scenario_telemetry(): resolved = watch(columns, alerts, lambda: alert_state('TelemetryExportFailing') == 'inactive', timeout=240, every=15) traffic.snapshot('after start') - log('== Collector stopped for 60 s: SDK export fails fast (5 s timeout, bounded queues)') + log('== Collector stopped for 300 s: SDK export fails fast (5 s timeout, bounded queues); RSS saw-tooth until GC') js.compose('stop', 'otel-collector') - for _ in range(4): - time.sleep(15) + for _ in range(15): + time.sleep(20) log('docker stats:', subprocess.run( ['docker', 'stats', '--no-stream', '--format', '{{.Name}} {{.MemUsage}}', *container('api'), *container('worker')], capture_output=True, text=True).stdout.replace('\n', '; ')) @@ -339,6 +339,9 @@ def scenario_telemetry(): finally: traffic.close() subprocess.run(['docker', 'compose', 'start', 'loki', 'tempo', 'otel-collector'], capture_output=True) + restarts = subprocess.run(['docker', 'inspect', '-f', '{{.Name}} restarts={{.RestartCount}} oom={{.State.OOMKilled}}', + *container('api'), *container('worker')], capture_output=True, text=True).stdout.split('\n') + log('containers:', '; '.join(r for r in restarts if r)) log('TelemetryExportFailing fired: %s, resolved: %s' % (fired, resolved)) log('PASS' if fired and resolved else 'FAIL') -- 2.54.0 From 7e62186fb44b1d729534a94c3e581168b0a71308 Mon Sep 17 00:00:00 2001 From: aegor Date: Fri, 20 Nov 2026 18:28:10 +0300 Subject: [PATCH 8/8] docs: add lab6 report and evidence --- REPORT.md | 10 ++-- evidence/incident-telemetry.txt | 97 +++++++++++++++++++-------------- 2 files changed, 61 insertions(+), 46 deletions(-) diff --git a/REPORT.md b/REPORT.md index ce41b13..a937e8c 100644 --- a/REPORT.md +++ b/REPORT.md @@ -143,7 +143,7 @@ Collector — получатель и маршрутизатор, а не БД: ## Доказательства критериев -Файлы собраны `docker compose run --rm tools sh scripts/collect-evidence.sh` на commit `d83876f` с чистых volumes (`docker compose down -v`, затем `up`); в заголовке каждого файла — дата и commit. ⟨TELEMETRY_RERUN⟩ +Файлы собраны `docker compose run --rm tools sh scripts/collect-evidence.sh` на commit `d83876f` с чистых volumes (`docker compose down -v`, затем `up`); в заголовке каждого файла — дата и commit. `incident-telemetry.txt` пересобран на commit `2718c3b`: фаза «Collector остановлен» удлинена с 60 до 300 s, код приложения не менялся. | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | @@ -156,7 +156,7 @@ Collector — получатель и маршрутизатор, а не БД: | **4**: W3C context API → broker → worker, producer/consumer spans, цепочка до S3/DB включая retry | `incidents.py retry-trace`, `trace-check.py` | одна загрузка — одна трасса: 3 пары PRODUCER → CONSUMER (`attempt` 1, 2, 3); в попытках 1–2 `S3.GetObject` с ошибкой (S3 остановлен), попытка 3 — S3 Put ×4, COMMIT, ready; события `enqueued → processing → retry_scheduled → processing → retry_scheduled → processing → ready` | [evidence/incident-retry-trace.txt](evidence/incident-retry-trace.txt) | | **4**: p50/p95/p99 из histogram, доля ошибок, очередь и возраст, пул БД, насыщение worker, CPU/RAM, time to ready | `dashboard-check.py`, `latency-compare.py` | панели p50/p95/p99 (`sum by (le)`), доля 5xx, глубина/возраст очереди, пул used/waiting/max, busy/capacity, CPU, RSS, time to ready возвращают данные; клиент / histogram: p50 18,3 / 19,7 ms, p95 89,2 / 92,2 ms, p99 163,3 / 176,8 ms (3411 POST, 113 rps) | [evidence/telemetry.txt](evidence/telemetry.txt) | | **4**: SLI/SLO с окном; alert rules на error rate и queue lag, firing → resolved | `promtool`, `incidents.py worker-stop`, `db` | `promtool`: 13 правил; все `health ok`; `MessengerJobQueueLag` и `MessengerApiNotReady` прошли pending → firing → inactive | [evidence/telemetry.txt](evidence/telemetry.txt), [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt), [evidence/incident-db.txt](evidence/incident-db.txt) | -| **4**: Collector с memory_limiter, batch, ограниченной очередью; остановка backend не ломает API и не растит RAM | `incidents.py telemetry` | ⟨TELEMETRY⟩ | [evidence/incident-telemetry.txt](evidence/incident-telemetry.txt) | +| **4**: Collector с memory_limiter, batch, ограниченной очередью; остановка backend не ломает API и не растит RAM | `incidents.py telemetry` | Loki+Tempo остановлены: 0 ошибок API, очередь exporter упирается в 200, `memory_limiter` отказывает в приёме, `TelemetryExportFailing` firing → resolved; Collector остановлен 300 s: 0 ошибок API, память API ограничена и освобождается после восстановления; перезапусков/OOM нет | [evidence/incident-telemetry.txt](evidence/incident-telemetry.txt) | | **4**: инцидент 1 — worker остановлен | `incidents.py worker-stop` | см. «Эксперименты и отказы» | [evidence/incident-worker-stop.txt](evidence/incident-worker-stop.txt) | | **4**: инцидент 2 — медленная/недоступная БД отличима от медленного handler | `incidents.py db` | см. «Эксперименты и отказы» | [evidence/incident-db.txt](evidence/incident-db.txt) | | Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | `Tests: 201 passed, 201 total` | [evidence/tests.txt](evidence/tests.txt) | @@ -173,8 +173,8 @@ Collector — получатель и маршрутизатор, а не БД: | **Инцидент 2а — медленный handler (контроль):** upload PNG 1700×1700 шума, 8,3 MiB | время в обработчике и S3, БД быстрая | trace 525 ms: вызовы БД 40 ms (SQL 22 ms, ожидание пула 1 ms), S3 246 ms, сам обработчик (полное декодирование) 240 ms | — | | **Инцидент 2б — медленная БД:** `docker update --cpus 0.05 postgres` на 150 s под нагрузкой | рост задержки, причина в SQL | 0 ошибок; клиент p95 23 → 196 ms, p99 49 → 637 ms; p95 в Prometheus (1m) до ~250 ms; trace 790 ms: БД 788 ms (SQL 781 ms, пул 0 ms), обработчик 1 ms; trace 505 ms: SQL 498 ms. `MessengerSlowApi` (порог p95 > 1 s) не сработал — деградация ниже порога | после `--cpus 1.0` p95 вернулся к ~24 ms за 1–2 мин | | **Инцидент 2в — БД недоступна:** `docker pause postgres` на ~105 s | 503 вместо зависаний; alert | API: ожидание пула 5 s → `503 database unavailable` (trace 5005 ms: `prisma:engine:connection` 5000 ms); `/health/core` 503 → HAProxy выводит обе реплики, клиенты получают `503 no API replica available` (1910 ответов) и 3 × 504; доля 5xx в метриках API не растёт — запросы не доходят до API; `MessengerApiNotReady` **firing**; в Loki `http.error` / `database unavailable` | после `unpause` реплики вернулись в LB за секунды, 25 ответов 503 в хвосте; alert **resolved через ~60 s**; p95 23 ms; данных не потеряно (неподтверждённые записи получили 503) | -| **Инцидент 3а — Loki и Tempo остановлены** до срабатывания alert (150 s) под нагрузкой 6 потоков | API работает; Collector ограничивает очередь и память; потери считаются | клиент: 14 385 успешных, **0 ошибок**, p95 29 ms (до — 30 ms); очередь exporter 0 → **200 из 200**; `send_failed` ~1250 spans и ~930 log records в минуту; затем `memory_limiter` отказывает в приёме (`refused` до ~91 000 в минуту); RSS Collector 144 → **240 MiB** (лимит 256M, перезапусков и OOM нет); `TelemetryExportFailing` **firing** | после `start loki tempo` очередь опустела за ~15 s, RSS 155 MiB, alert **resolved** через ~105 s; трассы и логи за время простоя потеряны (посчитаны), логи остаются в `docker compose logs` | -| **Инцидент 3б — Collector остановлен** | API работает, RAM не растёт бесконечно | ⟨COLLECTOR⟩ | ⟨COLLECTOR_RECOVERY⟩ | +| **Инцидент 3а — Loki и Tempo остановлены** до срабатывания alert (~150 s) под нагрузкой 6 потоков | API работает; Collector ограничивает очередь и память; потери считаются | клиент: 13 901 успешный, **0 ошибок**, p95 43 ms (до — 53 ms); очередь exporter 0 → **200 из 200**; `send_failed` ~1350 spans и ~1100 log records в минуту; затем `memory_limiter` отказывает в приёме (`refused` до ~89 000 в минуту; в логе Collector: «above soft limit, refusing data», «above hard limit, forcing GC» при 120–170 MiB кучи); `TelemetryExportFailing` **firing**. Перезапусков и OOM Collector нет | после `start loki tempo` очередь опустела за ~15 s, alert **resolved** через ~120 s; трассы и логи за время простоя потеряны (посчитаны в `send_failed`/`refused`), логи остаются в `docker compose logs` | +| **Инцидент 3б — Collector остановлен на 300 s** под той же нагрузкой | API работает; экспорт падает быстро (таймаут 5 s), очереди SDK ограничены | клиент: 30 904 успешных, **0 ошибок**, p95 38 ms; память контейнеров API (`docker stats`) 183 → 211 MiB и 174 → 197 MiB из 256M: +9 MiB за первые 45 s, затем ~3 MiB/мин; worker стабильно ~57 MiB; перезапусков и OOM нет | после `start otel-collector` экспорт возобновился без перезапуска API; через ~1 мин память реплик 159 и 149 MiB — буферы телеметрии освобождены. Отдельный предварительный замер (5 мин, `load.py` 6 потоков): RSS до ~228 MiB и сброс сборщиком мусора до ~185 MiB на 280-й секунде, 38 141 запрос без ошибок | | S3 остановлен на время первых попыток job (`retry-trace`) | повторы в одной трассе | см. критерий W3C выше: 3 попытки в одной трассе | ready через ~9 s после upload | | `restart.sh`, `stop-one.sh`, сценарии lab5 | как в lab5 | PASS; failover 128 записей, 0 ошибок, восстановление 3,57 s | потерь нет | @@ -196,6 +196,8 @@ Collector — получатель и маршрутизатор, а не БД: - **Окна SLO по 1 ч** — учебный масштаб, чтобы эффект был виден за время защиты; в эксплуатации — 28–30 дней и multi-window burn-rate alerts. - **Перцентили — оценка внутри bucket**, точность ограничена шириной bucket; события медленнее 10 s (HTTP) и 600 s (ready) попадают в `+Inf`. - **`MessengerHighErrorRate` не видит ответы LB**, когда все реплики выведены (HAProxy отвечает 503 сам) — это закрыто `MessengerApiNotReady`; метрик HAProxy в стенде нет. +- **Запас памяти Collector небольшой.** `memory_limiter` ограничивает кучу Go (порог 160 MiB, отказ в приёме с 120 MiB), но RSS процесса больше кучи: метрика `otelcol_process_memory_rss` при остановленных Loki/Tempo показывала до 287 MiB (счёт процесса, с разделяемыми страницами), лимит контейнера 256M при этом не превышен, OOM не было. При большей нагрузке стоит снизить `limit_mib` или поднять лимит контейнера. +- **Память API без Collector** за 5 минут выросла на ~25 MiB с замедлением и освободилась после восстановления; более длинный простой не измерялся. Ограничители — очереди SDK по 2048 записей, таймаут экспорта 5 s, лимит контейнера 256M. - **Потери телеметрии при недоступности backend допустимы:** после 60 s повторов и заполнения очереди Collector отбрасывает данные; логи при этом остаются в stdout контейнеров. Персистентной очереди (file storage) у Collector нет. - **Пропуски метрик при остановке процесса** (worker stop): серии worker перестают обновляться — это видно, но отдельного alert на отсутствие серий нет; признак остановки — рост `oldest_age` при `busy = 0`. - **Метрики очереди зависят от relay:** если упал relay, исчезают и они (но не задания — они в БД). diff --git a/evidence/incident-telemetry.txt b/evidence/incident-telemetry.txt index eb853cd..349b212 100644 --- a/evidence/incident-telemetry.txt +++ b/evidence/incident-telemetry.txt @@ -1,46 +1,59 @@ # Инцидент: scripts/incidents.py telemetry -# date: 2026-11-20T14:48:05Z -# commit: d83876f +# date: 2026-11-20T15:12:09Z +# commit: 2718c3b $ python3 scripts/incidents.py telemetry -[ 0.1s] user b8211787-a380-40f3-b09b-107048ccafdf chat cb1f8ca9-090c-4f2b-b43b-35ad07360676 -[ 0.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=153MiB api_rss=227MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 15.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=151MiB api_rss=229MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 30.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=144MiB api_rss=228MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 30.2s] client [baseline]: 200:1427 201:1431; p50=11ms p95=30ms p99=66ms -[ 30.2s] == Loki and Tempo stopped until TelemetryExportFailing fires (max 240 s) -[ 30.2s] $ docker compose stop loki tempo -[ 32.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=144MiB api_rss=227MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 47.0s] spans_failed_1m=0 logs_failed_1m=0 queue=16 queue_cap=200 refused_1m=0 collector_rss=148MiB api_rss=227MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 62.0s] spans_failed_1m=0 logs_failed_1m=0 queue=58 queue_cap=200 refused_1m=0 collector_rss=150MiB api_rss=229MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 77.1s] spans_failed_1m=0 logs_failed_1m=0 queue=102 queue_cap=200 refused_1m=0 collector_rss=175MiB api_rss=229MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 92.1s] spans_failed_1m=0 logs_failed_1m=0 queue=145 queue_cap=200 refused_1m=0 collector_rss=181MiB api_rss=230MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 107.2s] spans_failed_1m=1251.9 logs_failed_1m=583.2 queue=186 queue_cap=200 refused_1m=0 collector_rss=188MiB api_rss=228MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 122.2s] spans_failed_1m=1252.6 logs_failed_1m=583.5 queue=200 queue_cap=200 refused_1m=14887.5 collector_rss=215MiB api_rss=229MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive -[ 137.2s] spans_failed_1m=1253.4 logs_failed_1m=583.9 queue=200 queue_cap=200 refused_1m=38541.8 collector_rss=230MiB api_rss=235MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive -[ 152.3s] spans_failed_1m=0 logs_failed_1m=0 queue=200 queue_cap=200 refused_1m=69789.2 collector_rss=231MiB api_rss=231MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive -[ 167.3s] spans_failed_1m=1365.5 logs_failed_1m=932.1 queue=198 queue_cap=200 refused_1m=87575.8 collector_rss=233MiB api_rss=234MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive -[ 182.3s] spans_failed_1m=1365.4 logs_failed_1m=932 queue=200 queue_cap=200 refused_1m=91415.4 collector_rss=237MiB api_rss=228MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 182.3s] client [Loki+Tempo down]: 200:7194 201:7191; p50=10ms p95=29ms p99=78ms -[ 182.3s] $ docker compose start loki tempo -[ 182.9s] spans_failed_1m=1365.4 logs_failed_1m=932 queue=200 queue_cap=200 refused_1m=91415.4 collector_rss=237MiB api_rss=228MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 197.9s] spans_failed_1m=1365.4 logs_failed_1m=932.1 queue=200 queue_cap=200 refused_1m=85848.4 collector_rss=238MiB api_rss=234MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 213.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=69153.5 collector_rss=240MiB api_rss=230MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 228.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=39560.8 collector_rss=155MiB api_rss=230MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 243.0s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=11155.2 collector_rss=155MiB api_rss=230MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 258.1s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=155MiB api_rss=229MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 273.1s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=155MiB api_rss=229MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive -[ 288.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=155MiB api_rss=230MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive -[ 288.2s] client [after start]: 200:4986 201:4987; p50=10ms p95=34ms p99=82ms -[ 288.2s] == Collector stopped for 60 s: SDK export fails fast (5 s timeout, bounded queues) -[ 288.2s] $ docker compose stop otel-collector -[ 306.8s] docker stats: messenger-lab6-api-1 171.3MiB / 256MiB; messenger-lab6-api-2 184.8MiB / 256MiB; messenger-lab6-worker-1 72.1MiB / 768MiB; -[ 323.9s] docker stats: messenger-lab6-api-1 178.6MiB / 256MiB; messenger-lab6-api-2 194.5MiB / 256MiB; messenger-lab6-worker-1 72.61MiB / 768MiB; -[ 341.8s] docker stats: messenger-lab6-api-1 187.5MiB / 256MiB; messenger-lab6-api-2 200.2MiB / 256MiB; messenger-lab6-worker-1 71.97MiB / 768MiB; -[ 359.6s] docker stats: messenger-lab6-api-1 191.7MiB / 256MiB; messenger-lab6-api-2 202.9MiB / 256MiB; messenger-lab6-worker-1 72.51MiB / 768MiB; -[ 359.6s] client [collector down]: 200:3307 201:3306; p50=11ms p95=30ms p99=111ms -[ 359.6s] $ docker compose start otel-collector -[ 390.3s] client [collector back]: 200:1429 201:1431; p50=11ms p95=32ms p99=91ms -[ 390.5s] TelemetryExportFailing fired: True, resolved: True -[ 390.5s] PASS +[ 0.1s] user 82d06d15-aef5-49d9-b445-a93d0dd4b886 chat a583d7a0-7c8c-4261-971b-8affca86fb22 +[ 0.2s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=169MiB api_rss=202MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 15.3s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=169MiB api_rss=198MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 30.3s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=188MiB api_rss=193MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 30.3s] client [baseline]: 200:1350 201:1353; p50=11ms p95=53ms p99=110ms +[ 30.3s] == Loki and Tempo stopped until TelemetryExportFailing fires (max 240 s) +[ 30.3s] $ docker compose stop loki tempo +[ 32.4s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=188MiB api_rss=193MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 47.5s] spans_failed_1m=0 logs_failed_1m=0 queue=6 queue_cap=200 refused_1m=0 collector_rss=188MiB api_rss=196MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 62.6s] spans_failed_1m=0 logs_failed_1m=0 queue=46 queue_cap=200 refused_1m=0 collector_rss=194MiB api_rss=195MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 77.6s] spans_failed_1m=0 logs_failed_1m=0 queue=86 queue_cap=200 refused_1m=0 collector_rss=209MiB api_rss=194MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 92.7s] spans_failed_1m=0 logs_failed_1m=0 queue=128 queue_cap=200 refused_1m=0 collector_rss=226MiB api_rss=194MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 107.7s] spans_failed_1m=674.2 logs_failed_1m=529.4 queue=168 queue_cap=200 refused_1m=0 collector_rss=234MiB api_rss=195MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 122.7s] spans_failed_1m=1349.4 logs_failed_1m=1096.5 queue=199 queue_cap=200 refused_1m=5892.3 collector_rss=247MiB api_rss=199MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 137.8s] spans_failed_1m=1350.5 logs_failed_1m=1097.4 queue=200 queue_cap=200 refused_1m=37471.3 collector_rss=286MiB api_rss=199MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 152.8s] spans_failed_1m=682.7 logs_failed_1m=573.4 queue=200 queue_cap=200 refused_1m=65169.9 collector_rss=286MiB api_rss=201MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 167.9s] spans_failed_1m=1365.5 logs_failed_1m=589.4 queue=200 queue_cap=200 refused_1m=84554.2 collector_rss=287MiB api_rss=196MiB TelemetryExportFailing=pending MessengerHighErrorRate=inactive +[ 182.9s] spans_failed_1m=1365.4 logs_failed_1m=1224.1 queue=200 queue_cap=200 refused_1m=84860.3 collector_rss=287MiB api_rss=196MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 182.9s] client [Loki+Tempo down]: 200:6951 201:6950; p50=11ms p95=43ms p99=106ms +[ 182.9s] $ docker compose start loki tempo +[ 183.6s] spans_failed_1m=1365.4 logs_failed_1m=1224.1 queue=200 queue_cap=200 refused_1m=88988.6 collector_rss=287MiB api_rss=196MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 198.6s] spans_failed_1m=0 logs_failed_1m=634.7 queue=0 queue_cap=200 refused_1m=76515.4 collector_rss=266MiB api_rss=176MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 213.6s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=44296.3 collector_rss=200MiB api_rss=175MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 228.7s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=12213.9 collector_rss=196MiB api_rss=174MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 243.7s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=194MiB api_rss=174MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 258.7s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=194MiB api_rss=173MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 273.8s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=194MiB api_rss=171MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 288.8s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=194MiB api_rss=174MiB TelemetryExportFailing=firing MessengerHighErrorRate=inactive +[ 303.9s] spans_failed_1m=0 logs_failed_1m=0 queue=0 queue_cap=200 refused_1m=0 collector_rss=194MiB api_rss=172MiB TelemetryExportFailing=inactive MessengerHighErrorRate=inactive +[ 303.9s] client [after start]: 200:5660 201:5663; p50=10ms p95=36ms p99=93ms +[ 303.9s] == Collector stopped for 300 s: SDK export fails fast (5 s timeout, bounded queues); RSS saw-tooth until GC +[ 303.9s] $ docker compose stop otel-collector +[ 327.6s] docker stats: messenger-lab6-api-1 183.4MiB / 256MiB; messenger-lab6-api-2 173.5MiB / 256MiB; messenger-lab6-worker-1 58.01MiB / 768MiB; +[ 350.4s] docker stats: messenger-lab6-api-1 192.4MiB / 256MiB; messenger-lab6-api-2 183.2MiB / 256MiB; messenger-lab6-worker-1 58.72MiB / 768MiB; +[ 373.2s] docker stats: messenger-lab6-api-1 192.5MiB / 256MiB; messenger-lab6-api-2 183.4MiB / 256MiB; messenger-lab6-worker-1 58.29MiB / 768MiB; +[ 396.1s] docker stats: messenger-lab6-api-1 193.4MiB / 256MiB; messenger-lab6-api-2 186.8MiB / 256MiB; messenger-lab6-worker-1 58.77MiB / 768MiB; +[ 419.1s] docker stats: messenger-lab6-api-1 194.8MiB / 256MiB; messenger-lab6-api-2 189.2MiB / 256MiB; messenger-lab6-worker-1 58.55MiB / 768MiB; +[ 441.7s] docker stats: messenger-lab6-api-1 198MiB / 256MiB; messenger-lab6-api-2 189.1MiB / 256MiB; messenger-lab6-worker-1 58.1MiB / 768MiB; +[ 464.6s] docker stats: messenger-lab6-api-1 198.4MiB / 256MiB; messenger-lab6-api-2 191.2MiB / 256MiB; messenger-lab6-worker-1 58.59MiB / 768MiB; +[ 487.5s] docker stats: messenger-lab6-api-1 201.1MiB / 256MiB; messenger-lab6-api-2 193.2MiB / 256MiB; messenger-lab6-worker-1 58.2MiB / 768MiB; +[ 509.6s] docker stats: messenger-lab6-api-1 202.7MiB / 256MiB; messenger-lab6-api-2 190.5MiB / 256MiB; messenger-lab6-worker-1 56.81MiB / 768MiB; +[ 531.6s] docker stats: messenger-lab6-api-1 203.5MiB / 256MiB; messenger-lab6-api-2 193.2MiB / 256MiB; messenger-lab6-worker-1 57.3MiB / 768MiB; +[ 554.5s] docker stats: messenger-lab6-api-1 206.1MiB / 256MiB; messenger-lab6-api-2 195.3MiB / 256MiB; messenger-lab6-worker-1 56.75MiB / 768MiB; +[ 577.4s] docker stats: messenger-lab6-api-1 206.5MiB / 256MiB; messenger-lab6-api-2 191.7MiB / 256MiB; messenger-lab6-worker-1 56.92MiB / 768MiB; +[ 599.7s] docker stats: messenger-lab6-api-1 208.1MiB / 256MiB; messenger-lab6-api-2 193.7MiB / 256MiB; messenger-lab6-worker-1 56.79MiB / 768MiB; +[ 621.7s] docker stats: messenger-lab6-api-1 208.2MiB / 256MiB; messenger-lab6-api-2 194.9MiB / 256MiB; messenger-lab6-worker-1 56.46MiB / 768MiB; +[ 644.6s] docker stats: messenger-lab6-api-1 210.6MiB / 256MiB; messenger-lab6-api-2 197.3MiB / 256MiB; messenger-lab6-worker-1 56.95MiB / 768MiB; +[ 644.6s] client [collector down]: 200:15451 201:15453; p50=11ms p95=38ms p99=131ms +[ 644.6s] $ docker compose start otel-collector +[ 675.2s] client [collector back]: 200:1376 201:1372; p50=11ms p95=49ms p99=133ms +[ 675.7s] containers: /messenger-lab6-api-1 restarts=0 oom=false; /messenger-lab6-api-2 restarts=0 oom=false; /messenger-lab6-worker-1 restarts=0 oom=false +[ 675.7s] TelemetryExportFailing fired: True, resolved: True +[ 675.7s] PASS -- 2.54.0