From 63872e86fea16c8124c28312651ec7c24750d8e6 Mon Sep 17 00:00:00 2001 From: Aleksandr Meshchryakov Date: Thu, 22 Oct 2026 21:30:18 +0200 Subject: [PATCH] feat: add versioned all-available source export catalog --- .dockerignore | 3 + .gitignore | 3 + docker-compose.dev.yml | 3 + docs/all-years-source-exports.md | 3 + docs/source-data-export-api-spec.md | 1196 +++++++++++ docs/source-export-catalog-operations.md | 144 ++ docs/source-export-catalog-verification.md | 62 + docs/source-record-export-matrix-ru.md | 3 + src/apps/parsers/tasks_registry_snapshots.py | 5 + src/core/openapi.json | 1804 ++++++++++++++--- .../commands/build_source_export_catalog.py | 47 + .../migrations/0019_source_export_catalog.py | 103 + .../0020_source_export_catalog_schedule.py | 40 + src/organizations/models.py | 67 + src/organizations/source_export_catalog.py | 1202 +++++++++++ .../source_export_serializers.py | 18 + src/organizations/tasks.py | 61 + src/organizations/views.py | 188 +- src/settings/base.py | 10 + .../organizations/test_canonical_openapi.py | 10 +- .../test_source_export_catalog.py | 683 +++++++ .../test_source_export_postgres.py | 115 ++ .../test_source_export_transport.py | 93 + tools/openapi/build.mjs | 2 + tools/openapi/check-source-export-runtime.mjs | 26 + tools/openapi/contract.ts | 18 + tools/openapi/orval.config.mjs | 9 +- tools/openapi/source-export-catalog.mjs | 76 + 28 files changed, 5754 insertions(+), 240 deletions(-) create mode 100644 docs/source-data-export-api-spec.md create mode 100644 docs/source-export-catalog-operations.md create mode 100644 docs/source-export-catalog-verification.md create mode 100644 src/organizations/management/commands/build_source_export_catalog.py create mode 100644 src/organizations/migrations/0019_source_export_catalog.py create mode 100644 src/organizations/migrations/0020_source_export_catalog_schedule.py create mode 100644 src/organizations/source_export_catalog.py create mode 100644 src/organizations/source_export_serializers.py create mode 100644 tests/apps/organizations/test_source_export_catalog.py create mode 100644 tests/apps/organizations/test_source_export_postgres.py create mode 100644 tests/apps/organizations/test_source_export_transport.py create mode 100644 tools/openapi/check-source-export-runtime.mjs create mode 100644 tools/openapi/source-export-catalog.mjs diff --git a/.dockerignore b/.dockerignore index 171cb95..2f28fed 100644 --- a/.dockerignore +++ b/.dockerignore @@ -32,3 +32,6 @@ data tests deploy *.log + +# Private generated source artifacts; never package or track runtime data. +private-source-exports/ diff --git a/.gitignore b/.gitignore index 007d0d1..becab05 100644 --- a/.gitignore +++ b/.gitignore @@ -53,3 +53,6 @@ input/fns/processed/*.xlsx # Local canonical schema build output .openapi-build/ + +# Private generated source artifacts; never package or track runtime data. +private-source-exports/ diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 82d57ee..feab159 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -5,6 +5,7 @@ x-app-build: &app-build INSTALL_DEV: "true" x-parser-runtime-env: &parser-runtime-env + SOURCE_EXPORT_DIRECTORY: /app/private-source-exports CHECKO_API_KEY: ${CHECKO_API_KEY:-} SUPERJOB_APP_ID: ${SUPERJOB_APP_ID:-} PROXY_TOOLS_API_KEY: ${PROXY_TOOLS_API_KEY:-} @@ -81,6 +82,7 @@ services: - "${MOSTOVIK_WEB_HOST_PORT:-18000}:8000" volumes: - ./media:/app/media + - ${SOURCE_EXPORT_HOST_DIRECTORY:-./data/source-exports}:/app/private-source-exports:ro - ./staticfiles:/app/staticfiles - ./input:/app/input command: ["/app/docker/scripts/start-web-dev.sh"] @@ -105,6 +107,7 @@ services: volumes: - ./input:/app/input - ./media:/app/media + - ${SOURCE_EXPORT_HOST_DIRECTORY:-./data/source-exports}:/app/private-source-exports command: ["/app/docker/scripts/start-celery-worker.sh"] celery_beat: diff --git a/docs/all-years-source-exports.md b/docs/all-years-source-exports.md index 974bb20..0442291 100644 --- a/docs/all-years-source-exports.md +++ b/docs/all-years-source-exports.md @@ -1,5 +1,8 @@ # Выгрузка за все годы +Новый каталог `all_available` описан отдельно: [контракт и эксплуатация](source-export-catalog-operations.md). Эта страница сохраняет описание прежнего scope. + + Годовая задача `organizations.tasks.refresh_source_record_export_artifacts` сохраняет прежнее поведение. Новая задача `organizations.tasks.refresh_all_years_source_record_export_artifacts` собирает все доступные записи каждого поддерживаемого источника без ограничения по году, включая все финансовые строки. Для источников с заменяемыми snapshot выгружается текущее опубликованное состояние: удалённые прежние snapshot не восстанавливаются. diff --git a/docs/source-data-export-api-spec.md b/docs/source-data-export-api-spec.md new file mode 100644 index 0000000..dd65551 --- /dev/null +++ b/docs/source-data-export-api-spec.md @@ -0,0 +1,1196 @@ +--- +template_id: source-backend-api +template_version: 1 +source_id: 'shared-source-data-export' +source_name: 'Выгрузка готовых файлов существующих источников' +document_status: review +change_scope: extension +observed_at: '2026-10-21' +--- + +# Backend API страницы «Выгрузка данных из источников» + +Назначение: самодостаточное задание backend-разработчику для подключения страницы +`/admin/source-data-export`. Страница уже реализована на моках: каталог источников, +раскрываемое описание и JSON-пример, отдельные части файлов, выбор формата у каждой части +и скачивание всего источника кнопкой в заголовке. + +Документ следует 19 разделам `templates/backend-api.template.md`. Это расширение общей +подсистемы экспорта существующих источников, а не регистрация нового предметного источника. +Передавать backend-разработчику следует этот файл целиком. Все новые URL, DTO и ограничения +ниже — целевые требования, а не утверждение об их наличии в production. + +Статус `review` означает готовность задания к техническому согласованию. Реализация, +публикация OpenAPI и контрактная приёмка ещё не выполнены; это отражено в checklist §17. + +## Принципы документа + +- Использовать существующие source registry, канонические записи и сборщик файлов. +- Подготовка CSV/XLSX/JSON выполняется фоновой задачей. Открытие страницы и скачивание + читают метаданные и готовые файлы без повторного парсинга внешних систем. +- Гигабайтные данные сохраняет штатный download manager браузера. Frontend не получает + весь файл через Axios/fetch Blob и не собирает ZIP в JavaScript. +- Каталог привязан к неизменяемому поколению выгрузки. После обновления поколения уже + показанный файл нельзя молча заменить другим содержимым. +- Разбивать нужно все крупные форматы, включая JSON и CSV; ограничение только XLSX + не решает задачу скачивания больших наборов. +- Публиковать фактически доступные форматы. Выбранный XLSX не может возвращаться как JSON. +- Пустой источник, ещё не подготовленный источник и техническая ошибка имеют разные состояния. +- Полнота означает все опубликованные записи, сохранённые в системе, включая прошлые годы. + Неподдерживаемые источники и пропущенные записи нельзя скрывать за успешной выгрузкой. +- Runtime API, manifest, OpenAPI и контрактные тесты описывают один согласованный контракт. + +## 1. Назначение и область реализации + +### Пользовательские сценарии + +| Сценарий | Ожидаемый результат | +| --------------------------------- | ----------------------------------------------------------------------------- | +| Открыть страницу | Получить все зарегистрированные источники и состояние их файлов | +| Раскрыть источник | Получить состав, происхождение, поля, JSON-пример и первую страницу частей | +| Посмотреть следующие части | Постранично читать тот же snapshot, без дубликатов и пропусков | +| Выбрать формат части | Выбрать готовый вариант той же логической части | +| Скачать часть | Сохранить один CSV/XLSX/JSON без ZIP-обёртки | +| Скачать источник | Получить ZIP со всеми частями выбранного формата, включая невидимые страницы | +| Обновить страницу | Увидеть последнее опубликованное поколение и время актуальности данных | +| Открыть устаревшую страницу | Скачать сохранённое поколение либо получить явное требование обновить каталог | +| Нет данных / идёт сборка / ошибка | Показать точное состояние и доступность предыдущей успешной выгрузки | + +### Границы + +В scope входят каталог, metadata, подготовка всех частей, одноразовые tickets, потоковое +скачивание, хранение поколений, RBAC, observability, OpenAPI и тесты. Имеющиеся парсеры, +upload, обогащение организаций и предметные DTO переиспользуются. + +Новые кнопки запуска парсеров, произвольные пользовательские фильтры записей, ручная +загрузка файлов на этой странице и вычисление новых финансовых показателей не требуются. +Полнота не означает восстановление удалённых данных, чтение quarantine или повторный обход +upstream: экспортируется всё доступное опубликованное содержимое канонического хранилища. + +Моковые четыре файла и названия «Рентабельность и ликвидность» — демонстрация интерфейса. +Backend не должен создавать фиктивные файлы, дублировать один dataset или рассчитывать +неописанную сводную таблицу ради соответствия числу плиток в макете. + +## 2. Нормативные ссылки и аудит текущих контрактов + +Проверено по локальному frontend `7847228` с рабочими изменениями новой страницы, +локальному backend `66fcacc` и локальному `openapi.json`. Live runtime не опрашивался; +backend перед началом реализации сверяет это задание со своей актуальной веткой. + +| Источник сведений | Что сверять | +| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | +| `docs/info/backend-endpoints-main-page-from-mocks.md` | Общие API/envelope и правила согласованности | +| `docs/source-integration/templates/backend-api.template.md` | Структура этого задания | +| `docs/source-integration/backend-openapi-contract-recovery.md` | Canonical OpenAPI 3, генерация Orval | +| `docs/source-integration/backend-testing-8-10-amendments.md`, §12 | Native form download, ошибки существующего экспорта | +| `src/pages/main/ui/SourceDataExportPage/` | Готовая композиция UI | +| `src/pages/main/model/source-data-export/` | Временные mocks и скачивание в браузере | +| `src/pages/main/model/reference-data/exportReferenceDataSourceRecords.ts` | Существующий ticket → HTML form flow | +| `src/pages/main/ui/MainPage/MainPageSettingsDialog/components/ReferenceDataSourcesExportCard.vue` | Соответствие slug → source group | +| `src/shared/config/hiddenSources.ts` | Текущая продуктовая видимость источников | +| `openapi.json`, `orval.config.ts` | Опубликованные схемы и конфигурация генерации | +| `src/shared/api/generated-api/`, `src/shared/model/generated-zod/` | Generated API и runtime-схемы | +| Backend: `src/organizations/source_record_export.py` | Сборщик, manifest, части, ticket, streaming ZIP | +| Backend: `src/organizations/views.py`, `serializers.py` | Экспортные actions и проверки запроса | +| Backend: `src/organizations/tasks.py`, `management/commands/build_source_record_exports.py` | Фоновая и первоначальная сборка | +| Backend: `docs/source-record-export-matrix-ru.md` | Фактическая текущая матрица форматов и ограничение по году | + +### Точки сверки по каждому активному endpoint + +Проверить URL/method, admin permissions, operationId, schema, MIME, ошибки и фактический +native-download flow. Новый API не должен конфликтовать с `{uid}` route: статические actions +`export-catalog`, `export-ticket`, `export-download`, `export` регистрируются раньше detail. + +### Подтверждённые расхождения и требуемые изменения + +| ID | Сейчас по локальному коду | Требуется | +| --------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `EXP-001` | Нет каталога готовых частей для страницы | Два GET endpoint §7 | +| `EXP-002` | Сборщик содержит девять групп; локальный frontend OpenAPI перечисляет 22 | Общий registry/adapters для всех 22; первые 16 покрывают текущую страницу | +| `EXP-003` | Поколение ограничено текущим годом, финансовые строки также фильтруются по году | Новый явно обозначенный scope `all_available`; старый годовой контракт сохранить | +| `EXP-004` | Финансы имеют только JSON; запрос XLSX/CSV молча подменяется JSON | Для новой страницы честный `supported_formats`, неподдерживаемый формат → 409 | +| `EXP-005` | На части разбивается только XLSX, по 100 000 строк | Согласованные части всех поддерживаемых форматов с ограничением размера | +| `EXP-006` | `records_count` каждой XLSX-части заполнен общим count группы | Считать строки именно части, отдельно хранить общее число записей | +| `EXP-007` | Ticket хранит sources/format/time; при download снова выбирается current generation | Зафиксировать generation/part/artifact и lease при выдаче ticket | +| `EXP-008` | Ticket потребляется через `cache.get` + `cache.delete` | Атомарное одноразовое потребление, исключающее конкурентный повтор | +| `EXP-009` | Нет привязки ticket к пользователю, выдавшему запрос | Хранить issuer и проверять его текущую активность/роль перед выдачей байтов | +| `EXP-010` | Хранятся два поколения без учёта открытых скачиваний | Retention + leases на tickets/streams, §13 | +| `EXP-011` | Manifest v2 содержит filesystem `relative_path`, нет публичных UUID/sha256 | Публичные DTO без путей, manifest для нового scope с version и checksum | + +Текущее наличие `export-ticket`/`export-download` и их MIME подтверждено локальным OpenAPI. +Старые утверждения об их отсутствии из ранних шаблонов к этому заданию не применяются. + +## 3. Идентификаторы источника + +Технический `source_id: shared-source-data-export` относится только к документу. +Новый parser source/source group для этой страницы не создаётся. API принимает существующий +`source_group`, а не frontend slug, route name или `tableKey`. + +| № | Источник / существующий slug | `source_group` | Parser sources / состав | +| --: | --------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------ | +| 1 | Финансово-экономические показатели / `financial-indicators` | `financial_indicators` | `fns_reports` | +| 2 | Государственные закупки по 44-ФЗ и 223-ФЗ / `public-procurements` | `government_procurements` | `procurements_44fz`, `procurements_223fz`; также сохранённые `procurements`, `contracts` той же группы | +| 3 | Производители и продукция России / `manufacturers-and-products` | `industrial_production` | `industrial`, `manufactures`, `industrial_products` | +| 4 | Плановые проверки Генпрокуратуры России / `planned-inspections` | `planned_inspections` | `inspections` | +| 5 | Сведения о процедурах банкротства / `bankruptcy-procedures` | `bankruptcy` | `fedresurs_bankruptcy` | +| 6 | Недобросовестные поставщики ГОЗ / `defense-unreliable-suppliers` | `defense_suppliers` | `unfair_suppliers`, `fas_goz` | +| 7 | Арбитражные дела / `arbitration-cases` | `arbitration` | `arbitration` | +| 8 | Реестры по информационной безопасности ФСТЭК России / `information-security-registries` | `security_registries` | `fstec` | +| 9 | Вакансии Работа России / `labor-vacancies` | `vacancies` | Все опубликованные adapters группы, включая `trudvsem` | +| 10 | ГосЭДО: Глобальный адресный справочник / `gosedo-global-address-directory` | `electronic_document_exchange` | `gosedo_address_directory` | +| 11 | Новости СМИ / `mass-media` | `media_mentions` | `media_news` | +| 12 | Зарубежные санкции / `ropk-sanctions` | `sanctions` | `ropk_sanctions` | +| 13 | Реестр участников бюджетного процесса / `budget-process-registry` | `budget_process_registry` | `budget_ubpandnubp` | +| 14 | Реестр субъектов МСП — получателей поддержки / `sme-support-recipients-registry` | `government_support` | `fns_sme_support_recipients` | +| 15 | Реестр организаций в составе СРО / `sro-membership-check` | `sro_membership` | `sro_membership_check` | +| 16 | Документы интегрированных структур / `integrated-structure-documents` | `integrated_structure_documents` | Parser `integrated_structure_documents`, records `integrated_structures` | +| 17 | Федресурс: сведения о юридических лицах / `fedresurs-company-profile` | `fedresurs_company_profile` | `fedresurs_company_profile` | +| 18 | Исполнительные производства ФССП / `fssp-enforcement-proceedings` | `enforcement_proceedings` | `fssp_enforcement_proceedings` | +| 19 | Лизинг / `checko-leasing` | `leasing` | `checko_leasing` | +| 20 | Сообщения организаций / `checko-messages` | `company_messages` | `checko_messages` | +| 21 | Лицензии организаций / `checko-licenses` | `company_licenses` | `checko_licenses` | +| 22 | Биржевая активность / `stock-exchange-activity` | `stock_exchange_activity` | `stock_exchange_activity`, включает СПБ и MOEX | + +Первые 16 — обязательный набор уже сделанной страницы. Остальные шесть также регистрируются +в общем API; их показ регулируется существующим frontend feature flag. Скрытый пункт меню +не считается проверкой прав. В production registry должен явно различать разрешённый, +отключённый и ещё не подготовленный источник; зарегистрированную группу нельзя молча исключить +из ответа из-за отсутствия файлов. `export_enabled=false` отражается состоянием `unavailable`. + +Состав выбирается по source_group канонических записей. Перечень parser sources в таблице +поясняет состав, а не ограничивает экспорт hardcoded allowlist, которая потеряет сохранённые +legacy records или дополнительные опубликованные adapters той же группы. + +Порядок стабилен по `(order, source_group)`, title совпадает с продуктовым каталогом. +Существующие алиасы parser source не переименовывать. Добавление нового источника в будущем +включает регистрацию export adapter и metadata в том же registry. + +## 4. Обязательный контракт организации + +API каталога возвращает metadata файлов, а не новые предметные записи. Формат уже +существующих records не меняется. Наименование, ИНН, ОГРН, ОКПО берутся из канонических +`organization.name`, `organization.inn`, `organization.ogrn`, `organization.okpo`. + +Файловый adapter может использовать существующие заголовки `Наименование`, `ИНН`, `ОГРН`, +`КПП`, `ОКПО` и развёрнутые `payload.*`. Это проекция тех же данных, а не второй справочник. +Сохранить UID записи, `source`, `source_group`, `record_type`, даты, decimal precision, +вложенные финансовые строки и source-specific поля согласно действующему adapter. + +Пустые исторические идентификаторы обрабатывать по действующей спецификации конкретного +источника и фиксировать quality counters. Этот экспорт не должен самовольно отбрасывать +такие опубликованные записи, подставлять выдуманные идентификаторы или запускать enrichment. +Quarantine, credentials и закрытые технические поля в экспорт не включаются. + +Моковый объект `{organization_card, section, record_name, data}` не является новым +каноническим DTO. JSON-пример на странице должен описывать фактическую schema файлов. + +## 5. Матрица endpoint и решение по реализации + +Все URL относительны к тому же backend-origin, который используется frontend `/api`. + +| Endpoint | Решение | Назначение | +| ------------------------------------------------------------------------ | --------------------------------- | ------------------------------------------------------------------ | +| `GET /api/v2/organization-source-records/export-catalog/` | Добавить | Сводный каталог источников без списка всех файлов | +| `GET /api/v2/organization-source-records/export-catalog/{source_group}/` | Добавить | Описание, JSON-пример и страница логических частей | +| `POST /api/v2/organization-source-records/export-ticket/` | Расширить совместимо | Выбор одного файла или архива одного источника с pinned generation | +| `POST /api/v2/organization-source-records/export-download/` | Расширить совместимо | Native form → один файл либо ZIP по ticket | +| `POST /api/v2/organization-source-records/export/` | Сохранить legacy | Старый синхронный API, новая страница его не вызывает | +| `GET /api/v1/sources/`, `GET /api/v1/sources/{slug}/` | Переиспользовать | Registry и labels существующих источников | +| `GET /api/v1/parsers/dashboard/` | Без нового контракта | Существующее состояние парсинга | +| `GET /api/v2/organization-source-records/`, detail | Без нового контракта | Каноническое содержимое готовых файлов | +| Existing refresh/run/upload/jobs/logs | Без нового пользовательского flow | Действуют по исходным спецификациям, см. §8–11 | + +Новые GET actions нужны, поскольку source cards и records list не описывают готовые +физические файлы, их поколения, размер, checksum и поддерживаемые варианты одной части. +Создавать отдельные URL для каждого из 22 предметных источников не требуется. + +Смежный inventory, без новых зависимостей страницы: `GET /api/v1/sources/statuses/`, +`GET /api/v1/parsers/sources/`, `GET/POST /api/v1/parsers/schedules/*`, +`GET /api/v1/parsers/load-logs/`, `GET /api/v1/parsers/records/`, `GET /api/v1/jobs/`, +`POST /api/v1/jobs/{task_id}/control/`, `GET /api/v1/jobs/{task_id}/stream/`. + +## 6. Общий паттерн описания endpoint + +GET и выдача ticket: Bearer access token, активный пользователь с ролью `admin`. +Binary download: короткоживущий capability ticket в теле обычной HTML-формы, §12.2. + +Новые GET используют envelope `{success, data, errors, meta}`: все четыре ключа required, +`errors=null` при успехе. Catalog `meta=null`; detail `meta.pagination` — именованный DTO. +Ticket сохраняет существующий top-level формат без envelope. + +Общие типы: timestamp ISO 8601 UTC, идентификаторы строками, UUID в формате UUID, +счётчики и размеры — integer `0..9007199254740991`, bytes без display-форматирования. +Nullable-поле передаётся явно как `null`. JSON-примеры ниже синтетические, но полные по форме. + +### Общая ошибка новых запросов + +`SourceExportError`: все пять полей required, `field` nullable. Пример `409`: + +```json +{ + "detail": "Выбранный формат отсутствует в этом поколении выгрузки.", + "code": "source_export_format_unavailable", + "field": "format", + "retryable": false, + "request_id": "ee38bd55-9ad4-43dd-a636-19d3fac0b4b9" +} +``` + +Конкретные code/status и действия frontend зафиксированы в §15; та же schema используется +для остальных бизнес-ошибок, меняются значения. Auth middleware может возвращать стандартный +`401 {"detail":"Учётные данные не предоставлены."}`: это отдельная named auth schema. +У legacy-запросов сохранить существующие error DTO, не менять общий API скрыто. + +## 7. Каталог источников + +### 7.1 `GET /api/v1/sources/` + +Request/response не меняются. Registry карточек — источник существующих slug/title/order, +но export metadata хранится отдельно от состояния парсера. Источник без выгрузки остаётся +в export-каталоге со своим состоянием. Объединение 44-ФЗ/223-ФЗ и других подисточников +в группы выполняется по §3, не по совпадению пользовательских названий. + +### 7.2 `GET /api/v1/sources/{slug}/` + +Request/response не меняются. Не добавлять в source detail полный manifest или массив +содержимого файлов. Перечень export parts запрашивается отдельным action ниже. + +### 7.3 `GET /api/v2/organization-source-records/export-catalog/` + +Request: + +```http +GET /api/v2/organization-source-records/export-catalog/ +Authorization: Bearer +Accept: application/json +``` + +Query-параметров в v1 нет; неизвестный query → `400 source_export_invalid_request`. +Список малый: все зарегистрированные группы без пагинации, включая ещё не готовые. +Содержимое records, variants и binary здесь не возвращается. + +Response `200 application/json`. Полный пример тестового registry с одним источником: + +```json +{ + "success": true, + "data": { + "schema_version": "1", + "catalog_revision": "20261021T023000Z-1", + "sources": [ + { + "source_group": "government_procurements", + "source_slug": "public-procurements", + "title": "Государственные закупки по 44-ФЗ и 223-ФЗ", + "order": 2, + "export_enabled": true, + "state": "ready", + "unavailable_reason": null, + "generation_id": "11111111-1111-4111-8111-111111111111", + "generated_at": "2026-10-21T02:30:00Z", + "data_as_of": "2026-10-21T02:00:00Z", + "data_scope": "all_available", + "records_count": 3, + "parts_count": 1, + "supported_formats": ["xlsx", "csv", "json"], + "default_format": "xlsx", + "is_stale": false, + "last_build": { + "state": "success", + "started_at": "2026-10-21T02:00:00Z", + "finished_at": "2026-10-21T02:30:00Z", + "error_code": null + } + } + ] + }, + "errors": null, + "meta": null +} +``` + +В production `sources` содержит все 22 зарегистрированные группы; массив из одного +элемента выше — JSON fixture, не разрешение реализовать только закупки. + +`SourceExportCatalogResponse.data`: `schema_version`, `catalog_revision`, `sources` required, +не nullable. Версия API-формы `"1"` отличается от внутренней версии filesystem manifest. + +Все поля `SourceExportSourceSummary` required: + +| Поле | Тип / nullable | Правило | +| -------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| `source_group` | Existing source group enum / нет | Ровно одна запись на группу §3 | +| `source_slug` | string / нет | Существующий slug, не новый frontend route | +| `title` | string / нет | Непустое продуктовое название | +| `order` | integer ≥ 0 / нет | Стабильный порядок | +| `export_enabled` | boolean / нет | Настройка registry, не наличие файлов | +| `state` | `ready, empty, not_ready, building, unavailable` / нет | Правила §13 | +| `unavailable_reason` | `disabled, adapter_missing, build_failed, storage_unavailable` / да | Причина unavailable, в других состояниях null | +| `generation_id` | UUID / да | Последнее полностью опубликованное поколение группы | +| `generated_at` | date-time / да | Завершение его публикации | +| `data_as_of` | date-time / да | Snapshot данных, не время GET или выдачи ticket | +| `data_scope` | enum `all_available` / нет | Включая сохранённые прошлые годы | +| `records_count` | integer ≥ 0 / да | Уникальные исходные записи группы, не сумма по форматам | +| `parts_count` | integer ≥ 0 / да | Число логических частей, не физических variants | +| `supported_formats` | unique array `xlsx,csv,json` / нет | Пересечение форматов всех частей текущего поколения | +| `default_format` | format enum / да | Входит в supported_formats; порядок предпочтения XLSX → CSV → JSON | +| `is_stale` | boolean / нет | Данные новее snapshot, возраст больше 36 часов или последняя сборка failed | +| `last_build` | `SourceExportBuildSummary` / нет | Последняя попытка сборки, включая неудачную | + +`SourceExportBuildSummary` имеет required `state` (`idle,queued,running,success,failed`), +`started_at: date-time|null`, `finished_at: date-time|null`, `error_code: string|null`. +Для `idle` timestamps/error null; для failed — публичный безопасный code, без traceback. +Отсутствие опубликованного поколения: nullable snapshot/count поля null, formats `[]`. +Состояние `empty`: опубликован пустой snapshot, counts `0`, formats `[]`, default null. + +Источник с ошибкой первой сборки остаётся в списке: `state=unavailable`, +`last_build.state=failed`. Если есть старый пригодный snapshot — `state=ready|empty`, +`is_stale=true`, скачивание доступно; last_build сообщает об ошибке новой попытки. + +Если нет ни одной готовой выгрузки, каталог всё равно возвращает `200` с полным registry +и состояниями. `503` применяется к недоступности самого metadata-сервиса, а не к пустой БД. + +Headers: `Cache-Control: private, no-store`, `X-Request-ID`. `catalog_revision` стабилен, +пока не изменились registry, опубликованные поколения или build states; время запроса +само по себе не меняет revision. Ошибки: `401,403,429,503,500`, schema §6/§15. + +### 7.4 `GET /api/v2/organization-source-records/export-catalog/{source_group}/` + +Request: + +```http +GET /api/v2/organization-source-records/export-catalog/government_procurements/?generation_id=11111111-1111-4111-8111-111111111111&page=1&page_size=50 +Authorization: Bearer +Accept: application/json +``` + +| Параметр | Тип | Required | Default / ограничение | +| --------------------- | ------------- | ---------------------- | ---------------------------------------------------------- | +| `source_group` path | Existing enum | Да | Только registry §3 | +| `generation_id` query | UUID | Нет на первой странице | Пропуск выбирает current generation; page > 1 требует UUID | +| `page` | integer | Нет | 1, минимум 1 | +| `page_size` | integer | Нет | 50; диапазон 1..200 | + +Каждая следующая страница использует полученный generation_id. Неизвестные параметры, +нечисловые/отрицательные значения и недопустимый размер → `400`; произвольный sort, search, +`format` или фильтры записей здесь не поддерживаются. Все variants одной части возвращаются +вместе, смена формата не требует запроса нового списка. + +Response `200 application/json`, полный пример одной части с тремя готовыми форматами: + +```json +{ + "success": true, + "data": { + "source_group": "government_procurements", + "generation_id": "11111111-1111-4111-8111-111111111111", + "current_generation_id": "11111111-1111-4111-8111-111111111111", + "state": "ready", + "unavailable_reason": null, + "generated_at": "2026-10-21T02:30:00Z", + "data_as_of": "2026-10-21T02:00:00Z", + "data_scope": "all_available", + "description": { + "composition": "Извещения о закупках и заключённые контракты по 44-ФЗ и 223-ФЗ.", + "origin": "Единая информационная система в сфере закупок; опубликованные записи системы.", + "fields": "Наименование; ИНН; ОГРН; КПП; ОКПО; UID; источник; тип и предмет записи; даты; сумма; статус; предметные поля закупки.", + "example_dataset_key": "records", + "example_is_synthetic": true, + "example_record": { + "Наименование": "АО «Пример»", + "ИНН": "7700000000", + "ОГРН": "1027700000000", + "КПП": "770001001", + "ОКПО": "00000001", + "uid": "77777777-7777-4777-8777-777777777777", + "source_group": "government_procurements", + "source": "procurements_44fz", + "record_type": "procurement_44fz", + "external_id": "0173100000125000001", + "title": "Поставка промышленного оборудования", + "record_date": "2025-10-01", + "amount": "2450000.00", + "status": "published", + "url": "https://example.org/procurements/1", + "load_batch": 42, + "created_at": "2025-10-01T08:00:00Z", + "updated_at": "2026-10-20T08:00:00Z" + } + }, + "datasets": [ + { + "key": "records", + "title": "Государственные закупки по 44-ФЗ и 223-ФЗ", + "export_schema_version": "1", + "records_count": 3, + "parts_count": 1 + } + ], + "files": [ + { + "part_id": "22222222-2222-4222-8222-222222222222", + "dataset_key": "records", + "title": "Государственные закупки по 44-ФЗ и 223-ФЗ", + "part_number": 1, + "parts_count": 1, + "records_count": 3, + "default_format": "xlsx", + "variants": [ + { + "artifact_id": "33333333-3333-4333-8333-333333333333", + "format": "xlsx", + "file_name": "public-procurements-part-000001.xlsx", + "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "size_bytes": 8192, + "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + }, + { + "artifact_id": "44444444-4444-4444-8444-444444444444", + "format": "csv", + "file_name": "public-procurements-part-000001.csv", + "mime_type": "text/csv; charset=utf-8", + "size_bytes": 2560, + "sha256": "1123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + }, + { + "artifact_id": "55555555-5555-4555-8555-555555555555", + "format": "json", + "file_name": "public-procurements-part-000001.json", + "mime_type": "application/json; charset=utf-8", + "size_bytes": 4096, + "sha256": "2123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + } + ] + } + ] + }, + "errors": null, + "meta": { + "pagination": { + "page": 1, + "page_size": 50, + "total_count": 1, + "total_pages": 1, + "has_next": false, + "has_previous": false + } + } +} +``` + +Catalog §7.3 и detail §7.4 описывают одно тестовое поколение. В реальных ответах +supported_formats и варианты одного generation также обязаны совпадать. + +Все поля `SourceExportSourceDetail` из примера required. `generation_id`, +`current_generation_id`, `generated_at`, `data_as_of`, `unavailable_reason` nullable; +остальные не nullable. +При чтении сохранённого старого поколения `generation_id != current_generation_id` допустимо: +состояние и description/files описывают именно выбранный snapshot. Для запроса current без +поколения возвращаются metadata registry, `datasets=[]`, `files=[]` и состояние §13. + +`SourceExportDescription`: три непустые строки для UI; `example_dataset_key: string|null`, +`example_is_synthetic: boolean`, `example_record: object|null`. Пример — одна JSON-запись +реальной export schema, не текст с многоточием. Максимум 32 КиБ UTF-8 и глубина 20; +использовать небольшой репрезентативный schema-valid пример, если реальная запись больше. +В этом случае `example_is_synthetic=true`. При отсутствии примера оба nullable поля null. +Пример нельзя получать чтением многогигабайтного JSON при каждом GET. + +`SourceExportDataset`: все пять полей required, не nullable. `key` стабилен в группе, +`export_schema_version` меняется при изменении формы файла; счётчики относятся к dataset. +В первой реализации одна группа обычно имеет один dataset `records`, содержащий все её +подисточники. Дополнительный dataset разрешён только при наличии реального адаптера и +описанной бизнес-семантики; frontend не выводит его из имени файла. + +`SourceExportPart`: все поля required, не nullable. UUID `part_id` уникален в generation, +`dataset_key` ссылается на datasets; `part_number` нумеруется с 1 внутри dataset, +`parts_count` — общее число его частей; `records_count` — число строк именно этой части. +`variants` непустой, format уникален; `default_format` присутствует в variants. +При одной части title не содержит «часть 1», при нескольких добавляется «— часть N из M». +Таким образом закупки с небольшим объёмом имеют одну плитку; большие закупки разбиваются +по реальному объёму. Число один из мока не является искусственным ограничением данных. + +`SourceExportArtifact`: все шесть полей required, не nullable; `artifact_id` UUID, +`format` enum `xlsx|csv|json`, `file_name` безопасный basename, `mime_type` по §12.2, +`size_bytes` integer ≥ 1, `sha256` — 64 lowercase hex characters от готового файла. +part_id и artifact_id создаются при сборке; не вычисляются из индекса текущей страницы. + +`SourceExportPagination`: все поля required, integer/boolean не nullable. +`total_count` — все логические части группы; `total_pages=max(1,ceil(total_count/page_size))`. +Для пустого источника page=1, total_count=0, total_pages=1, flags=false; page за пределами +диапазона → `400 source_export_invalid_page`. Порядок фиксирован по `(dataset_key,part_number)`. + +Header download использует все datasets/parts выбранного поколения, а не только data.files +текущей страницы. Неизвестная группа → 404, удалённое ранее известное поколение → 409, +принадлежность поколения другой группе → 404. Ошибки и cache headers — §6/§15. + +## 8. Dashboard парсеров + +### 8.1 `GET /api/v1/parsers/dashboard/` + +Request/response не меняются. Dashboard остаётся источником операционной статистики парсеров. +`registry_enrichment_analytics.source_coverage[].organizations_count` и +`population.active_registry_organizations` описывают количество организаций ОПК, а не файлов. +Значения `/sources[].organizations_count` также нельзя подменять export records_count. +Полный исторический экспорт закономерно может содержать больше записей, чем текущая +таблица или аналитика dashboard. Время data_as_of делает эту разницу объяснимой. + +## 9. Записи источника + +### 9.1 `GET /api/v2/organization-source-records/` + +Request/response существующей таблицы не меняются. Экспорт строится из того же canonical +источника данных с теми же правилами доступа и публикации, но scope all_available включает +все сохранённые даты и все record types внутри группы. Не копировать page/page_size из UI +или фильтр текущего года из старого export builder. + +Snapshot должен включать связанные финансовые строки всех сохранённых лет. Для групп +закупок, промышленности и ГОЗ проверять полноту каждого подисточника §3. Если какая-либо +зарегистрированная группа не поддержана сборщиком, вернуть unavailable и блокировать +приёмку этой группы; нельзя считать отсутствие adapter пустым набором. + +### 9.2 `GET /api/v2/organization-source-records/{uid}/` + +Request/response не меняются. Сохранённый UID в выгрузке относится к той же предметной записи. +Вложения интегрированных структур остаются отдельным существующим attachment-контрактом; +архив данной страницы содержит экспортные CSV/XLSX/JSON, а не все RTF/бинарные вложения. +Добавлять бинарные вложения в состав ZIP можно только отдельным расширением контракта. + +### Snapshot и полнота + +Публикуется согласованный snapshot данных каждой группы с `data_as_of`. +Допустимы существующий immutable published batch либо readonly repeatable-read snapshot +при потоковом создании spool. Простой cutoff updated_at без сохранения версий недостаточен: +изменившаяся после cutoff запись не должна потеряться или попасть частично. +При нескольких запросах/financial prefetch все читают один snapshot. + +После spool дальнейшая сериализация не перечитывает изменяющиеся records. +Count вычисляется при перечислении входа и сверяется с суммой counts частей. При наличии +нескольких datasets основной `records` dataset определяет records_count группы; +производные datasets считаются отдельно и не увеличивают общий count исходных записей. + +## 10. Refresh и фоновые задачи + +### 10.1 `POST /api/v1/sources/{slug}/refresh/` + +Request/response не меняются: это обновление исходных данных, не сборка выгрузки. +После успешной публикации source batch пометить snapshot соответствующей группы stale +и поставить idempotent/coalesced export build после commit транзакции. Для новой страницы +не запускать parser refresh из GET или кнопки скачивания. + +### 10.2 `POST /api/v1/parsers/run/{source_key}/` + +Request/response не меняются. Parser key, refresh key и task_ids остаются текущими. +Export builder не обращается к upstream и не имитирует новый parser source. +Существующий nightly task `organizations.tasks.refresh_source_record_export_artifacts` +и management command расширяются общими adapters с явным параметром scope. Legacy default +сохраняется, new scope `all_available` выпускает отдельные версии manifest/artifacts. + +Плановая сверка — ежедневно в 05:30 Europe/Moscow, как у текущего nightly schedule. +Триггер после загрузки дополняет расписание; отсутствие первого поколения устраняется +первоначальной management command после деплоя. Перезапуск одного источника не блокирует +публикацию остальных; last_build ведётся отдельно по группе. + +### 10.3 `GET /api/v1/jobs/{task_id}/` + +Request/response не меняются. Если backend регистрирует export build в существующих jobs, +использовать отдельный task_name, не выдуманный parser source. Каталог содержит компактный +last_build; frontend не обязан опрашивать job для каждой карточки. +UI-статусы парсера «Выполняется»/«Обновлено» сохраняются по старому контракту; +export states не подменяют успешность парсинга. + +### 10.4 `POST /api/v1/parsers/upload/{source_key}/` (условный) + +Новый upload не требуется. Request/response действующих загрузок сохраняются. +Для интегрированных структур действует multipart `archive` (ZIP), для СМИ/санкций — +существующий `file`, а не устаревшие workbook/attachments из раннего документа. +Сборка export начинается после успешного опубликованного результата upload. + +## 11. История обновлений + +### 11.1 `GET /api/v1/system/logs/` + +Request/response существующей истории парсеров не меняются. Создание download ticket +не создаёт фиктивную запись загрузки источника и не обновляет дату парсинга. +Export observability хранится в отдельном существующем audit/logger либо типизированном +расширении событий: actor, source_group, generation_id, selection_kind, format, count, +bytes sent, outcome, request_id; ticket и абсолютный storage path в лог не пишутся. + +### 11.2 `GET /api/v1/system/logs/{id}/` + +Request/response не меняются. Для ошибок сборки наружу выдаётся безопасный error_code, +подробная внутренняя диагностика доступна backend по request_id/build id. +Начало выдачи файла, полная передача байтов и оборванное соединение — разные события; +backend и frontend не утверждают, что браузер гарантированно сохранил файл на диск. + +### 11.3 `GET /api/v1/system/logs/export/` + +Request/response не меняются. Выгрузка истории обновлений и готовые файлы источников — +разные назначения; новый поток не использует log-export как file endpoint. + +## 12. Выгрузка данных источника + +Canonical flow новой страницы: metadata GET → authenticated POST export-ticket → native +form POST export-download. Backend формирует один физический файл либо ZIP из готовых +артефактов; браузер пишет ответ на диск. Не использовать client-side ExcelJS/JSZip из мока. + +### 12.1 `POST /api/v2/organization-source-records/export-ticket/` + +Request headers: + +```http +POST /api/v2/organization-source-records/export-ticket/ +Authorization: Bearer +Content-Type: application/json +``` + +Request schema — `oneOf` трёх **непересекающихся** вариантов. В каждом запрещены неизвестные +поля; обязательность и nullable перечислены ниже. Нельзя одновременно передать `sources` +и `selection_kind`, `part_id` в source_archive или только часть обязательных selector-полей. + +**A. Одна часть — `SourceExportFileTicketRequest`:** + +```json +{ + "selection_kind": "file", + "source_group": "government_procurements", + "generation_id": "11111111-1111-4111-8111-111111111111", + "part_id": "22222222-2222-4222-8222-222222222222", + "format": "xlsx" +} +``` + +Все пять полей required, не nullable. `selection_kind` — singleton enum `file`, +группа и UUID проверяются как единый связанный набор, format выбирает готовый variant части. +Ответ содержит basename/mime/size именно этого artifact; файл не оборачивается в ZIP. + +**B. Весь источник — `SourceExportArchiveTicketRequest`:** + +```json +{ + "selection_kind": "source_archive", + "source_group": "government_procurements", + "generation_id": "11111111-1111-4111-8111-111111111111", + "format": "xlsx" +} +``` + +Все четыре поля required, не nullable. В ZIP входят все datasets и все их части указанного +формата в указанном поколении. `part_id`, page/page_size и массив частичных files не допускаются. +При одном файле ZIP также остаётся ZIP: семантика кнопки заголовка не меняется. +Если запрошенного формата нет хотя бы у одной части, `409 source_export_format_unavailable`; +архив с неполным составом или молчаливой заменой формата запрещён. + +**C. Старый запрос — `OrganizationSourceRecordExportRequest`:** + +```json +{ + "sources": ["government_procurements"], + "format": "xlsx" +} +``` + +Сохраняет прежние group enum, response shape, scope текущего календарного года, финансовый +JSON fallback и ошибки. Новая страница его не вызывает. Legacy default не должен внезапно +скачивать все годы; новый all_available manifest нельзя неявно подставить legacy-клиенту. +При расширении request serializer явное ветвление формата обязательно. + +**Response новой страницы `201 application/json`, `SourceExportSelectionTicket`:** + +```json +{ + "ticket": "bV7k8nC0sD2fG4hJ6lP8qR0tU2wX4yZ6aB8cD0eF2gH", + "file_name": "public-procurements-part-000001.xlsx", + "expires_in": 300, + "selection_kind": "file", + "source_group": "government_procurements", + "generation_id": "11111111-1111-4111-8111-111111111111", + "format": "xlsx", + "mime_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "size_bytes": 8192, + "parts_count": 1 +} +``` + +Все десять полей required; только `size_bytes` nullable для streaming ZIP, остальные не nullable. +Для source_archive selection_kind меняется, MIME `application/zip`, `parts_count` — число +выбранных data artifacts; file_name вида `public-procurements--xlsx.zip`. +При невозможности вычислить точный ZIP-size заранее возвращается null, а не сумма файлов +под видом точного Content-Length. Для file size_bytes точно совпадает с variant. +Имена короткие, ASCII basename, без путей; допускается UTF-8 display filename по §12.2. + +Response legacy сохраняет прежние `ticket`, `file_name`, `expires_in` и не обязывает старый +frontend обрабатывать новые поля. OpenAPI описывает legacy/new response как named schemas. +Для response oneOf legacy schema должна иметь `additionalProperties: false`, как и новая: +ответ с selection_kind не должен одновременно удовлетворять обеим веткам. У legacy response +по-прежнему ровно три поля. Новая ветка содержит все десять полей примера. + +### Проверки и содержимое ticket + +Перед `201` выполнить admin RBAC, проверку всех selectors, поколения, complete manifest, +непустого набора, доступности выбранных файлов и их declared sizes. Не строить файлы, +не создавать ZIP на диске и не перечитывать всю БД ради выдачи ticket. + +В серверном хранилище ticket сохранить: + +- hash/token key, issuer_user_id, выданную роль, issued_at, expires_at; +- versioned request kind, source_group, scope `all_available`, pinned generation_id; +- selection_kind, выбранный format, part/artifact UUID и полный состав архива из manifest; +- ожидаемые basename/MIME/sizes/checksums, lease_id, file_name и audit/request id. + +Ticket — случайный непрозрачный token не менее 256 бит энтропии; TTL 300 секунд. +Он даёт право на конкретное скачивание: обычная form не умеет передать Bearer из памяти SPA. +issuer_user_id позволяет повторно проверить активность и роль владельца, но **не доказывает**, +что предъявитель формы — тот же пользователь. Сам ticket является секретным capability: +не включать его в URL, history, referer, analytics, серверные логи или persistent frontend storage. + +При выдаче взять generation lease и сохранить его вместе с ticket. Исчезновение поколения +между metadata и выдачей ticket → `409 source_export_generation_gone`; frontend перечитывает +каталог и явно повторяет действие пользователя. Нельзя заменить его новым поколением. +Ошибка ticket storage → `503 source_export_ticket_unavailable`, `Retry-After: 5`. + +Ошибки выдачи: `400,401,403,404,409,429,503,500` по §15. Состояние building/not_ready — +бизнес-ошибка `409` с retryable=true; GET каталога при этом продолжает возвращать `200`. +Header `Cache-Control: private, no-store` обязателен для любого ticket response. + +### 12.2 `POST /api/v2/organization-source-records/export-download/` + +Request — обычная same-origin HTML form, `FormParser` принимает urlencoded body: + +```http +POST /api/v2/organization-source-records/export-download/ +Content-Type: application/x-www-form-urlencoded + +ticket=bV7k8nC0sD2fG4hJ6lP8qR0tU2wX4yZ6aB8cD0eF2gH +``` + +Body schema `SourceRecordExportDownloadRequest`: единственное required поле ticket, string +непустое до 128 символов, whitespace не trim; malformed → 400. Параметры source/group/path, +format и selection из form не принимаются: они уже зафиксированы на сервере. + +Endpoint может принимать запрос без Authorization header исключительно по валидному ticket. +Проверить issuer всё ещё активен/admin, generation доступно и lease действителен. +Семантика legacy tickets сохраняется отдельной веткой; новые tickets атомарно поглощаются +через Redis GETDEL/Lua либо transactional row lock. `get` → `delete` двумя действиями +недопустим: два параллельных POST не должны получить два успешных потока. + +После успешного claim закрепить stream lease, открыть/проверить все selected artifacts, +и только затем посылать `200`. Ticket поглощается при принятии скачивания, а не после +прочтения последнего байта. Если клиент оборвал загрузку, frontend получает новый ticket +для той же части. TTL ticket ограничивает начало запроса, а не длительность активного потока. + +**Response файла `200`:** + +```http +Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet +Content-Disposition: attachment; filename="public-procurements-part-000001.xlsx" +Content-Length: 8192 +Cache-Control: private, no-store +Accept-Ranges: none +X-Content-Type-Options: nosniff +``` + +Тело — точные байты XLSX artifact, а не JSON/envelope/base64. CSV: +`text/csv; charset=utf-8`; JSON: `application/json; charset=utf-8`. При UTF-8 basename +передавать корректный RFC 5987 `filename*` плюс безопасный ASCII filename fallback. +Файл отправляется FileResponse/stream с ограниченным буфером; ETag при его использовании +равен checksum данного неизменяемого artifact, не текущей записи registry. + +**Response архива `200`:** + +```http +Content-Type: application/zip +Content-Disposition: attachment; filename="public-procurements-11111111-1111-4111-8111-111111111111-xlsx.zip" +Cache-Control: private, no-store +Accept-Ranges: none +X-Content-Type-Options: nosniff +``` + +Тело — streaming ZIP64 (`ZIP_STORED`, chunk около 1 МиБ), без промежуточного полного ZIP +и без ложного Content-Length. Записи ZIP идут по dataset_key/part_number, paths внутри +`/` безопасны и не пересекаются. Дополнительно `manifest.json` +содержит публичный состав, scope, snapshot, schemas, counts, sizes и sha256. `parts_count` +в ticket не включает manifest. Internal manifest с storage paths в архив не копируется. + +Range/resume в этой версии не поддерживается: Range не приводит к `206`, выдаётся полный +`200` с `Accept-Ranges: none`. После обрыва скачивается заново только нужная часть по новому +ticket; UI не обещает возобновление потока. При добавлении resume потребуется отдельный +auth/range контракт, не повторное использование одноразового ticket. + +Ошибки до отправки заголовков: `400,403,410,429,503,500`, JSON schema §6/§15. +После начала binary-потока JSON-ошибку в тело не дописывать: оборвать соединение, записать +download_failed и освободить lease. Браузер должен видеть неполную загрузку, а не валидный +на вид архив с отброшенными entries. + +Frontend может сохранить текущий hidden iframe/form подход. Для native form он не может +надёжно прочитать HTTP-ошибку cross-document download и не знает момент сохранения на диск. +Основные ошибки выявляются до `201`; в UI допустимо только «Скачивание началось» и повторное +получение ticket. Backend обязан вернуть безопасную JSON-ошибку, а не HTML login/traceback. + +### 12.3 `POST /api/v2/organization-source-records/export/` + +Request/response старого synchronous API сохраняются: `{sources,format}` → streaming ZIP +из legacy scope. Новый selector `file|source_archive` здесь не поддерживается и даёт 400. +Новая страница всегда использует ticket-flow, даже если у маленького файла возможен Blob. +Удалять существующий endpoint или менять scope старого потребителя в рамках задачи нельзя. + +### Форматы, разбиение и содержимое файлов + +1. Разбивать канонический вход на логические части **до** формирования форматов. Для всех + variants одного part_id набор UID/строк и part_number одинаковы. Предел определяется + самым крупным поддерживаемым variant; XLSX может потребовать более раннего разбиения. +2. Цель — до 256 МиБ на файл; жёсткий предел — 512 МиБ. XLSX дополнительно ограничен + 100 000 строками данных по умолчанию и никогда не превышает лимит листа Excel. + Это конфигурируемые backend limits, а не аргументы пользователя. +3. Перед публикацией проверить **фактический** размер каждого готового variant, включая + header/JSON framing/XLSX ZIP overhead. При превышении переподелить соответствующий part + для всех variants. Если одна неделимая запись превышает предел, сборка группы завершается + failed с code `source_export_record_too_large`; предыдущий snapshot сохраняется. +4. Порядок входа — стабильный `(source,record_type,uid)` с подходящими индексами/keyset scan. + Для financial lines сохранять стабильный `(year,form_code,line_code,id)` внутри записи. + Не применять OFFSET по многомиллионному набору, не делать полный RAM sort. +5. Каждая JSON-часть — самостоятельный UTF-8 JSON array; её можно разобрать без остальных + частей. Это не NDJSON и не разрезанный байтовый диапазон общего JSON. Nested JSON + сохраняется по текущему adapter/schema; смена сериализации требует export_schema_version. +6. CSV — UTF-8 BOM, разделитель запятая, quoting по текущему CSV adapter; каждый part имеет + одинаковый header для dataset. XLSX — валидный `.xlsx`, текстовые ИНН/ОГРН/ОКПО/КПП, + без потери ведущих нулей и decimal precision. Формулы из внешних строк не исполняются; + действуют общие правила защиты spreadsheet exports. +7. Поддержка форматов: сохранить фактический JSON-only adapter финансов, пока CSV/XLSX для + него отдельно не реализованы и не протестированы; остальные группы поставляются с + CSV/XLSX/JSON на основе существующих DTO/adapters. В новой странице отсутствует fallback. + Форматы публикуются только целиком для dataset, случайный пропуск одного variant — failed. +8. Названия файлов стабильны внутри generation: `-part-000001.`; + UUID не заменяется вычислением frontend. Расширение всегда соответствует реальному MIME. +9. Источник без строк получает published empty manifest и `files=[]`, а не четыре пустых + файла. Counts групп/частей/физических variants хранятся раздельно. Один исходный record + с финансовыми lines считается одной записью, если adapter не объявляет отдельный dataset. +10. Существующую нормализацию/санитизацию экспортных данных сохранить. Новые секретные + provenance/storage fields не должны попасть ни в файлы, ни в JSON-пример. + +## 13. Статусы и жизненный цикл + +### Публикация и хранение + +Новая область storage отделена от legacy annual files логически и физически, например +`SOURCE_RECORD_EXPORT_DIRECTORY/all-available//generations//`. +Новые manifest имеют `version: 3`, `data_scope: all_available`, source_group, generation_id, +generated_at, data_as_of, datasets, parts, variants, реальные per-part counts, sizes и sha256. +UUID generation относится к **одной группе и одному scope**. Legacy `current.json` v2 не +перезаписывается manifest другой версии без migration/backward-compatible reader. + +Общий registry указывает current_generation каждой группы; global catalog_revision меняется +атомарно при изменении опубликованного metadata. Нельзя сканировать все файлы и вычислять +sha256 на каждом GET: metadata индексируется в БД/manifest cache при публикации. + +Порядок сборки: distributed lock на `(group,scope)` → consistent snapshot/spool → staging +`.building-*` → все части/форматы → checksums/count validation → immutable manifest → atomic +rename/current pointer switch. Ошибка оставляет предыдущий pointer и убирает staging. +Сборка одной группы не создаёт неполное общее поколение остальных источников. + +Lock должен иметь owner token и продление; освобождение только compare-and-delete своим +владельцем. Текущий фиксированный lock TTL не должен позволить второму worker опубликовать +конкурирующее поколение после долгой сборки. Повторы после одного batch coalesce; при новых +данных во время build ставится следующий build, чтобы stale snapshot не считался актуальным. + +Успешная генерация хранится не менее 24 часов, минимум два последних успешных поколения +каждой группы; current сохраняется всегда. Retention считает bytes/disk budget и проверяет +leases. Ticket lease действует TTL+60 секунд; active stream lease продлевается каждые +60 секунд с TTL 10 минут. Окончание/обрыв освобождает lease; crash освобождается по TTL. +Поколение с живым ticket/stream нельзя удалить при cleanup или deployment. + +При claim ticket переводить lease в active stream атомарно относительно cleanup. Все +selected artifacts проверяются до HTTP 200. Storage missing/corrupt → 503, snapshot помечается +unavailable; checksum проверяется при публикации/фоновой проверке, не полным чтением перед +каждым download. Появление более нового current не влияет на уже выданный pinned ticket. + +### Состояния API + +| Ситуация | `state` | Snapshot / скачивание | +| ------------------------------------------ | ------------------- | ------------------------------------------------------ | +| Первая сборка ещё не запланирована | `not_ready` | generation=null, counts=null, files=[] | +| Первая сборка queued/running | `building` | generation=null, files=[] | +| Успешный snapshot, есть записи | `ready` | Все части/форматы доступны | +| Успешный snapshot, нет записей | `empty` | generation есть, counts=0, files=[] | +| Новая сборка идёт поверх старой | `ready` или `empty` | Старое поколение доступно; is_stale по данным/возрасту | +| Новая сборка упала, старое пригодно | `ready` или `empty` | Старое поколение доступно, last_build.failed | +| Нет пригодного snapshot, ошибка/отключение | `unavailable` | Скачивание блокируется, причина безопасна | + +Для `unavailable` поле `unavailable_reason` summary/detail содержит enum +`disabled|adapter_missing|build_failed|storage_unavailable`, в остальных состояниях null. +Backend не смешивает отсутствие данных (`empty`) +с отсутствием adapter или ошибкой storage. `last_build.error_code` уточняет build failure. + +Удалённый старый generation при metadata/ticket request → 409 generation_gone, повтор +current-запроса возвращает новое поколение. Валидный ticket обеспечивает lease; его snapshot +не может штатно исчезнуть. Если storage повреждён аварийно, download → 503, без нового файла +под старым именем. Новогодняя смена календаря не инвалидирует scope all_available. + +## 14. Согласованность данных между endpoint + +- source_group, source_slug и title определяются общим registry, а не копиями моков. +- Summary counts описывают current snapshot; pinned detail может описывать сохранённый + предыдущий snapshot. Frontend сравнивает generation_id, а не только название источника. +- Детальный список, ticket и bytes ответа относятся к одному generation и scope. +- Сумма part.records_count dataset равна dataset.records_count; source.records_count + равен count основного dataset. Нельзя умножать count на количество форматов. +- source.parts_count = сумма datasets.parts_count; meta.pagination.total_count равен + количеству всех логических частей группы, не размеру текущей страницы. +- Все variants части содержат те же записи; supported_formats соответствует полной матрице. +- Выбранный format, extension, MIME, Content-Disposition и bytes ответа совпадают. +- Header ZIP включает все части выбранного формата, а не первую страницу и не выбранные + форматы индивидуальных плиток. Независимый выбор формата плитки не меняет header selector. +- description.example_record соответствует export_schema_version; это пример файловой + проекции, а не обещание повторить временный mock DTO. +- generated_at/data_as_of не обновляются при скачивании, не заменяют parser last_updated_at. +- Старый annual экспорт и новый all_available имеют разные явно описанные scopes; + сравнивать их counts как будто это один набор запрещено. + +## 15. Ошибки, доступ, производительность и ограничения + +### Матрица доступа + +| Действие | Anonymous | Обычный user | Активный admin | +| -------------------------- | ----------------------------------------- | ------------------------------------- | ------------------------------------- | +| Catalog/detail | 401 | 403 | 200 | +| Выдать ticket | 401 | 403 | 201 при доступном выборе | +| Download без ticket | 400 | 400 | 400 | +| Download с валидным ticket | Capability; повторная проверка issuer | Capability; повторная проверка issuer | Capability; повторная проверка issuer | +| Build/cleanup | Только internal worker/management command | Нет | Нет нового UI endpoint | + +Download не доверяет роли из form/cookie; возможность выполнить запрос определяется +capability и актуальными правами issuer. Если issuer заблокирован или лишён admin, +вернуть 403 и поглотить ticket. Публичная раздача файла по `/media/...` без этих проверок +недопустима. Защитить также filesystem alias/nginx location, а не только DRF route. + +### Ошибки новых запросов + +Все строки используют `SourceExportError` §6, кроме стандартной auth schema 401. +GET возвращает обычный каталог состояний вместо ошибки, если проблема только в готовности группы. + +| HTTP | `code` | Где / действие frontend | +| ---- | ------------------------------------ | ------------------------------------------------------------------------ | +| 400 | `source_export_invalid_request` | Неизвестный параметр/неполный selector; исправить запрос | +| 400 | `source_export_invalid_page` | Некорректная пагинация; первая страница того же поколения | +| 400 | `source_export_ticket_malformed` | Неверная форма ticket; получить новый | +| 403 | `source_export_forbidden` | Нет admin/issuer лишён прав/экспорт отключён; не повторять автоматически | +| 404 | `source_export_source_not_found` | Неизвестная группа | +| 404 | `source_export_part_not_found` | Часть/поколение не принадлежат выбранной группе | +| 409 | `source_export_generation_gone` | Устаревшее удалённое поколение; обновить каталог, повторить осознанно | +| 409 | `source_export_not_ready` | Первая сборка; retryable=true, Retry-After: 30 | +| 409 | `source_export_empty` | Нет файлов; отключить кнопку | +| 409 | `source_export_format_unavailable` | Формат не опубликован; использовать варианты metadata | +| 410 | `source_export_ticket_expired` | Ticket истёк/уже использован/не существует; выдать новый | +| 429 | `source_export_rate_limited` | Retry-After, не повторять циклически | +| 503 | `source_export_metadata_unavailable` | Registry/metadata storage недоступен; Retry-After: 30 | +| 503 | `source_export_ticket_unavailable` | Ticket cache недоступен; Retry-After: 5 | +| 503 | `source_export_artifact_unavailable` | Повреждён/недоступен готовый файл; Retry-After: 30 | +| 500 | `source_export_internal_error` | Безопасная ошибка с request_id | + +`retryable=true` только для not_ready, rate_limited и временных 503. Все остальные false. +Файл не найден при аварии storage и устаревшее generation — разные ошибки. Смешанный selector +не должен уходить в legacy ветку. Имеющий правильную форму неизвестный UUID generation +возвращает 404; известное ранее опубликованное, но удалённое поколение — 409, metadata +tombstone сохраняется минимум 30 дней. Ответ не раскрывает существование чужих артефактов. + +### Производительность и эксплуатация + +- Catalog и страницы metadata не читают канонические records, binary artifacts или всю FS. + На горячем metadata cache p95 GET ≤ 1 секунды; выдача ticket ≤ 2 секунд без подготовки ZIP. +- Целевые limits: metadata page_size ≤ 200, example ≤ 32 КиБ; никакого binary/base64 в JSON. +- Стриминг не зависит по памяти от общего размера: чтение около 1 МиБ за раз; прибавка RSS + на активное скачивание ≤ 64 МиБ при испытании на архиве ≥ 5 ГиБ. ZIP64 обязателен. +- Минимальный load-test: два параллельных скачивания частей и один ZIP ≥ 5 ГиБ. Каталог + продолжает отвечать; лимиты worker/proxy и число соединений согласованы с инфраструктурой. +- Rate limits по умолчанию: GET metadata 120/min/user; ticket 30/min/user; + активных streams 3/user, 20/instance с общим shared limiter. Превышение → 429 до headers, + Retry-After: 10 для concurrency и до сброса окна для request rate. Все limits конфигурируемы. +- Браузер и backend за одним origin; если используются разные origins, отдельно настроить + CORS для metadata/ticket и form-action CSP. Базовая приёмка использует same-origin `/api`. +- Proxy buffering для binary выключен, auto gzip не меняет размеры/checksums, idle timeout + продлевается при передаче чанков. Не создавать временный гигабайтный proxy cache. +- Web и worker видят общий persistent volume/object storage с одинаковыми permissions. + Доступность volume, свободное место, длительность build, возраст snapshot, failed builds, + bytes sent/aborted streams и leases должны иметь metrics/alerts. +- Disk budget учитывает current, retained, staging и spool для all-history. При нехватке + места build завершается безопасно, current не удаляется и частичный manifest не публикуется. +- Не допускать path traversal/symlink escape, CRLF в filename и произвольных URL/file paths + в selectors. UUID проверяются через manifest/registry с allowlist group/scope. + +## 16. Требования к OpenAPI и generated-клиенту + +Canonical схема публикуется backend через `/openapi.json` (OpenAPI 3), существующий +командный адрес — `https://so1-admin.dev.nii-ecos.ru/openapi.json`. Legacy Swagger export +`/?format=openapi` не используется для frontend generation. + +Обязательные stable operationId: + +| Method/path | operationId | +| ---------------------------------------- | ---------------------------------------------------------- | +| GET `.../export-catalog/` | `v2_organization_source_records_export_catalog_list` | +| GET `.../export-catalog/{source_group}/` | `v2_organization_source_records_export_catalog_read` | +| POST `.../export-ticket/` | Сохранить `v2_organization_source_records_export_ticket` | +| POST `.../export-download/` | Сохранить `v2_organization_source_records_export_download` | +| POST `.../export/` | Сохранить `v2_organization_source_records_export` | + +Использовать существующий Organizations tag без переименования generated tag-файлов. +Named components: SourceExportCatalogResponse, SourceExportSourceSummary, +SourceExportBuildSummary, SourceExportSourceDetailResponse, SourceExportSourceDetail, +SourceExportDescription, SourceExportDataset, SourceExportPart, SourceExportArtifact, +SourceExportPagination, SourceExportError, SourceExportFileTicketRequest, +SourceExportArchiveTicketRequest, SourceExportSelectionTicket, SourceRecordExportDownloadRequest. +Legacy request/ticket/error components сохранить. + +Для каждого object указать required и nullable ровно по таблицам. Для UUID — format uuid, +дат — date-time; positive sizes/counts и enum описать constraints. `description.example_record` +разрешает JSON object с `additionalProperties` только как иллюстрацию разных файловых схем, +остальные metadata DTO не публиковать как нетипизированный object/unknown/void. +Содержимое файлов — binary; file downloads имеют три MIME, archives — application/zip. +У download error responses application/json, body `application/x-www-form-urlencoded`; +requestBody не должен ошибочно требовать JSON для обычной HTML-формы. + +Request ticket — oneOf legacy/file/source_archive с singleton selection_kind и запретом +лишних полей; response — legacy/new named variants. Проверить, что Orval реально генерирует +пригодные union types и function signature; не оставлять discriminator только в prose. + +### Подключение frontend после реализации backend + +1. Обновить локальный `openapi.json` с canonical host и выполнить: + + ```bash + bun run apigen + bun run type-check + bun run contracts:check + bun run test:contract + ``` + +2. Владелец новых GET и расширенных ticket/download контрактов — `pages/main`. + Зарегистрировать endpoints в `src/shared/api/contracts/owners.json` одновременно + с добавлением реальных `*.contract.spec.ts`; generated-файлы вручную не исправлять. +3. Заменить `SOURCE_DATA_EXPORT_MOCKS` запросом catalog. Существующие hidden source flags + применить к source_slug/source_group; отсутствие файлов не скрывает разрешённый источник. +4. При раскрытии карточки загружать detail с catalog generation_id. Обработать страницы + файлов; query key включает source_group/generation_id/page/page_size. Смена поколения + сбрасывает pages/part selection; не склеивать snapshots в один список. +5. Поля UI: id ← source_group/part_id, title ← backend title, composition/origin/fields ← + description, JSON ← example_record, форматы плитки ← variants, header ← supported_formats. + Индивидуальный выбор не должен изменять общий selector. Недоступные форматы не показывать. +6. Убрать `records` из runtime view model файла: они не загружаются в браузер. Удалить + mock download через ExcelJS/JSZip; отдельная часть и ZIP используют POST ticket + form. + Иконка/название файла обновляются по фактическому variant, не предположению по индексу. +7. Добавить состояния not_ready/building/empty/unavailable/stale и disabled controls. + После 409 generation_gone заново запросить catalog/detail. Не стартовать новый download + автоматически после замены snapshot без понятного действия пользователя. +8. Перенести готовые backend fixtures в mock E2E, покрыть pagination, JSON-only finance, + one-file закупки, разные selectors и live contract download. Только после приёмки удалить + временные mock data; структуру карточек и общие стили сохранять. + +Генерация API не выполняется из выдуманных frontend DTO: backend сначала публикует schema +и проходит свои тесты. Обновлять live клиент или включать неподтверждённые API в рамках +подготовки этого задания не требуется. + +## 17. Backend-тесты и acceptance criteria + +### Минимальная матрица backend/contract tests + +| ID | Проверка | Ожидаемый результат | +| --------- | -------------------------------------------------------- | ------------------------------------------------------------------------- | +| `EXP-T01` | Registry всех групп §3 | 22 записи без дублей; исходные slug/group не переименованы | +| `EXP-T02` | Права metadata и ticket | Anonymous 401, user 403, admin success | +| `EXP-T03` | Нет первой генерации | Catalog 200 с not_ready/building, ticket 409 | +| `EXP-T04` | Пустой источник | empty, counts=0, files=[], ticket 409 empty | +| `EXP-T05` | Обе ветки закупок | В файлах присутствуют 44-ФЗ и 223-ФЗ, в малой fixture одна плитка | +| `EXP-T06` | Подисточники промышленности/ГОЗ/вакансий | Нет потерянного adapter или record type | +| `EXP-T07` | Годы и финансовые lines | Записи минимум двух лет входят в all_available; legacy scope не изменился | +| `EXP-T08` | JSON-only finance | Catalog/parts показывают JSON; запрос XLSX новой формы → 409 | +| `EXP-T09` | Пагинация > 50 частей | Нет пропусков/дублей, counts и meta.pagination точны | +| `EXP-T10` | Неверные page/page_size/UUID/extra params | Документированный 400/404, нет 500 | +| `EXP-T11` | Изменение current между страницами | Pinned generation сохраняет тот же состав | +| `EXP-T12` | Разбиение CSV/JSON/XLSX | Каждый файл ≤ limit, JSON отдельно парсится, CSV имеет header | +| `EXP-T13` | Матрица вариантов части | Одинаковые UID/counts across formats, уникальные artifact UUID | +| `EXP-T14` | Counts | Per-part count точен, сумма не умножается на число форматов | +| `EXP-T15` | Single file selector | Exact MIME/name/Content-Length/sha256, без ZIP-обёртки | +| `EXP-T16` | Header selector при > 1 странице | ZIP содержит все части/manifest и только выбранный format | +| `EXP-T17` | Обновление current после выдачи ticket | Скачиваются bytes указанного старого generation | +| `EXP-T18` | Два одновременных POST одного ticket | Ровно один 200, второй 410 | +| `EXP-T19` | Expired/malformed/used ticket | 410/400/410, без выдачи файла | +| `EXP-T20` | Issuer заблокирован/лишён admin | 403, ticket больше не используется | +| `EXP-T21` | Cleanup при ticket/active stream | Generation не удаляется; после lease допускается retention | +| `EXP-T22` | Оборванная передача | Lease освобождён, audit failed; новый ticket позволяет повтор части | +| `EXP-T23` | Missing/corrupt file | До headers 503; нет неполного успешного ZIP | +| `EXP-T24` | Ошибка build, ENOSPC, lock timeout | Current сохранён, last_build.failed, другие группы доступны | +| `EXP-T25` | Пустые исторические identifiers / decimal / leading zero | Существующие данные не пропадают и не искажаются | +| `EXP-T26` | Extra selectors, чужие UUID, paths, symlinks | Ошибка до чтения произвольного файла | +| `EXP-T27` | Native browser form с Bearer SPA | Download работает без Bearer header, ticket не попадает в URL | +| `EXP-T28` | ZIP ≥ 5 ГиБ / несколько streams | ZIP64, bounded RSS, metadata доступно, rate limits работают | +| `EXP-T29` | Legacy regression | Старый sources/format ticket/download/export и годовой scope работают | +| `EXP-T30` | OpenAPI / generated code | JSON examples schema-valid; DTO не void; apigen/type-check успешны | + +Большие fixtures генерируются потоково тестовым инструментом; нельзя объявлять load-test +пройденным только по маленькому архиву или моковому Content-Length. Внутренние unit tests +проверяют builders и locks, integration — реальные manifests/tickets/storage, E2E — браузер. + +### Backend acceptance criteria + +- [ ] Все 22 группы зарегистрированы; 16 групп новой страницы имеют рабочие adapters и + корректные ready/empty snapshots на тестовом опубликованном наборе. Отключённые остальные + группы явно описаны unavailable, их включение не требует нового frontend кода. +- [ ] GET catalog/detail, все metadata DTO и состояния работают по §7. +- [ ] Для scope all_available нет скрытого ограничения текущим годом или текущей страницей. +- [ ] JSON/CSV/XLSX делятся на ограниченные по размеру части без потерь/дублирования записей. +- [ ] Финансовые форматы и реальные datasets соответствуют capabilities, нет фиктивных плиток. +- [ ] Single-file и source-archive selector работают через authenticated ticket + native form. +- [ ] Download стабильно привязан к generation, одноразовое потребление ticket атомарно. +- [ ] Retention/cleanup учитывают tickets, active streams, staging и disk budget. +- [ ] Права issuer проверяются, прямые публичные ссылки на файлы отсутствуют. +- [ ] Большие файлы не буферизуются целиком ни на backend, ни в proxy, ни в JS frontend. +- [ ] MIME, filename, counts, schema versions и checksums проверены тестами. +- [ ] Старые экспортные endpoints и прежний annual scope проходят regression suite. +- [ ] Canonical OpenAPI опубликован, request/response examples валидируются по schemas. +- [ ] `bun run apigen`, `bun run type-check`, `bun run test:contract` проходят после подключения + frontend к реализованному стенду; временные DTO не патчатся вместо исправления schema. +- [ ] Переданы фактические curl/form примеры, fixture минимум двух лет, generation id, + результаты backend tests/load-test и deployment инструкция с первым запуском сборки. + +## 18. Чего backend не должен возвращать + +- Содержимое гигабайтных файлов внутри catalog/detail, base64 или массив всех records. +- Фиктивные XLSX/CSV при реальном JSON, неописанные derived datasets и копии файлов ради UI. +- Display-размеры «1,5 ГБ», локализованные даты и CSS/HTML вместо структурированных metadata. +- Абсолютные/относительные storage paths, raw internal manifest, credentials или stack traces. +- Постоянные публичные URLs на source artifacts; capability ticket в query string. +- Другое поколение под ранее выбранным generation_id или другой формат под тем же выбором. +- Архив из только первой страницы частей либо частично доступных artifacts с HTTP 200. +- Count всего источника в поле records_count одной части или сумму одинаковых записей по форматам. +- Ошибку парсера, замаскированную под empty export, или успешность сборки на основании одних mocks. +- UI-only route names/tableKey как новые идентификаторы источника. + +## 19. Решения и открытые вопросы + +### Зафиксированные решения для реализации + +| ID | Решение | +| --------- | --------------------------------------------------------------------------------------- | +| `EXP-D01` | Расширяется существующая export subsystem, новые предметные источники не создаются | +| `EXP-D02` | Новая страница экспортирует all_available, старый annual API сохраняет scope | +| `EXP-D03` | Первые 16 групп обязательны; общий registry заранее поддерживает все 22 | +| `EXP-D04` | Финансы исходно JSON-only; UI получает фактические capabilities | +| `EXP-D05` | Кнопка части скачивает файл; кнопка заголовка — ZIP всех частей выбранного формата | +| `EXP-D06` | Один dataset `records` по умолчанию; несколько плиток возникают из реального разбиения | +| `EXP-D07` | Администраторский доступ, same-origin ticket/form flow, 300 секунд на начало скачивания | +| `EXP-D08` | Pinned immutable generations, атомарные tickets, leases для cleanup | +| `EXP-D09` | Лимит файла 512 МиБ, цель 256 МиБ; пагинация metadata 50/200 | +| `EXP-D10` | Range/resume не обещается; после обрыва повторяется отдельная часть | + +Открытых продуктовых решений, которые нужно угадывать при реализации, в этом задании нет. +До приёмки backend обязан предоставить фактические сведения по стенду: + +| Проверка | Ответственный | Срок | Критерий закрытия | +| -------------------------------------------------------------- | ------------------------ | ---------------------- | --------------------------------------------------------------------- | +| Актуальная backend-ветка и наличие всех source models/adapters | Backend | До разработки adapters | Сверка с §2–3, зарегистрированные группы не потеряны | +| Объём all-history и capacity persistent storage | Backend + инфраструктура | До первого full build | Измеренный размер/время, запас под spool/staging/retention | +| Read isolation и индексы для стабильного полного прохода | Backend + DBA | До нагрузочной приёмки | Snapshot без пропусков, нет неограниченного RAM/disk sort | +| Shared volume/cache/proxy configuration | Backend + инфраструктура | До выкладки | Worker и web видят те же files/tickets, native stream не буферизуется | + +Эти проверки не разрешают уменьшить scope до одного года, выкинуть группы или изменить +публичный контракт без обновления задания. `ready` ставится только после §17 и закрытия +блокирующих результатов проверок; schema/runtime/tests должны совпадать. diff --git a/docs/source-export-catalog-operations.md b/docs/source-export-catalog-operations.md new file mode 100644 index 0000000..00bf497 --- /dev/null +++ b/docs/source-export-catalog-operations.md @@ -0,0 +1,144 @@ +# Каталог all_available: эксплуатация и проверка + +Контракт: [исходное задание](source-data-export-api-spec.md). Новая область включает все +опубликованные записи канонического хранилища всех 22 групп, включая финансовые строки +прошлых лет. Legacy годовой API, `--all-years` и их storage не изменены. +Фронтенд в эту реализацию не входит. +Фактические результаты локальных проверок: [QA report](source-export-catalog-verification.md). + +## Подготовка контура + +1. Применить миграции `python src/manage.py migrate --noinput`. +2. `SOURCE_EXPORT_DIRECTORY` должен указывать на **приватный persistent volume**, одинаково + смонтированный в web/worker. Он не должен быть внутри `MEDIA_ROOT` и не должен иметь + публичный nginx/static alias. Default — `PROJECT_ROOT/private-source-exports`; для + контейнеров его обязательно заменить общим persistent mount до первой сборки. + В `docker-compose.dev.yml` уже предусмотрен общий `./data/source-exports` + (host override `SOURCE_EXPORT_HOST_DIRECTORY`): worker пишет, web читает через `:ro`. + Bootstrap/cleanup команды в таком режиме выполнять в worker, не в web. +3. До полного запуска измерить объём канонических данных, свободное место и запас для + минимум двух поколений каждой группы, spools/staging и параллельных сборок. Тесты на + синтетических данных не заменяют эту проверку. При необходимости сначала собрать одну группу. +4. Запустить сборку. Проверить `last_build`, counts, размеры, контрольные суммы, загрузку + одного файла и ZIP через тот же origin `/api`, который использует браузер. +5. После проверки включить зарегистрированную миграцией **отключённую по умолчанию** задачу + Beat `organizations:source-export-catalog:nightly-msk` (06:30 Europe/Moscow, после annual). + `SOURCE_EXPORT_AUTOBUILD=true` дополнительно включает enqueue после публикации snapshot. + При изменении данных во время сборки Celery повторяет сборку после завершения текущей. + Без Beat использовать command в штатном таймере контура. + +```sh +python src/manage.py build_source_export_catalog --source-group government_procurements +python src/manage.py build_source_export_catalog +python src/manage.py build_source_export_catalog --verify-only +python src/manage.py build_source_export_catalog --cleanup-only +``` + +Команда продолжает остальные группы при ошибке одной и завершается ненулевым кодом, +если хотя бы одна группа не обработана. Новый current публикуется транзакционно только +после готовых checksums/manifest и atomic rename. Ошибка сохраняет старый current. +Сборка сортирует канонический snapshot по `(source,record_type,uid)` на локальном диске +SQLite с индексом вместо неограниченного RAM sort/PostgreSQL sort; financial lines +упорядочены `(year,form_code,line_code,id)`. Финансы JSON-only; CSV/XLSX fallback в новом API нет. + +## Лимиты + +Django settings (при необходимости задать в настройках контура): + +| Setting | Default | +| --- | --- | +| `SOURCE_EXPORT_TARGET_FILE_BYTES` | 256 MiB | +| `SOURCE_EXPORT_MAX_FILE_BYTES` | 512 MiB | +| `SOURCE_EXPORT_ROWS_PER_PART` | 100000 | +| `SOURCE_RECORD_EXPORT_XLSX_ROWS_PER_FILE` | 100000, совместимый верхний предел | +| `SOURCE_EXPORT_MIN_FREE_BYTES` | 1 GiB, резерв проверяется между batch/render | +| `SOURCE_EXPORT_DISK_BUDGET_BYTES` | 0 (нет дополнительной квоты; filesystem capacity + reserve) | +| `SOURCE_EXPORT_GENERATIONS_TO_KEEP` | 2, минимум 2 и минимум 24 часа | +| `SOURCE_EXPORT_METADATA_RATE` | 120/min/user | +| `SOURCE_EXPORT_TICKET_RATE` | 30/min/user | +| `SOURCE_EXPORT_MAX_STREAMS_PER_USER` | 3 | +| `SOURCE_EXPORT_MAX_STREAMS` | 20, общий shared limiter | + +`SOURCE_EXPORT_DISABLED_GROUPS` — env, группы через запятую; они остаются в каталоге +как unavailable/disabled. Настройки лимитов не являются query/body параметрами API. +Данные по всем форматам одной части одинаковы; при превышении фактического byte limit +делятся все варианты. Запись, которая сама превышает лимит, приводит к failed build. + +Метаданные, tickets, locks и leases — общая БД PostgreSQL. Tokens — capability с 256 битами +энтропии; новый внутренний namespace `se1_` отделён от legacy. В БД хранится только digest, +issuer, selectors и срок. Ticket TTL 300 секунд, lease 360; stream lease 10 минут с +обновлением раз в 30 секунд (в том числе во время блокировки socket write). Claim и admission +атомарны относительно cleanup. В SQLite unit tests renewal thread отключён; проверку +распределённых locks/leases следует выполнять на PostgreSQL. + +## Native download + +Пример selector (UUID брать из GET detail): + +```http +POST /api/v2/organization-source-records/export-ticket/ +Authorization: Bearer +Content-Type: application/json + +{"selection_kind":"file","source_group":"government_procurements","generation_id":"","part_id":"","format":"json"} +``` + +Для всего источника использовать `selection_kind: source_archive`, без `part_id`. +Полученный `ticket` передать только в body HTML form POST `export-download/`. +Не помещать capability в URL/analytics/logs. Native download не требует Bearer; +перед выдачей байтов сервер повторно проверяет active/admin issuer. Новое поколение +не меняет уже выданный ticket. ZIP включает `records/` всех частей нужного +формата и публичный `manifest.json`. ZIP64, ZIP_STORED, без полного ZIP spool/Blob. + +Binary route: `proxy_buffering off`, `proxy_request_buffering off`, `gzip off` и достаточный +read/send timeout. Ответ включает `X-Accel-Buffering: no`, `Accept-Ranges: none`, nosniff, +private/no-store. Настроить FD limit под количество частей, так как выбранные файлы открываются +до HTTP 200. HTML error page/login redirect вместо JSON ошибки недопустимы. + +## Контроль + +Регулярный `--verify-only` проверяет размеры и sha256 и помечает повреждённые поколения +storage_unavailable. GET и download не перечитывают гигабайты ради checksum. Перед download +проверяются размеры/типы/безопасные пути всех выбранных файлов. При повреждении нужен новый +успешный build, а не замена байтов существующего generation. + +Метрики/алерты контура следует привязать к structured log событиям +`source_export_build_success`, `source_export_build_failed`, +`source_export_download_complete`, `source_export_download_failed`, а также shared-volume +free bytes, возрасту `SourceExportGeneration`, `SourceExportState.last_build` и живым +`SourceExportLease`. Audit не содержит capability. Следить за возрастом >36h, +failed builds, ENOSPC, длительностью build, bytes sent/aborts, количеством streams. + +До приёмки контура отдельно необходимы реальный all-history build/capacity, PostgreSQL +конкурентные запросы, native browser через proxy и нагрузочное испытание: два файла параллельно +и ZIP >=5 GiB, p95 каталога <=1s, RSS прирост <=64 MiB/stream. Успешный unit test или generated +client не подтверждает состояние живого стенда. Страница frontend пока не подключена. + + +## Локальные контрактные и нагрузочные проверки + +```sh +SOURCE_EXPORT_RUNTIME_FIXTURES=/tmp/source-export-runtime.json PYTHONPATH=src uv run pytest tests/apps/organizations/test_source_export_catalog.py +cd tools/openapi +bun build.mjs --check +bun run apigen +bun run type-check +bun check-source-export-runtime.mjs /tmp/source-export-runtime.json +``` + +Для отдельного транспортного прогона из корня backend: + +```sh +SOURCE_EXPORT_TRANSPORT_LOAD=1 SOURCE_EXPORT_TRANSPORT_REPORT=/tmp/source-export-transport.json PYTHONPATH=src uv run pytest tests/apps/organizations/test_source_export_transport.py +``` + +Тест действительно читает 5.5 GiB и формирует ZIP64 потоком, одновременно читает два +файла по 512 MiB и запрашивает каталог. Источник — sparse synthetic binary, выходной ZIP +не накапливается в RAM или на диске. Это проверка транспорта и ORM metadata, без HTTP proxy, +браузера и реальных предметных файлов. Она не подменяет нагрузочную приёмку контура. +`test_source_export_postgres.py` проверяет два одновременных native POST одного ticket; +его запуск требует отдельного PostgreSQL test settings и в SQLite явно пропускается. + +У Orval/Zod для export-ticket включён strict mode: иначе legacy вариант union с тремя +полями способен принять новый ответ и silently strip selection fields. Generated файлы +не патчатся. Canonical timestamps публикуются в UTC с `Z`, поддерживаемым generated validator. diff --git a/docs/source-export-catalog-verification.md b/docs/source-export-catalog-verification.md new file mode 100644 index 0000000..bb55be1 --- /dev/null +++ b/docs/source-export-catalog-verification.md @@ -0,0 +1,62 @@ +# Проверка каталога all_available — 2026-10-22 + +Реализация backend в `dev`; frontend, реальные базы и серверы контуров не изменялись. +[Операционная инструкция](source-export-catalog-operations.md), +[исходное задание](source-data-export-api-spec.md). + +## Выполненные проверки + +| Проверка | Фактический результат | +| --- | --- | +| Полный pytest backend с opt-in transport load | 2078 passed, 47 skipped, 13 warnings | +| После финальных guards: новый + legacy экспорт на SQLite | 59 passed | +| Новый каталог и конкурентный native POST на PostgreSQL 15.19 | 35 passed | +| Полный migration graph на изолированном PostgreSQL | PASS; новые 5 таблиц, schedule disabled | +| Migration drift `makemigrations --check --dry-run` | Нет изменений | +| Canonical OpenAPI generation и `build.mjs --check` | PASS | +| Orval apigen и TypeScript type-check, включая union ticket selectors | PASS | +| Generated Zod — новые фактические ответы API | 5 passed без потери полей | +| Generated Zod — прежние runtime fixtures | 48 passed | +| Ruff / Black затронутых Python-файлов, Django check | PASS | +| Compose dev `config --quiet`, `git diff --check` | PASS | + +Полный прогон предшествовал двум финальным guard tests; затем они и весь новый каталог +повторно проверены targeted SQLite/PostgreSQL прогонами. Skipped не считаются PASS. +PostgreSQL integration tests пропускаются в основном SQLite-прогоне и выполнены отдельно. +Первый PostgreSQL прогон выявил закрытие outer TestCase transaction тестовым helper при +ручном `response.close()`; helper исправлен по стандартному test-client signal handling, +повторный прогон прошёл. Production connection handling этим исправлением не менялся. + +На PostgreSQL два одновременно отправленных form POST одного ticket дали ровно 200/410. +Отдельный тест реальным SQL и независимым connection проверил продление stream lease и +обнаружение его потери. Только timer этого теста ускорен; DB checks не подменяются mocks. +PostgreSQL запускался в отдельном временном локальном контейнере, привязанном к loopback. + +## Синтетический snapshot + +- source_group: `government_procurements` +- generation_id: `8c4f4096-14c9-4256-9dcb-0e209b7b493e` +- records: 3; fixture содержит 2024, 2025, 2026 годы +- части: 2; варианты XLSX/CSV/JSON одной части содержат одинаковые UID +- registry/adapters: все 22 группы и все зарегистрированные подисточники +- финансовые строки: fixture 2022 и 2023, JSON-only без fallback +- pagination/ZIP: отдельный тест с 51 частью проверяет обе страницы и весь архив + +Данные синтетические; capability tokens в этот отчёт не включены. + +## Локальный transport load + +Фактически обработаны 5905582210 bytes ZIP64 (5.5 GiB плюс framing), +одновременно два file reader по 536870912 bytes. +Рост peak RSS всего тестового процесса: 13631488 bytes. +Catalog samples: 57; p95 0.000748 seconds. +Источник — sparse synthetic binary, полный ZIP не сохраняется на диск или в RAM. +Это не измерение сети, браузера, proxy или предметного full-history build. + +## Осталось для приёмки контура + +Реальный all-history объём/время и capacity; persistent volume на контуре; +через-origin native browser flow и proxy buffering/timeouts; реальные HTTP p95/RSS, +alerts/log ingestion и включение nightly/autobuild после проверки capacity. +Новые runtime migrations, build и deployment на dev-сервере этим локальным прогоном +не выполнялись. Фронт не подключался; его файлы не изменялись. diff --git a/docs/source-record-export-matrix-ru.md b/docs/source-record-export-matrix-ru.md index c2bff0a..bed01d7 100644 --- a/docs/source-record-export-matrix-ru.md +++ b/docs/source-record-export-matrix-ru.md @@ -1,5 +1,8 @@ # Матрица файловых выгрузок источников +Новый каталог `all_available` описан отдельно: [контракт и эксплуатация](source-export-catalog-operations.md). Эта страница сохраняет описание прежнего scope. + + ## Пользовательский контракт Frontend отправляет администраторский diff --git a/src/apps/parsers/tasks_registry_snapshots.py b/src/apps/parsers/tasks_registry_snapshots.py index d5099fd..fa02aca 100644 --- a/src/apps/parsers/tasks_registry_snapshots.py +++ b/src/apps/parsers/tasks_registry_snapshots.py @@ -15,6 +15,7 @@ from apps.parsers.registry_snapshots import SnapshotValidationError from apps.parsers.services import ParserLoadLogService from apps.parsers.sme_support import SME_SOURCE, refresh_sme_support from celery import shared_task +from django.conf import settings from django.db import transaction from django.utils import timezone @@ -26,6 +27,10 @@ def _refresh_published_exports() -> None: try: refresh_source_record_export_artifacts.delay() + if settings.SOURCE_EXPORT_AUTOBUILD: + from organizations.tasks import refresh_source_export_catalog + + refresh_source_export_catalog.delay() except Exception as exc: # Publication already committed; export readiness remains separately visible. logger.error("Published source export enqueue failed (%s)", type(exc).__name__) diff --git a/src/core/openapi.json b/src/core/openapi.json index 056da6e..a7a9de0 100644 --- a/src/core/openapi.json +++ b/src/core/openapi.json @@ -9829,67 +9829,444 @@ }, "parameters": [] }, + "/api/v2/organization-source-records/export-catalog/": { + "get": { + "operationId": "v2_organization_source_records_export_catalog_list", + "description": "Read-only flat API for source records across source extensions.", + "parameters": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportCatalogResponse" + } + } + } + }, + "400": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "401": { + "description": "Authentication required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportAuthenticationError" + } + } + } + }, + "403": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "404": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "409": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "410": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "429": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "500": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "503": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + } + }, + "tags": [ + "Организации" + ] + }, + "parameters": [] + }, + "/api/v2/organization-source-records/export-catalog/{source_group}/": { + "get": { + "operationId": "v2_organization_source_records_export_catalog_read", + "description": "Read-only flat API for source records across source extensions.", + "parameters": [ + { + "name": "source_group", + "in": "path", + "required": true, + "schema": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + } + }, + { + "name": "generation_id", + "in": "query", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "page", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "default": 1 + } + }, + { + "name": "page_size", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportSourceDetailResponse" + } + } + } + }, + "400": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "401": { + "description": "Authentication required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportAuthenticationError" + } + } + } + }, + "403": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "404": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "409": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "410": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "429": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "500": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "503": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + } + }, + "tags": [ + "Организации" + ] + }, + "parameters": [ + { + "name": "source_group", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, "/api/v2/organization-source-records/export-download/": { "post": { "operationId": "v2_organization_source_records_export_download", "summary": "Скачать готовые записи источников по ticket", "description": "Read-only flat API for source records across source extensions.", "requestBody": { + "required": true, "content": { "application/x-www-form-urlencoded": { "schema": { - "type": "object", - "properties": { - "ticket": { - "type": "string" - } - }, - "required": [ - "ticket" - ] + "$ref": "#/components/schemas/SourceRecordExportDownloadRequest" } } - }, - "required": true + } }, "responses": { "200": { - "description": "Потоковый ZIP-архив записей источников.", + "description": "Pinned artifact or streaming ZIP64", "content": { "application/zip": { "schema": { "type": "string", "format": "binary" } + }, + "application/json": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "text/csv": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "schema": { + "type": "string", + "format": "binary" + } } } }, "400": { - "description": "", + "description": "Legacy or all-available export failure", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SourceRecordExportInvalidTicket" + "oneOf": [ + { + "$ref": "#/components/schemas/SourceRecordExportInvalidTicket" + }, + { + "$ref": "#/components/schemas/SourceExportError" + } + ] + } + } + } + }, + "403": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "404": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "409": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" } } } }, "410": { - "description": "", + "description": "Legacy or all-available export failure", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SourceRecordExportTicketExpired" + "oneOf": [ + { + "$ref": "#/components/schemas/SourceRecordExportTicketExpired" + }, + { + "$ref": "#/components/schemas/SourceExportError" + } + ] + } + } + } + }, + "429": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "500": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" } } } }, "503": { - "description": "", + "description": "Legacy or all-available export failure", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SourceRecordExportUnavailable" + "oneOf": [ + { + "$ref": "#/components/schemas/SourceRecordExportUnavailable" + }, + { + "$ref": "#/components/schemas/SourceExportError" + } + ] } } } @@ -9907,31 +10284,129 @@ "summary": "Подготовить нативное скачивание записей источников", "description": "Возвращает короткоживущий одноразовый ticket. Frontend отправляет его обычной HTML-формой в export-download, чтобы браузер сохранял потоковый ZIP напрямую на диск без Blob в JavaScript.", "requestBody": { - "$ref": "#/components/requestBodies/OrganizationSourceRecordExportRequest" + "required": true, + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/OrganizationSourceRecordExportRequest" + }, + { + "$ref": "#/components/schemas/SourceExportFileTicketRequest" + }, + { + "$ref": "#/components/schemas/SourceExportArchiveTicketRequest" + } + ] + } + } + } }, "responses": { "201": { - "description": "", + "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SourceRecordExportTicket" + "oneOf": [ + { + "$ref": "#/components/schemas/SourceRecordExportTicket" + }, + { + "$ref": "#/components/schemas/SourceExportSelectionTicket" + } + ] } } } }, "400": { - "description": "Некорректные параметры выгрузки." - }, - "403": { - "description": "Доступ разрешён только администраторам." - }, - "503": { - "description": "", + "description": "Export request failed", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SourceRecordExportUnavailable" + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "401": { + "description": "Authentication required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportAuthenticationError" + } + } + } + }, + "403": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "404": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "409": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "410": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "429": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "500": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" + } + } + } + }, + "503": { + "description": "Export request failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SourceExportError" } } } @@ -18736,211 +19211,6 @@ } } }, - "SourceRecordExportInvalidTicket": { - "required": [ - "detail", - "code" - ], - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "string", - "minLength": 1 - }, - "code": { - "title": "Code", - "type": "string", - "enum": [ - "invalid_ticket" - ] - } - } - }, - "SourceRecordExportTicketExpired": { - "required": [ - "detail", - "code" - ], - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "string", - "minLength": 1 - }, - "code": { - "title": "Code", - "type": "string", - "enum": [ - "ticket_expired" - ] - } - } - }, - "SourceRecordExportUnavailable": { - "required": [ - "detail", - "code" - ], - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "string", - "minLength": 1 - }, - "code": { - "title": "Code", - "type": "string", - "enum": [ - "source_export_not_ready", - "source_export_ticket_unavailable" - ] - } - } - }, - "OrganizationSourceRecordExportRequest": { - "required": [ - "sources", - "format" - ], - "type": "object", - "properties": { - "sources": { - "type": "array", - "items": { - "type": "string", - "enum": [ - "financial_indicators", - "government_procurements", - "industrial_production", - "planned_inspections", - "bankruptcy", - "defense_suppliers", - "arbitration", - "security_registries", - "vacancies", - "electronic_document_exchange", - "media_mentions", - "sanctions", - "government_support", - "sro_membership", - "budget_process_registry", - "integrated_structure_documents", - "fedresurs_company_profile", - "enforcement_proceedings", - "stock_exchange_activity", - "leasing", - "company_messages", - "company_licenses" - ] - } - }, - "format": { - "title": "Format", - "type": "string", - "enum": [ - "csv", - "xlsx", - "json" - ] - } - } - }, - "SourceRecordExportTicket": { - "required": [ - "ticket", - "expires_in", - "file_name" - ], - "type": "object", - "properties": { - "ticket": { - "title": "Ticket", - "type": "string", - "minLength": 1 - }, - "expires_in": { - "title": "Expires in", - "type": "integer", - "minimum": 1 - }, - "file_name": { - "title": "File name", - "type": "string", - "minLength": 1 - } - } - }, - "SourceRecordFilterOption": { - "required": [ - "value", - "label", - "records_count" - ], - "type": "object", - "properties": { - "value": { - "title": "Value", - "type": "string", - "minLength": 1 - }, - "label": { - "title": "Label", - "type": "string", - "minLength": 1 - }, - "records_count": { - "title": "Records count", - "type": "integer", - "minimum": 0 - } - } - }, - "SourceRecordFilterOptionsMeta": { - "required": [ - "total_count" - ], - "type": "object", - "properties": { - "total_count": { - "title": "Total count", - "type": "integer", - "minimum": 0 - } - } - }, - "SourceRecordFilterOptionsResponse": { - "required": [ - "success", - "data", - "errors", - "meta" - ], - "type": "object", - "properties": { - "success": { - "title": "Success", - "type": "boolean" - }, - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SourceRecordFilterOption" - } - }, - "errors": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SourceRecordError" - } - }, - "meta": { - "$ref": "#/components/schemas/SourceRecordFilterOptionsMeta" - } - } - }, "OrganizationSourceRecordDetailPayload": { "type": "object", "properties": { @@ -19460,6 +19730,213 @@ }, "description": "Published source record. source_group selects the variant; record_type and source are fixed within each registry variant." }, + "SourceRecordExportInvalidTicket": { + "required": [ + "detail", + "code" + ], + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "string", + "minLength": 1 + }, + "code": { + "title": "Code", + "type": "string", + "enum": [ + "invalid_ticket" + ] + } + } + }, + "SourceRecordExportTicketExpired": { + "required": [ + "detail", + "code" + ], + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "string", + "minLength": 1 + }, + "code": { + "title": "Code", + "type": "string", + "enum": [ + "ticket_expired" + ] + } + } + }, + "SourceRecordExportUnavailable": { + "required": [ + "detail", + "code" + ], + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "string", + "minLength": 1 + }, + "code": { + "title": "Code", + "type": "string", + "enum": [ + "source_export_not_ready", + "source_export_ticket_unavailable" + ] + } + } + }, + "OrganizationSourceRecordExportRequest": { + "required": [ + "sources", + "format" + ], + "type": "object", + "properties": { + "sources": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + } + }, + "format": { + "title": "Format", + "type": "string", + "enum": [ + "csv", + "xlsx", + "json" + ] + } + }, + "additionalProperties": false + }, + "SourceRecordExportTicket": { + "required": [ + "ticket", + "expires_in", + "file_name" + ], + "type": "object", + "properties": { + "ticket": { + "title": "Ticket", + "type": "string", + "minLength": 1 + }, + "expires_in": { + "title": "Expires in", + "type": "integer", + "minimum": 1 + }, + "file_name": { + "title": "File name", + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "SourceRecordFilterOption": { + "required": [ + "value", + "label", + "records_count" + ], + "type": "object", + "properties": { + "value": { + "title": "Value", + "type": "string", + "minLength": 1 + }, + "label": { + "title": "Label", + "type": "string", + "minLength": 1 + }, + "records_count": { + "title": "Records count", + "type": "integer", + "minimum": 0 + } + } + }, + "SourceRecordFilterOptionsMeta": { + "required": [ + "total_count" + ], + "type": "object", + "properties": { + "total_count": { + "title": "Total count", + "type": "integer", + "minimum": 0 + } + } + }, + "SourceRecordFilterOptionsResponse": { + "required": [ + "success", + "data", + "errors", + "meta" + ], + "type": "object", + "properties": { + "success": { + "title": "Success", + "type": "boolean" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SourceRecordFilterOption" + } + }, + "errors": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SourceRecordError" + } + }, + "meta": { + "$ref": "#/components/schemas/SourceRecordFilterOptionsMeta" + } + } + }, "OrganizationSourceExtension": { "type": "object", "properties": { @@ -24814,6 +25291,865 @@ } } } + }, + "SourceExportBuildSummary": { + "type": "object", + "additionalProperties": false, + "properties": { + "state": { + "type": "string", + "enum": [ + "idle", + "queued", + "running", + "success", + "failed" + ] + }, + "started_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "finished_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "error_code": { + "type": "string", + "nullable": true + } + }, + "required": [ + "state", + "started_at", + "finished_at", + "error_code" + ] + }, + "SourceExportSourceSummary": { + "type": "object", + "additionalProperties": false, + "properties": { + "source_group": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + }, + "generation_id": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "state": { + "type": "string", + "enum": [ + "ready", + "empty", + "not_ready", + "building", + "unavailable" + ] + }, + "unavailable_reason": { + "type": "string", + "enum": [ + "disabled", + "adapter_missing", + "build_failed", + "storage_unavailable" + ], + "nullable": true + }, + "generated_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "data_as_of": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "data_scope": { + "type": "string", + "enum": [ + "all_available" + ] + }, + "source_slug": { + "type": "string" + }, + "title": { + "type": "string" + }, + "order": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "export_enabled": { + "type": "boolean" + }, + "records_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "nullable": true + }, + "parts_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "nullable": true + }, + "supported_formats": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ] + }, + "uniqueItems": true + }, + "default_format": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ], + "nullable": true + }, + "is_stale": { + "type": "boolean" + }, + "last_build": { + "$ref": "#/components/schemas/SourceExportBuildSummary" + } + }, + "required": [ + "source_group", + "generation_id", + "state", + "unavailable_reason", + "generated_at", + "data_as_of", + "data_scope", + "source_slug", + "title", + "order", + "export_enabled", + "records_count", + "parts_count", + "supported_formats", + "default_format", + "is_stale", + "last_build" + ] + }, + "SourceExportCatalogResponse": { + "type": "object", + "additionalProperties": false, + "properties": { + "success": { + "type": "boolean", + "enum": [ + true + ] + }, + "data": { + "type": "object", + "additionalProperties": false, + "properties": { + "schema_version": { + "type": "string", + "enum": [ + "1" + ] + }, + "catalog_revision": { + "type": "string" + }, + "sources": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SourceExportSourceSummary" + } + } + }, + "required": [ + "schema_version", + "catalog_revision", + "sources" + ] + }, + "errors": { + "type": "object", + "nullable": true, + "enum": [ + null + ] + }, + "meta": { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + }, + "required": [ + "success", + "data", + "errors", + "meta" + ] + }, + "SourceExportDescription": { + "type": "object", + "additionalProperties": false, + "properties": { + "composition": { + "type": "string" + }, + "origin": { + "type": "string" + }, + "fields": { + "type": "string" + }, + "example_dataset_key": { + "type": "string", + "nullable": true + }, + "example_is_synthetic": { + "type": "boolean" + }, + "example_record": { + "type": "object", + "additionalProperties": true, + "nullable": true + } + }, + "required": [ + "composition", + "origin", + "fields", + "example_dataset_key", + "example_is_synthetic", + "example_record" + ] + }, + "SourceExportDataset": { + "type": "object", + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "export_schema_version": { + "type": "string" + }, + "records_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "parts_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "key", + "title", + "export_schema_version", + "records_count", + "parts_count" + ] + }, + "SourceExportArtifact": { + "type": "object", + "additionalProperties": false, + "properties": { + "artifact_id": { + "type": "string", + "format": "uuid" + }, + "format": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ] + }, + "file_name": { + "type": "string", + "pattern": "^[A-Za-z0-9._-]+$" + }, + "mime_type": { + "type": "string" + }, + "size_bytes": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + }, + "required": [ + "artifact_id", + "format", + "file_name", + "mime_type", + "size_bytes", + "sha256" + ] + }, + "SourceExportPart": { + "type": "object", + "additionalProperties": false, + "properties": { + "part_id": { + "type": "string", + "format": "uuid" + }, + "dataset_key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "part_number": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "parts_count": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "records_count": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "default_format": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ] + }, + "variants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SourceExportArtifact" + }, + "minItems": 1 + } + }, + "required": [ + "part_id", + "dataset_key", + "title", + "part_number", + "parts_count", + "records_count", + "default_format", + "variants" + ] + }, + "SourceExportPagination": { + "type": "object", + "additionalProperties": false, + "properties": { + "page": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "page_size": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "total_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "total_pages": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + "has_next": { + "type": "boolean" + }, + "has_previous": { + "type": "boolean" + } + }, + "required": [ + "page", + "page_size", + "total_count", + "total_pages", + "has_next", + "has_previous" + ] + }, + "SourceExportSourceDetail": { + "type": "object", + "additionalProperties": false, + "properties": { + "source_group": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + }, + "generation_id": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "state": { + "type": "string", + "enum": [ + "ready", + "empty", + "not_ready", + "building", + "unavailable" + ] + }, + "unavailable_reason": { + "type": "string", + "enum": [ + "disabled", + "adapter_missing", + "build_failed", + "storage_unavailable" + ], + "nullable": true + }, + "generated_at": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "data_as_of": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "data_scope": { + "type": "string", + "enum": [ + "all_available" + ] + }, + "current_generation_id": { + "type": "string", + "format": "uuid", + "nullable": true + }, + "description": { + "$ref": "#/components/schemas/SourceExportDescription" + }, + "datasets": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SourceExportDataset" + } + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SourceExportPart" + } + } + }, + "required": [ + "source_group", + "generation_id", + "state", + "unavailable_reason", + "generated_at", + "data_as_of", + "data_scope", + "current_generation_id", + "description", + "datasets", + "files" + ] + }, + "SourceExportSourceDetailResponse": { + "type": "object", + "additionalProperties": false, + "properties": { + "success": { + "type": "boolean", + "enum": [ + true + ] + }, + "data": { + "$ref": "#/components/schemas/SourceExportSourceDetail" + }, + "errors": { + "type": "object", + "nullable": true, + "enum": [ + null + ] + }, + "meta": { + "type": "object", + "additionalProperties": false, + "properties": { + "pagination": { + "$ref": "#/components/schemas/SourceExportPagination" + } + }, + "required": [ + "pagination" + ] + } + }, + "required": [ + "success", + "data", + "errors", + "meta" + ] + }, + "SourceExportAuthenticationError": { + "type": "object", + "additionalProperties": false, + "properties": { + "detail": { + "type": "string" + } + }, + "required": [ + "detail" + ] + }, + "SourceExportError": { + "type": "object", + "additionalProperties": false, + "properties": { + "detail": { + "type": "string" + }, + "code": { + "type": "string" + }, + "field": { + "type": "string", + "nullable": true + }, + "retryable": { + "type": "boolean" + }, + "request_id": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "detail", + "code", + "field", + "retryable", + "request_id" + ] + }, + "SourceExportFileTicketRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "selection_kind": { + "type": "string", + "enum": [ + "file" + ] + }, + "source_group": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + }, + "generation_id": { + "type": "string", + "format": "uuid" + }, + "part_id": { + "type": "string", + "format": "uuid" + }, + "format": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ] + } + }, + "required": [ + "selection_kind", + "source_group", + "generation_id", + "part_id", + "format" + ] + }, + "SourceExportArchiveTicketRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "selection_kind": { + "type": "string", + "enum": [ + "source_archive" + ] + }, + "source_group": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + }, + "generation_id": { + "type": "string", + "format": "uuid" + }, + "format": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ] + } + }, + "required": [ + "selection_kind", + "source_group", + "generation_id", + "format" + ] + }, + "SourceExportSelectionTicket": { + "type": "object", + "additionalProperties": false, + "properties": { + "ticket": { + "type": "string", + "minLength": 47, + "maxLength": 47 + }, + "file_name": { + "type": "string" + }, + "expires_in": { + "type": "integer", + "enum": [ + 300 + ] + }, + "selection_kind": { + "type": "string", + "enum": [ + "file", + "source_archive" + ] + }, + "source_group": { + "type": "string", + "enum": [ + "financial_indicators", + "government_procurements", + "industrial_production", + "planned_inspections", + "bankruptcy", + "defense_suppliers", + "arbitration", + "security_registries", + "vacancies", + "electronic_document_exchange", + "media_mentions", + "sanctions", + "government_support", + "sro_membership", + "budget_process_registry", + "integrated_structure_documents", + "fedresurs_company_profile", + "enforcement_proceedings", + "stock_exchange_activity", + "leasing", + "company_messages", + "company_licenses" + ] + }, + "generation_id": { + "type": "string", + "format": "uuid" + }, + "format": { + "type": "string", + "enum": [ + "xlsx", + "csv", + "json" + ] + }, + "mime_type": { + "type": "string" + }, + "size_bytes": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "nullable": true + }, + "parts_count": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + }, + "required": [ + "ticket", + "file_name", + "expires_in", + "selection_kind", + "source_group", + "generation_id", + "format", + "mime_type", + "size_bytes", + "parts_count" + ] + }, + "SourceRecordExportDownloadRequest": { + "type": "object", + "additionalProperties": false, + "properties": { + "ticket": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "required": [ + "ticket" + ] } } } diff --git a/src/organizations/management/commands/build_source_export_catalog.py b/src/organizations/management/commands/build_source_export_catalog.py new file mode 100644 index 0000000..b5bd3e3 --- /dev/null +++ b/src/organizations/management/commands/build_source_export_catalog.py @@ -0,0 +1,47 @@ +"""Prepare new all-available export generations without changing annual exports.""" +from django.core.management.base import BaseCommand, CommandError + +from organizations.models import SourceExportGeneration +from organizations.source_export_catalog import ( + build_source, + cleanup, + registry, + verify_generation, +) + + +class Command(BaseCommand): + help = "Собрать all_available каталог и файлы существующих источников" + + def add_arguments(self, parser): + parser.add_argument("--source-group", choices=list(registry())) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--cleanup-only", action="store_true") + modes.add_argument("--verify-only", action="store_true") + + def handle(self, *args, **options): + failed = [] + for group, entry in registry().items(): + if ( + options["source_group"] and options["source_group"] != group + ) or not entry["export_enabled"]: + continue + try: + if options["verify_only"]: + for generation in SourceExportGeneration.objects.filter( + source_group=group, deleted_at=None + ).iterator(): + if not verify_generation(generation): + raise CommandError("Artifact integrity failure") + elif not options["cleanup_only"]: + generation = build_source(group) + self.stdout.write( + f"{group}: {generation.pk} records={generation.manifest['records_count']}" + ) + if not options["verify_only"]: + cleanup(group) + except Exception as exc: + failed.append(group) + self.stderr.write(f"{group}: failed ({type(exc).__name__})") + if failed: + raise CommandError("Export groups failed: " + ", ".join(failed)) diff --git a/src/organizations/migrations/0019_source_export_catalog.py b/src/organizations/migrations/0019_source_export_catalog.py new file mode 100644 index 0000000..9e8e3a6 --- /dev/null +++ b/src/organizations/migrations/0019_source_export_catalog.py @@ -0,0 +1,103 @@ +# Generated by Django 3.2.25 on 2026-10-22 19:05 + +import uuid + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("organizations", "0018_stock_exchange_activity"), + ] + + operations = [ + migrations.CreateModel( + name="SourceExportGeneration", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ("source_group", models.CharField(db_index=True, max_length=64)), + ("manifest", models.JSONField(default=dict)), + ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)), + ("deleted_at", models.DateTimeField(null=True)), + ("storage_available", models.BooleanField(default=True)), + ("data_revision", models.CharField(max_length=64)), + ], + ), + migrations.CreateModel( + name="SourceExportLease", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ("issuer_id", models.CharField(db_index=True, max_length=128)), + ("kind", models.CharField(default="ticket", max_length=8)), + ("expires_at", models.DateTimeField(db_index=True)), + ( + "generation", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="organizations.sourceexportgeneration", + ), + ), + ], + ), + migrations.CreateModel( + name="SourceExportLimiter", + fields=[ + ( + "key", + models.CharField(max_length=180, primary_key=True, serialize=False), + ), + ("window", models.BigIntegerField(default=0)), + ("count", models.PositiveIntegerField(default=0)), + ], + ), + migrations.CreateModel( + name="SourceExportState", + fields=[ + ( + "source_group", + models.CharField(max_length=64, primary_key=True, serialize=False), + ), + ("current_generation", models.UUIDField(null=True)), + ("last_build", models.JSONField(default=dict)), + ("lock_owner", models.UUIDField(null=True)), + ("lock_expires_at", models.DateTimeField(null=True)), + ], + ), + migrations.CreateModel( + name="SourceExportTicket", + fields=[ + ( + "token_hash", + models.CharField(max_length=64, primary_key=True, serialize=False), + ), + ("selection", models.JSONField()), + ("expires_at", models.DateTimeField(db_index=True)), + ("consumed_at", models.DateTimeField(null=True)), + ( + "lease", + models.OneToOneField( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to="organizations.sourceexportlease", + ), + ), + ], + ), + ] diff --git a/src/organizations/migrations/0020_source_export_catalog_schedule.py b/src/organizations/migrations/0020_source_export_catalog_schedule.py new file mode 100644 index 0000000..43bb142 --- /dev/null +++ b/src/organizations/migrations/0020_source_export_catalog_schedule.py @@ -0,0 +1,40 @@ +"""Register an opt-in schedule; capacity/shared-volume acceptance precedes enablement.""" +from django.db import migrations + +NAME = "organizations:source-export-catalog:nightly-msk" + + +def seed(apps, schema_editor): + Cron = apps.get_model("django_celery_beat", "CrontabSchedule") + Task = apps.get_model("django_celery_beat", "PeriodicTask") + cron, _ = Cron.objects.get_or_create( + minute="30", + hour="6", + day_of_week="*", + day_of_month="*", + month_of_year="*", + timezone="Europe/Moscow", + ) + Task.objects.get_or_create( + name=NAME, + defaults={ + "task": "organizations.tasks.refresh_source_export_catalog", + "crontab": cron, + "enabled": False, + "description": "Enable after all-available storage capacity and shared-volume acceptance.", + }, + ) + + +def remove(apps, schema_editor): + apps.get_model("django_celery_beat", "PeriodicTask").objects.filter( + name=NAME + ).delete() + + +class Migration(migrations.Migration): + dependencies = [ + ("organizations", "0019_source_export_catalog"), + ("django_celery_beat", "0018_improve_crontab_helptext"), + ] + operations = [migrations.RunPython(seed, reverse_code=remove)] diff --git a/src/organizations/models.py b/src/organizations/models.py index 7885de3..486f5ac 100644 --- a/src/organizations/models.py +++ b/src/organizations/models.py @@ -1083,3 +1083,70 @@ class StockExchangeActivityExtension(OrganizationSourceExtension): db_table = "organizations_stock_exchange_activity_extension" verbose_name = _("биржевая активность") verbose_name_plural = _("биржевая активность") + + +class SourceExportState(models.Model): + """Current pointer and renewable owner lock for one all-available source.""" + + def __str__(self): + return "SourceExportState" + + source_group = models.CharField(max_length=64, primary_key=True) + current_generation = models.UUIDField(null=True) + last_build = models.JSONField(default=dict) + lock_owner = models.UUIDField(null=True) + lock_expires_at = models.DateTimeField(null=True) + + +class SourceExportGeneration(models.Model): + """Immutable public metadata; deleted_at retains generation tombstones.""" + + def __str__(self): + return "SourceExportGeneration" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + source_group = models.CharField(max_length=64, db_index=True) + manifest = models.JSONField(default=dict) + created_at = models.DateTimeField(auto_now_add=True, db_index=True) + deleted_at = models.DateTimeField(null=True) + storage_available = models.BooleanField(default=True) + data_revision = models.CharField(max_length=64) + + +class SourceExportLease(models.Model): + """Ticket/stream retention protection, shared by worker and web processes.""" + + def __str__(self): + return "SourceExportLease" + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + generation = models.ForeignKey(SourceExportGeneration, on_delete=models.CASCADE) + issuer_id = models.CharField(max_length=128, db_index=True) + kind = models.CharField(max_length=8, default="ticket") + expires_at = models.DateTimeField(db_index=True) + + +class SourceExportTicket(models.Model): + """Only a SHA-256 token digest is persisted; claim uses a conditional update.""" + + def __str__(self): + return "SourceExportTicket" + + token_hash = models.CharField(max_length=64, primary_key=True) + lease = models.OneToOneField( + SourceExportLease, on_delete=models.SET_NULL, null=True + ) + selection = models.JSONField() + expires_at = models.DateTimeField(db_index=True) + consumed_at = models.DateTimeField(null=True) + + +class SourceExportLimiter(models.Model): + """Shared fixed-window request counter and stream admission mutex.""" + + def __str__(self): + return "SourceExportLimiter" + + key = models.CharField(max_length=180, primary_key=True) + window = models.BigIntegerField(default=0) + count = models.PositiveIntegerField(default=0) diff --git a/src/organizations/source_export_catalog.py b/src/organizations/source_export_catalog.py new file mode 100644 index 0000000..04366bb --- /dev/null +++ b/src/organizations/source_export_catalog.py @@ -0,0 +1,1202 @@ +"""All-available export metadata, bounded builds and pinned native downloads. + +Annual export storage and tickets deliberately keep their existing contract. +Public metadata lives in the database; binary artifacts live on a private shared +volume, never under MEDIA_ROOT. All deletion and ticket/stream admission serialize +on the generation row. No records or artifact bytes are read by metadata GETs. +""" +from __future__ import annotations + +import hashlib +import json +import logging +import math +import os +import re +import secrets +import shutil +import threading +import time +import zipfile +from contextlib import ExitStack, contextmanager, suppress +from datetime import UTC, timedelta +from pathlib import Path +from typing import BinaryIO, cast +from uuid import UUID, uuid4 + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.db import close_old_connections, connection, transaction +from django.db.models import Prefetch, Q +from django.http import StreamingHttpResponse +from django.utils import timezone + +from organizations.models import ( + OrganizationSourceFinancialLine, + OrganizationSourceRecord, + SourceExportGeneration, + SourceExportLease, + SourceExportLimiter, + SourceExportState, + SourceExportTicket, + SourceGroup, +) +from organizations.source_cache import get_source_data_cache_version +from organizations.source_groups import SOURCE_GROUP_DESCRIPTORS +from organizations.source_record_export import ( + FINANCIAL_SOURCE_GROUP, + ORGANIZATION_EXPORT_FIELDS, + SANCTIONS_EXPORT_FIELDS, + SANCTIONS_XLSX_HEADERS, + SOURCE_GROUP_EXPORT_FILE_STEMS, + SOURCE_RECORD_EXPORT_FIELDS, + _build_record_row, + _iter_spooled_rows, + _render_source_group_artifact, + _resolve_export_directory, + _source_export_read_snapshot, + _StreamingZipSink, +) + +logger = logging.getLogger(__name__) +MIMES = { + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "csv": "text/csv; charset=utf-8", + "json": "application/json; charset=utf-8", +} +FORMATS = ("xlsx", "csv", "json") +IDLE_BUILD = { + "state": "idle", + "started_at": None, + "finished_at": None, + "error_code": None, +} +CHUNK_SIZE = 1024 * 1024 +HEARTBEAT_RENEW_SECONDS = 30 +TICKET_PATTERN = re.compile(r"se1_[A-Za-z0-9_-]{43}") + + +class ExportError(Exception): + def __init__(self, code, status=400, field=None): + self.code = f"source_export_{code}" + self.status = status + self.field = field + self.retryable = code in { + "not_ready", + "rate_limited", + "metadata_unavailable", + "ticket_unavailable", + "artifact_unavailable", + } + super().__init__(self.code) + + +def _timestamp(value=None): + return (value or timezone.now()).astimezone(UTC).isoformat().replace("+00:00", "Z") + + +def _limit(name, default): + return max(1, int(getattr(settings, f"SOURCE_EXPORT_{name}", default))) + + +def registry(): + # Importing definitions does not execute their database-backed card service. + from apps.parsers.source_cards import SOURCE_CARD_DEFINITIONS + + by_slug = {card.slug: card for card in SOURCE_CARD_DEFINITIONS} + result = {} + for order, (group, stem) in enumerate(SOURCE_GROUP_EXPORT_FILE_STEMS.items(), 1): + card = by_slug.get(stem) + descriptors = [ + d for d in SOURCE_GROUP_DESCRIPTORS.values() if d.source_group == group + ] + result[group] = { + "source_group": group, + "source_slug": stem, + "title": card.title if card else str(SourceGroup(group).label), + "order": card.order if card else order * 10, + "export_enabled": group + not in getattr(settings, "SOURCE_EXPORT_DISABLED_GROUPS", ()), + "composition": card.description if card else str(SourceGroup(group).label), + "origin": "Опубликованные канонические записи системы: " + + ", ".join(sorted({d.source for d in descriptors})), + } + return dict(sorted(result.items(), key=lambda item: item[1]["order"])) + + +def _entry(group): + try: + return registry()[group] + except KeyError: + raise ExportError("source_not_found", 404, "source_group") from None + + +def _root(): + root = ( + Path( + getattr( + settings, + "SOURCE_EXPORT_DIRECTORY", + _resolve_export_directory(None).parent / "private-source-exports", + ) + ).resolve() + / "all-available" + ) + media = Path(settings.MEDIA_ROOT).resolve() + if root.resolve() == media or media in root.resolve().parents: + raise ExportError("artifact_unavailable", 503) + return root + + +def _directory(generation): + return _root() / generation.source_group / "generations" / str(generation.pk) + + +def _json_bytes(value): + return json.dumps( + value, ensure_ascii=False, separators=(",", ":"), sort_keys=True + ).encode("utf-8") + + +def rate_limit(user_id, kind): + maximum = _limit( + "METADATA_RATE" if kind == "metadata" else "TICKET_RATE", + 120 if kind == "metadata" else 30, + ) + key = f"{kind}:{user_id}" + window = int(time.time()) // 60 + with transaction.atomic(): + SourceExportLimiter.objects.get_or_create(key=key) + row = SourceExportLimiter.objects.select_for_update().get(pk=key) + count = row.count if row.window == window else 0 + if count >= maximum: + raise ExportError("rate_limited", 429) + row.window, row.count = window, count + 1 + row.save(update_fields=["window", "count"]) + + +def summary(entry, state=None, generation=None, revision=None): + manifest = generation.manifest if generation and not generation.deleted_at else None + build = state.last_build if state and state.last_build else dict(IDLE_BUILD) + reason = None + if not entry["export_enabled"]: + status, reason = "unavailable", "disabled" + elif generation and not generation.storage_available: + status, reason = "unavailable", "storage_unavailable" + elif manifest: + status = "ready" if manifest["records_count"] else "empty" + elif build["state"] == "failed": + status, reason = "unavailable", "build_failed" + else: + status = "building" if build["state"] in {"running", "queued"} else "not_ready" + formats = manifest["supported_formats"] if manifest else [] + stale = bool( + manifest + and ( + build["state"] == "failed" + or generation.created_at < timezone.now() - timedelta(hours=36) + or generation.data_revision + != (revision if revision is not None else get_source_data_cache_version()) + ) + ) + return { + **{ + key: entry[key] + for key in ( + "source_group", + "source_slug", + "title", + "order", + "export_enabled", + ) + }, + "state": status, + "unavailable_reason": reason, + "generation_id": str(generation.pk) if manifest else None, + "generated_at": manifest["generated_at"] if manifest else None, + "data_as_of": manifest["data_as_of"] if manifest else None, + "data_scope": "all_available", + "records_count": manifest["records_count"] if manifest else None, + "parts_count": len(manifest["parts"]) if manifest else None, + "supported_formats": formats, + "default_format": formats[0] if formats else None, + "is_stale": stale, + "last_build": build, + } + + +def catalog(): + states = {s.pk: s for s in SourceExportState.objects.all()} + generations = { + str(g.pk): g + for g in SourceExportGeneration.objects.filter( + id__in=[ + s.current_generation for s in states.values() if s.current_generation + ] + ) + } + entries = registry() + revision = get_source_data_cache_version() + sources = [ + summary( + entry, + states.get(group), + generations.get(str(states[group].current_generation)) + if group in states + else None, + revision, + ) + for group, entry in entries.items() + ] + # is_stale may change solely with age; revision tracks actual persisted metadata. + persisted = [{k: v for k, v in item.items() if k != "is_stale"} for item in sources] + return { + "schema_version": "1", + "catalog_revision": hashlib.sha256(_json_bytes(persisted)).hexdigest(), + "sources": sources, + } + + +def _uuid(value, field): + try: + return UUID(str(value)) + except (ValueError, TypeError, AttributeError): + raise ExportError("invalid_request", field=field) from None + + +def get_generation(group, generation_id): + uid = _uuid(generation_id, "generation_id") + generation = SourceExportGeneration.objects.filter( + pk=uid, source_group=group + ).first() + if generation is None: + raise ExportError("part_not_found", 404, "generation_id") + if generation.deleted_at: + raise ExportError("generation_gone", 409, "generation_id") + return generation + + +def detail(group, query): + entry = _entry(group) + if set(query) - {"generation_id", "page", "page_size"} or any( + len(query.getlist(k)) != 1 for k in query + ): + raise ExportError("invalid_request") + try: + page, size = int(query.get("page", 1)), int(query.get("page_size", 50)) + if page < 1 or not 1 <= size <= 200: + raise ValueError + except (ValueError, TypeError): + raise ExportError("invalid_page", field="page") from None + if page > 1 and not query.get("generation_id"): + raise ExportError("invalid_request", field="generation_id") + state = SourceExportState.objects.filter(pk=group).first() + uid = query.get("generation_id") or (state.current_generation if state else None) + generation = get_generation(group, uid) if uid else None + item = summary(entry, state, generation) + manifest = generation.manifest if generation else {} + parts = manifest.get("parts", []) + pages = max(1, math.ceil(len(parts) / size)) + if page > pages: + raise ExportError("invalid_page", field="page") + data = { + key: item[key] + for key in ( + "source_group", + "generation_id", + "state", + "unavailable_reason", + "generated_at", + "data_as_of", + "data_scope", + ) + } + data.update( + { + "current_generation_id": str(state.current_generation) + if state and state.current_generation + else None, + "description": manifest.get("description", _description(entry)), + "datasets": manifest.get("datasets", []), + "files": parts[(page - 1) * size : page * size], + } + ) + return data, { + "page": page, + "page_size": size, + "total_count": len(parts), + "total_pages": pages, + "has_next": page < pages, + "has_previous": page > 1, + } + + +def _description(entry, example=None): + return { + "composition": entry["composition"], + "origin": entry["origin"], + "fields": "; ".join( + [ + *ORGANIZATION_EXPORT_FIELDS, + *SOURCE_RECORD_EXPORT_FIELDS, + "предметные поля источника", + ] + ), + "example_dataset_key": "records" if example else None, + "example_is_synthetic": False, + "example_record": example, + } + + +@contextmanager +def _heartbeat(callback): + """Dedicated connections keep leases alive even while a socket write blocks.""" + stopped, lost = threading.Event(), threading.Event() + + def run(): + close_old_connections() + try: + while not stopped.wait(HEARTBEAT_RENEW_SECONDS): + if not callback(): + lost.set() + return + except Exception: + lost.set() + logger.exception("Export lease renewal failed") + finally: + connection.close() + + # SQLite is the unit-test backend; its in-memory transactions are thread-local. + thread = ( + threading.Thread(target=run, daemon=True) + if connection.vendor != "sqlite" + else None + ) + if thread: + thread.start() + try: + yield lost + finally: + stopped.set() + if thread: + thread.join(timeout=5) + + +def _build_state(group, owner, **values): + return SourceExportState.objects.filter(pk=group, lock_owner=owner).update(**values) + + +@contextmanager +def _build_lock(group): + owner, now = uuid4(), timezone.now() + SourceExportState.objects.get_or_create(source_group=group) + claimed = ( + SourceExportState.objects.filter(pk=group) + .filter(Q(lock_expires_at__lte=now) | Q(lock_owner=None)) + .update( + lock_owner=owner, + lock_expires_at=now + timedelta(minutes=5), + last_build={ + "state": "running", + "started_at": _timestamp(now), + "finished_at": None, + "error_code": None, + }, + ) + ) + if not claimed: + raise ExportError("not_ready", 409) + try: + with _heartbeat( + lambda: _build_state( + group, owner, lock_expires_at=timezone.now() + timedelta(minutes=5) + ) + ) as lost: + yield owner, lost + finally: + _build_state(group, owner, lock_owner=None, lock_expires_at=None) + + +def _spool(group, path): + """Use a disk-backed sort, bounded RAM and one repeatable-read snapshot. + + The canonical table has extension joins, so an external local index is used + instead of an unbounded PostgreSQL ORDER BY over millions of joined rows. + """ + import sqlite3 + + count, headers, example = 0, set(), None + ordered = path.with_suffix(".sqlite3") + db = sqlite3.connect(ordered) + try: + db.execute("PRAGMA journal_mode=OFF") + db.execute("CREATE TABLE rows (source TEXT, kind TEXT, uid TEXT, data TEXT)") + with _source_export_read_snapshot(): + revision = get_source_data_cache_version() + as_of = _timestamp() + queryset = ( + OrganizationSourceRecord.objects.filter(extension__source_group=group) + .select_related("extension", "extension__organization") + .order_by() + ) + if group == FINANCIAL_SOURCE_GROUP: + queryset = queryset.prefetch_related( + Prefetch( + "financial_lines", + queryset=OrganizationSourceFinancialLine.objects.order_by( + "year", "form_code", "line_code", "id" + ), + ) + ) + # iterator() ignores prefetch in Django 3.2; explicitly prefetch batches. + from itertools import islice + + from django.db.models import prefetch_related_objects + + iterator = queryset.iterator(chunk_size=1000) + while batch := list(islice(iterator, 1000)): + if group == FINANCIAL_SOURCE_GROUP: + prefetch_related_objects( + batch, + Prefetch( + "financial_lines", + queryset=OrganizationSourceFinancialLine.objects.order_by( + "year", "form_code", "line_code", "id" + ), + ), + ) + rows = [] + for record in batch: + row = _build_record_row( + record, include_financial_lines=group == FINANCIAL_SOURCE_GROUP + ) + headers.update(key for key in row if key.startswith("payload.")) + encoded = _json_bytes(row).decode("utf-8") + if example is None and len(encoded.encode("utf-8")) <= 32768: + # Example is the actual JSON file projection, including OKPO grouping. + example_row = dict(row) + okpo = example_row.pop("ОКПО", None) or example_row.pop( + "okpo", None + ) + candidate = {"okpo": okpo or None, group: [example_row]} + if len(_json_bytes(candidate)) <= 32768: + example = candidate + rows.append( + (record.source, record.record_type, str(record.uid), encoded) + ) + _check_capacity(path.parent) + db.executemany("INSERT INTO rows VALUES (?, ?, ?, ?)", rows) + count += len(rows) + db.commit() + db.execute("CREATE INDEX row_order ON rows(source, kind, uid)") + with path.open("w", encoding="utf-8") as output: + for (data,) in db.execute( + "SELECT data FROM rows ORDER BY source, kind, uid" + ): + output.write(data + "\n") + if group == SourceGroup.SANCTIONS: + fields = list(SANCTIONS_EXPORT_FIELDS) + else: + fields = [ + *ORGANIZATION_EXPORT_FIELDS, + *SOURCE_RECORD_EXPORT_FIELDS, + *sorted(headers), + ] + return fields, count, example, as_of, revision + finally: + db.close() + ordered.unlink(missing_ok=True) + + +def _render_part(group, spool, directory, headers, count, formats, serial): + """Render then split every variant together when actual bytes exceed the cap.""" + max_bytes = min(_limit("MAX_FILE_BYTES", 512 * 1024 * 1024), 512 * 1024 * 1024) + stem = SOURCE_GROUP_EXPORT_FILE_STEMS[group] + files = [] + for fmt in formats: + _check_capacity(directory) + paths = _render_source_group_artifact( + source_group=group, + row_spool_path=spool, + output_path=directory / f"{stem}-part-{serial:06d}.{fmt}", + headers=headers, + file_format=fmt, + records_count=count, + display_headers=SANCTIONS_XLSX_HEADERS + if group == SourceGroup.SANCTIONS + else None, + ) + if len(paths) != 1: + raise ExportError("internal_error", 500) + files.append((fmt, paths[0])) + if any(path.stat().st_size > max_bytes for _, path in files): + for _, path in files: + path.unlink() + if count == 1: + raise ExportError("record_too_large", 503) + halves = [spool.with_suffix(".left"), spool.with_suffix(".right")] + try: + with halves[0].open("w", encoding="utf-8") as left, halves[1].open( + "w", encoding="utf-8" + ) as right: + for index, row in enumerate(_iter_spooled_rows(spool)): + (left if index < count // 2 else right).write( + _json_bytes(row).decode("utf-8") + "\n" + ) + parts = _render_part( + group, halves[0], directory, headers, count // 2, formats, serial + ) + parts.extend( + _render_part( + group, + halves[1], + directory, + headers, + count - count // 2, + formats, + serial + len(parts), + ) + ) + return parts + finally: + for path in halves: + path.unlink(missing_ok=True) + variants = [] + for fmt, path in files: + with path.open("rb") as handle: + checksum = hashlib.file_digest(handle, "sha256").hexdigest() + variants.append( + { + "artifact_id": str(uuid4()), + "format": fmt, + "file_name": path.name, + "mime_type": MIMES[fmt], + "size_bytes": path.stat().st_size, + "sha256": checksum, + } + ) + return [ + { + "part_id": str(uuid4()), + "dataset_key": "records", + "part_number": serial, + "parts_count": 0, + "title": "", + "records_count": count, + "default_format": formats[0], + "variants": variants, + } + ] + + +def _render_parts(group, staging, spool, headers, formats): + max_rows = min( + _limit("ROWS_PER_PART", 100000), + _limit( + "XLSX_ROWS_PER_FILE", + int(getattr(settings, "SOURCE_RECORD_EXPORT_XLSX_ROWS_PER_FILE", 100000)), + ), + 100000, + ) + target = min( + _limit("TARGET_FILE_BYTES", 256 * 1024 * 1024), + _limit("MAX_FILE_BYTES", 512 * 1024 * 1024), + ) + parts, batch_count, batch_bytes = [], 0, 0 + part_spool = staging / ".part.jsonl" + output = part_spool.open("w", encoding="utf-8") + try: + with spool.open(encoding="utf-8") as source: + for line in source: + size = len(line.encode("utf-8")) + if batch_count and ( + batch_count >= max_rows or batch_bytes + size > target + ): + output.close() + parts.extend( + _render_part( + group, + part_spool, + staging, + headers, + batch_count, + formats, + len(parts) + 1, + ) + ) + output = part_spool.open("w", encoding="utf-8") + batch_count, batch_bytes = 0, 0 + output.write(line) + batch_count += 1 + batch_bytes += size + output.close() + if batch_count: + parts.extend( + _render_part( + group, + part_spool, + staging, + headers, + batch_count, + formats, + len(parts) + 1, + ) + ) + finally: + output.close() + part_spool.unlink(missing_ok=True) + return parts + + +def build_source(group): + entry = _entry(group) + if not entry["export_enabled"]: + raise ExportError("forbidden", 403) + with _build_lock(group) as (owner, lost): + uid = uuid4() + staging = final = None + started = _timestamp() + try: + parent = _root() / group / "generations" + staging, final = parent / f".building-{uid}", parent / str(uid) + parent.mkdir(parents=True, exist_ok=True, mode=0o700) + required = _limit("MIN_FREE_BYTES", 1024 * 1024 * 1024) + if shutil.disk_usage(parent).free < required: + raise OSError("Export disk reserve exhausted") + staging.mkdir(mode=0o700) + spool = staging / ".rows.jsonl" + headers, count, example, as_of, revision = _spool(group, spool) + formats = ("json",) if group == FINANCIAL_SOURCE_GROUP else FORMATS + parts = _render_parts(group, staging, spool, headers, formats) + spool.unlink() + for part in parts: + part["parts_count"] = len(parts) + part["title"] = entry["title"] + ( + f" — часть {part['part_number']} из {len(parts)}" + if len(parts) > 1 + else "" + ) + _check_capacity(staging) + manifest = { + "version": 3, + "data_scope": "all_available", + "source_group": group, + "generation_id": str(uid), + "generated_at": _timestamp(), + "data_as_of": as_of, + "records_count": count, + "supported_formats": list(formats) if count else [], + "description": _description(entry, example), + "datasets": [ + { + "key": "records", + "title": entry["title"], + "export_schema_version": "1", + "records_count": count, + "parts_count": len(parts), + } + ], + "parts": parts, + } + (staging / "manifest.json").write_bytes(_json_bytes(manifest)) + if lost.is_set(): + raise ExportError("not_ready", 409) + os.replace(staging, final) + with transaction.atomic(): + state = SourceExportState.objects.select_for_update().get(pk=group) + if state.lock_owner != owner or state.lock_expires_at <= timezone.now(): + raise ExportError("not_ready", 409) + generation = SourceExportGeneration.objects.create( + id=uid, + source_group=group, + manifest=manifest, + data_revision=revision, + ) + state.current_generation = uid + state.last_build = { + "state": "success", + "started_at": started, + "finished_at": _timestamp(), + "error_code": None, + } + state.save(update_fields=["current_generation", "last_build"]) + logger.info( + "source_export_build_success group=%s generation=%s count=%s", + group, + uid, + count, + ) + return generation + except Exception as exc: + _build_state( + group, + owner, + last_build={ + "state": "failed", + "started_at": started, + "finished_at": _timestamp(), + "error_code": exc.code + if isinstance(exc, ExportError) + else "source_export_build_failed", + }, + ) + if final and not SourceExportGeneration.objects.filter(pk=uid).exists(): + shutil.rmtree(final, ignore_errors=True) + logger.exception( + "source_export_build_failed group=%s generation=%s", group, uid + ) + raise + finally: + if staging: + shutil.rmtree(staging, ignore_errors=True) + + +def cleanup(group): + """Keep two generations and >=24h, honoring ticket and active stream leases.""" + now = timezone.now() + _cleanup_abandoned(group, now) + keep = max(2, _limit("GENERATIONS_TO_KEEP", 2)) + ids = list( + SourceExportGeneration.objects.filter(source_group=group, deleted_at=None) + .order_by("-created_at") + .values_list("pk", flat=True) + ) + removed = 0 + for uid in ids[keep:]: + with transaction.atomic(): + state = SourceExportState.objects.select_for_update().get(pk=group) + generation = SourceExportGeneration.objects.select_for_update().get(pk=uid) + if ( + state.current_generation == uid + or generation.created_at > now - timedelta(hours=24) + ): + continue + if SourceExportLease.objects.filter( + generation=generation, expires_at__gt=now + ).exists(): + continue + with suppress(FileNotFoundError): + shutil.rmtree(_directory(generation), ignore_errors=False) + generation.deleted_at = now + generation.save(update_fields=["deleted_at"]) + removed += 1 + SourceExportLease.objects.filter(expires_at__lte=now).delete() + SourceExportTicket.objects.filter(expires_at__lt=now - timedelta(days=30)).delete() + SourceExportGeneration.objects.filter( + deleted_at__lt=now - timedelta(days=30) + ).delete() + return removed + + +def _select(generation, selection): + manifest = generation.manifest + if not manifest["parts"]: + raise ExportError("empty", 409) + parts = manifest["parts"] + if selection["selection_kind"] == "file": + parts = [part for part in parts if part["part_id"] == selection["part_id"]] + if not parts: + raise ExportError("part_not_found", 404, "part_id") + artifacts = [] + for part in parts: + variant = next( + (v for v in part["variants"] if v["format"] == selection["format"]), None + ) + if variant is None: + raise ExportError("format_unavailable", 409, "format") + artifacts.append(variant) + return artifacts + + +def _open_artifacts(generation, artifacts, stack): + directory = _directory(generation) + base = directory.resolve() + # Reject symlinks at every private-storage path component. + if any(path.is_symlink() for path in (directory, *directory.parents)): + raise ExportError("artifact_unavailable", 503) + opened = [] + for artifact in artifacts: + name = artifact["file_name"] + if ( + Path(name).name != name + or not name.isascii() + or "\r" in name + or "\n" in name + ): + raise ExportError("artifact_unavailable", 503) + path = directory / name + if path.is_symlink() or path.resolve().parent != base: + raise ExportError("artifact_unavailable", 503) + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + handle = stack.enter_context(os.fdopen(fd, "rb")) + stat = os.fstat(handle.fileno()) + import stat as stat_module + + if ( + not stat_module.S_ISREG(stat.st_mode) + or stat.st_size != artifact["size_bytes"] + ): + raise OSError("Invalid artifact") + except OSError: + raise ExportError("artifact_unavailable", 503) from None + opened.append((artifact, handle)) + return opened + + +def _issue_ticket(user, selection): + entry = _entry(selection["source_group"]) + if not entry["export_enabled"]: + raise ExportError("forbidden", 403) + token = "se1_" + secrets.token_urlsafe(32) + now = timezone.now() + with transaction.atomic(): + generation = get_generation( + selection["source_group"], selection["generation_id"] + ) + generation = SourceExportGeneration.objects.select_for_update().get( + pk=generation.pk + ) + if generation.deleted_at: + raise ExportError("generation_gone", 409) + if not generation.storage_available: + raise ExportError("artifact_unavailable", 503) + artifacts = _select(generation, selection) + with ExitStack() as stack: + _open_artifacts(generation, artifacts, stack) + lease = SourceExportLease.objects.create( + generation=generation, + issuer_id=str(user.pk), + expires_at=now + timedelta(seconds=360), + ) + file = selection["selection_kind"] == "file" + name = ( + artifacts[0]["file_name"] + if file + else f"{entry['source_slug']}-{generation.pk}-{selection['format']}.zip" + ) + response = { + **selection, + "file_name": name, + "expires_in": 300, + "mime_type": artifacts[0]["mime_type"] if file else "application/zip", + "size_bytes": artifacts[0]["size_bytes"] if file else None, + "parts_count": len(artifacts), + } + response.pop("part_id", None) + SourceExportTicket.objects.create( + token_hash=hashlib.sha256(token.encode()).hexdigest(), + lease=lease, + selection={ + "request": selection, + "response": response, + "artifacts": artifacts, + "request_id": str(uuid4()), + "issued_role": "admin", + "issued_at": _timestamp(now), + }, + expires_at=now + timedelta(seconds=300), + ) + logger.info( + "source_export_ticket_issued group=%s generation=%s actor=%s kind=%s parts=%s", + generation.source_group, + generation.pk, + user.pk, + selection["selection_kind"], + len(artifacts), + ) + return {"ticket": token, **response} + + +def _stream_zip(opened, manifest): + sink = _StreamingZipSink() + with zipfile.ZipFile( + cast(BinaryIO, sink), "w", compression=zipfile.ZIP_STORED, allowZip64=True + ) as archive: + for artifact, handle in opened: + with archive.open( + "records/" + artifact["file_name"], "w", force_zip64=True + ) as target: + yield from sink.drain() + transferred = 0 + while chunk := handle.read(CHUNK_SIZE): + transferred += len(chunk) + target.write(chunk) + yield from sink.drain() + if transferred != artifact["size_bytes"]: + raise OSError("Export artifact changed while streaming") + yield from sink.drain() + archive.writestr("manifest.json", _json_bytes(manifest)) + yield from sink.drain() + yield from sink.drain() + + +class DownloadStream: + """Explicit close handles aborts even if the generator has never started.""" + + def __init__(self, lease, opened, stack, manifest, file): + self.lease, self.opened, self.stack, self.manifest, self.file = ( + lease, + opened, + stack, + manifest, + file, + ) + self.closed = False + self.bytes_sent = 0 + + def __iter__(self): + completed = False + try: + with _heartbeat( + lambda: SourceExportLease.objects.filter( + pk=self.lease.pk, expires_at__gt=timezone.now() + ).update(expires_at=timezone.now() + timedelta(minutes=10)) + ) as lost: + if self.file: + + def chunks(): + transferred = 0 + while chunk := self.opened[0][1].read(CHUNK_SIZE): + transferred += len(chunk) + yield chunk + if transferred != self.opened[0][0]["size_bytes"]: + raise OSError("Export artifact changed while streaming") + + iterator = chunks() + else: + iterator = _stream_zip(self.opened, self.manifest) + for chunk in iterator: + if lost.is_set(): + raise OSError("Export stream lease lost") + self.bytes_sent += len(chunk) + yield chunk + completed = True + finally: + logger.info( + "source_export_download_%s generation=%s bytes=%s", + "complete" if completed else "failed", + self.lease.generation_id, + self.bytes_sent, + ) + self.close() + + def close(self): + if not self.closed: + self.closed = True + self.stack.close() + SourceExportLease.objects.filter(pk=self.lease.pk).delete() + + +def consume_ticket(token): + """Returns None only for tokens belonging to the separate legacy namespace.""" + if not isinstance(token, str) or not token.startswith("se1_"): + return None + record, digest = _lookup_ticket(token) + now, error, stream, payload = timezone.now(), None, None, record.selection + stack = ExitStack() + try: + # Global admission mutex, generation lock, then a conditional ticket claim. + with transaction.atomic(): + SourceExportLimiter.objects.get_or_create(key="streams") + SourceExportLimiter.objects.select_for_update().get(pk="streams") + now = timezone.now() + lease = SourceExportLease.objects.filter(pk=record.lease_id).first() + if lease is None: + raise ExportError("ticket_expired", 410) + generation = SourceExportGeneration.objects.select_for_update().get( + pk=lease.generation_id + ) + claimed = SourceExportTicket.objects.filter( + pk=digest, consumed_at=None, expires_at__gt=now + ).update(consumed_at=now) + if not claimed: + error = ExportError("ticket_expired", 410) + else: + error = _admission_error(generation, lease, now) + if not error: + try: + stream = _prepare_stream(generation, lease, payload, stack, now) + except ExportError as exc: + error = exc + generation.storage_available = False + generation.save(update_fields=["storage_available"]) + if error: + lease.delete() + if error: + raise error + return _download_response(stream, payload) + except Exception: + stack.close() + raise + + +def verify_generation(generation): + """Background integrity verification, never a per-download full-file hash.""" + try: + with ExitStack() as stack: + artifacts = [ + v for part in generation.manifest["parts"] for v in part["variants"] + ] + for artifact, handle in _open_artifacts(generation, artifacts, stack): + if ( + hashlib.file_digest(handle, "sha256").hexdigest() + != artifact["sha256"] + ): + raise ExportError("artifact_unavailable", 503) + except ExportError: + SourceExportGeneration.objects.filter(pk=generation.pk).update( + storage_available=False + ) + return False + return True + + +def _download_response(stream, payload): + response = StreamingHttpResponse( + stream, content_type=payload["response"]["mime_type"] + ) + response[ + "Content-Disposition" + ] = f'attachment; filename="{payload["response"]["file_name"]}"' + response["Cache-Control"] = "private, no-store" + response["Accept-Ranges"] = "none" + response["X-Content-Type-Options"] = "nosniff" + response["X-Accel-Buffering"] = "no" + if payload["response"]["size_bytes"] is not None: + response["Content-Length"] = str(payload["response"]["size_bytes"]) + return response + + +def _admission_error(generation, lease, now): + user = ( + get_user_model() + .objects.filter(pk=lease.issuer_id, is_active=True, is_staff=True) + .exists() + ) + if not user or not _entry(generation.source_group)["export_enabled"]: + return ExportError("forbidden", 403) + if ( + generation.deleted_at + or not generation.storage_available + or lease.expires_at <= now + ): + return ExportError("artifact_unavailable", 503) + active = SourceExportLease.objects.filter(kind="stream", expires_at__gt=now) + if active.count() >= _limit("MAX_STREAMS", 20) or active.filter( + issuer_id=lease.issuer_id + ).count() >= _limit("MAX_STREAMS_PER_USER", 3): + return ExportError("rate_limited", 429) + return None + + +def _prepare_stream(generation, lease, payload, stack, now): + opened = _open_artifacts(generation, payload["artifacts"], stack) + lease.kind, lease.expires_at = "stream", now + timedelta(minutes=10) + lease.save(update_fields=["kind", "expires_at"]) + manifest = { + **generation.manifest, + "supported_formats": [payload["request"]["format"]], + "parts": [ + { + **part, + "variants": [v for v in part["variants"] if v in payload["artifacts"]], + } + for part in generation.manifest["parts"] + ], + } + return DownloadStream( + lease, opened, stack, manifest, payload["request"]["selection_kind"] == "file" + ) + + +def _lookup_ticket(token): + if not isinstance(token, str) or not TICKET_PATTERN.fullmatch(token): + raise ExportError("ticket_malformed") + digest = hashlib.sha256(token.encode()).hexdigest() + record = SourceExportTicket.objects.filter(pk=digest).first() + if record is None: + raise ExportError("ticket_expired", 410) + if record.consumed_at or record.lease_id is None: + raise ExportError("ticket_expired", 410) + return record, digest + + +def issue_ticket(user, selection): + try: + return _issue_ticket(user, selection) + except ExportError as exc: + if exc.code == "source_export_artifact_unavailable": + SourceExportGeneration.objects.filter( + pk=selection["generation_id"], source_group=selection["source_group"] + ).update(storage_available=False) + raise + + +def _check_capacity(directory): + if shutil.disk_usage(directory).free < _limit("MIN_FREE_BYTES", 1024 * 1024 * 1024): + raise OSError("Export disk reserve exhausted") + maximum = int(getattr(settings, "SOURCE_EXPORT_DISK_BUDGET_BYTES", 0)) + if maximum: + # Used only by builds, never by catalog/detail or ticket requests. + used = sum( + path.stat().st_size + for path in _root().rglob("*") + if path.is_file() and not path.is_symlink() + ) + if used >= maximum: + raise OSError("Export storage budget exhausted") + + +def _cleanup_abandoned(group, now): + with transaction.atomic(): + state, _ = SourceExportState.objects.get_or_create(source_group=group) + state = SourceExportState.objects.select_for_update().get(pk=state.pk) + if state.lock_expires_at and state.lock_expires_at > now: + return + if state.last_build.get("state") in {"running", "queued"}: + state.last_build = { + **state.last_build, + "state": "failed", + "finished_at": _timestamp(now), + "error_code": "source_export_build_interrupted", + } + state.lock_owner, state.lock_expires_at = None, None + state.save(update_fields=["last_build", "lock_owner", "lock_expires_at"]) + parent = _root() / group / "generations" + if not parent.is_dir() or parent.is_symlink(): + return + known = { + str(uid) + for uid in SourceExportGeneration.objects.filter( + source_group=group + ).values_list("id", flat=True) + } + for path in parent.iterdir(): + if path.is_symlink() or not path.is_dir() or path.name in known: + continue + try: + UUID(path.name.removeprefix(".building-")) + except ValueError: + continue + if path.stat().st_mtime < now.timestamp() - 86400: + shutil.rmtree(path) + + +def mark_queued(group): + now = timezone.now() + with transaction.atomic(): + SourceExportState.objects.get_or_create(source_group=group) + state = SourceExportState.objects.select_for_update().get(pk=group) + if state.lock_expires_at and state.lock_expires_at > now: + return False + state.lock_owner = None + state.last_build = { + "state": "queued", + "started_at": None, + "finished_at": None, + "error_code": None, + } + state.lock_expires_at = now + timedelta(minutes=10) + state.save(update_fields=["last_build", "lock_owner", "lock_expires_at"]) + return True diff --git a/src/organizations/source_export_serializers.py b/src/organizations/source_export_serializers.py new file mode 100644 index 0000000..7b98ea8 --- /dev/null +++ b/src/organizations/source_export_serializers.py @@ -0,0 +1,18 @@ +"""Strict selectors for the new export scope (legacy DTOs stay unchanged).""" +from rest_framework import serializers + + +class SourceExportSelectionSerializer(serializers.Serializer): + selection_kind = serializers.ChoiceField(choices=("file", "source_archive")) + source_group = serializers.CharField(max_length=64) + generation_id = serializers.UUIDField() + part_id = serializers.UUIDField(required=False) + format = serializers.ChoiceField(choices=("xlsx", "csv", "json")) + + def validate(self, attrs): + expected = {"selection_kind", "source_group", "generation_id", "format"} + if attrs["selection_kind"] == "file": + expected.add("part_id") + if set(self.initial_data) != expected: + raise serializers.ValidationError("Некорректный состав selector.") + return {key: str(value) for key, value in attrs.items()} diff --git a/src/organizations/tasks.py b/src/organizations/tasks.py index 03498bf..7bbae28 100644 --- a/src/organizations/tasks.py +++ b/src/organizations/tasks.py @@ -124,3 +124,64 @@ def refresh_organization_data_snapshots_for_parser_batch( batch_id=batch_id, batch_size=batch_size, ) + + +@shared_task(bind=True, base=CorePeriodicTask) +def refresh_source_export_catalog(self, source_group=None): + """Independent group publication; contention retries the latest canonical data.""" + from organizations.source_export_catalog import ( + ExportError, + build_source, + cleanup, + mark_queued, + registry, + ) + + groups = [source_group] if source_group else list(registry()) + if source_group is None: + queued, failed = 0, [] + for group in groups: + if not registry()[group]["export_enabled"] or not mark_queued(group): + continue + try: + refresh_source_export_catalog.delay(source_group=group) + queued += 1 + except Exception: + from django.utils import timezone + + from organizations.models import SourceExportState + + SourceExportState.objects.filter( + pk=group, lock_owner=None, last_build__state="queued" + ).update( + lock_expires_at=None, + last_build={ + "state": "failed", + "started_at": None, + "finished_at": timezone.now() + .isoformat() + .replace("+00:00", "Z"), + "error_code": "source_export_enqueue_failed", + }, + ) + logger.exception("Source export enqueue failed group=%s", group) + failed.append(group) + if failed: + raise self.retry(countdown=30, max_retries=1000) + return {"status": "queued", "groups": queued} + try: + generation = build_source(source_group) + except ExportError as exc: + if exc.code == "source_export_not_ready": + raise self.retry(countdown=30, max_retries=1000) from exc + raise + cleanup(source_group) + from organizations.source_cache import get_source_data_cache_version + + if generation.data_revision != get_source_data_cache_version(): + raise self.retry(countdown=30, max_retries=1000) + return { + "status": "success", + "source_group": source_group, + "generation_id": str(generation.pk), + } diff --git a/src/organizations/views.py b/src/organizations/views.py index 96cac61..579ce31 100644 --- a/src/organizations/views.py +++ b/src/organizations/views.py @@ -3,15 +3,18 @@ from __future__ import annotations import hashlib +import logging import os +from collections.abc import Mapping from contextlib import suppress from tempfile import NamedTemporaryFile from typing import Any -from uuid import UUID +from uuid import UUID, uuid4 from apps.core.openapi import swagger_tag from django.conf import settings from django.core.cache import cache +from django.db import DatabaseError from django.db.models import Case, CharField, Count, F, Max, Q, Value, When from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Cast, Coalesce, NullIf @@ -21,13 +24,14 @@ from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.decorators import action -from rest_framework.exceptions import NotFound, ValidationError +from rest_framework.exceptions import NotFound, ParseError, ValidationError from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework.parsers import FormParser, JSONParser, MultiPartParser from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ReadOnlyModelViewSet +from organizations import source_export_catalog as export_catalog_service from organizations.cache import ( DEFAULT_ORGANIZATION_API_CACHE_TIMEOUT_SECONDS, ORGANIZATION_API_CACHE_CONTRACT_VERSION, @@ -62,6 +66,7 @@ from organizations.serializers import ( SourceRecordExportUnavailableSerializer, SourceRecordFilterOptionsResponseSerializer, ) +from organizations.source_export_serializers import SourceExportSelectionSerializer from organizations.source_record_export import ( SourceRecordExportArchive, SourceRecordExportArtifactsUnavailable, @@ -599,7 +604,12 @@ class OrganizationSourceRecordViewSet(ReadOnlyModelViewSet): def get_permissions(self): if self.action == "integrated_attachment": return [IsAuthenticated()] - if self.action in {"export", "export_ticket"}: + if self.action in { + "export", + "export_ticket", + "export_catalog", + "export_catalog_detail", + }: return [IsAdminUser()] if self.action == "export_download": return [AllowAny()] @@ -976,6 +986,13 @@ class OrganizationSourceRecordViewSet(ReadOnlyModelViewSet): *args: Any, **kwargs: Any, ) -> StreamingHttpResponse | Response: + if not isinstance(request.data, Mapping) or set(request.data) != { + "sources", + "format", + }: + return self._catalog_error( + export_catalog_service.ExportError("invalid_request") + ) serializer = OrganizationSourceRecordExportRequestSerializer(data=request.data) serializer.is_valid(raise_exception=True) @@ -997,6 +1014,127 @@ class OrganizationSourceRecordViewSet(ReadOnlyModelViewSet): return self._source_record_export_response(package) + def finalize_response(self, request, response, *args, **kwargs): + response = super().finalize_response(request, response, *args, **kwargs) + if self.action in {"export_catalog", "export_catalog_detail", "export_ticket"}: + response.setdefault("Cache-Control", "private, no-store") + response.setdefault("X-Request-ID", str(uuid4())) + return response + + def handle_exception(self, exc): + if getattr(exc, "status_code", None) == 401: + return super().handle_exception(exc) + is_new = self.action in {"export_catalog", "export_catalog_detail"} + if self.action in {"export_ticket", "export_download"}: + try: + data = self.request.data + except ParseError: + return self._catalog_error( + export_catalog_service.ExportError("invalid_request") + ) + is_new = ( + ( + not isinstance(data, Mapping) + or "selection_kind" in data + or "sources" not in data + ) + if self.action == "export_ticket" + else ( + not isinstance(data, Mapping) + or str(data.get("ticket", "")).startswith("se1_") + ) + ) + if is_new: + if getattr(exc, "status_code", None) == 403: + return self._catalog_error( + export_catalog_service.ExportError("forbidden", 403) + ) + if isinstance(exc, DatabaseError | OSError): + code = ( + "ticket_unavailable" + if self.action in {"export_ticket", "export_download"} + else "metadata_unavailable" + ) + return self._catalog_error( + export_catalog_service.ExportError(code, 503) + ) + if not getattr(exc, "status_code", None): + logging.getLogger(__name__).exception("Source export API failed") + return self._catalog_error( + export_catalog_service.ExportError("internal_error", 500) + ) + return super().handle_exception(exc) + + @staticmethod + def _catalog_error(error): + request_id = str(uuid4()) + headers = {"Cache-Control": "private, no-store", "X-Request-ID": request_id} + if error.retryable: + headers["Retry-After"] = ( + "10" + if error.status == 429 + else ("5" if error.code.endswith("ticket_unavailable") else "30") + ) + return Response( + { + "detail": "Не удалось выполнить запрос выгрузки.", + "code": error.code, + "field": error.field, + "retryable": error.retryable, + "request_id": request_id, + }, + status=error.status, + headers=headers, + ) + + @staticmethod + def _catalog_response(data, pagination=None): + return Response( + { + "success": True, + "data": data, + "errors": None, + "meta": {"pagination": pagination} if pagination is not None else None, + }, + headers={ + "Cache-Control": "private, no-store", + "X-Request-ID": str(uuid4()), + }, + ) + + @swagger_auto_schema( + tags=[ORGANIZATIONS_TAG], + operation_id="v2_organization_source_records_export_catalog_list", + ) + @action(detail=False, methods=["get"], url_path="export-catalog") + def export_catalog(self, request, *args, **kwargs): + try: + export_catalog_service.rate_limit(request.user.pk, "metadata") + if request.query_params: + raise export_catalog_service.ExportError("invalid_request") + return self._catalog_response(export_catalog_service.catalog()) + except export_catalog_service.ExportError as error: + return self._catalog_error(error) + + @swagger_auto_schema( + tags=[ORGANIZATIONS_TAG], + operation_id="v2_organization_source_records_export_catalog_read", + ) + @action( + detail=False, + methods=["get"], + url_path=r"export-catalog/(?P[^/.]+)", + ) + def export_catalog_detail(self, request, source_group, *args, **kwargs): + try: + export_catalog_service.rate_limit(request.user.pk, "metadata") + data, pagination = export_catalog_service.detail( + source_group, request.query_params + ) + return self._catalog_response(data, pagination) + except export_catalog_service.ExportError as error: + return self._catalog_error(error) + @swagger_auto_schema( tags=[ORGANIZATIONS_TAG], operation_id="v2_organization_source_records_export_ticket", @@ -1016,6 +1154,33 @@ class OrganizationSourceRecordViewSet(ReadOnlyModelViewSet): ) @action(detail=False, methods=["post"], url_path="export-ticket") def export_ticket(self, request, *args: Any, **kwargs: Any) -> Response: + if not isinstance(request.data, Mapping): + return self._catalog_error( + export_catalog_service.ExportError("invalid_request") + ) + if "selection_kind" in request.data or "sources" not in request.data: + serializer = SourceExportSelectionSerializer(data=request.data) + if not serializer.is_valid(): + return self._catalog_error( + export_catalog_service.ExportError("invalid_request") + ) + try: + export_catalog_service.rate_limit(request.user.pk, "ticket") + result = export_catalog_service.issue_ticket( + request.user, serializer.validated_data + ) + return Response( + result, status=201, headers={"Cache-Control": "private, no-store"} + ) + except export_catalog_service.ExportError as error: + return self._catalog_error(error) + if not isinstance(request.data, Mapping) or set(request.data) != { + "sources", + "format", + }: + return self._catalog_error( + export_catalog_service.ExportError("invalid_request") + ) serializer = OrganizationSourceRecordExportRequestSerializer(data=request.data) serializer.is_valid(raise_exception=True) @@ -1085,6 +1250,23 @@ class OrganizationSourceRecordViewSet(ReadOnlyModelViewSet): *args: Any, **kwargs: Any, ) -> StreamingHttpResponse | Response: + if ( + not isinstance(request.data, Mapping) + or set(request.data) != {"ticket"} + or ( + hasattr(request.data, "getlist") + and len(request.data.getlist("ticket")) != 1 + ) + ): + return self._catalog_error( + export_catalog_service.ExportError("ticket_malformed") + ) + try: + response = export_catalog_service.consume_ticket(request.data.get("ticket")) + if response is not None: + return response + except export_catalog_service.ExportError as error: + return self._catalog_error(error) serializer = OrganizationSourceRecordExportDownloadSerializer(data=request.data) if not serializer.is_valid(): return Response( diff --git a/src/settings/base.py b/src/settings/base.py index 5f8b6e2..0ae5b60 100644 --- a/src/settings/base.py +++ b/src/settings/base.py @@ -262,6 +262,16 @@ BACKUP_EXPORT_DIRECTORY = os.getenv( "BACKUP_EXPORT_DIRECTORY", str(PROJECT_ROOT / "media" / "backups"), ) +# Private persistent volume, mounted identically in web and workers; no media alias. +SOURCE_EXPORT_DIRECTORY = os.getenv( + "SOURCE_EXPORT_DIRECTORY", str(PROJECT_ROOT / "private-source-exports") +) +SOURCE_EXPORT_AUTOBUILD = ( + os.getenv("SOURCE_EXPORT_AUTOBUILD", "false").lower() == "true" +) +SOURCE_EXPORT_DISABLED_GROUPS = tuple( + filter(None, os.getenv("SOURCE_EXPORT_DISABLED_GROUPS", "").split(",")) +) SOURCE_RECORD_EXPORT_DIRECTORY = os.getenv( "SOURCE_RECORD_EXPORT_DIRECTORY", str(PROJECT_ROOT / "media" / "source-record-exports"), diff --git a/tests/apps/organizations/test_canonical_openapi.py b/tests/apps/organizations/test_canonical_openapi.py index 00d6c9f..c6ab75f 100644 --- a/tests/apps/organizations/test_canonical_openapi.py +++ b/tests/apps/organizations/test_canonical_openapi.py @@ -202,9 +202,15 @@ def test_testing_amendments_download_and_options_contract(contract): assert set(download["requestBody"]["content"]) == { "application/x-www-form-urlencoded" } - assert set(download["responses"]["200"]["content"]) == {"application/zip"} + assert set(download["responses"]["200"]["content"]) == { + "application/zip", + "application/json", + "text/csv", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + } invalid = download["responses"]["400"]["content"]["application/json"]["schema"] - schema = contract["components"]["schemas"][invalid["$ref"].rsplit("/", 1)[1]] + legacy = invalid["oneOf"][0] + schema = contract["components"]["schemas"][legacy["$ref"].rsplit("/", 1)[1]] assert schema["properties"]["code"]["enum"] == ["invalid_ticket"] options = contract["paths"]["/api/v2/organization-source-records/filter-options/"][ "get" diff --git a/tests/apps/organizations/test_source_export_catalog.py b/tests/apps/organizations/test_source_export_catalog.py new file mode 100644 index 0000000..70cd8dd --- /dev/null +++ b/tests/apps/organizations/test_source_export_catalog.py @@ -0,0 +1,683 @@ +"""New all-available contract on real ORM metadata and temporary artifact storage.""" +import csv +import hashlib +import json +import zipfile +from datetime import timedelta +from io import BytesIO, StringIO +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch +from uuid import uuid4 + +from django.core.cache import cache +from django.http import QueryDict +from django.test import override_settings +from django.utils import timezone +from openpyxl import load_workbook +from organizations.models import ( + FinancialIndicatorsExtension, + GovernmentProcurementExtension, + Organization, + OrganizationSourceFinancialLine, + OrganizationSourceRecord, + SourceExportGeneration, + SourceExportLease, + SourceExportState, + SourceExportTicket, + SourceGroup, +) +from organizations.source_export_catalog import ( + ExportError, + _directory, + build_source, + catalog, + cleanup, + consume_ticket, + detail, + issue_ticket, + registry, +) +from rest_framework.test import APITestCase + +from tests.apps.user.factories import UserFactory + +GROUP = "government_procurements" + + +class SourceExportCatalogTest(APITestCase): + def setUp(self): + self.directory = TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + settings = override_settings( + SOURCE_EXPORT_DIRECTORY=self.directory.name, + SOURCE_EXPORT_ROWS_PER_PART=2, + SOURCE_RECORD_EXPORT_DIRECTORY=self.directory.name + "/annual", + ) + settings.enable() + self.addCleanup(settings.disable) + cache.clear() + self.user = UserFactory.create_superuser() + self.client.force_authenticate(self.user) + self.base = "/api/v2/organization-source-records/" + self.organization = Organization.objects.create( + name="Тест", inn="0012345678", ogrn="1027700132195", okpo="00123456" + ) + self.extension = GovernmentProcurementExtension.objects.create( + organization=self.organization + ) + + def records(self, count=3): + return [ + OrganizationSourceRecord.objects.create( + extension=self.extension, + source="procurements_44fz" if i % 2 else "procurements_223fz", + record_type="procurement", + external_id=str(uuid4()), + record_date=f"{2024+i%3}-01-01", + title="=unsafe", + payload={"subject": str(i)}, + ) + for i in range(count) + ] + + def selector(self, generation, kind="file", fmt="json"): + result = { + "selection_kind": kind, + "source_group": generation.source_group, + "generation_id": str(generation.pk), + "format": fmt, + } + if kind == "file": + result["part_id"] = generation.manifest["parts"][0]["part_id"] + return result + + def bytes(self, response): + try: + return b"".join(response.streaming_content) + finally: + self.close_response(response) + + @staticmethod + def close_response(response): + # Direct service responses are not wrapped by Django's test client. + # Keep TestCase's outer transaction open while still closing all streams. + from django.core.signals import request_finished + from django.db import close_old_connections + + request_finished.disconnect(close_old_connections) + try: + response.close() + finally: + request_finished.connect(close_old_connections) + + def test_registry_not_ready_no_record_queries(self): + with patch( + "organizations.source_export_catalog.OrganizationSourceRecord.objects.filter", + side_effect=AssertionError("records queried"), + ): + response = self.client.get(self.base + "export-catalog/") + self.assertEqual(response.status_code, 200) + self.assertEqual(len(response.data["data"]["sources"]), 22) + self.assertEqual( + {s["state"] for s in response.data["data"]["sources"]}, {"not_ready"} + ) + self.assertEqual(set(response.data), {"success", "data", "errors", "meta"}) + self.assertEqual(response["Cache-Control"], "private, no-store") + self.assertEqual( + response.data["data"]["catalog_revision"], catalog()["catalog_revision"] + ) + + def test_admin_access(self): + self.client.force_authenticate(None) + self.assertEqual( + self.client.get(self.base + "export-catalog/").status_code, 401 + ) + self.client.force_authenticate(UserFactory.create_user()) + self.assertEqual( + self.client.get(self.base + "export-catalog/").status_code, 403 + ) + + def test_empty_published_not_not_ready(self): + generation = build_source(GROUP) + self.assertEqual(generation.manifest["parts"], []) + self.assertEqual(catalog()["sources"][1]["state"], "empty") + with self.assertRaises(ExportError) as error: + issue_ticket(self.user, self.selector(generation, "source_archive")) + self.assertEqual(error.exception.code, "source_export_empty") + + def test_all_years_variants_counts_and_checksums(self): + records = self.records(5) + generation = build_source(GROUP) + parts = generation.manifest["parts"] + self.assertEqual([p["records_count"] for p in parts], [2, 2, 1]) + self.assertEqual(generation.manifest["records_count"], 5) + all_uids = [] + for part in parts: + by_format = {} + for variant in part["variants"]: + data = (_directory(generation) / variant["file_name"]).read_bytes() + self.assertEqual(hashlib.sha256(data).hexdigest(), variant["sha256"]) + self.assertEqual(len(data), variant["size_bytes"]) + if variant["format"] == "json": + rows = [r for org in json.loads(data) for r in org[GROUP]] + elif variant["format"] == "csv": + self.assertTrue(data.startswith(b"\xef\xbb\xbf")) + rows = list(csv.DictReader(StringIO(data.decode("utf-8-sig")))) + self.assertEqual(rows[0]["ИНН"], "0012345678") + self.assertEqual(rows[0]["title"], "'=unsafe") + else: + workbook = load_workbook(BytesIO(data), read_only=True) + values = list(workbook["data"].values) + rows = [ + dict(zip(values[0], row, strict=False)) for row in values[1:] + ] + workbook.close() + by_format[variant["format"]] = {r["uid"] for r in rows} + self.assertEqual(by_format["json"], by_format["csv"]) + self.assertEqual(by_format["json"], by_format["xlsx"]) + all_uids.extend(by_format["json"]) + self.assertCountEqual(all_uids, [str(r.uid) for r in records]) + + def test_pagination_and_generation_pin(self): + self.records(5) + first = build_source(GROUP) + data, pagination = detail(GROUP, QueryDict("page_size=1")) + self.assertEqual(pagination["total_count"], 3) + build_source(GROUP) + second_page, _ = detail( + GROUP, QueryDict(f"page=2&page_size=1&generation_id={first.pk}") + ) + self.assertEqual(second_page["generation_id"], str(first.pk)) + self.assertNotEqual(second_page["current_generation_id"], str(first.pk)) + self.assertNotEqual( + second_page["files"][0]["part_id"], data["files"][0]["part_id"] + ) + + def test_invalid_queries(self): + for query in [ + "page=0", + "page=x", + "page_size=201", + "page=3", + "generation_id=bad", + "foo=bar", + "page=1&page=2", + ]: + response = self.client.get(self.base + f"export-catalog/{GROUP}/?{query}") + self.assertEqual(response.status_code, 400, query) + self.assertEqual( + set(response.data), + {"detail", "code", "field", "retryable", "request_id"}, + ) + self.assertEqual( + self.client.get(self.base + "export-catalog/?foo=bar").status_code, 400 + ) + self.assertEqual( + self.client.get(self.base + "export-catalog/missing/").status_code, 404 + ) + + def test_native_single_file_and_used_ticket(self): + self.records() + generation = build_source(GROUP) + response = self.client.post( + self.base + "export-ticket/", self.selector(generation), format="json" + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(len(response.data), 10) + token = response.data["ticket"] + self.client.force_authenticate(None) + url = self.base + "export-download/" + download = self.client.post(url, {"ticket": token}, format="multipart") + self.assertEqual(download.status_code, 200) + self.assertEqual(download["Content-Type"], "application/json; charset=utf-8") + expected = (_directory(generation) / response.data["file_name"]).read_bytes() + self.assertEqual(int(download["Content-Length"]), len(expected)) + self.assertEqual(self.bytes(download), expected) + repeated = self.client.post(url, {"ticket": token}, format="multipart") + self.assertEqual(repeated.status_code, 410, repeated.data) + self.assertFalse(SourceExportLease.objects.exists()) + + def test_zip_all_parts_not_first_page_and_public_manifest(self): + self.records(5) + generation = build_source(GROUP) + ticket = issue_ticket( + self.user, self.selector(generation, "source_archive", "csv") + ) + response = consume_ticket(ticket["ticket"]) + self.assertNotIn("Content-Length", response) + with zipfile.ZipFile(BytesIO(self.bytes(response))) as archive: + self.assertEqual(len(archive.namelist()), 4) + self.assertEqual( + len([n for n in archive.namelist() if n.endswith(".csv")]), 3 + ) + manifest = json.loads(archive.read("manifest.json")) + self.assertNotIn("relative_path", json.dumps(manifest)) + self.assertEqual(manifest["generation_id"], str(generation.pk)) + + def test_ticket_survives_new_current(self): + self.records() + generation = build_source(GROUP) + ticket = issue_ticket(self.user, self.selector(generation)) + expected = (_directory(generation) / ticket["file_name"]).read_bytes() + self.records() + build_source(GROUP) + self.assertEqual(self.bytes(consume_ticket(ticket["ticket"])), expected) + + def test_issuer_revoked_consumes_ticket(self): + self.records() + generation = build_source(GROUP) + ticket = issue_ticket(self.user, self.selector(generation)) + self.user.is_staff = False + self.user.save(update_fields=["is_staff"]) + with self.assertRaises(ExportError) as error: + consume_ticket(ticket["ticket"]) + self.assertEqual(error.exception.status, 403) + with self.assertRaises(ExportError) as error: + consume_ticket(ticket["ticket"]) + self.assertEqual(error.exception.status, 410) + + def test_expired_and_malformed(self): + self.records() + generation = build_source(GROUP) + ticket = issue_ticket(self.user, self.selector(generation)) + SourceExportTicket.objects.update( + expires_at=timezone.now() - timedelta(seconds=1) + ) + with self.assertRaises(ExportError) as error: + consume_ticket(ticket["ticket"]) + self.assertEqual(error.exception.status, 410) + with self.assertRaises(ExportError) as error: + consume_ticket("se1_ path ") + self.assertEqual(error.exception.status, 400) + + def test_cleanup_ticket_and_stream_leases_and_tombstone(self): + self.records() + old = build_source(GROUP) + ticket = issue_ticket(self.user, self.selector(old)) + build_source(GROUP) + build_source(GROUP) + SourceExportGeneration.objects.filter(pk=old.pk).update( + created_at=timezone.now() - timedelta(days=2) + ) + self.assertEqual(cleanup(GROUP), 0) + stream = consume_ticket(ticket["ticket"]) + self.assertEqual(cleanup(GROUP), 0) + self.close_response( + stream + ) # Close before first iteration must release all resources. + self.assertEqual(cleanup(GROUP), 1) + with self.assertRaises(ExportError) as error: + detail(GROUP, QueryDict(f"generation_id={old.pk}")) + self.assertEqual(error.exception.status, 409) + + def test_missing_artifact_before_200_marks_unavailable(self): + self.records() + generation = build_source(GROUP) + ticket = issue_ticket(self.user, self.selector(generation)) + (_directory(generation) / ticket["file_name"]).unlink() + with self.assertRaises(ExportError) as error: + consume_ticket(ticket["ticket"]) + self.assertEqual(error.exception.status, 503) + generation.refresh_from_db() + self.assertFalse(generation.storage_available) + + def test_symlink_rejected(self): + self.records() + generation = build_source(GROUP) + artifact = generation.manifest["parts"][0]["variants"][0] + path = _directory(generation) / artifact["file_name"] + outside = Path(self.directory.name) / "outside" + path.rename(outside) + path.symlink_to(outside) + with self.assertRaises(ExportError): + issue_ticket(self.user, self.selector(generation, fmt=artifact["format"])) + + def test_failure_keeps_current_and_cleans_staging(self): + self.records() + first = build_source(GROUP) + with patch( + "organizations.source_export_catalog._render_part", + side_effect=OSError("no space"), + ), self.assertRaises(OSError): + build_source(GROUP) + state = SourceExportState.objects.get(pk=GROUP) + self.assertEqual(state.current_generation, first.pk) + self.assertEqual(state.last_build["state"], "failed") + self.assertEqual(list((_directory(first).parent).glob(".building-*")), []) + item = next(s for s in catalog()["sources"] if s["source_group"] == GROUP) + self.assertEqual(item["state"], "ready") + self.assertTrue(item["is_stale"]) + + def test_finances_all_lines_json_only(self): + extension = FinancialIndicatorsExtension.objects.create( + organization=self.organization + ) + record = OrganizationSourceRecord.objects.create( + extension=extension, + source="fns_reports", + record_type="financial_report", + title="Report", + ) + for year in [2022, 2023]: + OrganizationSourceFinancialLine.objects.create( + source_record=record, year=year, form_code="1", line_code=str(year) + ) + generation = build_source("financial_indicators") + self.assertEqual(generation.manifest["supported_formats"], ["json"]) + ticket = issue_ticket(self.user, self.selector(generation)) + rows = json.loads(self.bytes(consume_ticket(ticket["ticket"]))) + self.assertEqual( + [r["year"] for r in rows[0]["financial_indicators"][0]["financial_lines"]], + [2022, 2023], + ) + with self.assertRaises(ExportError) as error: + issue_ticket(self.user, self.selector(generation, fmt="xlsx")) + self.assertEqual(error.exception.status, 409) + + def test_strict_selector(self): + self.records() + generation = build_source(GROUP) + for extra in [{"sources": [GROUP]}, {"path": "/etc/passwd"}, {"page": 1}]: + response = self.client.post( + self.base + "export-ticket/", + {**self.selector(generation), **extra}, + format="json", + ) + self.assertEqual(response.status_code, 400) + response = self.client.post( + self.base + "export/", self.selector(generation), format="json" + ) + self.assertEqual(response.status_code, 400) + + def test_actual_oversize_splits_every_variant_together(self): + import secrets + + for record in self.records(5): + record.payload = {"text": secrets.token_hex(1200)} + record.save(update_fields=["payload"]) + with override_settings( + SOURCE_EXPORT_ROWS_PER_PART=100, SOURCE_EXPORT_MAX_FILE_BYTES=10000 + ): + generation = build_source(GROUP) + self.assertGreater(len(generation.manifest["parts"]), 1) + for part in generation.manifest["parts"]: + self.assertTrue(all(v["size_bytes"] <= 10000 for v in part["variants"])) + self.assertEqual( + sum(p["records_count"] for p in generation.manifest["parts"]), 5 + ) + + def test_one_indivisible_record_fails(self): + self.records(1) + with override_settings(SOURCE_EXPORT_MAX_FILE_BYTES=10), self.assertRaises( + ExportError + ) as error: + build_source(GROUP) + self.assertEqual(error.exception.code, "source_export_record_too_large") + self.assertIsNone(SourceExportState.objects.get(pk=GROUP).current_generation) + + def test_rate_and_stream_limits(self): + self.records() + generation = build_source(GROUP) + first = issue_ticket(self.user, self.selector(generation)) + second = issue_ticket(self.user, self.selector(generation)) + stream = consume_ticket(first["ticket"]) + try: + with override_settings( + SOURCE_EXPORT_MAX_STREAMS_PER_USER=1 + ), self.assertRaises(ExportError) as error: + consume_ticket(second["ticket"]) + self.assertEqual(error.exception.status, 429) + finally: + self.close_response(stream) + with override_settings(SOURCE_EXPORT_METADATA_RATE=1): + self.assertEqual( + self.client.get(self.base + "export-catalog/").status_code, 200 + ) + self.assertEqual( + self.client.get(self.base + "export-catalog/").status_code, 429 + ) + + def test_unknown_new_ticket_and_foreign_generation(self): + with self.assertRaises(ExportError) as error: + consume_ticket("se1_" + "x" * 43) + self.assertEqual(error.exception.status, 410) + self.records() + generation = build_source(GROUP) + selection = {**self.selector(generation), "source_group": "arbitration"} + response = self.client.post( + self.base + "export-ticket/", selection, format="json" + ) + self.assertEqual(response.status_code, 404) + selection["source_group"] = "unknown" + self.assertEqual( + self.client.post( + self.base + "export-ticket/", selection, format="json" + ).status_code, + 404, + ) + + def test_same_size_corruption_background_verification(self): + from organizations.source_export_catalog import verify_generation + + self.records() + generation = build_source(GROUP) + variant = generation.manifest["parts"][0]["variants"][0] + path = _directory(generation) / variant["file_name"] + with path.open("r+b") as handle: + handle.write(b"BAD!") + self.assertFalse(verify_generation(generation)) + with self.assertRaises(ExportError) as error: + issue_ticket(self.user, self.selector(generation)) + self.assertEqual(error.exception.status, 503) + + def test_all_registry_adapters_and_subsources(self): + from organizations.source_groups import SOURCE_GROUP_DESCRIPTORS + + extensions, expected = {}, {} + for source, descriptor in SOURCE_GROUP_DESCRIPTORS.items(): + group = descriptor.source_group + if group not in extensions: + extensions[group] = descriptor.extension_model.objects.filter( + organization=self.organization + ).first() or descriptor.extension_model.objects.create( + organization=self.organization + ) + record = OrganizationSourceRecord.objects.create( + extension=extensions[group], + source=source, + record_type=descriptor.record_type, + external_id=str(uuid4()), + title="Synthetic", + ) + expected.setdefault(group, set()).add(str(record.uid)) + self.assertEqual(set(expected), set(registry())) + for group, uids in expected.items(): + generation = build_source(group) + exported = set() + for part in generation.manifest["parts"]: + variant = next(v for v in part["variants"] if v["format"] == "json") + rows = json.loads( + (_directory(generation) / variant["file_name"]).read_bytes() + ) + if group != SourceGroup.SANCTIONS: + exported.update( + row["uid"] + for organization in rows + for row in organization[group] + ) + self.assertEqual(generation.manifest["records_count"], len(uids)) + if group != SourceGroup.SANCTIONS: + self.assertEqual(exported, uids, group) + + def test_two_pages_more_than_fifty_parts(self): + self.records(51) + with override_settings(SOURCE_EXPORT_ROWS_PER_PART=1): + generation = build_source(GROUP) + first, meta = detail(GROUP, QueryDict(f"generation_id={generation.pk}")) + second, meta2 = detail( + GROUP, QueryDict(f"page=2&generation_id={generation.pk}") + ) + self.assertEqual(len(first["files"]), 50) + self.assertEqual(len(second["files"]), 1) + self.assertEqual(meta["total_count"], 51) + self.assertFalse(meta2["has_next"]) + ticket = issue_ticket(self.user, self.selector(generation, "source_archive")) + with zipfile.ZipFile( + BytesIO(self.bytes(consume_ticket(ticket["ticket"]))) + ) as archive: + self.assertEqual(len(archive.namelist()), 52) + + def test_storage_failure_issuance_and_request_errors(self): + self.records() + generation = build_source(GROUP) + variant = next( + v + for v in generation.manifest["parts"][0]["variants"] + if v["format"] == "json" + ) + (_directory(generation) / variant["file_name"]).unlink() + response = self.client.post( + self.base + "export-ticket/", self.selector(generation), format="json" + ) + self.assertEqual(response.status_code, 503) + generation.refresh_from_db() + self.assertFalse(generation.storage_available) + from django.db import OperationalError + + with patch( + "organizations.source_export_catalog.catalog", + side_effect=OperationalError("private detail"), + ): + response = self.client.get(self.base + "export-catalog/") + self.assertEqual(response.status_code, 503) + self.assertNotIn("private detail", json.dumps(response.data)) + + def test_runtime_contract_fixtures(self): + import os + + self.records(3) + generation = build_source(GROUP) + cases = [] + for name, response in [ + ("catalog", self.client.get(self.base + "export-catalog/")), + ( + "detail", + self.client.get( + self.base + f"export-catalog/{GROUP}/?generation_id={generation.pk}" + ), + ), + ( + "file-ticket", + self.client.post( + self.base + "export-ticket/", + self.selector(generation), + format="json", + ), + ), + ( + "archive-ticket", + self.client.post( + self.base + "export-ticket/", + self.selector(generation, "source_archive"), + format="json", + ), + ), + ("invalid", self.client.get(self.base + "export-catalog/?unknown=true")), + ]: + cases.append( + {"name": name, "status": response.status_code, "body": response.data} + ) + destination = os.environ.get("SOURCE_EXPORT_RUNTIME_FIXTURES") + if destination: + Path(destination).write_text(json.dumps(cases), encoding="utf-8") + + def test_json_request_must_be_an_object(self): + for value in [[], 123, "bad"]: + response = self.client.post( + self.base + "export-ticket/", value, format="json" + ) + self.assertEqual(response.status_code, 400) + response = self.client.post( + self.base + "export-ticket/", "{bad", content_type="application/json" + ) + self.assertEqual(response.status_code, 400) + + def test_short_artifact_aborts_zip(self): + from organizations.source_export_catalog import _stream_zip + + with self.assertRaises(OSError): + b"".join( + _stream_zip( + [ + ( + {"file_name": "short.json", "size_bytes": 100}, + BytesIO(b"short"), + ) + ], + {}, + ) + ) + + def test_expired_build_lock_can_be_queued_and_owner_cannot_release_successor(self): + from organizations.source_export_catalog import _build_state, mark_queued + + old = uuid4() + SourceExportState.objects.create( + source_group=GROUP, + lock_owner=old, + lock_expires_at=timezone.now() - timedelta(seconds=1), + ) + self.assertTrue(mark_queued(GROUP)) + self.assertFalse(mark_queued(GROUP)) + self.assertEqual(_build_state(GROUP, old, lock_owner=None), 0) + self.assertIsNone(SourceExportState.objects.get(pk=GROUP).lock_owner) + self.assertIsNotNone(build_source(GROUP)) + + def test_new_build_task_coalesces_queued_groups(self): + from organizations.tasks import refresh_source_export_catalog + + with patch.object(refresh_source_export_catalog, "delay") as enqueue: + first = refresh_source_export_catalog.run() + second = refresh_source_export_catalog.run() + self.assertEqual(first["groups"], 22) + self.assertEqual(second["groups"], 0) + self.assertEqual(enqueue.call_count, 22) + self.assertTrue(all(s["state"] == "building" for s in catalog()["sources"])) + + def test_new_management_command_and_verify_mode(self): + from django.core.management import call_command + + self.records() + call_command( + "build_source_export_catalog", source_group=GROUP, stdout=StringIO() + ) + generation = SourceExportGeneration.objects.get(source_group=GROUP) + with patch( + "organizations.management.commands.build_source_export_catalog.cleanup", + side_effect=AssertionError("verify must not delete"), + ): + call_command( + "build_source_export_catalog", + source_group=GROUP, + verify_only=True, + stdout=StringIO(), + ) + self.assertEqual(generation.manifest["records_count"], 3) + + def test_single_file_truncation_aborts_and_releases_lease(self): + self.records() + generation = build_source(GROUP) + ticket = issue_ticket(self.user, self.selector(generation)) + response = consume_ticket(ticket["ticket"]) + (_directory(generation) / ticket["file_name"]).write_bytes(b"short") + with self.assertRaises(OSError): + self.bytes(response) + self.assertFalse(SourceExportLease.objects.exists()) + + def test_authentication_precedes_malformed_ticket_json(self): + self.client.force_authenticate(None) + response = self.client.post( + self.base + "export-ticket/", "{bad", content_type="application/json" + ) + self.assertEqual(response.status_code, 401) diff --git a/tests/apps/organizations/test_source_export_postgres.py b/tests/apps/organizations/test_source_export_postgres.py new file mode 100644 index 0000000..11c79bd --- /dev/null +++ b/tests/apps/organizations/test_source_export_postgres.py @@ -0,0 +1,115 @@ +"""Run against settings pointing to an isolated PostgreSQL test database.""" +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier +from uuid import uuid4 + +import pytest +from django.db import close_old_connections, connection +from django.test import override_settings +from organizations.models import ( + GovernmentProcurementExtension, + Organization, + OrganizationSourceRecord, +) +from organizations.source_export_catalog import build_source, issue_ticket +from rest_framework.test import APIClient + +from tests.apps.user.factories import UserFactory + + +@pytest.mark.django_db(transaction=True) +@pytest.mark.skipif( + connection.vendor != "postgresql", + reason="Requires PostgreSQL row locks and independent connections", +) +def test_two_simultaneous_native_posts_one_ticket(tmp_path): + with override_settings(SOURCE_EXPORT_DIRECTORY=str(tmp_path)): + user = UserFactory.create_superuser() + organization = Organization.objects.create( + name="Synthetic race fixture", inn="0012345678", ogrn="1027700132195" + ) + extension = GovernmentProcurementExtension.objects.create( + organization=organization + ) + OrganizationSourceRecord.objects.create( + extension=extension, + source="procurements_44fz", + record_type="procurement", + external_id=str(uuid4()), + ) + generation = build_source("government_procurements") + ticket = issue_ticket( + user, + { + "selection_kind": "file", + "source_group": "government_procurements", + "generation_id": str(generation.pk), + "part_id": generation.manifest["parts"][0]["part_id"], + "format": "json", + }, + ) + barrier = Barrier(2) + + def post(): + close_old_connections() + try: + barrier.wait(timeout=10) + response = APIClient().post( + "/api/v2/organization-source-records/export-download/", + "ticket=" + ticket["ticket"], + content_type="application/x-www-form-urlencoded", + ) + if response.streaming: + assert sum(len(chunk) for chunk in response.streaming_content) > 0 + code = response.status_code + response.close() + return code + finally: + connection.close() + + with ThreadPoolExecutor(max_workers=2) as workers: + futures = [workers.submit(post) for _ in range(2)] + assert sorted(f.result(timeout=30) for f in futures) == [200, 410] + + +@pytest.mark.django_db(transaction=True) +@pytest.mark.skipif( + connection.vendor != "postgresql", + reason="Requires independent PostgreSQL connections", +) +def test_stream_lease_renewal_and_loss_use_independent_database_connection(): + import time + from datetime import timedelta + from unittest.mock import patch + + from django.utils import timezone + from organizations.models import SourceExportGeneration, SourceExportLease + from organizations.source_export_catalog import _heartbeat + + generation = SourceExportGeneration.objects.create( + source_group="arbitration", data_revision="test" + ) + expires = timezone.now() + timedelta(minutes=2) + lease = SourceExportLease.objects.create( + generation=generation, issuer_id="test", kind="stream", expires_at=expires + ) + + def renew(): + return SourceExportLease.objects.filter( + pk=lease.pk, expires_at__gt=timezone.now() + ).update(expires_at=timezone.now() + timedelta(minutes=10)) + + # Accelerate only the timer; connection, SQL and expiry/ownership checks are real. + with patch( + "organizations.source_export_catalog.HEARTBEAT_RENEW_SECONDS", 0.05 + ), _heartbeat(renew) as lost: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + lease.refresh_from_db() + if lease.expires_at > expires: + break + time.sleep(0.02) + assert lease.expires_at > expires + assert not lost.is_set() + lease.delete() + assert lost.wait(timeout=5) diff --git a/tests/apps/organizations/test_source_export_transport.py b/tests/apps/organizations/test_source_export_transport.py new file mode 100644 index 0000000..e2c941c --- /dev/null +++ b/tests/apps/organizations/test_source_export_transport.py @@ -0,0 +1,93 @@ +"""Opt-in synthetic transport load. Does not claim proxy/browser/production acceptance.""" +import json +import os +import resource +import sys +import threading +import time +from concurrent.futures import ThreadPoolExecutor + +import pytest +from organizations.source_export_catalog import CHUNK_SIZE, _stream_zip, catalog + + +@pytest.mark.slow +@pytest.mark.django_db +@pytest.mark.skipif( + os.environ.get("SOURCE_EXPORT_TRANSPORT_LOAD") != "1", + reason="Opt-in 5.5 GiB transport read", +) +def test_zip64_two_parallel_files_and_catalog(tmp_path): + # Sparse source emits actual zero bytes on every read. No Content-Length mock, + # giant allocation, full archive file, production data or upstream access. + size = 512 * 1024 * 1024 + path = tmp_path / "synthetic.bin" + with path.open("wb") as handle: + handle.truncate(size) + barrier = threading.Barrier(4) + metrics = {} + before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + + def download_file(): + barrier.wait(timeout=10) + total = 0 + with path.open("rb") as handle: + while chunk := handle.read(CHUNK_SIZE): + total += len(chunk) + return total + + def download_zip(): + handles = [path.open("rb") for _ in range(11)] + opened = [ + ({"file_name": f"synthetic-{index}.bin", "size_bytes": size}, handle) + for index, handle in enumerate(handles) + ] + try: + barrier.wait(timeout=10) + total, tail = 0, b"" + for chunk in _stream_zip(opened, {"fixture": "synthetic-transport-only"}): + total += len(chunk) + tail = chunk[-4096:] if len(chunk) >= 4096 else (tail + chunk)[-4096:] + assert total > 5 * 1024**3 + assert ( + b"PK\x06\x06" in tail + ) # ZIP64 end of central directory, actual >4 GiB offsets. + return total + finally: + for handle in handles: + handle.close() + + latencies = [] + started = time.monotonic() + with ThreadPoolExecutor(max_workers=3) as workers: + archive = workers.submit(download_zip) + files = [workers.submit(download_file) for _ in range(2)] + barrier.wait(timeout=10) + while not archive.done(): + before_get = time.monotonic() + assert len(catalog()["sources"]) == 22 + latencies.append(time.monotonic() - before_get) + # Local load sampling, not production request scheduling. + time.sleep(0.01) + metrics["zip_bytes"] = archive.result() + assert [f.result() for f in files] == [size, size] + rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - before + rss_bytes = rss if sys.platform == "darwin" else rss * 1024 + p95 = sorted(latencies)[max(0, int(len(latencies) * 0.95) - 1)] + assert rss_bytes < 64 * 1024 * 1024 + assert p95 < 1.0 + metrics.update( + { + "elapsed_seconds": time.monotonic() - started, + "rss_growth_bytes": rss_bytes, + "catalog_samples": len(latencies), + "catalog_p95_seconds": p95, + "parallel_file_bytes": size, + "scope": "local transport and metadata; no HTTP proxy/browser", + } + ) + destination = os.environ.get("SOURCE_EXPORT_TRANSPORT_REPORT") + if destination: + from pathlib import Path + + Path(destination).write_text(json.dumps(metrics, indent=2) + "\n") diff --git a/tools/openapi/build.mjs b/tools/openapi/build.mjs index c20b2a3..0e90f4a 100644 --- a/tools/openapi/build.mjs +++ b/tools/openapi/build.mjs @@ -3,6 +3,7 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import converter from 'swagger2openapi'; +import { addSourceExportCatalog } from './source-export-catalog.mjs'; import validator from 'oas-validator'; const base = fileURLToPath(new URL('../..', import.meta.url)); @@ -236,6 +237,7 @@ function removeEmptyRequired(value) { if (Array.isArray(value.required) && value.required.length === 0) delete value.required; for (const child of Object.values(value)) removeEmptyRequired(child); } +addSourceExportCatalog(document); removeEmptyRequired(document); const encoded = JSON.stringify(document, null, 2) + '\n'; diff --git a/tools/openapi/check-source-export-runtime.mjs b/tools/openapi/check-source-export-runtime.mjs new file mode 100644 index 0000000..66dfcd8 --- /dev/null +++ b/tools/openapi/check-source-export-runtime.mjs @@ -0,0 +1,26 @@ +/** Validate actual new-scope responses using the generated client validators. */ +import { readFileSync } from 'node:fs'; +import { isDeepStrictEqual } from 'node:util'; +import { + V2OrganizationSourceRecordsExportCatalogList200Response, + V2OrganizationSourceRecordsExportCatalogRead200Response, + V2OrganizationSourceRecordsExportTicket201Response, + V2OrganizationSourceRecordsExportCatalogList400Response, +} from './generated-zod/contract.ts'; +const validators = { + catalog: V2OrganizationSourceRecordsExportCatalogList200Response, + detail: V2OrganizationSourceRecordsExportCatalogRead200Response, + 'file-ticket': V2OrganizationSourceRecordsExportTicket201Response, + 'archive-ticket': V2OrganizationSourceRecordsExportTicket201Response, + invalid: V2OrganizationSourceRecordsExportCatalogList400Response, +}; +const cases = JSON.parse(readFileSync(process.argv[2], 'utf8')); +const seen = new Set(); +for (const fixture of cases) { + if (seen.has(fixture.name) || !validators[fixture.name]) throw new Error('Unexpected fixture'); + seen.add(fixture.name); + const value = validators[fixture.name].parse(fixture.body); + if (!isDeepStrictEqual(value, fixture.body)) throw new Error(`Lossy generated validator: ${fixture.name}`); +} +if (seen.size !== Object.keys(validators).length) throw new Error('Missing fixtures'); +console.log(`Source export generated Zod: ${seen.size} actual API responses passed`); diff --git a/tools/openapi/contract.ts b/tools/openapi/contract.ts index a591237..265f985 100644 --- a/tools/openapi/contract.ts +++ b/tools/openapi/contract.ts @@ -39,3 +39,21 @@ export function total(response: OrganizationSourceRecordListResponse): number { } export const existingOrder: V2OrganizationSourceRecordsListOrdering = '-payload__united_states'; + +import { v2OrganizationSourceRecordsExportTicket } from './generated/client'; +import type { SourceExportFileTicketRequest, SourceExportArchiveTicketRequest, OrganizationSourceRecordExportRequest } from './generated/schemas'; + +// All three selectors must remain callable through the actual generated function. +export async function exportSelection(selector: SourceExportFileTicketRequest | SourceExportArchiveTicketRequest | OrganizationSourceRecordExportRequest): Promise { + const response = await v2OrganizationSourceRecordsExportTicket(selector); + if (response.status === 201) { + const ticket: string = response.data.ticket; + if ('selection_kind' in response.data) { + const format: 'xlsx' | 'csv' | 'json' = response.data.format; + const size: number | null = response.data.size_bytes; + return `${ticket}:${format}:${size}`; + } + return ticket; + } + return ''; +} diff --git a/tools/openapi/orval.config.mjs b/tools/openapi/orval.config.mjs index 7fe23b0..3b1c772 100644 --- a/tools/openapi/orval.config.mjs +++ b/tools/openapi/orval.config.mjs @@ -13,7 +13,14 @@ export default defineConfig({ output: { mode: 'single', target: './generated-zod/contract.ts', client: 'zod', clean: true, - override: { zod: { generateEachHttpStatus: true } }, + override: { + zod: { generateEachHttpStatus: true }, + operations: { + v2_organization_source_records_export_ticket: { + zod: { strict: { body: true, response: true } }, + }, + }, + }, }, }, }); diff --git a/tools/openapi/source-export-catalog.mjs b/tools/openapi/source-export-catalog.mjs new file mode 100644 index 0000000..716d143 --- /dev/null +++ b/tools/openapi/source-export-catalog.mjs @@ -0,0 +1,76 @@ +/** Typed all-available contract, composed with generated legacy DRF operations. */ +export function addSourceExportCatalog(document) { + const schemas = document.components.schemas; + const ref = name => ({ $ref: `#/components/schemas/${name}` }); + const string = { type: 'string' }; + const uuid = { type: 'string', format: 'uuid' }; + const date = { type: 'string', format: 'date-time' }; + const integer = { type: 'integer', minimum: 0, maximum: 9007199254740991 }; + const positive = { ...integer, minimum: 1 }; + const bool = { type: 'boolean' }; + const enumeration = values => ({ type: 'string', enum: values }); + const format = enumeration(['xlsx', 'csv', 'json']); + const nullable = schema => ({ ...schema, nullable: true }); + const nil = { type: 'object', nullable: true, enum: [null] }; + const array = items => ({ type: 'array', items }); + const object = properties => ({ type: 'object', additionalProperties: false, properties, required: Object.keys(properties) }); + const group = structuredClone(schemas.OrganizationSourceRecordExportRequest.properties.sources.items); + schemas.SourceExportBuildSummary = object({ state: enumeration(['idle', 'queued', 'running', 'success', 'failed']), started_at: nullable(date), finished_at: nullable(date), error_code: nullable(string) }); + const snapshot = { + source_group: group, generation_id: nullable(uuid), + state: enumeration(['ready', 'empty', 'not_ready', 'building', 'unavailable']), + unavailable_reason: nullable(enumeration(['disabled', 'adapter_missing', 'build_failed', 'storage_unavailable'])), + generated_at: nullable(date), data_as_of: nullable(date), data_scope: enumeration(['all_available']), + }; + schemas.SourceExportSourceSummary = object({ ...snapshot, source_slug: string, title: string, order: integer, export_enabled: bool, + records_count: nullable(integer), parts_count: nullable(integer), supported_formats: { ...array(format), uniqueItems: true }, + default_format: nullable(format), is_stale: bool, last_build: ref('SourceExportBuildSummary') }); + const envelope = (data, meta = nil) => object({ success: { type: 'boolean', enum: [true] }, data, errors: nil, meta }); + schemas.SourceExportCatalogResponse = envelope(object({ schema_version: enumeration(['1']), catalog_revision: string, sources: array(ref('SourceExportSourceSummary')) })); + schemas.SourceExportDescription = object({ composition: string, origin: string, fields: string, example_dataset_key: nullable(string), example_is_synthetic: bool, + example_record: { type: 'object', additionalProperties: true, nullable: true } }); + schemas.SourceExportDataset = object({ key: string, title: string, export_schema_version: string, records_count: integer, parts_count: integer }); + schemas.SourceExportArtifact = object({ artifact_id: uuid, format, file_name: { type: 'string', pattern: '^[A-Za-z0-9._-]+$' }, mime_type: string, + size_bytes: positive, sha256: { type: 'string', pattern: '^[0-9a-f]{64}$' } }); + schemas.SourceExportPart = object({ part_id: uuid, dataset_key: string, title: string, part_number: positive, parts_count: positive, records_count: positive, + default_format: format, variants: { ...array(ref('SourceExportArtifact')), minItems: 1 } }); + schemas.SourceExportPagination = object({ page: positive, page_size: { ...positive, maximum: 200 }, total_count: integer, total_pages: positive, has_next: bool, has_previous: bool }); + schemas.SourceExportSourceDetail = object({ ...snapshot, current_generation_id: nullable(uuid), description: ref('SourceExportDescription'), datasets: array(ref('SourceExportDataset')), files: array(ref('SourceExportPart')) }); + schemas.SourceExportSourceDetailResponse = envelope(ref('SourceExportSourceDetail'), object({ pagination: ref('SourceExportPagination') })); + schemas.SourceExportAuthenticationError = object({ detail: string }); + schemas.SourceExportError = object({ detail: string, code: string, field: nullable(string), retryable: bool, request_id: uuid }); + schemas.SourceExportFileTicketRequest = object({ selection_kind: enumeration(['file']), source_group: group, generation_id: uuid, part_id: uuid, format }); + schemas.SourceExportArchiveTicketRequest = object({ selection_kind: enumeration(['source_archive']), source_group: group, generation_id: uuid, format }); + schemas.OrganizationSourceRecordExportRequest.additionalProperties = false; + schemas.SourceRecordExportTicket.additionalProperties = false; + schemas.SourceRecordExportTicket.required = Object.keys(schemas.SourceRecordExportTicket.properties); + schemas.SourceExportSelectionTicket = object({ ticket: { type: 'string', minLength: 47, maxLength: 47 }, file_name: string, expires_in: { type: 'integer', enum: [300] }, + selection_kind: enumeration(['file', 'source_archive']), source_group: group, generation_id: uuid, format, mime_type: string, size_bytes: nullable(positive), parts_count: positive }); + schemas.SourceRecordExportDownloadRequest = object({ ticket: { type: 'string', minLength: 1, maxLength: 128 } }); + const base = '/api/v2/organization-source-records/'; + const json = schema => ({ 'application/json': { schema } }); + const response = (schema, description = 'Success') => ({ description, content: json(schema) }); + const errorResponses = Object.fromEntries([400,403,404,409,410,429,503,500].map(code => [code, response(ref('SourceExportError'), 'Export request failed')])); + for (const [endpoint, schema] of [['export-catalog/', 'SourceExportCatalogResponse'], ['export-catalog/{source_group}/', 'SourceExportSourceDetailResponse']]) { + const operation = document.paths[base + endpoint].get; + operation.responses = { ...errorResponses, 200: response(ref(schema)), 401: response(ref('SourceExportAuthenticationError'), 'Authentication required') }; + operation.parameters = endpoint.includes('{') ? [ + { name: 'source_group', in: 'path', required: true, schema: group }, + { name: 'generation_id', in: 'query', schema: uuid }, + { name: 'page', in: 'query', schema: { ...positive, default: 1 } }, + { name: 'page_size', in: 'query', schema: { ...positive, maximum: 200, default: 50 } }, + ] : []; + } + const ticket = document.paths[base + 'export-ticket/'].post; + ticket.requestBody = { required: true, content: json({ oneOf: ['OrganizationSourceRecordExportRequest', 'SourceExportFileTicketRequest', 'SourceExportArchiveTicketRequest'].map(ref) }) }; + ticket.responses = { ...errorResponses, 201: response({ oneOf: ['SourceRecordExportTicket', 'SourceExportSelectionTicket'].map(ref) }), 401: response(ref('SourceExportAuthenticationError'), 'Authentication required') }; + const download = document.paths[base + 'export-download/'].post; + download.requestBody = { required: true, content: { 'application/x-www-form-urlencoded': { schema: ref('SourceRecordExportDownloadRequest') } } }; + download.responses = { ...errorResponses, 200: { description: 'Pinned artifact or streaming ZIP64', content: Object.fromEntries([ + 'application/zip', 'application/json', 'text/csv', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ].map(mime => [mime, { schema: { type: 'string', format: 'binary' } }])) } }; + for (const [status, legacy] of [[400, 'SourceRecordExportInvalidTicket'], [410, 'SourceRecordExportTicketExpired'], [503, 'SourceRecordExportUnavailable']]) { + download.responses[status] = response({ oneOf: [ref(legacy), ref('SourceExportError')] }, 'Legacy or all-available export failure'); + } + +}