diff --git a/.env.example b/.env.example index 119384b5..57292069 100644 --- a/.env.example +++ b/.env.example @@ -1,25 +1,31 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# Copy to .env for a LOCAL synthetic test environment; never commit .env. APP_HOST=0.0.0.0 -APP_PORT=8080 +APP_INTERNAL_PORT=8080 +PUBLIC_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +CACHE_URL=redis://redis:6379/0 API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 +S3_ENDPOINT=http://minio:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key +S3_OPERATION_TIMEOUT=5s MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 BROKER_URL_FILE=/run/secrets/broker_url WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 +JOB_RETRY_BASE=250ms +JOB_RETRY_MAX=4s +JOB_LEASE_SECONDS=75 STAGING_RETENTION_SECONDS=86400 +STAGING_CLEANUP_INTERVAL_SECONDS=30 +API_GO_MEMORY_LIMIT=220MiB +WORKER_GO_MEMORY_LIMIT=448MiB +WORKER_MEMORY_LIMIT=512M diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..8c9473b6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,41 @@ +FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder + +WORKDIR /build + +COPY go.mod go.sum ./ +RUN go mod download + +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ + + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/reconciler ./cmd/reconciler/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/worker ./cmd/worker/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/dispatcher ./cmd/dispatcher/main.go +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/jobctl ./cmd/jobctl/main.go + +FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 + +RUN addgroup -g 1000 appgroup && \ + adduser -u 1000 -G appgroup -s /bin/sh -D appuser + +WORKDIR /app + +COPY --from=builder /build/server /app/server +COPY --from=builder /build/reconciler /app/reconciler +COPY --from=builder /build/worker /app/worker +COPY --from=builder /build/dispatcher /app/dispatcher +COPY --from=builder /build/jobctl /app/jobctl + +RUN chown -R appuser:appgroup /app + +USER appuser:appgroup + +EXPOSE 8080 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \ + CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1 + + +ENTRYPOINT ["/app/server"] diff --git a/Makefile b/Makefile index 5d86d171..a47de586 100644 --- a/Makefile +++ b/Makefile @@ -2,13 +2,17 @@ PYTHON ?= python3 BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= +RECONCILE_GRACE ?= 15m TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.PHONY: help init-secrets check validate test load test-attachment-boundaries test-attachment-memory test-storage-outage test-minio-policy test-async-resilience test-level4-resilience test-level5-idempotency jobs-failed replay-job upgrade-pipeline inject-job test-persistence test-failover test-reconcile test-reconcile-scale reconcile-dry-run reconcile-apply help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" +init-secrets: + ./scripts/init-secrets.sh + check: $(PYTHON) scripts/check_contract.py @@ -21,6 +25,42 @@ test: load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) +test-attachment-memory: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/attachment_memory.py + +test-attachment-boundaries: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/attachment_boundaries.py + +test-storage-outage: + BASE_URL="$(BASE_URL)" $(PYTHON) tests/storage_outage.py + +test-minio-policy: + ./tests/minio_policy.sh +test-async-resilience: + $(PYTHON) tests/async_resilience.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-level4-resilience: + $(PYTHON) tests/level4_resilience.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-level5-idempotency: + $(PYTHON) tests/level5_idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +jobs-failed: + docker compose run --rm --no-deps --entrypoint /app/jobctl dispatcher list-failed + +replay-job: + @test -n "$(JOB_ID)" || (echo "Set JOB_ID to a failed attachment job UUID"; exit 2) + docker compose run --rm --no-deps --entrypoint /app/jobctl dispatcher replay "$(JOB_ID)" + +upgrade-pipeline: + @test -n "$(ATTACHMENT_ID)" || (echo "Set ATTACHMENT_ID"; exit 2) + @test -n "$(PIPELINE_VERSION)" || (echo "Set PIPELINE_VERSION=2"; exit 2) + docker compose run --rm --no-deps --entrypoint /app/jobctl worker upgrade "$(ATTACHMENT_ID)" "$(PIPELINE_VERSION)" + +inject-job: + @test -n "$(JOB_ID)" || (echo "Set JOB_ID"; exit 2) + docker compose run --rm --no-deps --entrypoint /app/jobctl dispatcher inject "$(JOB_ID)" + test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) @@ -28,3 +68,15 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-reconcile: + $(PYTHON) tests/reconcile_integration.py + +test-reconcile-scale: + $(PYTHON) tests/reconcile_scale.py + +reconcile-dry-run: + docker compose run --rm --entrypoint /app/reconciler api --grace-period "$(RECONCILE_GRACE)" + +reconcile-apply: + docker compose run --rm --entrypoint /app/reconciler api --grace-period "$(RECONCILE_GRACE)" --apply diff --git a/REPORT.md b/REPORT.md index e98f75e9..f214810c 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,254 @@ # Отчёт — лабораторная 5 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Чурилин Данила, БВТ2301 +- Текущий завершённый уровень: оценка «5» +- Выбранный трек 5: трек 2 — доказанная идемпотентность versioned pipeline +- Ветка: `solution/bvt2301-churilin` +- Commit/PR: пока не созданы по просьбе автора; весь уровень 5 и финальный аудит подготовлены к одному коммиту +- Использованные источники, библиотеки и помощь ИИ: Go standard library, `amqp091-go`, `disintegration/imaging`, [pure-Go go-webp v0.4.0](https://github.com/mayahiro/go-webp), PostgreSQL/pgx, MinIO SDK и RabbitMQ; OpenAI Codex использован для проектирования, реализации, fault injection, тестирования и отчёта ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Engine с Compose v2, GNU Make, Python 3.9+ и OpenSSL. Go локально не нужен: builder закреплён как `golang:1.27.1-alpine`. -## Архитектура и решения +```sh +cp .env.example .env +make init-secrets -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +docker compose --env-file .env up -d --wait -## Доказательства критериев +make check +make test BASE_URL=http://127.0.0.1:8080 +make test-async-resilience BASE_URL=http://127.0.0.1:8080 +make test-level4-resilience BASE_URL=http://127.0.0.1:8080 +make test-level5-idempotency BASE_URL=http://127.0.0.1:8080 +``` -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +`make init-secrets` создаёт локальные файлы с mode 600 в игнорируемом `secrets/` и не перезаписывает существующие значения. Миграции выполняет одноразовый `migrate`; `minio-bootstrap` идемпотентно создаёт приватный bucket, ограниченную policy и отдельного S3-пользователя. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Операторские команды failed registry, replay и versioned pipeline: -## Эксперименты и отказы +```sh +make jobs-failed +make replay-job JOB_ID= +make upgrade-pipeline ATTACHMENT_ID= PIPELINE_VERSION=2 +make inject-job JOB_ID= +``` -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Replay разрешён только для `failed`, требует ещё сохранённый staging и записывает audit event. Попытка replay для `queued`, `processing` или `succeeded` завершается ошибкой без изменения job. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +Безопасная остановка с сохранением данных: -## Ограничения и следующие шаги +```sh +docker compose --env-file .env down +``` -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Намеренное удаление всех учебных данных: + +```sh +docker compose --env-file .env down --volumes +``` + +## Архитектура и транзакционные границы + +```text +client -> HAProxy -> API x2 + |-- MinIO staging/{attachment_id}/original + '-- PostgreSQL attachment + attachment_job/outbox (COMMIT) + | + dispatcher + lease reaper <----+----> publisher confirm + | + durable RabbitMQ queue + | + manual ack -> worker (prefetch=2) + |-- MinIO original + v{1,2}/{thumbnail,crop,optimized} + '-- PostgreSQL variants + ready/succeeded (COMMIT) + | + delete/clear staging +``` + +Источники истины: + +- PostgreSQL: состояния, metadata, job/outbox, `available_at`, lease, failed registry и audit events; +- MinIO: durable staging и конечные объекты; +- RabbitMQ: persistent at-least-once transport; +- Redis: восстанавливаемый cache, не источник истины. + +### Граница ответа 202 + +1. API ограниченно читает максимум 10 MiB, проверяет MIME, полный decode и максимум 40 млн пикселей. +2. Проверенный оригинал устойчиво записывается в приватный MinIO staging. +3. `attachments(status=queued)` и `attachment_jobs(status=queued, attempt=1)` фиксируются одной транзакцией PostgreSQL. +4. Только после успешного commit возвращается `202 Accepted`. Resize в API не выполняется. + +Job-row одновременно является outbox-записью. Dispatcher выбирает только `queued AND published_at IS NULL AND available_at <= now()`, публикует persistent-message в durable queue, ждёт publisher confirm и затем ставит publish-marker. Если процесс падает после DB commit до publish, строка остаётся видимой. Если он падает после confirm до marker, будет безопасный дубль. + +Broker message содержит только schema/job/attachment/pipeline/attempt и время. Bytes, credentials, произвольный URL и клиентский filename в очередь не попадают. + +### Media pipeline + +Worker повторно проверяет размер, SHA-256 и pixel limit, применяет EXIF orientation и создаёт: + +| Variant | Формат и параметры | Геометрия | +| --- | --- | --- | +| `thumbnail` | JPEG quality 85 (v1) / 90 (v2), alpha на белом | fit 256×256, floor, минимум 1 px, без upscale | +| `crop` | JPEG quality 85 (v1) / 90 (v2), alpha на белом | центрированный square 128×128, upscale разрешён | +| `optimized` | lossy WebP quality 80 (v1) / 85 (v2) | fit 1280×1280, floor, без upscale, alpha сохраняется | + +Все варианты строятся из декодированных ориентированных пикселей. EXIF/ICC/XMP не передаются кодировщикам, поэтому metadata удаляется. WebP вызывается через cancellable `EncodeContext`. Новые upload используют v1; операторский upgrade повторно ставит готовый или остановленный после side effect original в v2 через отдельный durable staging. + +Ограничения ресурсов worker: + +- повторная проверка 10 MiB и 40 млн пикселей до полного worker-decode; +- `JOB_TIMEOUT_SECONDS=60`; +- `GOMEMLIMIT=448MiB` и hard Compose limit 512 MiB; +- concurrency/prefetch равны 2; +- lease 75 секунд, то есть длиннее timeout; +- S3/DB операции имеют отдельные bounded timeouts. + +### Идемпотентность, retry и lease + +Ключ эффекта — `(attachment_id, pipeline_version, variant)`; это PK таблицы вариантов. Object keys детерминированы и содержат версию. Все три variant metadata и переход `ready/succeeded` фиксируются одной DB-транзакцией. Повтор не создаёт новые строки и не откатывает ready. + +Upgrade v1→v2 сначала создаёт новый durable staging из неизменного final original, затем одной PostgreSQL-транзакцией меняет активную `attachments.pipeline_version`, переводит прежнюю queued/processing job в `superseded` и создаёт v2 job/outbox. Completion, retry, permanent failure, replay и lease recovery сравнивают версию job с активной версией attachment. Устаревший результат может оставить объект только в своём `/v1/` prefix, но не публикует metadata и не очищает v2 staging. + +Transient error: + +- job `processing -> queued`; +- attempt увеличивается; +- `published_at` и lease сбрасываются; +- `available_at` получает exponential backoff; +- base 250 ms, cap 4 s, deterministic per-job jitter в диапазоне 0.5–1.5; +- после пятой попытки: job `failed/processing_failed`, attachment `failed/retry_exhausted`. + +Permanent error (`invalid_image`, `staging_expired`, `unsupported_pipeline`) сразу переводит активную job в failed без расходования остальных попыток. Устаревшая версия получает `superseded` без изменения активного attachment. Все переходы регистрируются в `attachment_job_events`. + +При claim worker ставит `lease_until` и `leased_by`. Dispatcher reaper возвращает просроченную processing-job в queued с новой попыткой и backoff. Старое broker-сообщение после смены attempt становится no-op. Сообщение для уже удалённой job также ack-ается как stale no-op, а не образует poison requeue loop. + +### Staging cleanup + +После commit результата worker удаляет staging и очищает `attachments.staging_key`. Фоновый cleaner запускается при старте и каждые 30 секунд: + +- ready staging удаляется немедленно как избыточный; +- failed staging и DB-orphan удаляются только старше retention 24 часа; +- queued/processing staging не удаляется независимо от возраста; +- replay после retention безопасно отклоняется. + +## Fault injection и доказательства уровня 4 + +`tests/level4_resilience.py` выполняет реальные управляемые сбои: + +1. создаёт и скачивает три настоящих варианта, проверяет MIME, dimensions, size и SHA-256; +2. создаёт marker в dispatcher, после DB commit процесс делает `os.Exit(87)` до publish; restart восстанавливает ту же outbox-job; +3. создаёт marker в worker, процесс делает `os.Exit(86)` после всех S3 writes, но до result commit/ack; lease принудительно истекает, reaper выполняет redelivery; +4. подменяет trusted SHA-256 и доказывает permanent `invalid_image` на attempt 1; +5. делает staging временно недоступным, получает четыре retry + финальный attempt 5; +6. находит job через `jobctl list-failed`, восстанавливает staging и делает явный replay; +7. повторный replay уже succeeded-job отклоняется; +8. проверяет ровно три variant rows и `staging_key IS NULL`. + +Фактический итог: + +```text +PASS: level-4 variants, outbox crash recovery, lease recovery, backoff/failed registry and safe replay verified. +``` + +## Исследование уровня 5 — трек 2 + +### Гипотеза + +Versioned keys и проверка активной версии во всех DB-переходах обеспечивают идемпотентный итог при at-least-once доставке: подтверждённая работа не теряется при crash до/после side effect, а дубликат, reorder и старая job после v2 не меняют новый результат. + +### Методика + +`tests/level5_idempotency.py` автоматически выполняет четыре группы воздействий: + +1. crash до первого object write (`os.Exit(85)`), проверка отсутствия final original, принудительное истечение lease и восстановление v1; +2. crash после object writes до result COMMIT/ACK (`os.Exit(86)`), upgrade processing v1→v2 и проверка `v1=superseded`; +3. завершение v1, upgrade v2 и сравнение трёх SHA-256 каждой версии; +4. два дубля v2 и затем reorder устаревшего v1-сообщения после v2. + +До воздействия фиксируются active version, job states, variant hashes и original SHA-256. После воздействия проверяются `ready:2`, неизменность v2/original, шесть исторических variant rows для завершённых v1+v2, отсутствие лишних строк и пустая очередь. + +### Результат + +~~~text +PASS: pipeline v1/v2 history, crash before/after side effect, +superseded in-flight work, duplicate and reordered stale deliveries verified. +~~~ + +Гипотеза подтверждена в заявленной модели отказов. Подробные команды, sample UUID/хеши, инварианты и ограничения сохранены в `evidence/lab5-grade5.md`. + +Это не exactly-once: RabbitMQ физически может доставить сообщение повторно, publisher может повторить publish после неясного confirm, а worker — повторить S3 write после смерти до ACK. Доказан идемпотентный effectively-once результат: только активная версия может атомарно опубликовать metadata, а versioned keys изолируют side effects. + +## Таблица проверок + +Все результаты ниже повторно получены 2026-11-08 на локальном WSL2/Docker Compose стенде после чистой пересборки образов и финального аудита. + +| Критерий | Команда/сценарий | Наблюдаемый результат | +| --- | --- | --- | +| Contract/OpenAPI | `make check`, `make validate` | PASS | +| Public API | `make test` | PASS | +| Уровень 3 | `make test-async-resilience` | durability, duplicate, bounded failed — PASS | +| Уровень 5, трек 2 | `make test-level5-idempotency` | v1/v2, crash before/after side effect, duplicate, reorder, stale-after-new — PASS | +| Три level-4 variants | `make test-level4-resilience` | thumbnail 256×160, crop 128×128, optimized WebP 320×200 — PASS | +| COMMIT → publish crash | dispatcher fault marker | один job, restart, publish и ready — PASS | +| S3 writes → commit/ack crash | worker fault marker + lease expiry | lease_recovered, ready, ровно 3 variants — PASS | +| Permanent/transient | SHA mismatch / missing staging | attempt 1 invalid_image / attempt 5 retry_exhausted — PASS | +| Failed registry/replay | `jobctl list-failed/replay` | replay_count=1; replay succeeded-job отклонён | +| Staging cleanup | integration + `cleaner_test.go` | ready удалён; active/recent сохранены — PASS | +| EXIF/alpha/no-upscale | `processor_test.go` | orientation, white JPEG background, WebP alpha, metadata stripping — PASS | +| Unit/static | `go test -count=1 ./...`, `go test -race -count=1 ./...`, `go vet ./...`, `go build ./...` | PASS | +| Go hygiene | `gofmt`, `go mod verify`, `go mod tidy -diff`, `git diff --check` | PASS, изменений/ошибок нет | +| Frontend | чистый `docker compose build --no-cache frontend` | 1/1 Vitest, TypeScript и Vite production build — PASS; 0 npm vulnerabilities | +| Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS | +| API failover | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 142 writes, 0 failures, recovery 2.757 s | +| Boundaries | `make test-attachment-boundaries` | 10 MiB/40M px accepted; excess/corruption rejected — PASS | +| API memory | `make test-attachment-memory` | 12/12, 2 replicas; peaks 28,531,752 / 32,516,341 bytes | +| MinIO policy | `make test-minio-policy` | least privilege и anonymous GET denied — PASS | +| MinIO outage | `make test-storage-outage` | readiness 503 2.003 s; upload 503 5.007 s; original preserved | +| Reconciler | `make test-reconcile` | 4 fixture-проблемы; apply удалил 2 объекта и пометил 1 attachment; повтор 0 mutations; reference protected — PASS | +| Reconciler scale | `make test-reconcile-scale` | 100/1000 orphan objects; traversal 33/46 ms — PASS | +| Fresh migrations | одноразовый чистый PostgreSQL + migrations `up` | версии 1→6 применены; `version=6`, `dirty=false` — PASS | +| Изолированный чистый стенд | новый Compose project/volumes, порт 18080 | smoke + уровни 3/4/5 + reconciler — PASS; после аудита временные volumes удалены | +| Secrets | Git ignore + exact-value scan локальных password/URL/key | `.env`, `secrets/`, `.venv` не входят в Git; совпадений чувствительных значений нет | +| Stale messages | memory cleanup + queue inspection | `messages_ready=0`, `messages_unacknowledged=0` | +| Compose | `docker compose --env-file .env config --quiet` | exit 0 | + +Подробные raw summaries сохранены в `evidence/lab5-grade4.md` и `evidence/lab5-grade5.md`. + +### Повторный предсдаточный аудит 2026-11-08 + +Аудит обнаружил и устранил две связанные регрессии совместимости lab4→lab5 в служебном reconciler: + +1. старая fixture использовала больше не допустимый статус `pending`, а reconciler через source-compatible alias мог считать давно стоящий `queued` устаревшим и ошибочно переводить его в `failed`; +2. inventory ownership учитывал только `attachments.object_key`, поэтому versioned variants и staging могли выглядеть как orphan objects. + +Текущая реализация не изменяет `queued/processing` по одному возрасту, а как принадлежащие attachment учитывает final original, ненулевой `staging_key` и все ключи из `attachment_variants`. Unit-тест отдельно фиксирует сохранность старых активных attachment/staging, integration-тест проверяет dry-run/apply/repeat на реальных PostgreSQL и MinIO, а scale-тест повторяет обход на 100 и 1000 объектах. + +Финальное состояние отдельного чистого Compose-проекта после всех намеренных crash/restart сценариев и до удаления его временных volumes: + +- обе API-реплики, PostgreSQL, Redis, MinIO, RabbitMQ, frontend и load balancer healthy; migration/bootstrap завершились с exit 0; +- schema migration `6`, `dirty=false`; +- jobs: `failed=2`, `succeeded=10`, `superseded=1`, активных `queued/processing=0`; +- variant metadata: `v1=24`, `v2=6`; +- RabbitMQ `messages_ready=0`, `messages_unacknowledged=0`; +- у девяти `ready` attachment нет staging; два failed staging сохранены намеренно до retention/replay; +- `/health/ready` возвращает `200 {"status":"ok"}`, frontend `/` возвращает 200. + +На основном стенде после такого же прогона fault-marker files отсутствуют, а за минуту после стабилизации новых `panic/fatal/error/warn` в логах не появилось. Временный чистый Compose-проект `mtusi2026lab5audit1108` и только его изолированные volumes после снятия результатов удалены. + +## Ограничения + +Уровень 4 и выбранный трек 5 полностью реализованы. + +- Поддержаны pipeline v1 и v2; произвольный registry версий и профилей не реализован. +- Upgrade является операторской командой, а не публичным пользовательским API. +- Старые versioned variant-объекты сохраняются для аудита; lifecycle архивных версий не реализован. +- Lease фиксированный и длиннее timeout; heartbeat-продление для динамических SLA отсутствует. +- Failed registry находится в PostgreSQL, а не отдельной broker DLQ, чтобы сохранить атомарную связь с attachment и audit. +- At-least-once плюс идемпотентный эффект не является exactly-once delivery. +- Эксперимент выполнен на одном Docker-host и не покрывает потерю host или volumes PostgreSQL/MinIO. diff --git a/cmd/dispatcher/main.go b/cmd/dispatcher/main.go new file mode 100644 index 00000000..b2f352c5 --- /dev/null +++ b/cmd/dispatcher/main.go @@ -0,0 +1,131 @@ +package main + +import ( + "context" + "errors" + "log" + "os" + "os/signal" + "syscall" + "time" + + "mtusi2026lab5/internal/adapter/broker" + "mtusi2026lab5/internal/adapter/postgres" + "mtusi2026lab5/internal/config" + "mtusi2026lab5/internal/database" + "mtusi2026lab5/internal/domain" + "mtusi2026lab5/internal/worker" +) + +const defaultBeforePublishFaultFile = "/tmp/mtusi-fault-before-publish" + +func main() { + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if cfg.BrokerURL == "" { + log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer pool.Close() + store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout) + client, err := broker.Open(cfg.BrokerURL, 0) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err) + } + defer client.Close() + + faultFile := os.Getenv("DISPATCHER_FAULT_BEFORE_PUBLISH_FILE") + if faultFile == "" { + faultFile = defaultBeforePublishFaultFile + } + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + log.Println("[INFO] Attachment job dispatcher and lease reaper started") + + for { + now := time.Now().UTC() + expired, queryErr := store.ListExpiredAttachmentJobs(ctx, now, 50) + if queryErr != nil { + if ctx.Err() != nil { + return + } + log.Printf("[WARN] List expired jobs failed: %v", queryErr) + } else { + for _, job := range expired { + delay := worker.RetryDelay( + job.JobID, + job.Attempt+1, + cfg.JobRetryBase, + cfg.JobRetryMax, + ) + recovered, final, recoverErr := store.RetryAttachmentJob( + ctx, + job.JobID, + "lease_expired", + now.Add(delay), + now, + "lease_recovered", + ) + if recoverErr != nil { + log.Printf("[WARN] Recover expired job %s failed: %v", job.JobID, recoverErr) + continue + } + if final && recovered.Status == domain.AttachmentJobFailed { + log.Printf("[WARN] Expired job %s exhausted retries", job.JobID) + } else if !final { + log.Printf("[INFO] Recovered expired job %s as attempt %d", job.JobID, recovered.Attempt) + } + } + } + + jobs, queryErr := store.ListUnpublishedAttachmentJobs(ctx, 50) + if queryErr != nil { + if ctx.Err() != nil { + return + } + log.Printf("[WARN] List unpublished jobs failed: %v", queryErr) + } else { + for _, job := range jobs { + removeErr := os.Remove(faultFile) + if removeErr == nil { + log.Printf("[FAULT] exiting after DB commit and before publish for job %s", job.JobID) + os.Exit(87) + } + if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + log.Printf("[WARN] Consume before-publish fault marker: %v", removeErr) + } + + publishContext, cancel := context.WithTimeout(ctx, 10*time.Second) + publishErr := client.Publish(publishContext, job) + cancel() + if publishErr != nil { + log.Fatalf("[FATAL] Publish job %s failed: %v", job.JobID, publishErr) + } + if err = store.MarkAttachmentJobPublished( + ctx, + job.JobID, + job.Attempt, + time.Now().UTC(), + ); err != nil { + // Publisher confirm proves broker acceptance. Leaving the + // marker unset intentionally causes a safe duplicate. + log.Printf("[WARN] Job %s was confirmed but publish marker failed: %v", job.JobID, err) + } + } + } + + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} diff --git a/cmd/jobctl/main.go b/cmd/jobctl/main.go new file mode 100644 index 00000000..b6b0a094 --- /dev/null +++ b/cmd/jobctl/main.go @@ -0,0 +1,259 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "strconv" + "time" + + "mtusi2026lab5/internal/adapter/broker" + "mtusi2026lab5/internal/adapter/objectstore" + "mtusi2026lab5/internal/adapter/postgres" + "mtusi2026lab5/internal/application" + "mtusi2026lab5/internal/config" + "mtusi2026lab5/internal/database" + "mtusi2026lab5/internal/domain" + + "github.com/google/uuid" +) + +type jobView struct { + JobID string `json:"job_id"` + AttachmentID string `json:"attachment_id"` + PipelineVersion int `json:"pipeline_version"` + Status domain.AttachmentJobStatus `json:"status"` + Attempt int `json:"attempt"` + MaxAttempts int `json:"max_attempts"` + ErrorCode *string `json:"error_code"` + ReplayCount int `json:"replay_count"` + UpdatedAt time.Time `json:"updated_at"` +} + +func main() { + if len(os.Args) < 2 { + usage() + } + switch os.Args[1] { + case "list-failed": + runListFailed() + case "replay": + runReplay() + case "inject": + runInject() + case "upgrade": + runUpgrade() + default: + usage() + } +} + +func openStore(ctx context.Context, cfg config.Config) (*postgres.PostgreSQLStore, func()) { + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("PostgreSQL initialization failed: %v", err) + } + return postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout), pool.Close +} + +func runListFailed() { + limit := 100 + if len(os.Args) == 3 { + parsed, err := strconv.Atoi(os.Args[2]) + if err != nil || parsed < 1 || parsed > 1000 { + log.Fatal("limit must be an integer between 1 and 1000") + } + limit = parsed + } else if len(os.Args) != 2 { + usage() + } + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + jobs, err := store.ListFailedAttachmentJobs(ctx, limit) + if err != nil { + log.Fatalf("list failed jobs: %v", err) + } + views := make([]jobView, 0, len(jobs)) + for _, job := range jobs { + views = append(views, view(job)) + } + writeJSON(views) +} + +func runReplay() { + if len(os.Args) != 3 { + usage() + } + jobID := requireUUID(os.Args[2], "job_id") + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + job, err := store.ReplayFailedAttachmentJob(ctx, jobID, time.Now().UTC()) + if errors.Is(err, postgres.ErrConflict) { + log.Fatal("replay rejected: job is not the active failed pipeline or retained staging is unavailable") + } + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("replay rejected: job not found") + } + if err != nil { + log.Fatalf("replay failed: %v", err) + } + writeJSON(view(job)) +} + +func runInject() { + if len(os.Args) != 3 { + usage() + } + jobID := requireUUID(os.Args[2], "job_id") + cfg, err := config.LoadDispatcher() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + job, err := store.GetAttachmentJob(ctx, jobID) + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("inject rejected: job not found") + } + if err != nil { + log.Fatalf("read job for injection: %v", err) + } + client, err := broker.Open(cfg.BrokerURL, 1) + if err != nil { + log.Fatalf("RabbitMQ initialization failed: %v", err) + } + defer client.Close() + if err = client.Publish(ctx, job); err != nil { + log.Fatalf("inject broker message: %v", err) + } + writeJSON(view(job)) +} + +func runUpgrade() { + if len(os.Args) != 4 { + usage() + } + attachmentID := requireUUID(os.Args[2], "attachment_id") + targetVersion, err := strconv.Atoi(os.Args[3]) + if err != nil || targetVersion != 2 { + log.Fatal("target pipeline version must be 2") + } + cfg, err := config.LoadWorker() + if err != nil { + log.Fatalf("invalid configuration: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + store, closeStore := openStore(ctx, cfg) + defer closeStore() + attachment, err := store.GetAttachmentForProcessing(ctx, attachmentID) + if errors.Is(err, postgres.ErrNotFound) { + log.Fatal("upgrade rejected: attachment not found") + } + if err != nil { + log.Fatalf("read attachment for upgrade: %v", err) + } + if attachment.PipelineVersion+1 != targetVersion { + log.Fatalf("upgrade rejected: current pipeline is v%d", attachment.PipelineVersion) + } + objects, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("object storage initialization failed: %v", err) + } + source, err := objects.Get(ctx, attachment.ObjectKey) + if err != nil { + log.Fatalf("upgrade source original is unavailable: %v", err) + } + defer source.Body.Close() + stagingKey := fmt.Sprintf("staging/%s/v%d/original", attachment.ID, targetVersion) + if err = objects.Put(ctx, application.ObjectPut{ + Key: stagingKey, + ContentType: attachment.ContentType, + SizeBytes: attachment.SizeBytes, + Body: source.Body, + }); err != nil { + log.Fatalf("create durable upgrade staging: %v", err) + } + now := time.Now().UTC() + job := domain.AttachmentJob{ + SchemaVersion: 1, + JobID: uuid.NewString(), + Type: domain.AttachmentJobType, + AttachmentID: attachment.ID, + PipelineVersion: targetVersion, + Attempt: 1, + MaxAttempts: cfg.JobMaxAttempts, + Status: domain.AttachmentJobQueued, + AvailableAt: now, + CreatedAt: now, + UpdatedAt: now, + } + job, err = store.UpgradeAttachmentPipeline(ctx, attachment.ID, targetVersion, stagingKey, job, now) + if errors.Is(err, postgres.ErrConflict) { + log.Fatal("upgrade rejected: attachment is not in an upgradeable state or target is not the next version") + } + if err != nil { + // Keep the copied source: a COMMIT error is ambiguous and cleanup can + // safely remove an actual orphan after the retention period. + log.Fatalf("upgrade pipeline: %v", err) + } + writeJSON(view(job)) +} + +func requireUUID(value, name string) string { + if _, err := uuid.Parse(value); err != nil { + log.Fatalf("%s must be a UUID", name) + } + return value +} + +func view(job domain.AttachmentJob) jobView { + return jobView{ + JobID: job.JobID, + AttachmentID: job.AttachmentID, + PipelineVersion: job.PipelineVersion, + Status: job.Status, + Attempt: job.Attempt, + MaxAttempts: job.MaxAttempts, + ErrorCode: job.ErrorCode, + ReplayCount: job.ReplayCount, + UpdatedAt: job.UpdatedAt, + } +} + +func writeJSON(value any) { + encoder := json.NewEncoder(os.Stdout) + encoder.SetEscapeHTML(true) + if err := encoder.Encode(value); err != nil { + log.Fatalf("encode output: %v", err) + } +} + +func usage() { + fmt.Fprintln(os.Stderr, "usage: jobctl list-failed [limit] | replay | inject | upgrade 2") + os.Exit(2) +} diff --git a/cmd/reconciler/main.go b/cmd/reconciler/main.go new file mode 100644 index 00000000..aac73fdf --- /dev/null +++ b/cmd/reconciler/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "time" + + "mtusi2026lab5/internal/adapter/objectstore" + "mtusi2026lab5/internal/adapter/postgres" + "mtusi2026lab5/internal/config" + "mtusi2026lab5/internal/database" + "mtusi2026lab5/internal/reconcile" +) + +func main() { + apply := flag.Bool("apply", false, "apply safe repairs; default is dry-run") + gracePeriod := flag.Duration("grace-period", 15*time.Minute, + "ignore metadata and objects newer than this duration") + timeout := flag.Duration("timeout", 2*time.Minute, "maximum reconciliation runtime") + flag.Parse() + + if *gracePeriod <= 0 || *timeout <= 0 { + log.Fatal("[FATAL] grace-period and timeout must be positive") + } + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + databasePool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + metadataStore := postgres.NewPostgreSQLStore(databasePool, cfg.DatabaseQueryTimeout) + + objectStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + if err = objectStore.Ping(ctx); err != nil { + log.Fatalf("[FATAL] Object storage unavailable: %v", err) + } + + reconciler, err := reconcile.New(metadataStore, objectStore) + if err != nil { + log.Fatalf("[FATAL] Reconciler initialization failed: %v", err) + } + result, err := reconciler.Run(ctx, *gracePeriod, *apply) + if err != nil { + log.Fatalf("[FATAL] Reconciliation failed: %v", err) + } + + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + if err = encoder.Encode(result); err != nil { + log.Fatalf("[FATAL] Encode reconciliation result: %v", err) + } + if !*apply && len(result.Issues) > 0 { + fmt.Fprintln(os.Stderr, "dry-run found reconciliation issues; rerun with --apply after review") + } +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..5661cd5f --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,260 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + cacheadapter "mtusi2026lab5/internal/adapter/cache" + "mtusi2026lab5/internal/adapter/health" + "mtusi2026lab5/internal/adapter/objectstore" + "mtusi2026lab5/internal/adapter/postgres" + redisadapter "mtusi2026lab5/internal/adapter/redis" + "mtusi2026lab5/internal/application" + "mtusi2026lab5/internal/config" + "mtusi2026lab5/internal/database" + "mtusi2026lab5/internal/transport/http/handlers" + "mtusi2026lab5/internal/transport/http/middleware" +) + +func main() { + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + startupContext, startupCancel := context.WithTimeout( + context.Background(), + cfg.DatabaseConnectTimeout, + ) + + databasePool, err := database.Open(startupContext, cfg) + startupCancel() + + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + + postgresStore := postgres.NewPostgreSQLStore( + databasePool, + cfg.DatabaseQueryTimeout, + ) + minioStore, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Invalid object storage configuration: %v", err) + } + storageContext, storageCancel := context.WithTimeout( + context.Background(), + cfg.S3OperationTimeout, + ) + if err = minioStore.Ping(storageContext); err != nil { + log.Printf("[WARN] Object storage unavailable at startup: %v", err) + } + storageCancel() + + var applicationStore application.Repository = postgresStore + + if cfg.RedisURL != "" { + redisChatCache, cacheError := redisadapter.NewRedisChatCache( + cfg.RedisURL, + cfg.RedisCacheTTL, + cfg.RedisOperationTimeout, + cfg.RedisPoolSize, + ) + if cacheError != nil { + log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError) + } + defer func() { + if closeError := redisChatCache.Close(); closeError != nil { + log.Printf("[WARN] Redis client close failed: %v", closeError) + } + }() + + cacheContext, cacheCancel := context.WithTimeout( + context.Background(), + cfg.RedisOperationTimeout, + ) + if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil { + log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError) + } else { + log.Println("[INFO] Redis chat cache is available") + } + cacheCancel() + + applicationStore = cacheadapter.NewCachedRepository( + postgresStore, + redisChatCache, + log.Default(), + ) + } + + cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey) + if err != nil { + log.Fatalf("[FATAL] Invalid cursor configuration: %v", err) + } + + service, err := application.NewService( + applicationStore, + cursorCodec, + cfg.SessionTTL, + application.WithIdempotencyTTL(cfg.IdempotencyTTL), + application.WithObjectStore(minioStore), + application.WithJobMaxAttempts(cfg.JobMaxAttempts), + ) + if err != nil { + log.Fatalf("[FATAL] Application initialization failed: %v", err) + } + + handler := handlers.NewHandler( + service, + handlers.WithReadiness( + health.NewMultiChecker(databasePool, minioStore), + cfg.ReadinessTimeout, + ), + handlers.WithSessionCookieSecure(cfg.SessionCookieSecure), + ) + + mux := http.NewServeMux() + + mux.HandleFunc("GET /health/live", handler.HealthLive) + mux.HandleFunc("GET /health/lb", handler.HealthLive) + mux.HandleFunc("GET /health/ready", handler.HealthReady) + + mux.HandleFunc( + "POST /api/v1/auth/sessions", + handler.CreateSession, + ) + + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + + requireAuth := func(next http.HandlerFunc) http.HandlerFunc { + return middleware.RequireAuth(service, next) + } + + mux.HandleFunc( + "GET /api/v1/users/me", + requireAuth(handler.GetMe), + ) + + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + requireAuth(handler.DeleteCurrentSession), + ) + + mux.HandleFunc( + "POST /api/v1/chats", + requireAuth(handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireAuth(handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireAuth(handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireAuth(handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireAuth(handler.GetMessages), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/attachments", + requireAuth(handler.UploadAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}", + requireAuth(handler.GetAttachment), + ) + mux.HandleFunc( + "GET /api/v1/attachments/{attachment_id}/content", + requireAuth(handler.DownloadAttachment), + ) + + var rootHandler http.Handler = mux + rootHandler = middleware.Recovery(rootHandler) + rootHandler = middleware.Logger(rootHandler) + availabilityGate := middleware.NewAvailabilityGate() + rootHandler = availabilityGate.Middleware(rootHandler) + rootHandler = middleware.RequestID(rootHandler) + rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler) + + server := &http.Server{ + Addr: cfg.HTTPAddress(), + Handler: rootHandler, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + serverErrors := make(chan error, 1) + + go func() { + log.Printf( + "[INFO] Server instance %s starting on %s", + cfg.InstanceID, + server.Addr, + ) + serverErrors <- server.ListenAndServe() + }() + + shutdownSignals := make(chan os.Signal, 1) + signal.Notify( + shutdownSignals, + os.Interrupt, + syscall.SIGTERM, + ) + defer signal.Stop(shutdownSignals) + + select { + case serverError := <-serverErrors: + if !errors.Is(serverError, http.ErrServerClosed) { + log.Fatalf("[FATAL] Server crashed: %v", serverError) + } + + case signalValue := <-shutdownSignals: + log.Printf( + "[INFO] Signal %v received. Starting graceful shutdown...", + signalValue, + ) + + availabilityGate.BeginDrain() + log.Printf( + "[INFO] Readiness disabled; draining new traffic for %s", + cfg.ShutdownDrainDelay, + ) + time.Sleep(cfg.ShutdownDrainDelay) + + shutdownContext, shutdownCancel := context.WithTimeout( + context.Background(), + cfg.ShutdownTimeout, + ) + defer shutdownCancel() + + if err := server.Shutdown(shutdownContext); err != nil { + log.Printf( + "[WARN] Graceful shutdown failed: %v. Forcing close.", + err, + ) + _ = server.Close() + } + + log.Println("[INFO] Server stopped gracefully.") + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go new file mode 100644 index 00000000..23662e5e --- /dev/null +++ b/cmd/worker/main.go @@ -0,0 +1,240 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "os/signal" + "sync" + "syscall" + "time" + + "mtusi2026lab5/internal/adapter/broker" + "mtusi2026lab5/internal/adapter/objectstore" + "mtusi2026lab5/internal/adapter/postgres" + "mtusi2026lab5/internal/config" + "mtusi2026lab5/internal/database" + "mtusi2026lab5/internal/domain" + "mtusi2026lab5/internal/worker" +) + +const ( + defaultBeforeObjectsFaultFile = "/tmp/mtusi-fault-before-objects" + defaultAfterObjectsFaultFile = "/tmp/mtusi-fault-after-objects" +) + +func main() { + cfg, err := config.LoadWorker() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + if cfg.BrokerURL == "" { + log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required") + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + pool, err := database.Open(ctx, cfg) + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer pool.Close() + store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout) + objects, err := objectstore.NewMinIOStore( + cfg.S3Endpoint, + cfg.S3Region, + cfg.S3Bucket, + cfg.S3AccessKeyID, + cfg.S3SecretAccessKey, + cfg.S3OperationTimeout, + ) + if err != nil { + log.Fatalf("[FATAL] Object storage initialization failed: %v", err) + } + + beforeFaultFile := os.Getenv("WORKER_FAULT_BEFORE_OBJECTS_FILE") + if beforeFaultFile == "" { + beforeFaultFile = defaultBeforeObjectsFaultFile + } + afterFaultFile := os.Getenv("WORKER_FAULT_AFTER_OBJECTS_FILE") + if afterFaultFile == "" { + afterFaultFile = defaultAfterObjectsFaultFile + } + processor, err := worker.NewProcessor(store, objects, worker.ProcessorHooks{ + BeforeObjects: func(job domain.AttachmentJob) error { + removeErr := os.Remove(beforeFaultFile) + if errors.Is(removeErr, os.ErrNotExist) { + return nil + } + if removeErr != nil { + return fmt.Errorf("consume before-objects fault marker: %w", removeErr) + } + log.Printf("[FAULT] exiting before object writes for job %s", job.JobID) + os.Exit(85) + return nil + }, + AfterObjects: func(job domain.AttachmentJob) error { + removeErr := os.Remove(afterFaultFile) + if errors.Is(removeErr, os.ErrNotExist) { + return nil + } + if removeErr != nil { + return fmt.Errorf("consume after-objects fault marker: %w", removeErr) + } + log.Printf("[FAULT] exiting after object writes and before DB commit for job %s", job.JobID) + os.Exit(86) + return nil + }, + }) + if err != nil { + log.Fatalf("[FATAL] Worker processor initialization failed: %v", err) + } + + cleaner, err := worker.NewStagingCleaner(store, objects, cfg.StagingRetention) + if err != nil { + log.Fatalf("[FATAL] Staging cleaner initialization failed: %v", err) + } + var maintenance sync.WaitGroup + maintenance.Add(1) + go func() { + defer maintenance.Done() + runCleanup := func() { + cleanupContext, cancel := context.WithTimeout(ctx, cfg.S3OperationTimeout+cfg.DatabaseQueryTimeout) + deleted, cleanupErr := cleaner.RunOnce(cleanupContext, time.Now().UTC()) + cancel() + if cleanupErr != nil && ctx.Err() == nil { + log.Printf("[WARN] Staging cleanup failed: %v", cleanupErr) + } else if deleted > 0 { + log.Printf("[INFO] Staging cleanup removed %d object(s)", deleted) + } + } + runCleanup() + ticker := time.NewTicker(cfg.StagingCleanupInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + runCleanup() + } + } + }() + + client, err := broker.Open(cfg.BrokerURL, cfg.WorkerConcurrency) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err) + } + defer client.Close() + deliveries, err := client.Consume(cfg.InstanceID) + if err != nil { + log.Fatalf("[FATAL] RabbitMQ consume failed: %v", err) + } + + var group sync.WaitGroup + for index := 0; index < cfg.WorkerConcurrency; index++ { + group.Add(1) + go func(workerIndex int) { + defer group.Done() + workerID := fmt.Sprintf("%s-%d", cfg.InstanceID, workerIndex) + for delivery := range deliveries { + message, decodeErr := broker.Decode(delivery) + if decodeErr != nil { + log.Printf("[WARN] Reject invalid broker message: %v", decodeErr) + _ = delivery.Reject(false) + continue + } + now := time.Now().UTC() + job, claimed, claimErr := store.ClaimAttachmentJob( + ctx, + message, + workerID, + now.Add(cfg.JobLease), + ) + if errors.Is(claimErr, postgres.ErrNotFound) { + log.Printf("[INFO] Stale broker message for missing job %s acknowledged", message.JobID) + _ = delivery.Ack(false) + continue + } + if claimErr != nil { + log.Printf("[WARN] Claim job %s failed: %v", message.JobID, claimErr) + _ = delivery.Nack(false, true) + continue + } + if !claimed { + _ = delivery.Ack(false) + continue + } + + jobContext, cancel := context.WithTimeout(ctx, cfg.JobTimeout) + processErr := processor.Process(jobContext, job) + cancel() + if processErr == nil { + _ = delivery.Ack(false) + continue + } + + var permanent *worker.PermanentError + if errors.As(processErr, &permanent) { + if failErr := store.FailAttachmentJob( + ctx, + job.JobID, + permanent.Code, + time.Now().UTC(), + ); failErr != nil { + log.Printf("[WARN] Persist permanent failure for job %s failed: %v", job.JobID, failErr) + _ = delivery.Nack(false, true) + } else { + log.Printf("[WARN] Job %s failed permanently with %s", job.JobID, permanent.Code) + _ = delivery.Ack(false) + } + continue + } + + retryAt := time.Now().UTC() + delay := worker.RetryDelay( + job.JobID, + job.Attempt+1, + cfg.JobRetryBase, + cfg.JobRetryMax, + ) + retried, final, retryErr := store.RetryAttachmentJob( + ctx, + job.JobID, + "processing_failed", + retryAt.Add(delay), + retryAt, + "retry_scheduled", + ) + if retryErr != nil { + log.Printf("[WARN] Schedule retry for job %s failed: %v", job.JobID, retryErr) + _ = delivery.Nack(false, true) + continue + } + if final && retried.Status == domain.AttachmentJobFailed { + log.Printf("[WARN] Job %s exhausted retries", job.JobID) + } else if final && retried.Status == domain.AttachmentJobSucceeded { + log.Printf("[INFO] Duplicate delivery for completed job %s acknowledged", job.JobID) + } else if final && retried.Status == domain.AttachmentJobSuperseded { + log.Printf("[INFO] Stale pipeline job %s acknowledged as superseded", job.JobID) + } else { + log.Printf("[INFO] Job %s retry %d scheduled after %s", job.JobID, retried.Attempt, delay) + } + _ = delivery.Ack(false) + } + }(index) + } + log.Printf( + "[INFO] Attachment worker started with concurrency=%d prefetch=%d lease=%s", + cfg.WorkerConcurrency, + cfg.WorkerConcurrency, + cfg.JobLease, + ) + <-ctx.Done() + _ = client.Close() + group.Wait() + maintenance.Wait() + log.Println("[INFO] Attachment worker stopped") +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..71e8e615 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,458 @@ +services: + load-balancer: + build: + context: . + dockerfile: infrastructure/haproxy/Dockerfile + image: mtusi2026lab5-load-balancer + ports: + - "127.0.0.1:${PUBLIC_PORT:-8080}:8080" + depends_on: + api: + condition: service_healthy + frontend: + condition: service_healthy + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:8080/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + frontend: + build: + context: . + dockerfile: infrastructure/nginx/Dockerfile + image: mtusi2026lab5-web + expose: + - "8080" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/ >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.10" + memory: 64M + + postgres: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "${POSTGRES_CPU_LIMIT:-1.00}" + memory: ${POSTGRES_MEMORY_LIMIT:-512M} + + redis: + image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0 + command: + [ + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--maxmemory", + "64mb", + "--maxmemory-policy", + "allkeys-lru", + ] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + migrate: + image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7 + entrypoint: ["/bin/sh", "-ec"] + command: + - > + exec migrate + -path=/migrations + -database="$$(cat /run/secrets/database_url)" + up + secrets: + - database_url + volumes: + - ./migrations:/migrations:ro + depends_on: + postgres: + condition: service_healthy + restart: "no" + deploy: + resources: + limits: + cpus: "0.25" + memory: 64M + + minio: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: server + args: + MINIO_VERSION: RELEASE.2025-10-15T17-29-55Z + image: mtusi2026lab5-minio:RELEASE.2025-10-15T17-29-55Z + command: ["server", "/data", "--address", ":9000"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + MINIO_BROWSER: "off" + secrets: + - minio_root_user + - minio_root_password + volumes: + - minio_data:/data + expose: + - "9000" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.75" + memory: 512M + + minio-bootstrap: + build: + context: . + dockerfile: infrastructure/minio/Dockerfile + target: client + args: + MC_VERSION: RELEASE.2025-08-13T08-35-41Z + image: mtusi2026lab5-mc:RELEASE.2025-08-13T08-35-41Z + entrypoint: ["/bin/sh", "-ec"] + command: + - | + root_user="$$(cat /run/secrets/minio_root_user)" + root_password="$$(cat /run/secrets/minio_root_password)" + api_user="$$(cat /run/secrets/s3_access_key_id)" + api_password="$$(cat /run/secrets/s3_secret_access_key)" + mc alias set local http://minio:9000 "$$root_user" "$$root_password" --api S3v4 + mc mb --ignore-existing "local/$${S3_BUCKET}" + mc anonymous set none "local/$${S3_BUCKET}" + sed "s/__BUCKET__/$${S3_BUCKET}/g" /config/api-policy.template.json > /tmp/api-policy.json + mc admin policy create local messenger-api /tmp/api-policy.json + if ! mc admin user info local "$$api_user" >/dev/null 2>&1; then + mc admin user add local "$$api_user" "$$api_password" + fi + mc admin policy attach local messenger-api --user "$$api_user" + environment: + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + secrets: + - minio_root_user + - minio_root_password + - s3_access_key_id + - s3_secret_access_key + volumes: + - ./infrastructure/minio/api-policy.template.json:/config/api-policy.template.json:ro + depends_on: + minio: + condition: service_healthy + restart: "no" + + broker: + image: rabbitmq:4.1.4-alpine + entrypoint: ["/bin/sh", "-ec"] + command: + - | + export RABBITMQ_DEFAULT_USER=messenger + export RABBITMQ_DEFAULT_PASS="$$(cat /run/secrets/broker_password)" + exec docker-entrypoint.sh rabbitmq-server + secrets: + - broker_password + volumes: + - broker_data:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 5s + retries: 20 + start_period: 10s + stop_grace_period: 20s + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + dispatcher: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab5-app + entrypoint: ["/app/dispatcher"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_RETRY_BASE: ${JOB_RETRY_BASE:-250ms} + JOB_RETRY_MAX: ${JOB_RETRY_MAX:-4s} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-75} + DISPATCHER_FAULT_BEFORE_PUBLISH_FILE: /tmp/mtusi-fault-before-publish + secrets: + - database_url + - broker_url + depends_on: + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + restart: unless-stopped + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "0.25" + memory: 128M + + worker: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab5-app + entrypoint: ["/app/worker"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio: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 + S3_OPERATION_TIMEOUT: ${S3_OPERATION_TIMEOUT:-5s} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_RETRY_BASE: ${JOB_RETRY_BASE:-250ms} + JOB_RETRY_MAX: ${JOB_RETRY_MAX:-4s} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-75} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} + STAGING_CLEANUP_INTERVAL_SECONDS: ${STAGING_CLEANUP_INTERVAL_SECONDS:-30} + WORKER_FAULT_BEFORE_OBJECTS_FILE: /tmp/mtusi-fault-before-objects + WORKER_FAULT_AFTER_OBJECTS_FILE: /tmp/mtusi-fault-after-objects + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + GOMEMLIMIT: ${WORKER_GO_MEMORY_LIMIT:-448MiB} + secrets: + - database_url + - broker_url + - s3_access_key_id + - s3_secret_access_key + depends_on: + broker: + condition: service_healthy + migrate: + condition: service_completed_successfully + minio-bootstrap: + condition: service_completed_successfully + stop_grace_period: 70s + restart: unless-stopped + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "1.00" + memory: ${WORKER_MEMORY_LIMIT:-512M} + api: + build: + context: . + dockerfile: Dockerfile + image: mtusi2026lab5-app + environment: + APP_HOST: ${APP_HOST:-0.0.0.0} + APP_PORT: ${APP_INTERNAL_PORT:-8080} + APP_ENV: ${APP_ENV:-lab} + + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + SESSION_STORE: ${SESSION_STORE:-postgres} + SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false} + CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key} + + CACHE_URL: ${CACHE_URL:-redis://redis:6379/0} + CACHE_TTL: ${CACHE_TTL:-5m} + CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms} + CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10} + + S3_ENDPOINT: ${S3_ENDPOINT:-http://minio:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: ${S3_ACCESS_KEY_ID_FILE:-/run/secrets/s3_access_key_id} + S3_SECRET_ACCESS_KEY_FILE: ${S3_SECRET_ACCESS_KEY_FILE:-/run/secrets/s3_secret_access_key} + S3_OPERATION_TIMEOUT: ${S3_OPERATION_TIMEOUT:-5s} + + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} + + DB_MAX_CONNS: ${DB_MAX_CONNS:-10} + DB_MIN_CONNS: ${DB_MIN_CONNS:-2} + DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m} + DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m} + DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s} + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + + READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s} + SHUTDOWN_DRAIN_DELAY: ${SHUTDOWN_DRAIN_DELAY:-2s} + SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s} + GOMEMLIMIT: ${API_GO_MEMORY_LIMIT:-220MiB} + secrets: + - database_url + - s3_access_key_id + - s3_secret_access_key + - cursor_signing_key + expose: + - "8080" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + minio-bootstrap: + condition: service_completed_successfully + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: "${API_CPU_LIMIT:-0.50}" + memory: ${API_MEMORY_LIMIT:-256M} + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + stop_grace_period: 15s + restart: unless-stopped + + redis-insight: + image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84 + profiles: ["tools"] + ports: + - "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540" + volumes: + - redis_insight_data:/data + depends_on: + redis: + condition: service_healthy + restart: unless-stopped + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + postgres-restore: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + profiles: ["recovery"] + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_RESTORE_DB:-messenger_restore_admin} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_restore_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_RESTORE_DB:-messenger_restore_admin}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: "no" + deploy: + resources: + limits: + cpus: "1.00" + memory: 512M + +volumes: + postgres_data: + redis_insight_data: + minio_data: + broker_data: + postgres_restore_data: + +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + database_url: + file: ./secrets/database_url.txt + cursor_signing_key: + file: ./secrets/cursor_signing_key.txt + minio_root_user: + file: ./secrets/minio_root_user.txt + minio_root_password: + file: ./secrets/minio_root_password.txt + s3_access_key_id: + file: ./secrets/s3_access_key_id.txt + s3_secret_access_key: + file: ./secrets/s3_secret_access_key.txt + broker_password: + file: ./secrets/broker_password.txt + broker_url: + file: ./secrets/broker_url.txt diff --git a/evidence/lab5-grade3.md b/evidence/lab5-grade3.md new file mode 100644 index 00000000..f85bee14 --- /dev/null +++ b/evidence/lab5-grade3.md @@ -0,0 +1,50 @@ +# Lab5 grade 3 — результаты проверок + +Дата: 2026-11-04 +Ветка: `solution/bvt2301-churilin` + +```text +make check +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +make validate PYTHON=/home/d1frend/HL/mtusi2026lab4/.venv/bin/python +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. + +make test BASE_URL=http://127.0.0.1:8080 +PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. + +make test-async-resilience BASE_URL=http://127.0.0.1:8080 +PASS: durable recovery, idempotent redelivery and bounded final failure verified. + +make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080 +PASS: persistence preserved confirmed data and existing session. + +make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080 +{"observed_instances_before": 2, "successful_writes": 142, "failed_attempts": 0, "first_recovery_seconds": 2.776} +PASS: failover preserved confirmed data and existing session. + +make test-attachment-boundaries +PASS: exact byte/pixel boundaries, complete decode, and filename validation are correct. + +make test-attachment-memory +{"api_instances_observed": 2, "concurrency": 12, "elapsed_seconds": 1.007, "payload_bytes": 6293028, "peak_memory_bytes_by_container": {"mtusi2026lab5-api-1": 27472691, "mtusi2026lab5-api-2": 27294433}, "successful_uploads": 12, "total_uploaded_bytes": 75516336} +PASS: concurrent attachment uploads remained within configured API memory limits. + +make test-minio-policy +PASS: API has no MinIO root credentials; limited policy permits object IO only in the private bucket; anonymous GET is denied. + +make test-storage-outage +{"original_bytes_verified": 111817, "readiness_503_seconds": 2.004, "upload_503_seconds": 5.011} +PASS: MinIO outage returns bounded JSON 503 and preserves existing originals. + +go test ./... +PASS + +go vet ./... +PASS + +docker compose --env-file .env config --quiet +exit 0 +``` + +Сценарии и ожидаемые инварианты находятся в `tests/async_resilience.py`, `tests/resilience.py`, `scripts/restart.sh` и `scripts/stop-one.sh`. diff --git a/evidence/lab5-grade4.md b/evidence/lab5-grade4.md new file mode 100644 index 00000000..1c9be0b4 --- /dev/null +++ b/evidence/lab5-grade4.md @@ -0,0 +1,56 @@ +# Lab5 grade 4 — результаты проверок + +Дата: 2026-11-05 +Автор: Чурилин Данила, БВТ2301 +Ветка: `solution/bvt2301-churilin` + +```text +make test-level4-resilience BASE_URL=http://127.0.0.1:8080 +PASS: level-4 variants, outbox crash recovery, lease recovery, backoff/failed registry and safe replay verified. + +make test-async-resilience BASE_URL=http://127.0.0.1:8080 +PASS: durable recovery, idempotent redelivery and bounded final failure verified. + +make test BASE_URL=http://127.0.0.1:8080 +PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. + +go test ./... +PASS + +go vet ./... +PASS + +make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080 +PASS: persistence preserved confirmed data and existing session. + +make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080 +{"observed_instances_before": 2, "successful_writes": 142, "failed_attempts": 0, "first_recovery_seconds": 2.989} +PASS: failover preserved confirmed data and existing session. + +make test-attachment-boundaries +PASS: exact byte/pixel boundaries, complete decode, and filename validation are correct. + +make test-attachment-memory +{"api_instances_observed": 2, "concurrency": 12, "elapsed_seconds": 0.754, "payload_bytes": 6293028, "peak_memory_bytes_by_container": {"mtusi2026lab5-api-1": 33774632, "mtusi2026lab5-api-2": 36217815}, "successful_uploads": 12, "total_uploaded_bytes": 75516336} +PASS: concurrent attachment uploads remained within configured API memory limits. + +make test-minio-policy +PASS: API has no MinIO root credentials; limited policy permits object IO only in the private bucket; anonymous GET is denied. + +make test-storage-outage +{"original_bytes_verified": 111817, "readiness_503_seconds": 2.009, "upload_503_seconds": 5.02} +PASS: MinIO outage returns bounded JSON 503 and preserves existing originals. + +rabbitmqctl list_queues name messages_ready messages_unacknowledged +attachment.process.v1 0 0 + +docker compose --env-file .env config --quiet +exit 0 +``` + +Fault points: + +- dispatcher: `/tmp/mtusi-fault-before-publish`, exit 87; +- worker: `/tmp/mtusi-fault-after-objects`, exit 86; +- тест: `tests/level4_resilience.py`; +- unit invariants: `internal/worker/processor_test.go`, `backoff_test.go`, `cleaner_test.go`. diff --git a/evidence/lab5-grade5.md b/evidence/lab5-grade5.md new file mode 100644 index 00000000..89c84f27 --- /dev/null +++ b/evidence/lab5-grade5.md @@ -0,0 +1,121 @@ +# Lab 5 — доказательства оценки «5», трек 2 + +Дата эксперимента: 2026-11-05 +Автор: Чурилин Данила, БВТ2301 +Трек: доказанная идемпотентность versioned pipeline + +## Гипотеза + +Если логический эффект адресуется ключом `(attachment_id, pipeline_version, variant)`, новая версия создаётся одной транзакцией с supersede старой активной job, а каждый переход проверяет текущую `attachments.pipeline_version`, то at-least-once доставка, дубли, изменение порядка и падения вокруг side effect: + +1. не теряют подтверждённый HTTP 202 upload; +2. не создают дополнительные variant rows той же версии; +3. не позволяют старой job изменить состояние или метаданные активной новой версии; +4. сохраняют историю v1 и v2 раздельно. + +## Реализация и инварианты + +- Новые upload создаются в pipeline v1. +- Операторский `jobctl upgrade 2` сначала копирует неизменный final original в новый durable staging key, затем транзакционно: + - переводит старую queued/processing job в `superseded`; + - обновляет активную версию attachment; + - создаёт v2 job/outbox; + - записывает audit events. +- v1 и v2 используют разные профили качества: + - v1: JPEG 85, WebP 80; + - v2: JPEG 90, WebP 85. +- S3 keys содержат `/v1/` или `/v2/`. +- DB PK variant: `(attachment_id, pipeline_version, name)`. +- Completion, retry, permanent failure, replay и lease recovery блокируют запись неактивной версии. +- Повтор сообщения ready-job нормализуется/подтверждается как no-op. +- Неизвестный или устаревший attempt подтверждается без requeue-loop. + +Проверяемые инварианты: + +- `attachments.pipeline_version` никогда не уменьшается; +- active attachment `ready:v2` выдаёт только три v2-варианта; +- old v1 completion не меняет v2 attachment; +- число строк одной версии и одного имени не больше одной; +- original SHA-256 до/после дублей одинаков; +- после завершения нет queued/processing job, ready staging и сообщений broker. + +## Повторяемая методика + +~~~sh +docker compose --env-file .env up -d --build --wait +make test-level5-idempotency +~~~ + +`tests/level5_idempotency.py` автоматически выполняет: + +1. Crash до первого S3 side effect через `/tmp/mtusi-fault-before-objects`. + - Проверяет, что upgrade v2 отклонён из-за отсутствующего final original. + - Истекает lease и доказывает восстановление той же подтверждённой v1 job до ready. +2. Crash после S3 writes, но до result COMMIT/ack. + - Создаёт v2, пока v1 ещё processing. + - Проверяет v1 `superseded`, v2 `succeeded`, отсутствие v1 metadata commit. +3. Завершает обычную v1, сохраняет три v1-хеша, запускает upgrade v2. + - Проверяет шесть строк истории (по три на версию). + - Проверяет различие v1/v2 SHA-256 из-за разных профилей. +4. Публикует два дубля v2, затем устаревшее v1-сообщение после v2. + - Проверяет состояние `ready:2`, неизменность v2-хешей и original. + - Проверяет отсутствие дополнительных variant rows. + +Команды ручной демонстрации: + +~~~sh +make upgrade-pipeline ATTACHMENT_ID= PIPELINE_VERSION=2 +make inject-job JOB_ID= +~~~ + +## Наблюдаемый результат + +~~~text +PASS: pipeline v1/v2 history, crash before/after side effect, +superseded in-flight work, duplicate and reordered stale deliveries verified. +~~~ + +Один зафиксированный version-history sample: + +- attachment `96a4af45-e784-4b8d-8031-4c6d0e98a06c`; +- active state: `ready:v2`; +- jobs: v1 `succeeded`, v2 `succeeded`; +- variants: три v1 + три v2; +- v1 thumbnail SHA-256: `b6c3170f7966802990e1bd448f7b5491ff5a45f637c87d19aa2b9c4db42aacae`; +- v2 thumbnail SHA-256: `8947478ff919ac36572552a347acdd564e5a68aeac797adc33e8dd7d5246bb2f`. + +Один race sample завершился как v1 `superseded` + v2 `succeeded`, без v1 variant metadata. + +Финальные инварианты стенда: + +~~~text +active queued/processing jobs = 0 +ready attachments with staging_key = 0 +RabbitMQ messages_ready = 0 +RabbitMQ messages_unacknowledged = 0 +~~~ + +Регрессия после эксперимента: + +~~~text +make test-level5-idempotency — PASS +make test-async-resilience — PASS +make test-level4-resilience — PASS +make test — PASS +go test ./... — PASS +go vet ./... — PASS +~~~ + +## Почему это не exactly-once + +RabbitMQ остаётся транспортом at least once: publisher может повторить публикацию после неясного confirm, а consumer может выполнить S3 write и умереть до ACK. Одно сообщение физически может быть доставлено и обработано несколько раз. + +Доказанное свойство слабее и практичнее: повторяемый side effect идемпотентен, DB публикует только результат активной версии, а versioned object keys не дают старой версии перезаписать новую. Это effectively-once результат в заявленных границах, но не exactly-once доставка. + +## Ограничения + +- Поддержаны только pipeline v1 и v2; произвольный registry профилей не реализован. +- Upgrade — операторская команда, а не публичный API. +- История старых variant-объектов сохраняется; отдельная lifecycle-policy для архивных версий не реализована. +- Эксперимент выполнялся на одном Docker-host и не доказывает устойчивость к потере host, PostgreSQL volume или MinIO volume. +- Crash markers учебные и локальные; они не являются production chaos framework. \ No newline at end of file diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 00000000..0e75fe55 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,3 @@ +node_modules +dist +coverage diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 00000000..74b8e760 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,17 @@ + + + + + + + + MTUCI Messenger + + +
+ + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 00000000..556c03bd --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,1688 @@ +{ + "name": "mtusi-messenger-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mtusi-messenger-web", + "version": "0.1.0", + "dependencies": { + "@tanstack/react-query": "^5.104.5", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", + "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", + "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", + "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", + "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", + "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", + "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", + "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", + "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", + "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", + "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", + "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", + "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", + "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", + "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", + "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tanstack/query-core": { + "version": "5.104.5", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.104.5.tgz", + "integrity": "sha512-Q94gI8Opd+CbdVNOdj8ZCyV8WqLYitrDq1t96Xc8WZT6lY0r5iRnJLXYDxMex7EEf2v+mXvn4FcjaBKSxXZQ9A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.104.5", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.104.5.tgz", + "integrity": "sha512-RORgFe052U+93weaNuqg7qHq7vNVNzXN/VrXqD4bbAuQCWUqOl2lV5Ui9flWk5CVvMyL/Bh27QWhzwH0aaOx9g==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.104.5" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz", + "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.152.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "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/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "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==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/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/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/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lucide-react": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz", + "integrity": "sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.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/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-router": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz", + "integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz", + "integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==", + "license": "MIT", + "dependencies": { + "react-router": "7.18.4" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/rolldown": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", + "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.155.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.15", + "@rolldown/binding-android-arm64": "1.2.15", + "@rolldown/binding-darwin-arm64": "1.2.15", + "@rolldown/binding-darwin-x64": "1.2.15", + "@rolldown/binding-freebsd-x64": "1.2.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", + "@rolldown/binding-linux-arm64-gnu": "1.2.15", + "@rolldown/binding-linux-arm64-musl": "1.2.15", + "@rolldown/binding-linux-ppc64-gnu": "1.2.15", + "@rolldown/binding-linux-s390x-gnu": "1.2.15", + "@rolldown/binding-linux-x64-gnu": "1.2.15", + "@rolldown/binding-linux-x64-musl": "1.2.15", + "@rolldown/binding-openharmony-arm64": "1.2.15", + "@rolldown/binding-win32-arm64-msvc": "1.2.15", + "@rolldown/binding-win32-x64-msvc": "1.2.15" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "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/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", + "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/vite": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 00000000..8f151c3e --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,27 @@ +{ + "name": "mtusi-messenger-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite --host 0.0.0.0", + "build": "tsc -b && vite build", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@tanstack/react-query": "^5.104.5", + "lucide-react": "^1.61.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.1.2", + "typescript": "^7.0.2", + "vite": "^8.3.5", + "vitest": "^5.0.5" + } +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts new file mode 100644 index 00000000..1e95a48a --- /dev/null +++ b/frontend/src/api/client.ts @@ -0,0 +1,163 @@ +import type { + ApiErrorBody, + Chat, + CreateChatInput, + LoginInput, + Message, + Page, + RegisterInput, + Session, + User, +} from "./types"; + +const publicApi = "/api/v1"; +const browserApi = "/web-api/v1"; + +export class ApiError extends Error { + readonly status: number; + readonly code?: string; + readonly requestId?: string; + + constructor(status: number, body: ApiErrorBody) { + super(body.error?.message || `HTTP ${status}`); + this.name = "ApiError"; + this.status = status; + this.code = body.error?.code; + this.requestId = body.error?.request_id; + } +} + +type RequestOptions = Omit & { + body?: unknown; +}; + +async function request(path: string, options: RequestOptions = {}): Promise { + const headers = new Headers(options.headers); + if (options.body !== undefined) { + headers.set("Content-Type", "application/json"); + } + + const response = await fetch(path, { + ...options, + headers, + credentials: "same-origin", + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + + if (!response.ok) { + let body: ApiErrorBody = {}; + try { + body = (await response.json()) as ApiErrorBody; + } catch { + // Preserve a useful HTTP-level error when a proxy returned non-JSON. + } + throw new ApiError(response.status, body); + } + + if (response.status === 204) { + return undefined as T; + } + return (await response.json()) as T; +} + +function encodeBasic({ username, password }: LoginInput): string { + const bytes = new TextEncoder().encode(`${username}:${password}`); + let binary = ""; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} + +async function collectPages(path: string): Promise { + const items: T[] = []; + let cursor: string | null = null; + + for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) { + const search = new URLSearchParams({ limit: "100" }); + if (cursor) { + search.set("cursor", cursor); + } + const page = await request>(`${path}?${search.toString()}`); + items.push(...page.items); + cursor = page.next_cursor; + if (!cursor) { + return items; + } + } + throw new Error("pagination safety limit exceeded"); +} + +export const api = { + register(input: RegisterInput): Promise { + return request(`${publicApi}/users`, { + method: "POST", + body: { + username: input.username, + display_name: input.displayName, + password: input.password, + }, + }); + }, + + login(input: LoginInput): Promise { + return request(`${publicApi}/auth/sessions`, { + method: "POST", + headers: { + Authorization: `Basic ${encodeBasic(input)}`, + }, + }); + }, + + logout(): Promise { + return request(`${browserApi}/auth/sessions/current`, { + method: "DELETE", + }); + }, + + me(): Promise { + return request(`${browserApi}/users/me`); + }, + + chats(): Promise { + return collectPages(`${browserApi}/chats`); + }, + + chat(chatID: string): Promise { + return request(`${browserApi}/chats/${encodeURIComponent(chatID)}`); + }, + + createChat(input: CreateChatInput): Promise { + return request(`${browserApi}/chats`, { + method: "POST", + body: { + title: input.title, + member_ids: input.memberIds, + }, + }); + }, + + messages(chatID: string): Promise { + return collectPages( + `${browserApi}/chats/${encodeURIComponent(chatID)}/messages`, + ); + }, + + sendMessage( + chatID: string, + text: string, + idempotencyKey: string, + attachmentIDs: string[] = [], + ): Promise { + return request( + `${browserApi}/chats/${encodeURIComponent(chatID)}/messages`, + { + method: "POST", + headers: { + "Idempotency-Key": idempotencyKey, + }, + body: { text, attachment_ids: attachmentIDs }, + }, + ); + }, +}; diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts new file mode 100644 index 00000000..0f7110a5 --- /dev/null +++ b/frontend/src/api/types.ts @@ -0,0 +1,58 @@ +export type User = { + id: string; + username: string; + display_name: string; + created_at: string; +}; + +export type Session = { + token: string; + token_type: "Bearer"; + expires_at: string; + user: User; +}; + +export type Chat = { + id: string; + title: string; + member_ids: string[]; + created_at: string; +}; + +export type Message = { + id: string; + chat_id: string; + sender_id: string; + text: string; + attachment_ids: string[]; + created_at: string; +}; + +export type Page = { + items: T[]; + next_cursor: string | null; +}; + +export type ApiErrorBody = { + error?: { + code?: string; + message?: string; + request_id?: string; + }; +}; + +export type RegisterInput = { + username: string; + displayName: string; + password: string; +}; + +export type CreateChatInput = { + title: string; + memberIds: string[]; +}; + +export type LoginInput = { + username: string; + password: string; +}; diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx new file mode 100644 index 00000000..c6aa7aed --- /dev/null +++ b/frontend/src/app/App.tsx @@ -0,0 +1,51 @@ +import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom"; + +import { useAuth } from "../auth/AuthProvider"; +import { LoadingScreen } from "../components/LoadingScreen"; +import { AuthPage } from "../pages/AuthPage"; +import { MessengerPage } from "../pages/MessengerPage"; + +function ProtectedRoute() { + const { user, isLoading } = useAuth(); + const location = useLocation(); + + if (isLoading) { + return ; + } + if (!user) { + return ; + } + return ; +} + +function PublicOnlyRoute() { + const { user, isLoading } = useAuth(); + + if (isLoading) { + return ; + } + if (user) { + return ; + } + return ; +} + +export function App() { + return ( + + }> + } /> + } /> + + + }> + } /> + } /> + } /> + + + } /> + } /> + + ); +} diff --git a/frontend/src/assets/chat-background.jpg b/frontend/src/assets/chat-background.jpg new file mode 100644 index 00000000..899884b3 Binary files /dev/null and b/frontend/src/assets/chat-background.jpg differ diff --git a/frontend/src/auth/AuthProvider.tsx b/frontend/src/auth/AuthProvider.tsx new file mode 100644 index 00000000..5154fad7 --- /dev/null +++ b/frontend/src/auth/AuthProvider.tsx @@ -0,0 +1,90 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { + createContext, + useCallback, + useContext, + type PropsWithChildren, +} from "react"; + +import { api, ApiError } from "../api/client"; +import type { LoginInput, RegisterInput, User } from "../api/types"; + +type AuthContextValue = { + user: User | null; + isLoading: boolean; + login: (input: LoginInput) => Promise; + register: (input: RegisterInput) => Promise; + logout: () => Promise; +}; + +const AuthContext = createContext(null); +const meQueryKey = ["current-user"] as const; + +async function loadCurrentUser(): Promise { + try { + return await api.me(); + } catch (error) { + if (error instanceof ApiError && error.status === 401) { + return null; + } + throw error; + } +} + +export function AuthProvider({ children }: PropsWithChildren) { + const queryClient = useQueryClient(); + const meQuery = useQuery({ + queryKey: meQueryKey, + queryFn: loadCurrentUser, + retry: false, + staleTime: 30_000, + }); + + const login = useCallback( + async (input: LoginInput) => { + const session = await api.login(input); + queryClient.setQueryData(meQueryKey, session.user); + }, + [queryClient], + ); + + const register = useCallback( + async (input: RegisterInput) => { + await api.register(input); + const session = await api.login({ + username: input.username, + password: input.password, + }); + queryClient.setQueryData(meQueryKey, session.user); + }, + [queryClient], + ); + + const logout = useCallback(async () => { + await api.logout(); + queryClient.setQueryData(meQueryKey, null); + queryClient.removeQueries({ queryKey: ["chats"] }); + }, [queryClient]); + + return ( + + {children} + + ); +} + +export function useAuth(): AuthContextValue { + const context = useContext(AuthContext); + if (!context) { + throw new Error("useAuth must be used within AuthProvider"); + } + return context; +} diff --git a/frontend/src/components/Avatar.tsx b/frontend/src/components/Avatar.tsx new file mode 100644 index 00000000..6fd07fb6 --- /dev/null +++ b/frontend/src/components/Avatar.tsx @@ -0,0 +1,26 @@ +import { initials } from "../lib/format"; + +type AvatarProps = { + label: string; + seed?: string; + size?: "small" | "medium" | "large"; +}; + +function tone(seed: string): number { + let hash = 0; + for (const character of seed) { + hash = (hash * 31 + character.codePointAt(0)!) >>> 0; + } + return hash % 5; +} + +export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) { + return ( + + ); +} diff --git a/frontend/src/components/ChatList.tsx b/frontend/src/components/ChatList.tsx new file mode 100644 index 00000000..1426d013 --- /dev/null +++ b/frontend/src/components/ChatList.tsx @@ -0,0 +1,121 @@ +import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react"; +import { useMemo, useState } from "react"; +import { useNavigate } from "react-router-dom"; + +import type { Chat, User } from "../api/types"; +import { formatMemberCount } from "../lib/format"; +import { Avatar } from "./Avatar"; + +type ChatListProps = { + chats: Chat[]; + currentUser: User; + error: boolean; + isLoading: boolean; + selectedChatID?: string; + onCreateChat: () => void; +}; + +export function ChatList({ + chats, + currentUser, + error, + isLoading, + selectedChatID, + onCreateChat, +}: ChatListProps) { + const navigate = useNavigate(); + const [search, setSearch] = useState(""); + + const filteredChats = useMemo(() => { + const normalized = search.trim().toLocaleLowerCase("ru"); + if (!normalized) { + return chats; + } + return chats.filter((chat) => + chat.title.toLocaleLowerCase("ru").includes(normalized), + ); + }, [chats, search]); + + return ( + + ); +} diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx new file mode 100644 index 00000000..64ffaad6 --- /dev/null +++ b/frontend/src/components/ChatView.tsx @@ -0,0 +1,236 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { + ArrowLeft, + CheckCheck, + RefreshCcw, + Send, + ShieldCheck, + UsersRound, +} from "lucide-react"; +import { + useEffect, + useMemo, + useRef, + useState, + type FormEvent, + type KeyboardEvent, +} from "react"; + +import { api } from "../api/client"; +import type { Chat, Message, User } from "../api/types"; +import { + dayKey, + formatDay, + formatMemberCount, + formatMessageTime, + shortID, +} from "../lib/format"; +import { createIdempotencyKey } from "../lib/idempotency"; +import { Avatar } from "./Avatar"; + +type ChatViewProps = { + chat: Chat; + currentUser: User; + onBack: () => void; +}; + +type SendEnvelope = { + text: string; + idempotencyKey: string; +}; + +export function ChatView({ chat, currentUser, onBack }: ChatViewProps) { + const queryClient = useQueryClient(); + const messagesEnd = useRef(null); + const [draft, setDraft] = useState(""); + const [failedEnvelope, setFailedEnvelope] = useState(null); + + const messagesQuery = useQuery({ + queryKey: ["messages", chat.id], + queryFn: () => api.messages(chat.id), + refetchInterval: 3_000, + staleTime: 1_000, + }); + + const messages = messagesQuery.data ?? []; + + useEffect(() => { + messagesEnd.current?.scrollIntoView({ + behavior: messages.length > 1 ? "smooth" : "auto", + block: "end", + }); + }, [chat.id, messages.length]); + + const mutation = useMutation({ + mutationFn: (envelope: SendEnvelope) => + api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey), + onSuccess: (message) => { + setFailedEnvelope(null); + queryClient.setQueryData( + ["messages", chat.id], + (current = []) => { + if (current.some((item) => item.id === message.id)) { + return current; + } + return [...current, message]; + }, + ); + }, + onError: (_error, envelope) => { + setFailedEnvelope(envelope); + }, + }); + + const groups = useMemo(() => { + const result: Array<{ key: string; label: string; messages: Message[] }> = []; + for (const message of messages) { + const key = dayKey(message.created_at); + const current = result.at(-1); + if (!current || current.key !== key) { + result.push({ + key, + label: formatDay(message.created_at), + messages: [message], + }); + } else { + current.messages.push(message); + } + } + return result; + }, [messages]); + + function send(envelope: SendEnvelope) { + if (!mutation.isPending) { + mutation.mutate(envelope); + } + } + + function submit(event: FormEvent) { + event.preventDefault(); + const text = draft.trim(); + if (!text || Array.from(text).length > 4_000) { + return; + } + const envelope = { text, idempotencyKey: createIdempotencyKey() }; + setDraft(""); + setFailedEnvelope(null); + send(envelope); + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + event.currentTarget.form?.requestSubmit(); + } + } + + return ( +
+
+ + +
+ {chat.title} + {formatMemberCount(chat.member_ids.length)} +
+
+
+
+ +
+
+
+ {messagesQuery.isLoading && ( +
+ + Загружаем историю +
+ )} + + {messagesQuery.isError && ( +
+

История временно недоступна

+ +
+ )} + + {!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && ( +
+
+ )} + + {groups.map((group) => ( +
+
{group.label}
+ {group.messages.map((message) => { + const own = message.sender_id === currentUser.id; + return ( +
+ + {own ? "Вы" : shortID(message.sender_id)} + +

{message.text}

+ + {formatMessageTime(message.created_at)} + {own && } + +
+ ); + })} +
+ ))} +
+
+
+ +