From 6e6048a0cfb78225d4b0c276c18d73582f9b928e Mon Sep 17 00:00:00 2001 From: Igor Apresov Date: Wed, 2 Sep 2026 11:47:43 +0300 Subject: [PATCH] feat(infobase): export CF CFE and DT artifacts - add typed CF/CFE and DT CLI contracts with pre-spawn provider selection - harden staged publication, locks, deadlines, and diagnostics - document ADR-0024 and cover the environment matrix --- Cargo.lock | 17 + Cargo.toml | 6 +- SKILL/SKILL.md | 33 +- .../references/file-and-artifact-workflows.md | 29 + docs/CAPABILITIES.md | 45 + docs/CONFIGURATION.md | 25 +- scripts/test/README.md | 4 + scripts/test/ci-rust.sh | 11 +- spec/IMPLEMENTATION_TODO.md | 6 +- .../arc42/09-architecture-decisions.md | 1 + spec/architecture/invariants.md | 13 + ...noe-vladenie-workpath-na-vremya-komandy.md | 11 +- ...rovat-eksport-konfiguratsii-i-snimka-ib.md | 252 +++ spec/decisions/README.md | 1 + src/app.rs | 93 +- src/cli/args.rs | 123 ++ src/cli/execute.rs | 846 ++++++++- src/cli/output.rs | 16 +- src/config/loader.rs | 16 +- src/config/validate.rs | 14 + src/domain/infobase_export.rs | 584 +++++++ src/domain/mod.rs | 2 + src/mcp/error.rs | 12 + src/platform/connection.rs | 46 + src/platform/designer.rs | 110 ++ src/platform/ibcmd.rs | 105 ++ src/support/error.rs | 28 + src/support/fs.rs | 598 +++++-- src/support/logging.rs | 90 +- src/support/path.rs | 110 +- src/use_cases/artifacts.rs | 114 +- src/use_cases/context.rs | 4 + src/use_cases/convert_sources.rs | 31 +- src/use_cases/dump_config.rs | 15 +- src/use_cases/infobase_export.rs | 1532 +++++++++++++++++ src/use_cases/mod.rs | 1 + src/use_cases/result.rs | 42 + src/use_cases/staged_publication.rs | 327 +++- src/use_cases/transport.rs | 38 +- src/use_cases/workspace_lock.rs | 13 +- tests/architecture_guardrails.rs | 5 +- tests/cli_help.rs | 30 + tests/cli_infobase.rs | 1191 +++++++++++++ tests/cli_infobase_cross_platform.rs | 178 ++ tests/support/fake_platform.rs | 49 + 45 files changed, 6459 insertions(+), 358 deletions(-) create mode 100644 spec/decisions/0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md create mode 100644 src/domain/infobase_export.rs create mode 100644 src/use_cases/infobase_export.rs create mode 100644 tests/cli_infobase.rs create mode 100644 tests/cli_infobase_cross_platform.rs create mode 100644 tests/support/fake_platform.rs diff --git a/Cargo.lock b/Cargo.lock index 2d8ea9be2..a97c0782a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2284,12 +2284,27 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" +[[package]] +name = "unicode-casefold" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f66b1c8f8caa2ab31dc6d3f35386f16efdab89668f93411e565ac368908e8f" + [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-xid" version = "0.2.6" @@ -2381,6 +2396,8 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", + "unicode-casefold", + "unicode-normalization", "uuid", "walkdir", "windows-sys 0.61.2", diff --git a/Cargo.toml b/Cargo.toml index ac3e007a1..473bb73d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,9 +36,13 @@ tokio = { version = "1", features = ["io-std", "io-util", "macros", "net", "proc tokio-util = "0.7" reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] } +[target.'cfg(any(windows, target_os = "macos"))'.dependencies] +unicode-casefold = "0.2" +unicode-normalization = "0.1" + [target.'cfg(windows)'.dependencies] process-wrap = { version = "9.1.0", default-features = false, features = ["std", "job-object", "creation-flags"] } -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Console"] } [dev-dependencies] assert_cmd = "2" diff --git a/SKILL/SKILL.md b/SKILL/SKILL.md index 394883c4a..1e2a26c50 100644 --- a/SKILL/SKILL.md +++ b/SKILL/SKILL.md @@ -48,10 +48,25 @@ Useful global flags: 1. Check whether `v8project.yaml` exists in the 1C project root. 2. If it is missing and source files already exist, run the narrowest `v8-runner config init ...` command that fits the project shape. -3. If it is missing and the current source of truth is an existing infobase, run `v8-runner bootstrap --connection --platform-version `. -4. Inspect generated `v8project.yaml` and keep machine-local overrides in generated `v8project.local.yaml`. -5. Run `v8-runner init` only when the file infobase or EDT workspace needs to be created. -6. Run the narrowest validation command that answers the user's goal. +3. If it is missing and the only goal is to export CF/CFE/DT from an existing infobase, create a + minimal `v8project.yaml` with `workPath`, `builder`, `infobase`, platform discovery settings and + `source-set: []`; do not bootstrap project sources that the user did not request. +4. If it is missing and the current source of truth is an existing infobase that must become + project sources, run `v8-runner bootstrap --connection --platform-version `. +5. Inspect generated `v8project.yaml` and keep machine-local overrides in generated `v8project.local.yaml`. +6. Run `v8-runner init` only when the file infobase or EDT workspace needs to be created. +7. Run the narrowest validation command that answers the user's goal. + +Minimal infobase-only shape: + +```yaml +workPath: build/v8-runner +format: DESIGNER +builder: DESIGNER +infobase: + connection: "File=/absolute/path/to/ib" +source-set: [] +``` Useful bootstrap commands: @@ -83,6 +98,16 @@ v8-runner init - Vanessa Automation debugging or scenario authoring: use `v8-runner launch mcp va --wait-ready ...` to start the client MCP server with VA loaded and verify the VA MCP tools before driving `.feature` workflows. - Extension properties need synchronization: use `v8-runner extensions` or `extensions --name `. - Infobase changes need to become Git-visible files: check `git status`, then run the relevant `v8-runner dump ...` command. +- Need a CF/CFE package of the state currently stored in the infobase: use + `v8-runner infobase configuration export --state --output `; + add `--extension ` and use `.cfe` for an extension. This is not `make`, which builds + artifacts from project sources. +- Need a complete portable DT image including data: use `v8-runner infobase dump --output `. + A DT is not a backup. Runner treats `builder` as a provider preference for infobase exports, + skips experimental IBCMD DT, and selects a ready Designer before spawn when available. +- For infobase export failures, distinguish `capability_unavailable` (no implemented adapter) + from `environment_unavailable` (adapter exists, but binary/version/connection is not ready). + Never retry another provider after the selected provider has been spawned. - Source files need conversion between Designer and EDT: use `v8-runner convert`; this is CLI-only and does not use the infobase. - Existing `.cf` or `.cfe` artifacts need to be applied to an infobase: use `v8-runner load ...`. - Release artifacts need to be exported or external artifacts published: use `v8-runner make ...` or the `artifacts` alias. diff --git a/SKILL/references/file-and-artifact-workflows.md b/SKILL/references/file-and-artifact-workflows.md index c9064675b..801891bba 100644 --- a/SKILL/references/file-and-artifact-workflows.md +++ b/SKILL/references/file-and-artifact-workflows.md @@ -40,6 +40,35 @@ degrades to incremental. For `format=EDT`, dump uses an internal Designer snapshot under `workPath/designer/`, then imports the result into the EDT target. +## Export From An Infobase + +Use configuration export when the artifact must reflect state already stored in the infobase: + +```bash +v8-runner infobase configuration export --state working --output dist/main.cf +v8-runner infobase configuration export --state database --output dist/main.cf +v8-runner infobase configuration export --state database --extension Sales --output dist/sales.cfe +``` + +These commands accept `source-set: []` because project source trees are not inputs. If no config +exists and sources are not requested, create the minimal infobase-only config described by the +skill entrypoint instead of running `bootstrap`. + +This differs from `make`: `make` builds from project sources, while this command reads the +working or database configuration from the configured infobase. The configured `builder` sets the +preferred provider; runner may choose a ready alternate during pure preflight, but never after +dispatch. + +Use a DT only as a portable full-infobase image, not as a backup: + +```bash +v8-runner infobase dump --output dist/base.dt +``` + +DT export uses the implemented Designer adapter. IBCMD DT remains experimental until a +no-active-connections or exclusive-access preflight is implemented and proved; if Designer is +ready, runner selects it even when `builder=IBCMD`. + ## Convert `convert` is repo-aware file conversion between Designer and EDT source formats. diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index 6b294d9c1..55b70d8a8 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -35,6 +35,8 @@ CLI help, доверяйте текущему коду и затем синхр | `dump` | `format=DESIGNER` + `builder=DESIGNER` | Полная, инкрементальная или object-scoped partial выгрузка | | `dump` | `format=DESIGNER` + `builder=IBCMD` | Полная и инкрементальная выгрузка; `partial` деградирует в incremental с warning; standalone-server state изолирован в `workPath/ibcmd-data` | | `dump` | `format=EDT` + `builder=DESIGNER|IBCMD` | Reverse sync из ИБ через internal Designer snapshot и EDT import | +| `infobase configuration export` | Designer и IBCMD | Выгружает working/database configuration в `.cf` или named extension в `.cfe`; `builder` задаёт preferred provider, runner выбирает готовый до spawn | +| `infobase dump` | Designer | Выгружает полную ИБ в переносимый `.dt`; это не backup; IBCMD остаётся experimental до exclusive-access preflight | | `convert` | CLI-only repo-aware конвертация текущих `source-set` | Не использует `builder` и не требует ИБ | | `load` | `format=DESIGNER` + `builder=DESIGNER` | Загрузка `.cf` / `.cfe` артефактов в ИБ | | `make` / `artifacts` | `format=DESIGNER` + `builder=DESIGNER` | Экспорт `.cf` / `.cfe` и публикация `.epf` / `.erf` | @@ -276,6 +278,49 @@ v8-runner convert [--source-set ] [--output ] - `--output` задаёт только target root и зеркалит `source-set.path` относительно каталога primary config. - Публикация остаётся staged full replacement с overlap guardrails. +### `infobase configuration export` + +```bash +v8-runner infobase configuration export --state --output +v8-runner infobase configuration export --state --extension --output +``` + +- Сохраняет состояние конфигурации из ИБ, а не собирает пакет из project sources. +- Без `--extension` экспортирует main configuration и требует `.cf`; с extension требует `.cfe`. +- `builder` задаёт preferred provider, но runner выбирает первый `implemented + ready` candidate. +- Fallback допустим только во время pure preflight; после первого spawn provider не переключается. +- Публикация идёт через sibling staging и target-specific lock; `published=true` означает, что + финальный файл уже заменён атомарно. +- Target lock сериализует cooperating запуски runner. Параллельный внешний writer обязан + использовать тот же lock или быть остановлен: path revalidation не является filesystem CAS. +- После аварийного завершения owner lock может остаться на диске. Для совместимости с уже + опубликованными версиями runner такой lock обрабатывается fail-closed: удалять его вручную можно + только при остановленных старых и новых процессах runner. +- `execution.status` использует общий terminal vocabulary runner; он не заменяет `published`, + который отдельно отвечает только за commit финального файла. +- `cancelled`, `timed_out` и `invalid_output` не сводятся к generic failure; ошибки считаются + non-retryable по умолчанию, а provider не переключается после dispatch. + +### `infobase dump` + +```bash +v8-runner infobase dump --output +``` + +- Сохраняет полную ИБ с данными в переносимый DT-файл. DT не является резервной копией. +- В первом slice implemented provider — Designer. При `builder=IBCMD` runner пропускает + experimental IBCMD DT и выбирает готовый Designer. +- Если implemented provider есть, но binary/version/connection не готовы, возвращается + `environment_unavailable`; `capability_unavailable` означает отсутствие implemented adapter. +- Для файловой ИБ readiness обоих process providers требует существующий файл + `/1Cv8.1CD`; один каталог или найденный бинарник не считаются готовой ИБ. +- Selection показывает каждого кандидата через независимые `implementation`, `readiness` и + `evidence`; `argv_tested` не выдаётся за live proof. +- Безопасный IBCMD path требует проверки отсутствия активных сеансов. +- Обе операции требуют существующий `v8project.yaml`, но используют infobase-only validation: + `source-set: []` допустим, а отсутствующие или сломанные project sources не блокируют чтение ИБ. + Build/source/test/EDT/client-MCP настройки для этих команд не валидируются. + ### `load` ```bash diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 78fd2c150..15ef03d2a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -256,6 +256,11 @@ tests: - Тип: путь - Обязателен: да +Для обычных project-команд список должен содержать поддерживаемый source-set. Исключение — +`infobase configuration export` и `infobase dump`: они используют только ИБ и принимают +`source-set: []`. Это command-specific validation, а не ослабление `build`, source `dump`, +`convert`, `make` или остальных project workflows. + Корень runtime state: - `workPath/hash-storages` @@ -264,7 +269,8 @@ tests: - `workPath/edt-workspace` - `workPath/designer` -Если каталога нет, он создаётся автоматически. +Если каталога нет, он создаётся автоматически при захвате workspace lock. Pure provider +selection для infobase export не создаёт `workPath` и runtime-файлы. ### `execution_timeout` @@ -291,9 +297,14 @@ tests: Ограничения: -- `builder=IBCMD` поддерживает `init`, `build`, `dump`, `extensions`; -- для server connection с `builder=IBCMD` обязательны `infobase.dbms.kind`, - `infobase.dbms.server`, `infobase.dbms.name`; +- `builder=IBCMD` поддерживает `init`, `build`, source `dump` и `extensions`; для infobase + export значение `builder` задаёт preferred provider, после чего runner выбирает первый + `implemented + ready` candidate до spawn; +- IBCMD DT остаётся experimental до реализации exclusive-access preflight, поэтому + `infobase dump` использует готовый Designer, если он доступен; +- для server connection IBCMD-кандидат готов только при наличии `infobase.dbms.kind`, + `infobase.dbms.server`, `infobase.dbms.name`; в infobase export отсутствие этих полей не + блокирует готовый Designer alternate; - для file connection секция `infobase.dbms` запрещена. ### `infobase` @@ -305,8 +316,10 @@ tests: - Тип: строка - Обязателен: да -Строка подключения к ИБ. Для file-based ИБ относительный `File=...` резолвится относительно -каталога конфига. +Строка подключения к ИБ. Поддерживается непустой `File=...`, server connection +`Srvr=...;Ref=...` или аргументная форма `/S server\ref`. Для file-based ИБ относительный +`File=...` резолвится относительно каталога конфига. Infobase export не считает произвольную +непустую строку готовым server connection. #### `infobase.user` / `infobase.password` diff --git a/scripts/test/README.md b/scripts/test/README.md index 8071f5b8e..9fbd7de48 100644 --- a/scripts/test/README.md +++ b/scripts/test/README.md @@ -59,6 +59,10 @@ live-mcp-http.py ### `ci-rust.sh` - Отвечает только за выбор CI-scope. +- Windows contract scope дополнительно запускает нативный CLI smoke выгрузок CFE и DT через + test-only platform fixture; это сохраняет end-to-end проверку маршрутизации, staging и + публикации на Windows без требования установленной платформы 1С. Тот же scope запускает + cross-process contention smoke и unit-регрессии общего OS/legacy lock protocol. - Не знает деталей live fixture и не должен дублировать live smoke-логику. ### `ci-happy-path.sh` diff --git a/scripts/test/ci-rust.sh b/scripts/test/ci-rust.sh index 44287b598..048da9080 100755 --- a/scripts/test/ci-rust.sh +++ b/scripts/test/ci-rust.sh @@ -12,14 +12,19 @@ case "$CI_SCOPE" in contract) case "$TARGET_OS_LABEL" in Windows|MINGW*|MSYS*|CYGWIN*) - echo "Windows contract scope runs compile/check smoke plus the detached stdio regression; full cargo test remains Linux-owned until the Windows test suite is hardened." + echo "Windows contract scope runs compile/check smoke, native infobase export CLI smoke, and selected OS regressions; full cargo test remains Linux-owned until the Windows test suite is hardened." cargo check --locked --all-targets - windows_stdio_tests=( + cargo test --locked --test cli_infobase_cross_platform + cargo test --locked --bin v8-runner 'support::fs::tests::' + windows_contract_tests=( "platform::process::tests::detached_child_does_not_hold_redirected_stdout_open" "platform::process::tests::managed_detached_child_does_not_hold_redirected_stdout_open" + "support::path::tests::filesystem_object_identity_changes_when_directory_is_replaced" + "support::fs::tests::replace_file_restores_original_bytes_when_stage_disappeared" + "use_cases::staged_publication::tests::orphan_cleanup_requires_exact_target_kind_and_run_name_contract" ) listed_tests="$(cargo test --locked -- --list)" - for test_name in "${windows_stdio_tests[@]}"; do + for test_name in "${windows_contract_tests[@]}"; do if ! grep -Fxq "$test_name: test" <<<"$listed_tests"; then echo "Windows detached stdio regression is missing: $test_name" >&2 exit 2 diff --git a/spec/IMPLEMENTATION_TODO.md b/spec/IMPLEMENTATION_TODO.md index 68c884d1d..9901bd1da 100644 --- a/spec/IMPLEMENTATION_TODO.md +++ b/spec/IMPLEMENTATION_TODO.md @@ -4,11 +4,13 @@ This file tracks open implementation work only. ## Current Status -- Open tasks as of `2026-05-11`: 0. +- Open tasks as of `2026-09-02`: 1. ## Open Tasks -No open implementation tasks. +1. Перевести IBCMD DT provider из `experimental` в `implemented` только после реализации и live + proof проверяемого no-active-connections или exclusive-access preflight; readiness при этом + остаётся отдельной проверкой конкретного окружения. ## Rules diff --git a/spec/architecture/arc42/09-architecture-decisions.md b/spec/architecture/arc42/09-architecture-decisions.md index 2fdd8f867..f36f2477a 100644 --- a/spec/architecture/arc42/09-architecture-decisions.md +++ b/spec/architecture/arc42/09-architecture-decisions.md @@ -25,6 +25,7 @@ | [ADR-0019: Обеспечивать наличие серверной ИБ через `ibcmd` в `init`](../../decisions/0019-sozdavat-servernuyu-infobazu-cherez-ibcmd-pri-init-pri-otsutstvii.md) | `accepted`, `2026-04-22` | Для `builder=IBCMD` + server connection `init` использует `ibcmd infobase create --create-database` как ensure-step; отдельный pre-check наличия не обязателен, а benign `already exists` нормализуется как non-error outcome. | | [ADR-0020: Упростить CLI-only `convert` до repo-aware конвертации текущих исходников проекта](../../decisions/0020-dobavit-cli-only-convert-dlya-dvustoronney-konvertatsii-edt-i-designer.md) | `accepted`, `2026-04-22` | Фиксирует и уже реализует repo-aware `convert [--source-set ] [--output ]`, который работает от `v8project.yaml`, выводит направление из `format`, публикует output под default `workPath/convert/out` или explicit mirror-layout root и не выносит low-level EDT flags в public surface. | | [ADR-0023: Fail-closed состояния проверки загрузки артефактов](../../decisions/0023-fail-closed-sostoyaniya-proverki-zagruzki.md) | `accepted`, `2026-09-02` | Compatibility probe использует закрытый allowlist целых диагностик; `absent` отделён от `not_supported`, `unknown` остаётся platform failure и не разрешает mutation. | +| [ADR-0024: Типизировать экспорт конфигурации и снимка информационной базы](../../decisions/0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md) | `accepted`, `2026-09-02` | IB→CF/CFE и IB→DT являются разными CLI-only use case; runner выбирает готовый provider до блокировок и публикует результат через общий staged-publication contract. | Архитектурные инварианты для агентов и контрибьюторов зафиксированы в [spec/architecture/invariants.md](../invariants.md). diff --git a/spec/architecture/invariants.md b/spec/architecture/invariants.md index 6d1560f40..b7c2c8704 100644 --- a/spec/architecture/invariants.md +++ b/spec/architecture/invariants.md @@ -92,6 +92,19 @@ См. [ADR-0015](../decisions/0015-atomarnaya-publikatsiya-dump-artifacts-cherez-staging-backup.md). +## Infobase Export Capabilities + +1. Source `dump`, source-built `artifacts`, configuration package export и DT snapshot являются разными use case. +2. Provider selection независимо сообщает implementation, current-environment readiness и evidence; только `implemented + ready` допускается к execution. +3. Для infobase export `builder` задаёт preferred provider; runner может выбрать alternate только до первого spawn. Семантика существующих команд не меняется. +4. После первого spawn provider не переключается ни при каком исходе. +5. Provider возвращает private staged file, а final output публикует общий owner по ADR-0015. +6. DT не называется backup; IBCMD DT недоступен без доказанного exclusive-access contract. +7. `implemented` не выдаётся за live proof: evidence отдельно различает documented, argv-tested и live-verified состояния. +8. Capability/readiness selection не создаёт runtime-файлы и предшествует workspace/target locks; отсутствие adapter и неготовое окружение имеют разные stable error codes. + +См. [ADR-0024](../decisions/0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md). + ## Pipeline Execution Outcome 1. Runner-like и pipeline-like сценарии должны использовать `ExecutionOutcome` как canonical domain outcome для статуса, structured errors, diagnostics, metrics, artifacts and typed payload. diff --git a/spec/decisions/0011-eksklyuzivnoe-vladenie-workpath-na-vremya-komandy.md b/spec/decisions/0011-eksklyuzivnoe-vladenie-workpath-na-vremya-komandy.md index 51b3200e9..13f40215e 100644 --- a/spec/decisions/0011-eksklyuzivnoe-vladenie-workpath-na-vremya-komandy.md +++ b/spec/decisions/0011-eksklyuzivnoe-vladenie-workpath-na-vremya-komandy.md @@ -27,12 +27,17 @@ 1. CLI adapter обязан брать workspace lock перед dispatch в use case для команд, работающих с `workPath`. 2. MCP adapter обязан брать тот же workspace lock перед dispatch в use case. 3. Lock берётся по canonical `workPath`, чтобы разные строковые представления одного каталога конкурировали за один lock. -4. Lock file хранится внутри `workPath` как `.v8-runner.workspace.lock`. +4. Стабильный OS file lock хранится внутри `workPath` как `.v8-runner.workspace.lock.system`. + Совместимый owner lock `.v8-runner.workspace.lock` публикуется атомарно и остаётся gate для + уже выпущенных процессов runner, которые ещё не используют OS lock. 5. Diagnostic sidecar `.v8-runner.workspace.lock.json` содержит metadata (`pid`, owner, command, start time, canonical path), но не является источником истины для блокировки. 6. Ошибка записи sidecar не должна снимать lock и не должна разрешать конкурентное выполнение. 7. Вложенная orchestration не должна повторно брать lock; она должна использовать явно названные internal functions, например `run_build_unlocked`, когда внешний command boundary уже владеет `workPath`. 8. `--clean-before-execution`, platform log cleanup, partial list generation, hash storage commits и generated EDT/Designer writes выполняются только внутри владения workspace lock. 9. Workspace lock является local advisory file lock, а не distributed lock для сетевых машин или разных файловых систем с невалидной семантикой блокировок. +10. Существующий owner lock без удерживаемого новым процессом OS lock трактуется fail-closed как + legacy/crash state и немедленно возвращает диагностику. Автоматическое удаление запрещено: + оператор может удалить owner lock только после остановки всех старых и новых процессов runner. ## Неграницы (Non-goals) @@ -54,7 +59,8 @@ Текущее состояние кода уже следует этому решению: -1. `src/use_cases/workspace_lock.rs` реализует canonical path lock, lock file и diagnostic sidecar. +1. `src/use_cases/workspace_lock.rs` реализует canonical path lock и diagnostic sidecar, а + `src/support/fs.rs` — общий OS/legacy lock protocol. 2. `src/cli/execute.rs` берёт workspace lock на CLI command boundary. 3. `src/mcp/port.rs` берёт workspace lock на MCP use-case port boundary. 4. `src/use_cases/build_project.rs` содержит `run_build_unlocked` для вложенного вызова из `test`. @@ -73,4 +79,5 @@ - [x] ADR разделяет workspace lock и MCP admission semaphore. - [x] ADR фиксирует canonical `workPath` как ключ блокировки. - [x] ADR фиксирует sidecar metadata как diagnostic-only. +- [x] ADR фиксирует OS lock, atomic legacy compatibility gate и fail-closed offline cleanup. - [x] ADR описывает nested `*_unlocked` pattern для сценариев вроде `test -> build`. diff --git a/spec/decisions/0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md b/spec/decisions/0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md new file mode 100644 index 000000000..08ae3f002 --- /dev/null +++ b/spec/decisions/0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md @@ -0,0 +1,252 @@ +# ADR-0024: Типизировать экспорт конфигурации и снимка информационной базы + +- Статус: `accepted` +- Дата: `2026-09-02` +- Связанные решения: [ADR-0001](0001-granitsy-podderzhki-ibcmd-kak-ogranichennogo-backend.md), [ADR-0005](0005-razdelit-cli-i-mcp-publichnye-poverhnosti.md), [ADR-0006](0006-sohranyat-transportno-neytralnyy-use-case-sloy.md), [ADR-0008](0008-derzhat-platformennye-backend-dsl-otdelno-ot-orchestration.md), [ADR-0011](0011-eksklyuzivnoe-vladenie-workpath-na-vremya-komandy.md), [ADR-0014](0014-edinaya-timeout-cancellation-policy-dlya-cli-i-mcp-komand.md), [ADR-0015](0015-atomarnaya-publikatsiya-dump-artifacts-cherez-staging-backup.md), [ADR-0016](0016-edinyy-executionoutcome-i-pipeline-steps-dlya-runner-like-stsenariev.md) + +## Контекст + +`dump` выгружает ИБ в XML/EDT source-set, а `make` строит CF/CFE/EPF/ERF из +исходников. Ни одна из этих команд не выражает два других намерения: + +1. сохранить текущее состояние конфигурации ИБ в CF/CFE; +2. сохранить всю ИБ вместе с данными в переносимый DT-файл. + +Платформа различает working configuration, database configuration, extension +и полный снимок ИБ. Сведение их в один generic artifact operation заставляет +вызывающего угадывать источник правды, destructive semantics и ожидаемое +расширение файла. + +## Решение + +Ввести два transport-neutral use case: + +```text +ExportConfigurationPackage { + state: Working | Database, + subject: Main | Extension { name }, + output +} -> CF | CFE + +ExportInfobaseSnapshot { output } -> DT +``` + +Они публикуются только в CLI; MCP surface runner не расширяется. Unica может +вызывать CLI как внутренний adapter, не копируя платформенные команды в свой +публичный контракт. + +Точная CLI grammar: + +```text +v8-runner infobase configuration export \ + --state \ + [--extension ] \ + --output + +v8-runner infobase dump --output +``` + +Canonical command identities: `infobase.configuration.export` и +`infobase.dump`. `--extension` отсутствует для основной конфигурации и задаёт +subject extension при наличии. Для main обязателен `.cf`, для extension — +`.cfe`, для снимка — `.dt`; регистр суффикса несущественен. Пустое или не +являющееся идентификатором 1С имя extension, неизвестный `state`, неверный +суффикс и параметры не своей команды отклоняются до workspace lock и provider +dispatch. Публичного `--provider`/`--engine` нет. + +Обе команды используют command-specific config validation: обязательны project/base path, +`workPath`, `infobase` и общий execution timeout. Версия платформы необязательна, а её +применение наследует общий locator contract: без explicit `path` она фильтрует обычный поиск, +с `path` проверяется при `strict: true` и игнорируется при `strict: false`. Build/source/test/EDT/ +client-MCP настройки не являются входами операции. Поэтому существующий +`v8project.yaml` с `source-set: []` допустим для этих двух команд; schema и full-validation +остальных команд не ослабляются. + +IBCMD DBMS-поля проверяются только в readiness этого кандидата. Их отсутствие не блокирует +Designer alternate: иначе `builder` снова становился бы строгим селектором до provider selection. +Для file connection readiness каждого process provider также требует существующий обычный файл +`/1Cv8.1CD`; наличие только каталога ИБ или platform binary недостаточно. + +`--json-message` использует существующий envelope +`ok/command/duration_ms/data/warnings/steps/error?`. Успешный и business-failure +payload сохраняет закрытые поля: + +```text +data = { + state, # только configuration export + subject: {kind: main} | {kind: extension, name}, + selection: { + provider: designer-batch | ibcmd-process | null, + reason, + candidates: [{ + provider, + implementation: implemented | experimental | unsupported, + readiness: ready | unavailable | not_checked, + evidence: documented | argv_tested | live_verified, + reason + }] + }, + artifact_kind: cf | cfe | dt, + output, + published, + target_state: unchanged | created | replaced | restored | uncertain, + execution: {status, diagnostics?, errors?, interruptions?} +} +``` + +Для `infobase.dump` `state` отсутствует, а `subject={kind: infobase}`. До +provider selection `selection.provider=null`; после выбора provider, список кандидатов и основание остаются +видимыми и при terminal failure. Text presenter сообщает те же факты без +отдельной схемы. `warnings` и `steps` живут только в общих верхнеуровневых +каналах envelope и не дублируются внутри `data`. + +`execution.status` различает `succeeded`, `failed`, `cancelled`, `timed_out` и +`invalid_output`; ошибка несёт stable code и interruption metadata. Для +`ExecutionError.retryable` действует общий serde default `false`: отсутствие +поля означает запрет автоматического retry. Если для точной комбинации операции нет +implemented adapter, selection возвращает `capability_unavailable`. Если adapter реализован, +но pure preflight не нашёл готового binary/version/connection, возвращается +`environment_unavailable`. Эти ошибки не являются `invalid_argument`. + +### Implementation, evidence и readiness + +Implementation имеет три состояния: + +- `implemented`: runner имеет adapter для точной operation matrix и разрешает dispatch; +- `experimental`: команда известна, но обязательный safety/lifecycle contract не завершён; +- `unsupported`: provider явно не может исполнить семантическую операцию. + +`implemented` не означает live proof конкретного окружения. Поле evidence показывает +максимальную доказанность: `documented`, `argv_tested`, `live_verified`. Readiness независимо +показывает pure preflight текущего окружения: `ready`, `unavailable`, `not_checked`. Только +`implemented + ready` участвует в выборе; `experimental` по умолчанию не dispatch-ится. + +Первый slice допускает только уже существующие process providers: + +- Designer batch; +- IBCMD. + +Designer Agent, `ibcmd-rs` и другие будущие providers остаются `experimental` до +отдельного lifecycle/credentials/artifact-transfer контракта и live proof. + +Начальная implementation matrix фиксирована по operation × state × subject × topology × +platform version × OS. `evidence` описывает уровень проверки адаптера в репозитории, а не +готовность текущей машины; её отдельно сообщает `readiness`. Текущий slice использует +документированные cross-platform команды и +argv/artifact tests; отсутствие live proof честно отражается evidence=`argv_tested`: + +| Intent | `designer-batch` | `ibcmd-process` | +| --- | --- | --- | +| working/database main CF | implemented | implemented | +| working/database extension CFE | implemented | implemented | +| infobase DT, file/server | implemented | experimental | + +Evidence=`argv_tested`: Designer batch argv-tests на `/DumpCfg`, +`/DumpDBCfg`, `-Extension` и `/DumpIB`; IBCMD argv-tests на +`infobase config save `, optional `--db`/`--extension`; use-case artifact +validation и publication tests. Само наличие команды `ibcmd infobase dump` в +справке не достаточно: документация требует отсутствия подключений и +предупреждает о возможном нарушении целостности DT, поэтому этот кандидат не +становится implemented без проверяемого session/exclusive-access preflight. + +### Selection и совместимость + +Для новых export use case существующий `builder` задаёт только первого кандидата. Runner +проверяет operation-specific candidates в детерминированном порядке и может выбрать alternate, +если preferred candidate не implemented или pure preflight пометил его unavailable. Поэтому DT +может использовать Designer при `builder=IBCMD`, а CF/CFE — Designer при отсутствующем IBCMD. +Поведение существующих команд не меняется; нового публичного selector нет. + +Канонический порядок: request validation до чтения config; minimal non-mutating config +validation; capability/readiness selection; workspace lock; target lock; metadata-authenticated +orphan cleanup; staging; dispatch. Preflight может только парсить config/connection и читать +filesystem через locator: он не запускает процессы, не создаёт workPath, логи, locks, staging или +output parent. Первый spawn provider является commit point: после него нет fallback, включая +исчезновение binary между preflight и `spawn()`. Auth/license +failure, timeout, cancellation, неизвестный terminal outcome, platform failure, +transfer или publication failure также не запускают другой provider. + +### Publication и lifecycle + +Provider пишет только в private sibling staging path. Под target lock общий owner удаляет только +старые staging/backup с валидной metadata, совпадающими tool и target identity. Use case проверяет, что +артефакт является обычным непустым файлом ожидаемого типа, и публикует его через +общий staging/backup owner из ADR-0015. `published=true` появляется только после +успешного final publish. Старый target гарантированно не меняется до publish и +сохраняется при provider/validation failure. При publish failure обязательна +попытка rollback; если rollback не удался, failed outcome явно сообщает, что +target требует ручной проверки. Cleanup failure считается degraded success только после +успешного publish. `target_state` различает отсутствие commit (`unchanged`), первую публикацию +(`created`), замену (`replaced`), успешный rollback (`restored`) и недоказанное состояние после +rollback failure (`uncertain`). `uncertain` всегда требует ручной проверки target. + +Обе команды владеют одним workspace lock, target-specific advisory lock и одним command execution +deadline от capability/readiness selection до cleanup. Pure selection не запускает процессы и не +ждёт locks, но учитывает тот же cancellation/deadline между проверками кандидатов. Порядок захвата всегда +`workspace lock -> target lock`; target lock берётся до staging/orphan cleanup и +удерживается до окончания publication cleanup. Held workspace lock возвращает `workspace_busy`. +Новые процессы дополнительно сериализуются OS file lock, а owner metadata публикуется атомарно. +Оставшийся после crash owner lock не удаляется автоматически: совместимость с legacy writer требует +fail-closed и offline cleanup после подтверждения, что процессы runner остановлены. +Ожидание target lock возвращает `timed_out` или `cancelled`; те же codes используются после spawn +без fallback. Внешний `error.code`, `execution.status` и nested error code совпадают. Identity +target повторно разрешается под lock +непосредственно перед publish. Это сериализует публикацию в +один output даже из разных workspace. DT — переносимый снимок, а не резервная +копия. IBCMD DT не становится `implemented`, пока runner не доказывает отсутствие +активных подключений либо иной безопасный exclusive-access contract. + +Гарантия сериализации относится к cooperating запускам v8-runner, использующим этот advisory +lock. Ревалидация обнаруживает подмену пути до commit, но не является filesystem CAS и не может +запретить постороннему процессу менять target в узком окне самого commit. Интеграция с внешним +publisher обязана координировать запись тем же lock или не запускаться параллельно; значения +`created/replaced` не являются доказательством при нарушении этой границы. + +## Неграницы + +1. Не добавлять MCP tools runner. +2. Не загружать CF/CFE и не восстанавливать DT в этом изменении. +3. Не добавлять Designer Agent transport/session. +4. Не менять `builder`, schema `v8project.yaml` или поведение существующих команд. +5. Не выполнять fallback после spawn и не выдавать неизвестный outcome за retryable. +6. Не называть DT backup и не обещать его целостность без exclusive-access proof. + +## Последствия + +1. `make`, source `dump`, configuration package export и infobase snapshot имеют + разные имена и результаты. +2. Новые providers могут подключаться к semantic contract без изменения CLI. +3. IBCMD CF/CFE использует реализованную команду `config save`; IBCMD DT остаётся + experimental до session preflight, а runner выбирает готовый Designer, если он доступен. +4. Reverse operations получат отдельные ADR и destructive acceptance matrix. + +## План реализации + +1. Добавить domain request/result и implementation/readiness/evidence vocabulary. +2. Добавить Designer batch DSL для `/DumpDBCfg` и `/DumpIB`; переиспользовать `/DumpCfg`. +3. Добавить IBCMD DSL для `config save`; IBCMD DT сначала оставить `experimental`. +4. Реализовать два use case с `ExecutionOutcome`, workspace lock и общей публикацией. +5. Добавить CLI group `infobase`, JSON/text presenters и compatibility snapshots. +6. Обновить `docs/CAPABILITIES.md`, `docs/CONFIGURATION.md`, `SKILL/SKILL.md` и acceptance. + +## Верификация + +- [x] Existing command parse/output snapshots не изменились. +- [x] Working/main экспорт вызывает `/DumpCfg` или `ibcmd config save`. +- [x] Database/main экспорт вызывает `/DumpDBCfg` или `ibcmd config save --db`. +- [x] Extension экспорт формирует CFE и передаёт точное имя extension. +- [x] DT через Designer batch вызывает `/DumpIB` и не называется backup. +- [x] Provider failure до publish сохраняет прежний target. +- [x] Два workspace, публикующие один output, сериализуются target lock. +- [x] Реальная ветка publish failure восстанавливает прежние байты target и возвращает `target_state=restored`. +- [x] Fault-injection всей ветки rollback failure подтверждает сохранённые stage/backup, отсутствие недостоверного target и `target_state=uncertain`. +- [x] Cross-provider retry после spawn отсутствует. +- [x] Parse/help snapshots фиксируют точную grammar и отклоняют неверные сочетания flags/suffixes. +- [x] Text и `--json-message` фиксируют command identity, provider reason и `published` без противоречий. +- [x] Timeout/cancellation/invalid output имеют разные terminal statuses и non-retryable errors. +- [x] Target lock соблюдает deadline, а identity повторно проверяется перед publish. +- [x] Infobase-only config с `source-set: []` не блокируется source validation. +- [x] Provider selection завершается до workspace lock и filesystem side effects. +- [x] Preferred provider допускает только pre-spawn fallback; после dispatch fallback отсутствует. +- [x] Outer error code совпадает с terminal/nested code для invalid output и interruption. +- [x] MCP tool list не изменился. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 19768a10a..9a5a6d4bf 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -27,6 +27,7 @@ - [ADR-0021: Ввести локальный overlay для `v8project.yaml`](0021-lokalnyy-overlay-config.md) — `accepted`, `2026-05-02` - [ADR-0022: Ввести общий механизм подготовки расширений и использовать его для `client_mcp`](0022-universalnyy-mehanizm-podgotovki-rasshireniy-i-client-mcp-extension.md) — `accepted`, `2026-05-02` - [ADR-0023: Fail-closed состояния проверки загрузки артефактов](0023-fail-closed-sostoyaniya-proverki-zagruzki.md) — `accepted`, `2026-09-02` +- [ADR-0024: Типизировать экспорт конфигурации и снимка информационной базы](0024-tipizirovat-eksport-konfiguratsii-i-snimka-ib.md) — `accepted`, `2026-09-02` ## Правила обновления diff --git a/src/app.rs b/src/app.rs index 211aec7b4..d6d0a858f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -10,8 +10,8 @@ use crate::cli::execute; use crate::cli::output::{failure_envelope, print_command_error}; use crate::command_envelope::Envelope; use crate::config::loader::{ - load_config, load_config_for_prepared_test, load_config_for_tools_download, - resolve_primary_config_path, + load_config, load_config_for_infobase_export, load_config_for_prepared_test, + load_config_for_tools_download, resolve_primary_config_path, }; use crate::output::presenter::Presenter; use crate::output::text::{TimelineItem, TimelineStatus}; @@ -51,15 +51,41 @@ pub fn run() -> i32 { return run_bootstrap(args, &cli, &presenter); } + if let Command::Infobase(args) = &cli.command { + if let Err(error) = execute::validate_infobase_request(args) { + let error = execute::render_invalid_infobase_request(args, &presenter, error); + return error.exit_code(); + } + } + let config = match load_cli_config(&cli) { Ok(c) => c, Err(e) => { let message = e.to_string(); let error = UseCaseError::from(AppError::from(e)); + if let Command::Infobase(args) = &cli.command { + let error = execute::render_infobase_pre_dispatch_failure( + args, + &presenter, + error, + "provider selection was not attempted because configuration loading failed", + crate::domain::infobase_export::ExportPhase::ConfigurationLoad, + ); + return error.exit_code(); + } print_command_error(&presenter, command_name(&cli.command), &error, &message); return error.exit_code(); } }; + let mut prepared_infobase = match &cli.command { + Command::Infobase(args) => { + match execute::prepare_infobase_cli_command(&config, args, &presenter) { + Ok(prepared) => Some(prepared), + Err(error) => return error.exit_code(), + } + } + _ => None, + }; let primary_config_path = match resolve_primary_config_path(cli.config.as_deref()) { Ok(path) => path, Err(e) => { @@ -71,12 +97,23 @@ pub fn run() -> i32 { }; let level = cli.log_level.as_deref().unwrap_or("info"); - let action_log_path = match crate::support::logging::init_action_logging( - level, - output_format, - !cli.no_color, - &config.work_path, - ) { + let is_infobase_command = matches!(&cli.command, Command::Infobase(_)); + let logging_result = if is_infobase_command { + crate::support::logging::init_action_logging_deferred( + level, + output_format, + !cli.no_color, + &config.work_path, + ) + } else { + crate::support::logging::init_action_logging( + level, + output_format, + !cli.no_color, + &config.work_path, + ) + }; + let action_log_path = match logging_result { Ok(path) => path, Err(e) => { let message = e.to_string(); @@ -86,14 +123,16 @@ pub fn run() -> i32 { } }; - debug!( - command = command_name(&cli.command), - output = output_format, - work_path = %config.work_path.display(), - "starting command" - ); - if let Some(path) = &action_log_path { - debug!(path = %path.display(), "action log file enabled"); + if !is_infobase_command { + debug!( + command = command_name(&cli.command), + output = output_format, + work_path = %config.work_path.display(), + "starting command" + ); + if let Some(path) = &action_log_path { + debug!(path = %path.display(), "action log file enabled"); + } } let result = match &cli.command { @@ -117,21 +156,31 @@ pub fn run() -> i32 { &presenter, cli.clean_before_execution, ), + Command::Infobase(_) => execute::execute_prepared_infobase_command( + &config, + prepared_infobase + .take() + .expect("infobase command was prepared before action logging"), + &presenter, + cli.clean_before_execution, + ), Command::Mcp(_) => unreachable!("mcp commands are handled before CLI presenter setup"), }; match result { Ok(()) => { - debug!( - command = command_name(&cli.command), - "command finished successfully" - ); + if !is_infobase_command { + debug!( + command = command_name(&cli.command), + "command finished successfully" + ); + } 0 } Err(e) => { // Text command adapters have already rendered the error; text action logs // go to stdout, so logging here would duplicate user-facing output. - if presenter.is_json() { + if presenter.is_json() && !is_infobase_command { error!("{e}"); } e.exit_code() @@ -149,6 +198,8 @@ fn load_cli_config( }) ) { load_config_for_tools_download(cli.config.as_deref(), cli.workdir.as_deref()) + } else if execute::uses_infobase_export_config(&cli.command) { + load_config_for_infobase_export(cli.config.as_deref(), cli.workdir.as_deref()) } else if matches!(&cli.command, Command::Test(args) if args.no_build) { load_config_for_prepared_test(cli.config.as_deref(), cli.workdir.as_deref()) } else { diff --git a/src/cli/args.rs b/src/cli/args.rs index 1a6f82c7b..a87cadb88 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -64,6 +64,8 @@ pub enum Command { Test(TestArgs), /// Dump infobase state back to project files Dump(DumpArgs), + /// Export configuration packages or a full DT snapshot from the configured infobase + Infobase(InfobaseArgs), /// Convert configured source-sets between EDT and Designer file formats Convert(ConvertArgs), /// Export release artifacts via Designer batch commands @@ -347,6 +349,56 @@ pub struct DumpArgs { pub objects: Vec, } +#[derive(Args, Debug)] +pub struct InfobaseArgs { + #[command(subcommand)] + pub command: InfobaseCommand, +} + +#[derive(Subcommand, Debug)] +pub enum InfobaseCommand { + /// Export working/database configuration state to CF or CFE + Configuration(InfobaseConfigurationArgs), + /// Export the complete infobase to a DT transfer file (not a backup) + Dump(InfobaseDumpArgs), +} + +#[derive(Args, Debug)] +pub struct InfobaseConfigurationArgs { + #[command(subcommand)] + pub command: InfobaseConfigurationCommand, +} + +#[derive(Subcommand, Debug)] +pub enum InfobaseConfigurationCommand { + /// Export the selected configuration state to a package file + Export(InfobaseConfigurationExportArgs), +} + +#[derive(Args, Debug)] +#[command(next_help_heading = "Command options")] +pub struct InfobaseConfigurationExportArgs { + /// Configuration state to export + #[arg(long, value_parser = ["working", "database"])] + pub state: String, + + /// Extension name; omit to export the main configuration + #[arg(long)] + pub extension: Option, + + /// Final CF/CFE output path + #[arg(long)] + pub output: String, +} + +#[derive(Args, Debug)] +#[command(next_help_heading = "Command options")] +pub struct InfobaseDumpArgs { + /// Final DT output path; a DT transfer image is not a database backup + #[arg(long)] + pub output: String, +} + #[derive(Args, Debug)] #[command(next_help_heading = "Command options")] pub struct ConvertArgs { @@ -1072,4 +1124,75 @@ mod tests { assert!(matches!(cli.command, Command::Artifacts(_))); } + + #[test] + fn parses_infobase_configuration_export_contract() { + let cli = Cli::try_parse_from([ + "v8-runner", + "infobase", + "configuration", + "export", + "--state", + "database", + "--extension", + "SalesAddon", + "--output", + "dist/sales.cfe", + ]) + .expect("parse configuration export"); + + match cli.command { + Command::Infobase(args) => match args.command { + super::InfobaseCommand::Configuration(configuration) => { + match configuration.command { + super::InfobaseConfigurationCommand::Export(export) => { + assert_eq!(export.state, "database"); + assert_eq!(export.extension.as_deref(), Some("SalesAddon")); + assert_eq!(export.output, "dist/sales.cfe"); + } + } + } + _ => panic!("unexpected infobase command"), + }, + _ => panic!("unexpected command"), + } + } + + #[test] + fn parses_infobase_dump_contract() { + let cli = Cli::try_parse_from([ + "v8-runner", + "infobase", + "dump", + "--output", + "dist/snapshot.dt", + ]) + .expect("parse infobase dump"); + + match cli.command { + Command::Infobase(args) => match args.command { + super::InfobaseCommand::Dump(dump) => { + assert_eq!(dump.output, "dist/snapshot.dt"); + } + _ => panic!("unexpected infobase command"), + }, + _ => panic!("unexpected command"), + } + } + + #[test] + fn infobase_configuration_export_rejects_unknown_state() { + let result = Cli::try_parse_from([ + "v8-runner", + "infobase", + "configuration", + "export", + "--state", + "current", + "--output", + "dist/main.cf", + ]); + + assert!(result.is_err()); + } } diff --git a/src/cli/execute.rs b/src/cli/execute.rs index 79f9bfb46..cc1f51381 100644 --- a/src/cli/execute.rs +++ b/src/cli/execute.rs @@ -4,16 +4,19 @@ use std::time::{Duration, Instant}; use serde::Serialize; use serde_json::json; use tokio_util::sync::CancellationToken; +use tracing::info; use crate::cli::args::{ ArtifactsArgs, BuildArgs, Command, ConvertArgs, DesignerConfigSyntaxArgs, - DesignerModulesSyntaxArgs, DirectLaunchOptionsArgs, DumpArgs, ExtensionsArgs, LaunchArgs, + DesignerModulesSyntaxArgs, DirectLaunchOptionsArgs, DumpArgs, ExtensionsArgs, InfobaseArgs, + InfobaseCommand, InfobaseConfigurationCommand, InfobaseConfigurationExportArgs, LaunchArgs, LaunchOptionsArgs, LoadArgs, SyntaxArgs, SyntaxTarget, TestArgs, TestLaunchOptionsArgs, TestRunner, TestScope, TestVaArgs, TestYaxunitArgs, ToolsArgs, ToolsCommand, ToolsDownloadArgs, ToolsDownloadCommand, }; use crate::cli::output::{ - failure_envelope, pre_dispatch_error_envelope, print_command_use_case_error, with_cli_error, + cli_error_contract, failure_envelope, pre_dispatch_error_envelope, + print_command_use_case_error, with_cli_error, }; use crate::cli::signal::CliSignalGuard; use crate::command_envelope::{test_envelope, Envelope}; @@ -26,7 +29,13 @@ use crate::domain::build::{BuildMode, BuildResult}; use crate::domain::convert::{ConvertDirection, ConvertResult, ConvertScope}; use crate::domain::dump::{DumpMode, DumpResult}; use crate::domain::execution::{ - ExecutionError, ExecutionInterruptionDetails, ExecutionOutcome, ExecutionStepStatus, StepResult, + ExecutionError, ExecutionInterruptionDetails, ExecutionOutcome, ExecutionStatus, + ExecutionStepStatus, StepResult, +}; +use crate::domain::infobase_export::{ + ConfigurationState, ConfigurationSubject, ExportConfigurationPackageRequest, + ExportConfigurationPackageResult, ExportInfobaseSnapshotRequest, ExportInfobaseSnapshotResult, + ExportPhase, ExportProviderDecision, }; use crate::domain::init::{InitResult, InitStep, InitStepStatus}; use crate::domain::issue::{Issue, IssueSeverity}; @@ -59,6 +68,7 @@ use crate::use_cases::configure_extensions; use crate::use_cases::context::{CommandName, ExecutionContext}; use crate::use_cases::convert_sources; use crate::use_cases::dump_config; +use crate::use_cases::infobase_export; use crate::use_cases::init_project; use crate::use_cases::launch_app; use crate::use_cases::load_artifact; @@ -74,7 +84,7 @@ use crate::use_cases::request::{ use crate::use_cases::result::{UseCaseError, UseCaseErrorKind}; use crate::use_cases::run_tests; use crate::use_cases::tools_download; -use crate::use_cases::transport::dispatch_with_workspace_lock; +use crate::use_cases::transport::{dispatch_with_workspace_lock_policy, WorkspaceBusyPolicy}; const EXTERNAL_EPF_WAIT_CLEANUP_MARGIN: Duration = Duration::from_millis(500); @@ -137,6 +147,13 @@ pub fn execute_command( clean_before_execution, cancellation, ), + Command::Infobase(args) => execute_infobase( + config, + args, + presenter, + clean_before_execution, + cancellation, + ), Command::Convert(args) => execute_convert( config, args, @@ -184,6 +201,15 @@ pub fn command_name(command: &Command) -> CommandName { Command::Load(_) => CommandName::Load, Command::Test(_) => CommandName::Test, Command::Dump(_) => CommandName::Dump, + Command::Infobase(InfobaseArgs { + command: + InfobaseCommand::Configuration(crate::cli::args::InfobaseConfigurationArgs { + command: InfobaseConfigurationCommand::Export(_), + }), + }) => CommandName::InfobaseConfigurationExport, + Command::Infobase(InfobaseArgs { + command: InfobaseCommand::Dump(_), + }) => CommandName::InfobaseDump, Command::Convert(_) => CommandName::Convert, Command::Artifacts(_) => CommandName::Artifacts, Command::Syntax(_) => CommandName::Syntax, @@ -192,6 +218,17 @@ pub fn command_name(command: &Command) -> CommandName { } } +pub fn uses_infobase_export_config(command: &Command) -> bool { + matches!( + command, + Command::Infobase(InfobaseArgs { + command: InfobaseCommand::Configuration(crate::cli::args::InfobaseConfigurationArgs { + command: InfobaseConfigurationCommand::Export(_), + }) | InfobaseCommand::Dump(_), + }) + ) +} + fn execute_tools( config: &AppConfig, args: &ToolsArgs, @@ -569,6 +606,683 @@ fn execute_dump( ) } +pub enum PreparedInfobaseCommand { + Configuration { + request: ExportConfigurationPackageRequest, + provider: infobase_export::PreparedExportProvider, + }, + Snapshot { + request: ExportInfobaseSnapshotRequest, + provider: infobase_export::PreparedExportProvider, + }, +} + +pub struct PreparedInfobaseCliCommand { + command: PreparedInfobaseCommand, + context: ExecutionContext, + _signal_guard: CliSignalGuard, +} + +pub fn validate_infobase_request(args: &InfobaseArgs) -> Result<(), AppError> { + match &args.command { + InfobaseCommand::Configuration(configuration) => match &configuration.command { + InfobaseConfigurationCommand::Export(args) => { + let request = map_infobase_configuration_export_request(args); + infobase_export::validate_configuration_request(&request) + } + }, + InfobaseCommand::Dump(args) => { + infobase_export::validate_snapshot_output(Path::new(&args.output)) + } + } +} + +pub fn render_invalid_infobase_request( + args: &InfobaseArgs, + presenter: &Presenter, + error: AppError, +) -> UseCaseError { + let error = UseCaseError::from(error); + render_infobase_pre_dispatch_failure( + args, + presenter, + error, + "provider selection was not attempted because the request is invalid", + ExportPhase::Validation, + ) +} + +pub fn render_infobase_pre_dispatch_failure( + args: &InfobaseArgs, + presenter: &Presenter, + error: UseCaseError, + selection_reason: &str, + phase: ExportPhase, +) -> UseCaseError { + let selection = ExportProviderDecision::unavailable(selection_reason, Vec::new()); + match &args.command { + InfobaseCommand::Configuration(configuration) => match &configuration.command { + InfobaseConfigurationCommand::Export(args) => { + let request = map_infobase_configuration_export_request(args); + let result = configuration_pre_dispatch_failure(&request, selection, &error, phase); + render_configuration_failure( + CommandName::InfobaseConfigurationExport, + result, + &error, + presenter, + ); + } + }, + InfobaseCommand::Dump(args) => { + let request = ExportInfobaseSnapshotRequest { + output: PathBuf::from(&args.output), + }; + let result = snapshot_pre_dispatch_failure(&request, selection, &error, phase); + render_snapshot_failure(CommandName::InfobaseDump, result, &error, presenter); + } + } + error +} + +pub fn prepare_infobase_command( + config: &AppConfig, + args: &InfobaseArgs, + presenter: &Presenter, + context: &ExecutionContext, +) -> Result { + match &args.command { + InfobaseCommand::Configuration(configuration) => match &configuration.command { + InfobaseConfigurationCommand::Export(args) => { + let request = map_infobase_configuration_export_request(args); + let command = CommandName::InfobaseConfigurationExport; + infobase_export::validate_configuration_request(&request) + .map_err(|error| render_pre_dispatch_error(presenter, command, error))?; + match infobase_export::prepare_configuration_export(context, config, &request) { + Ok(provider) => { + Ok(PreparedInfobaseCommand::Configuration { request, provider }) + } + Err(failure) => { + let error = failure.error; + if let Some(result) = failure.payload { + render_configuration_failure(command, result, &error, presenter); + } + Err(error) + } + } + } + }, + InfobaseCommand::Dump(args) => { + let request = ExportInfobaseSnapshotRequest { + output: PathBuf::from(&args.output), + }; + let command = CommandName::InfobaseDump; + infobase_export::validate_snapshot_output(&request.output) + .map_err(|error| render_pre_dispatch_error(presenter, command, error))?; + match infobase_export::prepare_infobase_snapshot(context, config, &request) { + Ok(provider) => Ok(PreparedInfobaseCommand::Snapshot { request, provider }), + Err(failure) => { + let error = failure.error; + if let Some(result) = failure.payload { + render_snapshot_failure(command, result, &error, presenter); + } + Err(error) + } + } + } + } +} + +pub fn prepare_infobase_cli_command( + config: &AppConfig, + args: &InfobaseArgs, + presenter: &Presenter, +) -> Result { + let cancellation = CancellationToken::new(); + let signal_guard = CliSignalGuard::install(cancellation.clone()); + let context = cli_context(config, infobase_command_name(args), cancellation); + let command = prepare_infobase_command(config, args, presenter, &context)?; + Ok(PreparedInfobaseCliCommand { + command, + context, + _signal_guard: signal_guard, + }) +} + +fn infobase_command_name(args: &InfobaseArgs) -> CommandName { + match &args.command { + InfobaseCommand::Configuration(_) => CommandName::InfobaseConfigurationExport, + InfobaseCommand::Dump(_) => CommandName::InfobaseDump, + } +} + +fn map_infobase_configuration_export_request( + args: &InfobaseConfigurationExportArgs, +) -> ExportConfigurationPackageRequest { + let state = match args.state.as_str() { + "working" => ConfigurationState::Working, + "database" => ConfigurationState::Database, + _ => unreachable!("clap validates configuration state"), + }; + let subject = args + .extension + .as_ref() + .map(|name| ConfigurationSubject::Extension { name: name.clone() }) + .unwrap_or(ConfigurationSubject::Main); + ExportConfigurationPackageRequest { + state, + subject, + output: PathBuf::from(&args.output), + } +} + +fn execute_infobase( + config: &AppConfig, + args: &InfobaseArgs, + presenter: &Presenter, + clean_before_execution: bool, + cancellation: CancellationToken, +) -> Result<(), UseCaseError> { + let context = cli_context(config, infobase_command_name(args), cancellation); + let prepared = prepare_infobase_command(config, args, presenter, &context)?; + execute_prepared_infobase( + config, + prepared, + &context, + presenter, + clean_before_execution, + ) +} + +pub fn execute_prepared_infobase( + config: &AppConfig, + prepared: PreparedInfobaseCommand, + context: &ExecutionContext, + presenter: &Presenter, + clean_before_execution: bool, +) -> Result<(), UseCaseError> { + match prepared { + PreparedInfobaseCommand::Configuration { request, provider } => { + execute_infobase_configuration_export( + config, + request, + provider, + context, + presenter, + clean_before_execution, + ) + } + PreparedInfobaseCommand::Snapshot { request, provider } => execute_infobase_dump( + config, + request, + provider, + context, + presenter, + clean_before_execution, + ), + } +} + +pub fn execute_prepared_infobase_command( + config: &AppConfig, + prepared: PreparedInfobaseCliCommand, + presenter: &Presenter, + clean_before_execution: bool, +) -> Result<(), UseCaseError> { + execute_prepared_infobase( + config, + prepared.command, + &prepared.context, + presenter, + clean_before_execution, + ) +} + +fn execute_infobase_configuration_export( + config: &AppConfig, + request: ExportConfigurationPackageRequest, + prepared: infobase_export::PreparedExportProvider, + context: &ExecutionContext, + presenter: &Presenter, + clean_before_execution: bool, +) -> Result<(), UseCaseError> { + let command = CommandName::InfobaseConfigurationExport; + let started = Instant::now(); + let mut workspace_lock_acquired = false; + let mut dispatched = false; + let outcome = with_cli_workspace_lock_observed( + config, + presenter, + command, + clean_before_execution, + || workspace_lock_acquired = true, + || { + dispatched = true; + info!( + command = command.as_str(), + "starting command under workspace lock" + ); + match infobase_export::execute_configuration_export( + context, config, &request, &prepared, + ) { + Ok(result) => { + let duration_ms = started.elapsed().as_millis() as u64; + if presenter.is_json() { + let warnings = result.warnings.clone(); + let steps = result.steps.clone(); + let mut envelope = Envelope::ok(command.as_str(), duration_ms, result); + envelope.warnings = warnings; + envelope.steps = steps; + presenter.print_envelope(&envelope); + } else { + render_configuration_export_text(command, &result, presenter); + } + Ok(()) + } + Err(failure) => { + let duration_ms = started.elapsed().as_millis() as u64; + let error = failure.error; + if presenter.is_json() { + match failure.payload { + Some(result) => { + let warnings = result.warnings.clone(); + let steps = result.steps.clone(); + let mut envelope = + failure_envelope(command.as_str(), duration_ms, result, &error); + envelope.warnings = warnings; + envelope.steps = steps; + presenter.print_envelope(&envelope); + } + None => presenter.print_envelope(&pre_dispatch_error_envelope( + command.as_str(), + &error, + )), + } + } else { + if let Some(result) = failure.payload.as_ref() { + render_configuration_export_text(command, result, presenter); + } + presenter.print_error(&error.to_string()); + } + Err(error) + } + } + }, + ); + if !dispatched { + if let Err(error) = &outcome { + let result = configuration_pre_dispatch_failure( + &request, + prepared.selection().clone(), + error, + infobase_pre_dispatch_execution_phase(workspace_lock_acquired), + ); + render_configuration_failure(command, result, error, presenter); + } + } + outcome +} + +fn execute_infobase_dump( + config: &AppConfig, + request: ExportInfobaseSnapshotRequest, + prepared: infobase_export::PreparedExportProvider, + context: &ExecutionContext, + presenter: &Presenter, + clean_before_execution: bool, +) -> Result<(), UseCaseError> { + let command = CommandName::InfobaseDump; + let started = Instant::now(); + let mut workspace_lock_acquired = false; + let mut dispatched = false; + let outcome = with_cli_workspace_lock_observed( + config, + presenter, + command, + clean_before_execution, + || workspace_lock_acquired = true, + || { + dispatched = true; + info!( + command = command.as_str(), + "starting command under workspace lock" + ); + match infobase_export::execute_infobase_snapshot(context, config, &request, &prepared) { + Ok(result) => { + let duration_ms = started.elapsed().as_millis() as u64; + if presenter.is_json() { + let warnings = result.warnings.clone(); + let steps = result.steps.clone(); + let mut envelope = Envelope::ok(command.as_str(), duration_ms, result); + envelope.warnings = warnings; + envelope.steps = steps; + presenter.print_envelope(&envelope); + } else { + render_snapshot_export_text(command, &result, presenter); + } + Ok(()) + } + Err(failure) => { + let duration_ms = started.elapsed().as_millis() as u64; + let error = failure.error; + if presenter.is_json() { + match failure.payload { + Some(result) => { + let warnings = result.warnings.clone(); + let steps = result.steps.clone(); + let mut envelope = + failure_envelope(command.as_str(), duration_ms, result, &error); + envelope.warnings = warnings; + envelope.steps = steps; + presenter.print_envelope(&envelope); + } + None => presenter.print_envelope(&pre_dispatch_error_envelope( + command.as_str(), + &error, + )), + } + } else { + if let Some(result) = failure.payload.as_ref() { + render_snapshot_export_text(command, result, presenter); + } + presenter.print_error(&error.to_string()); + } + Err(error) + } + } + }, + ); + if !dispatched { + if let Err(error) = &outcome { + let result = snapshot_pre_dispatch_failure( + &request, + prepared.selection().clone(), + error, + infobase_pre_dispatch_execution_phase(workspace_lock_acquired), + ); + render_snapshot_failure(command, result, error, presenter); + } + } + outcome +} + +fn infobase_pre_dispatch_execution_phase(workspace_lock_acquired: bool) -> ExportPhase { + if workspace_lock_acquired { + ExportPhase::WorkspacePreparation + } else { + ExportPhase::WorkspaceLock + } +} + +fn annotate_pre_dispatch_failure(execution: &mut ExecutionOutcome<()>, error: &UseCaseError) { + let (code, _) = cli_error_contract(error.kind()); + execution.status = match error.kind() { + UseCaseErrorKind::InvalidOutput => ExecutionStatus::InvalidOutput, + UseCaseErrorKind::Cancelled => ExecutionStatus::Cancelled, + UseCaseErrorKind::TimedOut => ExecutionStatus::TimedOut, + _ => ExecutionStatus::Failed, + }; + execution + .errors + .push(ExecutionError::new(code, error.message())); +} + +fn configuration_pre_dispatch_failure( + request: &ExportConfigurationPackageRequest, + selection: ExportProviderDecision, + error: &UseCaseError, + phase: ExportPhase, +) -> ExportConfigurationPackageResult { + let mut result = ExportConfigurationPackageResult::new(request.clone(), selection); + annotate_pre_dispatch_failure(&mut result.execution, error); + result.steps.push( + StepResult::failed(phase.as_str(), phase.kind(), 0) + .with_message(error.message().to_owned()), + ); + result +} + +fn snapshot_pre_dispatch_failure( + request: &ExportInfobaseSnapshotRequest, + selection: ExportProviderDecision, + error: &UseCaseError, + phase: ExportPhase, +) -> ExportInfobaseSnapshotResult { + let mut result = ExportInfobaseSnapshotResult::new(request.clone(), selection); + annotate_pre_dispatch_failure(&mut result.execution, error); + result.steps.push( + StepResult::failed(phase.as_str(), phase.kind(), 0) + .with_message(error.message().to_owned()), + ); + result +} + +fn render_configuration_failure( + command: CommandName, + result: ExportConfigurationPackageResult, + error: &UseCaseError, + presenter: &Presenter, +) { + if presenter.is_json() { + let warnings = result.warnings.clone(); + let steps = result.steps.clone(); + let mut envelope = failure_envelope(command.as_str(), 0, result, error); + envelope.warnings = warnings; + envelope.steps = steps; + presenter.print_envelope(&envelope); + } else { + render_configuration_export_text(command, &result, presenter); + presenter.print_error(&error.to_string()); + } +} + +fn render_snapshot_failure( + command: CommandName, + result: ExportInfobaseSnapshotResult, + error: &UseCaseError, + presenter: &Presenter, +) { + if presenter.is_json() { + let warnings = result.warnings.clone(); + let steps = result.steps.clone(); + let mut envelope = failure_envelope(command.as_str(), 0, result, error); + envelope.warnings = warnings; + envelope.steps = steps; + presenter.print_envelope(&envelope); + } else { + render_snapshot_export_text(command, &result, presenter); + presenter.print_error(&error.to_string()); + } +} + +struct InfobaseExportText<'a> { + command: &'a str, + label: &'a str, + state: Option<&'a str>, + subject: String, + implementation: &'a str, + readiness: &'a str, + evidence: &'a str, + artifact_kind: &'a str, + execution_status: &'a str, + output: &'a Path, + provider: Option, + provider_reason: &'a str, + published: bool, + target_state: &'a str, + candidates: &'a [crate::domain::infobase_export::ProviderCandidate], + warnings: &'a [String], +} + +fn render_configuration_export_text( + command: CommandName, + result: &ExportConfigurationPackageResult, + presenter: &Presenter, +) { + render_infobase_export_text( + InfobaseExportText { + command: command.as_str(), + label: "Configuration package export", + state: Some(result.state.as_str()), + subject: render_configuration_subject(&result.subject), + implementation: selected_candidate(&result.selection) + .map(|candidate| candidate.implementation.as_str()) + .unwrap_or("none"), + readiness: selected_candidate(&result.selection) + .map(|candidate| candidate.readiness.as_str()) + .unwrap_or("unavailable"), + evidence: selected_candidate(&result.selection) + .map(|candidate| candidate.evidence.as_str()) + .unwrap_or("none"), + artifact_kind: result.artifact_kind.as_str(), + execution_status: execution_status_label(result.execution.status), + output: &result.output, + provider: result.selection.provider(), + provider_reason: result.selection.reason(), + published: result.published, + target_state: export_target_state_label(result.target_state), + candidates: result.selection.candidates(), + warnings: &result.warnings, + }, + presenter, + ); +} + +fn render_snapshot_export_text( + command: CommandName, + result: &ExportInfobaseSnapshotResult, + presenter: &Presenter, +) { + render_infobase_export_text( + InfobaseExportText { + command: command.as_str(), + label: "Infobase DT export", + state: None, + subject: "infobase".to_owned(), + implementation: selected_candidate(&result.selection) + .map(|candidate| candidate.implementation.as_str()) + .unwrap_or("none"), + readiness: selected_candidate(&result.selection) + .map(|candidate| candidate.readiness.as_str()) + .unwrap_or("unavailable"), + evidence: selected_candidate(&result.selection) + .map(|candidate| candidate.evidence.as_str()) + .unwrap_or("none"), + artifact_kind: result.artifact_kind.as_str(), + execution_status: execution_status_label(result.execution.status), + output: &result.output, + provider: result.selection.provider(), + provider_reason: result.selection.reason(), + published: result.published, + target_state: export_target_state_label(result.target_state), + candidates: result.selection.candidates(), + warnings: &result.warnings, + }, + presenter, + ); +} + +fn render_infobase_export_text(view: InfobaseExportText<'_>, presenter: &Presenter) { + let InfobaseExportText { + command, + label, + state, + subject, + implementation, + readiness, + evidence, + artifact_kind, + execution_status, + output, + provider, + provider_reason, + published, + target_state, + candidates, + warnings, + } = view; + let status = if published { + TimelineStatus::Succeeded + } else { + TimelineStatus::Failed + }; + let provider = provider + .map(|value| value.as_str().to_owned()) + .unwrap_or_else(|| "none".to_owned()); + let mut details = vec![ + format!("command: {command}"), + format!("subject: {subject}"), + format!("implementation: {implementation}"), + format!("readiness: {readiness}"), + format!("evidence: {evidence}"), + format!("artifact kind: {artifact_kind}"), + format!("provider: {provider}"), + format!("provider reason: {provider_reason}"), + format!("execution status: {execution_status}"), + format!("published: {published}"), + format!("target state: {target_state}"), + format!("output: {}", output.display()), + ]; + for candidate in candidates { + details.push(format!( + "candidate {}: implementation={}, readiness={}, evidence={}; {}", + candidate.provider.as_str(), + candidate.implementation.as_str(), + candidate.readiness.as_str(), + candidate.evidence.as_str(), + candidate.reason + )); + } + if let Some(state) = state { + details.insert(0, format!("state: {state}")); + } + details.extend(warnings.iter().map(|warning| format!("warning: {warning}"))); + presenter.print_timeline(&[TimelineItem::new(status, label).with_detail(details.join("\n"))]); +} + +fn selected_candidate( + selection: &crate::domain::infobase_export::ExportProviderDecision, +) -> Option<&crate::domain::infobase_export::ProviderCandidate> { + let provider = selection.provider()?; + selection + .candidates() + .iter() + .find(|candidate| candidate.provider == provider) +} + +fn export_target_state_label( + state: crate::domain::infobase_export::ExportTargetState, +) -> &'static str { + use crate::domain::infobase_export::ExportTargetState; + match state { + ExportTargetState::Unchanged => "unchanged", + ExportTargetState::Created => "created", + ExportTargetState::Replaced => "replaced", + ExportTargetState::Restored => "restored", + ExportTargetState::Uncertain => "uncertain", + } +} + +fn render_configuration_subject( + subject: &crate::domain::infobase_export::ConfigurationSubject, +) -> String { + match subject { + crate::domain::infobase_export::ConfigurationSubject::Main => "main".to_owned(), + crate::domain::infobase_export::ConfigurationSubject::Extension { name } => { + format!("extension:{name}") + } + } +} + +fn execution_status_label(status: crate::domain::execution::ExecutionStatus) -> &'static str { + match status { + crate::domain::execution::ExecutionStatus::Succeeded => "succeeded", + crate::domain::execution::ExecutionStatus::Failed => "failed", + crate::domain::execution::ExecutionStatus::Cancelled => "cancelled", + crate::domain::execution::ExecutionStatus::TimedOut => "timed_out", + crate::domain::execution::ExecutionStatus::InvalidOutput => "invalid_output", + } +} + fn execute_convert( config: &AppConfig, args: &ConvertArgs, @@ -791,10 +1505,38 @@ fn with_cli_workspace_lock( clean_before_execution: bool, run: impl FnOnce() -> Result, ) -> Result { - dispatch_with_workspace_lock( + with_cli_workspace_lock_observed( + config, + presenter, + command, + clean_before_execution, + || {}, + run, + ) +} + +fn with_cli_workspace_lock_observed( + config: &AppConfig, + presenter: &Presenter, + command: CommandName, + clean_before_execution: bool, + workspace_lock_acquired: impl FnOnce(), + run: impl FnOnce() -> Result, +) -> Result { + let busy_policy = if matches!( + command, + CommandName::InfobaseConfigurationExport | CommandName::InfobaseDump + ) { + WorkspaceBusyPolicy::Typed + } else { + WorkspaceBusyPolicy::LegacyRuntime + }; + let result = dispatch_with_workspace_lock_policy( config, command, + busy_policy, || { + workspace_lock_acquired(); if clean_before_execution { clean_platform_logs_under_lock(config) } else { @@ -802,8 +1544,14 @@ fn with_cli_workspace_lock( } }, run, - ) - .map_err(|error| render_pre_dispatch_error(presenter, command, error))? + ); + result.map_err(|error| { + if matches!(busy_policy, WorkspaceBusyPolicy::Typed) { + error + } else { + render_pre_dispatch_error(presenter, command, error) + } + })? } fn clean_platform_logs_under_lock(config: &AppConfig) -> Result<(), UseCaseError> { @@ -2463,15 +3211,17 @@ fn status_label(status: &TestStatus) -> &'static str { #[cfg(test)] mod tests { use super::{ - build_load_envelope, command_name, execute_command, map_artifacts_request_with_config, - map_build_request, map_designer_config_request, map_dump_request, map_extensions_request, - map_launch_request, map_load_request, map_syntax_request, map_test_request, + build_load_envelope, command_name, execute_command, infobase_pre_dispatch_execution_phase, + map_artifacts_request_with_config, map_build_request, map_designer_config_request, + map_dump_request, map_extensions_request, map_launch_request, map_load_request, + map_syntax_request, map_test_request, }; use crate::cli::args::{ ArtifactsArgs, BuildArgs, Command, DesignerConfigSyntaxArgs, DesignerModulesSyntaxArgs, - DirectLaunchOptionsArgs, DumpArgs, ExtensionsArgs, LaunchArgs, LaunchOptionsArgs, LoadArgs, - SyntaxArgs, SyntaxTarget, TestArgs, TestLaunchOptionsArgs, TestRunner, TestScope, - TestVaArgs, TestYaxunitArgs, + DirectLaunchOptionsArgs, DumpArgs, ExtensionsArgs, InfobaseArgs, InfobaseCommand, + InfobaseConfigurationArgs, InfobaseConfigurationCommand, InfobaseConfigurationExportArgs, + InfobaseDumpArgs, LaunchArgs, LaunchOptionsArgs, LoadArgs, SyntaxArgs, SyntaxTarget, + TestArgs, TestLaunchOptionsArgs, TestRunner, TestScope, TestVaArgs, TestYaxunitArgs, }; use crate::cli::output::pre_dispatch_error_envelope; use crate::config::model::{ @@ -2480,6 +3230,7 @@ mod tests { }; use crate::domain::artifacts::ArtifactBuildMode; use crate::domain::execution::{ExecutionOutcome, ExecutionStatus}; + use crate::domain::infobase_export::ExportPhase; use crate::domain::load::{ CompatibilityState, LoadExecutionMetadata, LoadMode, LoadResult, LoadTargetKind, }; @@ -3076,6 +3827,63 @@ mod tests { assert!(error.to_string().contains("already")); } + #[test] + fn infobase_commands_report_workspace_lock_conflict_before_provider_dispatch() { + let dir = tempdir().expect("tempdir"); + let work = dir.path().join("work"); + fs::create_dir_all(&work).expect("work dir"); + let infobase = dir.path().join("ib"); + fs::create_dir_all(&infobase).expect("infobase dir"); + fs::write(infobase.join("1Cv8.1CD"), b"fixture").expect("infobase file"); + let platform = dir + .path() + .join(format!("1cv8{}", std::env::consts::EXE_SUFFIX)); + fs::write(&platform, b"fixture").expect("platform executable"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut permissions = fs::metadata(&platform) + .expect("platform metadata") + .permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&platform, permissions).expect("platform permissions"); + } + let mut config = sample_config(&work); + config.infobase = + crate::config::model::InfobaseConfig::file(format!("File={}", infobase.display())); + config.tools.platform.path = Some(platform); + let canonical_work = fs::canonicalize(&config.work_path).expect("canonical work"); + let lock_path = workspace_lock_path(&canonical_work); + let _guard = acquire_advisory_lock(&lock_path).expect("workspace lock"); + let presenter = Presenter::new("text".to_owned(), ColorMode::Disabled); + let commands = [ + Command::Infobase(InfobaseArgs { + command: InfobaseCommand::Configuration(InfobaseConfigurationArgs { + command: InfobaseConfigurationCommand::Export( + InfobaseConfigurationExportArgs { + state: "working".to_owned(), + extension: None, + output: dir.path().join("main.cf").display().to_string(), + }, + ), + }), + }), + Command::Infobase(InfobaseArgs { + command: InfobaseCommand::Dump(InfobaseDumpArgs { + output: dir.path().join("base.dt").display().to_string(), + }), + }), + ]; + + for command in commands { + let error = execute_command(&config, &command, None, &presenter, false) + .expect_err("busy workspace"); + assert_eq!(error.kind(), UseCaseErrorKind::WorkspaceBusy); + assert!(error.to_string().contains("workspace")); + assert!(error.to_string().contains("already")); + } + } + #[test] fn execute_command_validates_before_trying_workspace_lock() { let dir = tempdir().expect("tempdir"); @@ -3192,6 +4000,18 @@ mod tests { } } + #[test] + fn infobase_pre_dispatch_phase_distinguishes_lock_from_workspace_preparation() { + assert_eq!( + infobase_pre_dispatch_execution_phase(false), + ExportPhase::WorkspaceLock + ); + assert_eq!( + infobase_pre_dispatch_execution_phase(true), + ExportPhase::WorkspacePreparation + ); + } + #[test] fn pre_dispatch_json_error_supports_config_init_identity() { let error = UseCaseError::new(UseCaseErrorKind::Validation, "bad config init request"); diff --git a/src/cli/output.rs b/src/cli/output.rs index c68029924..d39a5847a 100644 --- a/src/cli/output.rs +++ b/src/cli/output.rs @@ -48,10 +48,20 @@ pub fn with_cli_error(envelope: Envelope, error: &UseCaseError) } fn cli_envelope_error(error: &UseCaseError) -> EnvelopeError { - let (code, kind) = match error.kind() { + let (code, kind) = cli_error_contract(error.kind()); + EnvelopeError::new(code, kind, error.message()) +} + +pub(crate) const fn cli_error_contract(kind: UseCaseErrorKind) -> (&'static str, &'static str) { + match kind { + UseCaseErrorKind::Capability => ("capability_unavailable", "capability"), + UseCaseErrorKind::Environment => ("environment_unavailable", "environment"), + UseCaseErrorKind::WorkspaceBusy => ("workspace_busy", "workspace"), + UseCaseErrorKind::InvalidOutput => ("invalid_output", "invalid_output"), + UseCaseErrorKind::Cancelled => ("cancelled", "interruption"), + UseCaseErrorKind::TimedOut => ("timed_out", "interruption"), UseCaseErrorKind::Validation => ("invalid_argument", "validation"), UseCaseErrorKind::Runtime => ("runtime_failure", "runtime"), UseCaseErrorKind::Platform => ("platform_failure", "platform"), - }; - EnvelopeError::new(code, kind, error.message()) + } } diff --git a/src/config/loader.rs b/src/config/loader.rs index c05d0ddd4..f31575a4b 100644 --- a/src/config/loader.rs +++ b/src/config/loader.rs @@ -6,7 +6,8 @@ use crate::config::schema::{ validate_local_overlay_schema_boundary, validate_main_config_schema_boundary, }; use crate::config::validate::{ - validate, validate_prepared_test, validate_tools_download_bootstrap, ConfigValidationError, + validate, validate_infobase_export, validate_prepared_test, validate_tools_download_bootstrap, + ConfigValidationError, }; use crate::support::path::normalize_windows_verbatim_path; @@ -72,8 +73,20 @@ pub fn load_config_for_prepared_test( ) } +pub fn load_config_for_infobase_export( + config_path: Option<&str>, + workdir_override: Option<&str>, +) -> Result { + load_config_with_mode( + config_path, + workdir_override, + ConfigValidationMode::InfobaseExport, + ) +} + enum ConfigValidationMode { Full, + InfobaseExport, PreparedTest, ToolsDownload, } @@ -117,6 +130,7 @@ fn load_config_with_mode( match validation_mode { ConfigValidationMode::Full => validate(&config)?, + ConfigValidationMode::InfobaseExport => validate_infobase_export(&config)?, ConfigValidationMode::PreparedTest => validate_prepared_test(&config)?, ConfigValidationMode::ToolsDownload => validate_tools_download_bootstrap(&config)?, } diff --git a/src/config/validate.rs b/src/config/validate.rs index 114f3fc7c..3d9ed04e2 100644 --- a/src/config/validate.rs +++ b/src/config/validate.rs @@ -238,6 +238,20 @@ pub fn validate_prepared_test(config: &AppConfig) -> Result<(), ConfigValidation Ok(()) } +/// Validate configuration for operations that read only the configured infobase. +/// +/// Source trees, build settings, test runners, EDT and client MCP tooling are not inputs to +/// CF/CFE/DT export and must not block an infobase-only workspace. +pub fn validate_infobase_export(config: &AppConfig) -> Result<(), ConfigValidationError> { + validate_base_path(&config.base_path)?; + // Export provider selection is intentionally side-effect free. workPath is + // created only when the selected command acquires its workspace lock. + validate_connection_contract(config)?; + validate_platform_version(config)?; + validate_execution_timeout(config)?; + Ok(()) +} + fn validate_base_path(path: &Path) -> Result<(), ConfigValidationError> { if !path.exists() || !path.is_dir() { return Err(ConfigValidationError::BasePathInvalid( diff --git a/src/domain/infobase_export.rs b/src/domain/infobase_export.rs new file mode 100644 index 000000000..c5408bc4c --- /dev/null +++ b/src/domain/infobase_export.rs @@ -0,0 +1,584 @@ +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +use crate::domain::execution::{ExecutionOutcome, ExecutionStatus, ExecutionStepKind, StepResult}; + +/// Closed vocabulary for every observable phase of an information-base export, +/// including failures before provider dispatch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExportPhase { + ConfigurationLoad, + Validation, + ProviderSelection, + WorkspaceLock, + WorkspacePreparation, + ResolveTarget, + TargetLock, + OrphanCleanup, + PrepareStaging, + ProviderCommand, + ValidateProviderOutput, + BeforePublication, + PublishTargetRevalidation, + Publication, +} + +impl ExportPhase { + pub const fn as_str(self) -> &'static str { + match self { + Self::ConfigurationLoad => "configuration load", + Self::Validation => "validation", + Self::ProviderSelection => "provider selection", + Self::WorkspaceLock => "workspace lock", + Self::WorkspacePreparation => "workspace preparation", + Self::ResolveTarget => "resolve target", + Self::TargetLock => "target lock", + Self::OrphanCleanup => "orphan cleanup", + Self::PrepareStaging => "prepare staging", + Self::ProviderCommand => "provider command", + Self::ValidateProviderOutput => "validate provider output", + Self::BeforePublication => "before publication", + Self::PublishTargetRevalidation => "publish target revalidation", + Self::Publication => "publication", + } + } + + pub const fn kind(self) -> ExecutionStepKind { + match self { + Self::ConfigurationLoad | Self::Validation | Self::ValidateProviderOutput => { + ExecutionStepKind::Validation + } + Self::WorkspaceLock + | Self::WorkspacePreparation + | Self::OrphanCleanup + | Self::PrepareStaging => ExecutionStepKind::PrepareWorkspace, + Self::ResolveTarget | Self::TargetLock | Self::PublishTargetRevalidation => { + ExecutionStepKind::ResolveTarget + } + Self::ProviderSelection => ExecutionStepKind::Other, + Self::ProviderCommand => ExecutionStepKind::PlatformCommand, + Self::BeforePublication | Self::Publication => ExecutionStepKind::Publish, + } + } +} + +/// Configuration state persisted into a package. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ConfigurationState { + Working, + Database, +} + +impl ConfigurationState { + pub const fn as_str(self) -> &'static str { + match self { + Self::Working => "working", + Self::Database => "database", + } + } +} + +/// Configuration whose state is persisted into a package. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ConfigurationSubject { + Main, + Extension { name: String }, +} + +impl ConfigurationSubject { + pub const fn artifact_kind(&self) -> InfobaseExportArtifactKind { + match self { + Self::Main => InfobaseExportArtifactKind::Cf, + Self::Extension { .. } => InfobaseExportArtifactKind::Cfe, + } + } +} + +/// Whether runner has an adapter for an exact export operation. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ProviderImplementation { + Implemented, + Experimental, + Unsupported, +} + +impl ProviderImplementation { + pub const fn as_str(self) -> &'static str { + match self { + Self::Implemented => "implemented", + Self::Experimental => "experimental", + Self::Unsupported => "unsupported", + } + } +} + +/// Current-environment readiness established without starting a provider process. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ProviderReadiness { + Ready, + Unavailable, + NotChecked, +} + +impl ProviderReadiness { + pub const fn as_str(self) -> &'static str { + match self { + Self::Ready => "ready", + Self::Unavailable => "unavailable", + Self::NotChecked => "not_checked", + } + } +} + +/// Strongest evidence currently attached to an implementation row. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ProviderEvidence { + Documented, + ArgvTested, + LiveVerified, +} + +impl ProviderEvidence { + pub const fn as_str(self) -> &'static str { + match self { + Self::Documented => "documented", + Self::ArgvTested => "argv_tested", + Self::LiveVerified => "live_verified", + } + } +} + +/// Process provider selected for an information-base export. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum ExportProvider { + DesignerBatch, + IbcmdProcess, +} + +impl ExportProvider { + pub const fn as_str(self) -> &'static str { + match self { + Self::DesignerBatch => "designer-batch", + Self::IbcmdProcess => "ibcmd-process", + } + } +} + +/// Closed file format vocabulary for information-base exports. +/// +/// This type is deliberately namespaced: [`crate::domain::artifact::ArtifactKind`] +/// classifies retained execution artifacts and does not distinguish CF, CFE, +/// and DT package formats. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum InfobaseExportArtifactKind { + Cf, + Cfe, + Dt, +} + +impl InfobaseExportArtifactKind { + pub const fn file_extension(self) -> &'static str { + match self { + Self::Cf => "cf", + Self::Cfe => "cfe", + Self::Dt => "dt", + } + } + + pub const fn as_str(self) -> &'static str { + self.file_extension() + } +} + +/// Subject marker for a complete DT export. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum InfobaseSnapshotSubject { + Infobase, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ProviderCandidate { + pub provider: ExportProvider, + pub implementation: ProviderImplementation, + pub readiness: ProviderReadiness, + pub evidence: ProviderEvidence, + pub reason: String, +} + +impl ProviderCandidate { + pub fn new( + provider: ExportProvider, + implementation: ProviderImplementation, + readiness: ProviderReadiness, + evidence: ProviderEvidence, + reason: impl Into, + ) -> Self { + Self { + provider, + implementation, + readiness, + evidence, + reason: reason.into(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ExportProviderDecision { + provider: Option, + reason: String, + candidates: Vec, +} + +impl ExportProviderDecision { + pub fn selected( + provider: ExportProvider, + reason: impl Into, + candidates: Vec, + ) -> Self { + debug_assert!(candidates.iter().any(|candidate| { + candidate.provider == provider + && candidate.implementation == ProviderImplementation::Implemented + && candidate.readiness == ProviderReadiness::Ready + })); + Self { + provider: Some(provider), + reason: reason.into(), + candidates, + } + } + + pub fn unavailable(reason: impl Into, candidates: Vec) -> Self { + Self { + provider: None, + reason: reason.into(), + candidates, + } + } + + pub const fn provider(&self) -> Option { + self.provider + } + + pub fn reason(&self) -> &str { + &self.reason + } + + pub fn candidates(&self) -> &[ProviderCandidate] { + &self.candidates + } +} + +/// Observable state of the final output path after an export attempt. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ExportTargetState { + Unchanged, + Created, + Replaced, + Restored, + Uncertain, +} + +/// Request to persist a working or database configuration into CF/CFE. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ExportConfigurationPackageRequest { + pub state: ConfigurationState, + pub subject: ConfigurationSubject, + pub output: PathBuf, +} + +/// Typed presentation data for a configuration package export. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ExportConfigurationPackageResult { + pub state: ConfigurationState, + pub subject: ConfigurationSubject, + pub selection: ExportProviderDecision, + pub artifact_kind: InfobaseExportArtifactKind, + pub output: PathBuf, + pub published: bool, + pub target_state: ExportTargetState, + #[serde(skip)] + pub warnings: Vec, + pub execution: ExecutionOutcome<()>, + #[serde(skip)] + pub steps: Vec, +} + +impl ExportConfigurationPackageResult { + pub fn new( + request: ExportConfigurationPackageRequest, + selection: ExportProviderDecision, + ) -> Self { + let artifact_kind = request.subject.artifact_kind(); + Self { + state: request.state, + subject: request.subject, + selection, + artifact_kind, + output: request.output, + published: false, + target_state: ExportTargetState::Unchanged, + warnings: Vec::new(), + execution: ExecutionOutcome::new(ExecutionStatus::Failed), + steps: Vec::new(), + } + } + + pub fn mark_succeeded(&mut self) { + self.execution.status = ExecutionStatus::Succeeded; + } +} + +/// Request to persist the complete information base into a DT snapshot. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ExportInfobaseSnapshotRequest { + pub output: PathBuf, +} + +/// Typed presentation data for an information-base snapshot export. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ExportInfobaseSnapshotResult { + pub subject: InfobaseSnapshotSubject, + pub selection: ExportProviderDecision, + pub artifact_kind: InfobaseExportArtifactKind, + pub output: PathBuf, + pub published: bool, + pub target_state: ExportTargetState, + #[serde(skip)] + pub warnings: Vec, + pub execution: ExecutionOutcome<()>, + #[serde(skip)] + pub steps: Vec, +} + +impl ExportInfobaseSnapshotResult { + pub fn new(request: ExportInfobaseSnapshotRequest, selection: ExportProviderDecision) -> Self { + Self { + subject: InfobaseSnapshotSubject::Infobase, + selection, + artifact_kind: InfobaseExportArtifactKind::Dt, + output: request.output, + published: false, + target_state: ExportTargetState::Unchanged, + warnings: Vec::new(), + execution: ExecutionOutcome::new(ExecutionStatus::Failed), + steps: Vec::new(), + } + } + + pub fn mark_succeeded(&mut self) { + self.execution.status = ExecutionStatus::Succeeded; + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use serde_json::json; + + use super::{ + ConfigurationState, ConfigurationSubject, ExportConfigurationPackageRequest, + ExportConfigurationPackageResult, ExportInfobaseSnapshotRequest, + ExportInfobaseSnapshotResult, ExportPhase, ExportProvider, ExportProviderDecision, + ExportTargetState, InfobaseExportArtifactKind, ProviderCandidate, ProviderEvidence, + ProviderImplementation, ProviderReadiness, + }; + use crate::domain::execution::ExecutionStepKind; + + fn ready(provider: ExportProvider) -> ProviderCandidate { + ProviderCandidate::new( + provider, + ProviderImplementation::Implemented, + ProviderReadiness::Ready, + ProviderEvidence::ArgvTested, + "adapter and utility are ready", + ) + } + + #[test] + fn export_phase_is_the_single_owner_of_step_name_and_kind() { + assert_eq!( + ExportPhase::ConfigurationLoad.as_str(), + "configuration load" + ); + assert_eq!( + ExportPhase::ConfigurationLoad.kind(), + ExecutionStepKind::Validation + ); + assert_eq!(ExportPhase::WorkspaceLock.as_str(), "workspace lock"); + assert_eq!( + ExportPhase::WorkspaceLock.kind(), + ExecutionStepKind::PrepareWorkspace + ); + assert_eq!( + ExportPhase::WorkspacePreparation.as_str(), + "workspace preparation" + ); + assert_eq!( + ExportPhase::WorkspacePreparation.kind(), + ExecutionStepKind::PrepareWorkspace + ); + assert_eq!( + ExportPhase::ProviderCommand.kind(), + ExecutionStepKind::PlatformCommand + ); + } + + #[test] + fn configuration_request_serializes_closed_transport_neutral_vocabulary() { + let request = ExportConfigurationPackageRequest { + state: ConfigurationState::Database, + subject: ConfigurationSubject::Extension { + name: "Sales".to_owned(), + }, + output: PathBuf::from("/tmp/sales.cfe"), + }; + + assert_eq!( + serde_json::to_value(&request).expect("configuration request json"), + json!({ + "state": "database", + "subject": {"kind": "extension", "name": "Sales"}, + "output": "/tmp/sales.cfe" + }) + ); + assert_eq!( + serde_json::to_value(ExportProvider::DesignerBatch).expect("provider json"), + json!("designer-batch") + ); + assert_eq!( + serde_json::to_value(ProviderImplementation::Experimental) + .expect("implementation json"), + json!("experimental") + ); + assert_eq!( + request.subject.artifact_kind(), + InfobaseExportArtifactKind::Cfe + ); + } + + #[test] + fn configuration_result_derives_artifact_kind_from_subject() { + let request = ExportConfigurationPackageRequest { + state: ConfigurationState::Working, + subject: ConfigurationSubject::Main, + output: PathBuf::from("/tmp/main.cf"), + }; + let selection = ExportProviderDecision::selected( + ExportProvider::IbcmdProcess, + "selected ready provider", + vec![ready(ExportProvider::IbcmdProcess)], + ); + + let result = ExportConfigurationPackageResult::new(request, selection); + + assert_eq!(result.artifact_kind, InfobaseExportArtifactKind::Cf); + assert!(!result.published); + assert!(result.warnings.is_empty()); + assert_eq!( + serde_json::to_value(result).expect("configuration result json"), + json!({ + "state": "working", + "subject": {"kind": "main"}, + "selection": { + "provider": "ibcmd-process", + "reason": "selected ready provider", + "candidates": [{ + "provider": "ibcmd-process", + "implementation": "implemented", + "readiness": "ready", + "evidence": "argv_tested", + "reason": "adapter and utility are ready" + }] + }, + "artifact_kind": "cf", + "output": "/tmp/main.cf", + "published": false, + "target_state": "unchanged", + "execution": {"status": "failed"} + }) + ); + } + + #[test] + fn unavailable_provider_decision_keeps_candidate_diagnostics() { + let decision = ExportProviderDecision::unavailable( + "no implemented provider is ready for DT export", + vec![ProviderCandidate::new( + ExportProvider::IbcmdProcess, + ProviderImplementation::Experimental, + ProviderReadiness::NotChecked, + ProviderEvidence::Documented, + "exclusive access is not implemented", + )], + ); + + assert_eq!(decision.provider(), None); + assert_eq!( + serde_json::to_value(&decision).expect("unsupported decision json"), + json!({ + "provider": null, + "reason": "no implemented provider is ready for DT export", + "candidates": [{ + "provider": "ibcmd-process", + "implementation": "experimental", + "readiness": "not_checked", + "evidence": "documented", + "reason": "exclusive access is not implemented" + }] + }) + ); + } + + #[test] + fn snapshot_result_is_always_a_dt_and_preserves_typed_presentation_fields() { + let request = ExportInfobaseSnapshotRequest { + output: PathBuf::from("/tmp/base.dt"), + }; + let selection = ExportProviderDecision::selected( + ExportProvider::DesignerBatch, + "selected ready provider", + vec![ready(ExportProvider::DesignerBatch)], + ); + let mut result = ExportInfobaseSnapshotResult::new(request, selection); + result.published = true; + result.target_state = ExportTargetState::Created; + result.mark_succeeded(); + result.warnings.push("staging cleanup deferred".to_owned()); + + assert_eq!(result.artifact_kind, InfobaseExportArtifactKind::Dt); + assert_eq!( + serde_json::to_value(result).expect("snapshot result json"), + json!({ + "subject": {"kind": "infobase"}, + "selection": { + "provider": "designer-batch", + "reason": "selected ready provider", + "candidates": [{ + "provider": "designer-batch", + "implementation": "implemented", + "readiness": "ready", + "evidence": "argv_tested", + "reason": "adapter and utility are ready" + }] + }, + "artifact_kind": "dt", + "output": "/tmp/base.dt", + "published": true, + "target_state": "created", + "execution": {"status": "succeeded"} + }) + ); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 054ae3d42..a2d8c3868 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -16,6 +16,8 @@ pub mod dump; pub mod execution; /// Extension-management domain models. pub mod extensions; +/// Information-base configuration package and snapshot export domain models. +pub mod infobase_export; /// Init domain models. pub mod init; /// Structured issue models. diff --git a/src/mcp/error.rs b/src/mcp/error.rs index 12d795478..909c22789 100644 --- a/src/mcp/error.rs +++ b/src/mcp/error.rs @@ -48,6 +48,11 @@ impl McpBusinessErrorKind { impl From for McpBusinessErrorKind { fn from(value: UseCaseErrorKind) -> Self { match value { + UseCaseErrorKind::Capability => Self::Runtime, + UseCaseErrorKind::Environment | UseCaseErrorKind::WorkspaceBusy => Self::Runtime, + UseCaseErrorKind::InvalidOutput + | UseCaseErrorKind::Cancelled + | UseCaseErrorKind::TimedOut => Self::Platform, UseCaseErrorKind::Validation => Self::Validation, UseCaseErrorKind::Runtime => Self::Runtime, UseCaseErrorKind::Platform => Self::Platform, @@ -68,6 +73,13 @@ impl McpBusinessError { pub fn from_use_case(error: &UseCaseError) -> Self { let kind = error.kind(); let code = match kind { + UseCaseErrorKind::Capability => McpErrorCode::RuntimeFailure, + UseCaseErrorKind::Environment | UseCaseErrorKind::WorkspaceBusy => { + McpErrorCode::RuntimeFailure + } + UseCaseErrorKind::InvalidOutput + | UseCaseErrorKind::Cancelled + | UseCaseErrorKind::TimedOut => McpErrorCode::PlatformFailure, UseCaseErrorKind::Validation => McpErrorCode::InvalidArgument, UseCaseErrorKind::Runtime => McpErrorCode::RuntimeFailure, UseCaseErrorKind::Platform => McpErrorCode::PlatformFailure, diff --git a/src/platform/connection.rs b/src/platform/connection.rs index c4880fa49..2105f5e99 100644 --- a/src/platform/connection.rs +++ b/src/platform/connection.rs @@ -60,6 +60,40 @@ impl V8Connection { }) } + /// Returns whether the raw value has a supported file or server connection shape. + pub fn has_supported_shape(&self) -> bool { + if let Some(path) = self.file_path() { + return !path.trim().is_empty(); + } + if self.raw.starts_with('/') || self.raw.starts_with('-') { + let mut args = self.connection_args.iter(); + while let Some(arg) = args.next() { + if arg.eq_ignore_ascii_case("/s") || arg.eq_ignore_ascii_case("-s") { + return args.next().is_some_and(|value| { + let value = value.trim(); + !value.is_empty() && value.contains('\\') + }); + } + } + return false; + } + + let mut server = None; + let mut reference = None; + for part in self.raw.split(';') { + let Some((key, value)) = part.split_once('=') else { + return false; + }; + match key.trim().to_ascii_lowercase().as_str() { + "srvr" => server = Some(value.trim()), + "ref" => reference = Some(value.trim()), + _ => {} + } + } + server.is_some_and(|value| !value.is_empty()) + && reference.is_some_and(|value| !value.is_empty()) + } + /// Returns a stable file-based infobase connection string when available. pub fn create_infobase_arg(&self) -> Option { self.file_path() @@ -135,6 +169,18 @@ mod tests { assert_eq!(connection.file_path(), Some("/tmp/ib")); } + #[test] + fn validates_supported_file_and_server_connection_shapes() { + assert!(V8Connection::from_connection_string("File=/tmp/ib").has_supported_shape()); + assert!( + V8Connection::from_connection_string("Srvr=cluster;Ref=demo").has_supported_shape() + ); + assert!(V8Connection::from_connection_string(r#"/S "cluster\demo""#).has_supported_shape()); + assert!(!V8Connection::from_connection_string("not a connection").has_supported_shape()); + assert!(!V8Connection::from_connection_string("Srvr=cluster;Ref=").has_supported_shape()); + assert!(!V8Connection::from_connection_string("File=").has_supported_shape()); + } + #[test] fn extracts_file_path_from_raw_f_args() { let connection = V8Connection::from_connection_string("/F \"/tmp/my ib\""); diff --git a/src/platform/designer.rs b/src/platform/designer.rs index 3f094a5ff..55ff536e2 100644 --- a/src/platform/designer.rs +++ b/src/platform/designer.rs @@ -234,6 +234,33 @@ impl<'a> DesignerDsl<'a> { self.run(&args) } + /// `/DumpDBCfg [-Extension ]` + pub fn dump_db_cfg( + &self, + target_file: &Path, + extension: Option<&str>, + ) -> Result { + let mut args = self.base_args(); + args.push("/DumpDBCfg".to_owned()); + args.push(target_file.display().to_string()); + if let Some(extension) = extension { + args.push("-Extension".to_owned()); + args.push(extension.to_owned()); + } + self.run(&args) + } + + /// `/DumpIB ` + pub fn dump_infobase( + &self, + target_file: &Path, + ) -> Result { + let mut args = self.base_args(); + args.push("/DumpIB".to_owned()); + args.push(target_file.display().to_string()); + self.run(&args) + } + /// `/DumpExternalDataProcessorOrReportToFiles ` pub fn dump_external_data_processor_or_report_to_files( &self, @@ -647,6 +674,89 @@ mod tests { assert_eq!(result.platform_log_path, Some(log_path)); } + #[cfg(unix)] + #[test] + fn dump_db_cfg_builds_expected_args_for_extension() { + let dir = tempdir().expect("tempdir"); + let script = dir.path().join("1cv8"); + let args_log = dir.path().join("args.log"); + let target = dir.path().join("database.cfe"); + write_script( + &script, + &format!("printf '%s\\n' \"$@\" > \"{}\"\nexit 0", args_log.display()), + ); + let runner = ProcessExecutor; + let dsl = DesignerDsl::new( + script, + V8Connection::from_connection_string("File=/tmp/ib"), + &runner as &dyn ProcessRunner, + None, + ); + + dsl.dump_db_cfg(&target, Some("SalesAddon")) + .expect("dump database configuration"); + + let args = fs::read_to_string(args_log) + .expect("args log") + .lines() + .map(str::to_owned) + .collect::>(); + assert_eq!( + args, + vec![ + "DESIGNER", + "/DisableStartupDialogs", + "/DisableStartupMessages", + "/IBConnectionString", + "File=/tmp/ib", + "/DumpDBCfg", + target.to_str().expect("utf-8 target"), + "-Extension", + "SalesAddon", + ] + ); + } + + #[cfg(unix)] + #[test] + fn dump_infobase_builds_expected_args() { + let dir = tempdir().expect("tempdir"); + let script = dir.path().join("1cv8"); + let args_log = dir.path().join("args.log"); + let target = dir.path().join("snapshot.dt"); + write_script( + &script, + &format!("printf '%s\\n' \"$@\" > \"{}\"\nexit 0", args_log.display()), + ); + let runner = ProcessExecutor; + let dsl = DesignerDsl::new( + script, + V8Connection::from_connection_string("File=/tmp/ib"), + &runner as &dyn ProcessRunner, + None, + ); + + dsl.dump_infobase(&target).expect("dump infobase"); + + let args = fs::read_to_string(args_log) + .expect("args log") + .lines() + .map(str::to_owned) + .collect::>(); + assert_eq!( + args, + vec![ + "DESIGNER", + "/DisableStartupDialogs", + "/DisableStartupMessages", + "/IBConnectionString", + "File=/tmp/ib", + "/DumpIB", + target.to_str().expect("utf-8 target"), + ] + ); + } + #[cfg(unix)] #[test] fn load_and_merge_cfg_pass_expected_arguments() { diff --git a/src/platform/ibcmd.rs b/src/platform/ibcmd.rs index a638666e8..7bc540df5 100644 --- a/src/platform/ibcmd.rs +++ b/src/platform/ibcmd.rs @@ -304,6 +304,24 @@ impl<'a> IbcmdDsl<'a> { self.run(&args) } + /// Saves the working or database configuration to a CF/CFE artifact. + pub fn config_save( + &self, + target_file: &Path, + database: bool, + extension: Option<&str>, + ) -> Result { + let mut args = self.authenticated_infobase_args(&["config", "save"]); + if database { + args.push("--db".to_owned()); + } + if let Some(extension) = extension { + push_option_value(&mut args, "--extension", extension); + } + args.push(target_file.display().to_string()); + self.run(&args) + } + /// Exports changes in sync mode relative to an existing target directory. pub fn config_export_incremental( &self, @@ -613,6 +631,93 @@ mod tests { assert!(args.contains("--force")); } + #[cfg(unix)] + #[test] + fn config_save_builds_expected_args_for_database_extension() { + let dir = tempdir().expect("tempdir"); + let script = dir.path().join("ibcmd"); + let args_log = dir.path().join("args.log"); + let target = dir.path().join("database.cfe"); + write_script( + &script, + &format!("printf '%s\\n' \"$@\" > \"{}\"\nexit 0", args_log.display()), + ); + let runner = ProcessExecutor; + let conn = file_connection("File=/ib"); + let dsl = IbcmdDsl::new(script, conn, &runner as &dyn ProcessRunner); + + dsl.config_save(&target, true, Some("SalesAddon")) + .expect("save database extension"); + + let args = fs::read_to_string(args_log) + .expect("args") + .lines() + .map(str::to_owned) + .collect::>(); + assert_eq!( + args, + vec![ + "infobase", + "--db-path", + "/ib", + "config", + "save", + "--db", + "--extension", + "SalesAddon", + target.to_str().expect("utf-8 target"), + ] + ); + } + + #[cfg(unix)] + #[test] + fn config_save_preserves_auth_and_data_path_conventions() { + let dir = tempdir().expect("tempdir"); + let script = dir.path().join("ibcmd"); + let args_log = dir.path().join("args.log"); + let target = dir.path().join("working.cf"); + let data_path = dir.path().join("ibcmd-data"); + write_script( + &script, + &format!("printf '%s\\n' \"$@\" > \"{}\"\nexit 0", args_log.display()), + ); + let runner = ProcessExecutor; + let conn = IbcmdConnection::from_infobase( + &InfobaseConfig::file("File=/ib") + .with_credentials(Some("admin".to_owned()), Some("secret".to_owned())), + ) + .expect("connection"); + let dsl = IbcmdDsl::new(script, conn, &runner as &dyn ProcessRunner) + .with_data_path(data_path.clone()); + + dsl.config_save(&target, false, None) + .expect("save working configuration"); + + let args = fs::read_to_string(args_log) + .expect("args") + .lines() + .map(str::to_owned) + .collect::>(); + assert_eq!( + args, + vec![ + "infobase".to_owned(), + "--data".to_owned(), + data_path.display().to_string(), + "--db-path".to_owned(), + "/ib".to_owned(), + "config".to_owned(), + "save".to_owned(), + "--user".to_owned(), + "admin".to_owned(), + "--password".to_owned(), + "secret".to_owned(), + target.display().to_string(), + ] + ); + } + #[cfg(unix)] #[test] fn config_export_full_with_data_path_builds_expected_args() { diff --git a/src/support/error.rs b/src/support/error.rs index a13f30682..17da496df 100644 --- a/src/support/error.rs +++ b/src/support/error.rs @@ -10,6 +10,24 @@ use thiserror::Error; #[derive(Debug, Error)] pub enum AppError { + #[error("capability unavailable: {0}")] + CapabilityUnavailable(String), + + #[error("environment unavailable: {0}")] + EnvironmentUnavailable(String), + + #[error("workspace busy: {0}")] + WorkspaceBusy(String), + + #[error("cancelled: {0}")] + Cancelled(String), + + #[error("timed out: {0}")] + TimedOut(String), + + #[error("invalid platform output: {0}")] + InvalidOutput(String), + #[error("validation error: {0}")] Validation(String), @@ -94,6 +112,16 @@ impl AppError { pub fn with_context(self, context: impl Into) -> Self { let context = context.into(); match self { + Self::CapabilityUnavailable(message) => { + Self::CapabilityUnavailable(format!("{context}; {message}")) + } + Self::EnvironmentUnavailable(message) => { + Self::EnvironmentUnavailable(format!("{context}; {message}")) + } + Self::WorkspaceBusy(message) => Self::WorkspaceBusy(format!("{context}; {message}")), + Self::Cancelled(message) => Self::Cancelled(format!("{context}; {message}")), + Self::TimedOut(message) => Self::TimedOut(format!("{context}; {message}")), + Self::InvalidOutput(message) => Self::InvalidOutput(format!("{context}; {message}")), Self::Validation(message) => Self::Validation(format!("{context}; {message}")), Self::ValidationIbcmd(source) => Self::ValidationIbcmdContext { context, source }, Self::ValidationIbcmdContext { diff --git a/src/support/fs.rs b/src/support/fs.rs index b44841bb5..7e80b43f8 100644 --- a/src/support/fs.rs +++ b/src/support/fs.rs @@ -1,4 +1,4 @@ -use std::fs::{File, OpenOptions}; +use std::fs::{File, OpenOptions, TryLockError}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::thread; @@ -81,9 +81,11 @@ pub struct AdvisoryLockGuard { impl Drop for AdvisoryLockGuard { fn drop(&mut self) { - self.file.take(); - if lock_file_owned_by(&self.path, &self.metadata.owner_id) { - let _ = std::fs::remove_file(&self.path); + if let Some(file) = self.file.take() { + if lock_file_owned_by(&self.path, &self.metadata.owner_id) { + let _ = std::fs::remove_file(&self.path); + } + let _ = file.unlock(); } } } @@ -96,6 +98,56 @@ pub struct ReplaceDirOutcome { #[derive(Debug)] pub struct ReplaceFileOutcome { pub cleanup_warning: Option, + pub previous_target_present: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReplaceFileFailureState { + Unchanged, + Restored, + Uncertain, +} + +#[derive(Debug, thiserror::Error)] +#[error("{source}")] +pub struct ReplaceFileError { + #[source] + pub source: std::io::Error, + pub target_state: ReplaceFileFailureState, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ReplaceFileTestPoint { + PublishStage, + RestoreBackup, +} + +#[cfg(test)] +thread_local! { + static REPLACE_FILE_TEST_HOOK: std::cell::RefCell std::io::Result<()>>>> = + std::cell::RefCell::new(None); +} + +#[cfg(test)] +fn run_replace_file_test_hook(point: ReplaceFileTestPoint) -> std::io::Result<()> { + REPLACE_FILE_TEST_HOOK.with(|hook| match hook.borrow().as_ref() { + Some(hook) => hook(point), + None => Ok(()), + }) +} + +#[cfg(not(test))] +fn run_replace_file_test_hook(_point: ReplaceFileTestPoint) -> std::io::Result<()> { + Ok(()) +} + +impl ReplaceFileError { + fn new(source: std::io::Error, target_state: ReplaceFileFailureState) -> Self { + Self { + source, + target_state, + } + } } pub fn acquire_advisory_lock(path: &Path) -> std::io::Result { @@ -115,9 +167,11 @@ pub fn try_acquire_advisory_lock(path: &Path) -> std::io::Result std::io::Result { - if let Some(parent) = path.parent() { - ensure_dir(parent)?; - } + let parent = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + ensure_dir(parent)?; let metadata = AdvisoryLockMetadata { tool: TOOL_NAME.to_owned(), @@ -127,45 +181,79 @@ fn try_acquire_advisory_lock_impl(path: &Path) -> std::io::Result { - #[cfg(test)] - TEST_LOCK_WRITE_HOOK.with(|cell| { - if let Some(hook) = cell.borrow().as_ref() { - hook(); - } - }); - - let write_result = file.write_all(&encoded).and_then(|()| file.sync_all()); - if let Err(error) = write_result { - let _ = std::fs::remove_file(path); - return Err(error); - } - return Ok(AdvisoryLockGuard { - file: Some(file), - path: path.to_path_buf(), - metadata, - }); - } - Err(error) if error.kind() == ErrorKind::AlreadyExists => { - if stale_advisory_lock_can_be_removed(path) { - match std::fs::remove_file(path) { - Ok(()) => continue, - Err(remove_error) if remove_error.kind() == ErrorKind::NotFound => continue, - Err(remove_error) => return Err(remove_error), - } - } - return Err(std::io::Error::new( - ErrorKind::WouldBlock, - format!("lock is already held: {}", path.display()), - )); - } - Err(error) => return Err(error), + let system_lock_path = advisory_system_lock_path(path)?; + let file = OpenOptions::new() + .create(true) + .read(true) + .write(true) + .truncate(false) + .open(system_lock_path)?; + match file.try_lock() { + Ok(()) => {} + Err(TryLockError::WouldBlock) => return Err(lock_already_held(path)), + Err(TryLockError::Error(error)) => return Err(error), + } + + publish_advisory_lock_metadata(path, parent, &encoded)?; + Ok(AdvisoryLockGuard { + file: Some(file), + path: path.to_path_buf(), + metadata, + }) +} + +fn advisory_system_lock_path(path: &Path) -> std::io::Result { + let name = path.file_name().ok_or_else(|| { + std::io::Error::new( + ErrorKind::InvalidInput, + format!("lock path has no file name: {}", path.display()), + ) + })?; + let mut system_name = name.to_os_string(); + system_name.push(".system"); + Ok(path.with_file_name(system_name)) +} + +fn publish_advisory_lock_metadata( + path: &Path, + parent: &Path, + encoded: &[u8], +) -> std::io::Result<()> { + let mut candidate = tempfile::Builder::new() + .prefix(".v8-runner-lock-candidate-") + .tempfile_in(parent)?; + write_advisory_lock_metadata(candidate.as_file_mut(), encoded)?; + candidate.as_file().sync_all()?; + + match candidate.persist_noclobber(path) { + Ok(_) => { + let _ = best_effort_fsync_dir(parent); + Ok(()) } + Err(error) if error.error.kind() == ErrorKind::AlreadyExists => { + Err(legacy_lock_requires_offline_cleanup(path)) + } + Err(error) => Err(error.error), } } +fn lock_already_held(path: &Path) -> std::io::Error { + std::io::Error::new( + ErrorKind::WouldBlock, + format!("lock is already held: {}", path.display()), + ) +} + +fn legacy_lock_requires_offline_cleanup(path: &Path) -> std::io::Error { + std::io::Error::new( + ErrorKind::AlreadyExists, + format!( + "legacy or crash owner lock remains at '{}'; stop all old and new v8-runner processes, then remove this file manually", + path.display() + ), + ) +} + pub fn advisory_lock_owner_id(guard: &AdvisoryLockGuard) -> &str { &guard.metadata.owner_id } @@ -175,14 +263,30 @@ pub fn read_advisory_lock_metadata(path: &Path) -> std::io::Result bool { - match read_advisory_lock_metadata(path) { - Ok(metadata) => !lock_holder_is_live(metadata.pid), - Err(error) if error.kind() == ErrorKind::NotFound => true, - Err(error) if error.kind() == ErrorKind::InvalidData => std::fs::metadata(path) - .map(|metadata| metadata.len() > 0) - .unwrap_or(true), - Err(_) => false, +fn lock_file_owned_by(path: &Path, owner_id: &str) -> bool { + read_advisory_lock_metadata(path) + .map(|metadata| metadata.owner_id == owner_id) + .unwrap_or(false) +} + +#[cfg(not(test))] +fn write_advisory_lock_metadata(file: &mut File, encoded: &[u8]) -> std::io::Result<()> { + file.write_all(encoded) +} + +#[cfg(test)] +fn write_advisory_lock_metadata(file: &mut File, encoded: &[u8]) -> std::io::Result<()> { + let has_hook = TEST_LOCK_WRITE_HOOK.with(|cell| cell.borrow().is_some()); + if has_hook && !encoded.is_empty() { + file.write_all(&encoded[..1])?; + TEST_LOCK_WRITE_HOOK.with(|cell| { + if let Some(hook) = cell.borrow().as_ref() { + hook(); + } + }); + file.write_all(&encoded[1..]) + } else { + file.write_all(encoded) } } @@ -204,53 +308,6 @@ where result } -#[cfg(unix)] -fn lock_holder_is_live(pid: u32) -> bool { - let rc = unsafe { libc::kill(pid as i32, 0) }; - rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) -} - -#[cfg(windows)] -fn lock_holder_is_live(pid: u32) -> bool { - type Bool = i32; - type Dword = u32; - type Handle = *mut std::ffi::c_void; - - const PROCESS_QUERY_LIMITED_INFORMATION: Dword = 0x1000; - const ERROR_INVALID_PARAMETER: Dword = 87; - const ERROR_ACCESS_DENIED: Dword = 5; - const STILL_ACTIVE: Dword = 259; - - #[link(name = "kernel32")] - extern "system" { - fn OpenProcess(desired_access: Dword, inherit_handle: Bool, process_id: Dword) -> Handle; - fn GetExitCodeProcess(process: Handle, exit_code: *mut Dword) -> Bool; - fn CloseHandle(handle: Handle) -> Bool; - fn GetLastError() -> Dword; - } - - unsafe { - let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); - if handle.is_null() { - return match GetLastError() { - ERROR_INVALID_PARAMETER => false, - ERROR_ACCESS_DENIED => true, - _ => true, - }; - } - - let mut exit_code = 0; - let ok = GetExitCodeProcess(handle, &mut exit_code); - let _ = CloseHandle(handle); - ok != 0 && exit_code == STILL_ACTIVE - } -} - -#[cfg(not(any(unix, windows)))] -fn lock_holder_is_live(_pid: u32) -> bool { - true -} - pub fn best_effort_fsync_dir(path: &Path) -> std::io::Result<()> { #[cfg(unix)] { @@ -339,12 +396,6 @@ fn publish_file_atomically_impl( } } -fn lock_file_owned_by(path: &Path, owner_id: &str) -> bool { - read_advisory_lock_metadata(path) - .map(|metadata| metadata.owner_id == owner_id) - .unwrap_or(false) -} - pub fn metadata_sidecar_path(dir: &Path) -> PathBuf { let file_name = dir .file_name() @@ -501,11 +552,14 @@ pub fn replace_file_atomically( target_file: &Path, run_id: &str, target_identity: &str, -) -> std::io::Result { +) -> Result { let parent = target_file.parent().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!("target path has no parent: {}", target_file.display()), + ReplaceFileError::new( + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("target path has no parent: {}", target_file.display()), + ), + ReplaceFileFailureState::Unchanged, ) })?; let backup_name = target_file @@ -517,23 +571,35 @@ pub fn replace_file_atomically( let backup_metadata_path = metadata_sidecar_path(&backup_file); if !target_file.exists() { - publish_file_atomically(staging_file, target_file)?; - let fsync_result = best_effort_fsync_dir(parent); + publish_file_atomically(staging_file, target_file) + .map_err(|error| ReplaceFileError::new(error, ReplaceFileFailureState::Unchanged))?; + if let Err(error) = best_effort_fsync_dir(parent) { + let rollback_result = std::fs::rename(target_file, staging_file) + .and_then(|()| best_effort_fsync_dir(parent)); + return Err(replace_file_rollback_error( + error, + rollback_result, + "failed to fsync parent after creating target file", + ReplaceFileFailureState::Unchanged, + )); + } let _ = remove_path_if_exists(&stage_metadata_path); - fsync_result?; return Ok(ReplaceFileOutcome { cleanup_warning: None, + previous_target_present: false, }); } - std::fs::rename(target_file, &backup_file)?; + std::fs::rename(target_file, &backup_file) + .map_err(|error| ReplaceFileError::new(error, ReplaceFileFailureState::Unchanged))?; if let Err(error) = best_effort_fsync_dir(parent) { let rollback_result = std::fs::rename(&backup_file, target_file).and_then(|()| best_effort_fsync_dir(parent)); - return Err(with_rollback_context( + return Err(replace_file_rollback_error( error, - rollback_result.err(), + rollback_result, "failed to fsync parent after moving target file to backup", + ReplaceFileFailureState::Restored, )); } @@ -546,20 +612,25 @@ pub fn replace_file_atomically( ) { let rollback_result = std::fs::rename(&backup_file, target_file).and_then(|()| best_effort_fsync_dir(parent)); - return Err(with_rollback_context( + return Err(replace_file_rollback_error( error, - rollback_result.err(), + rollback_result, "failed to write backup file metadata", + ReplaceFileFailureState::Restored, )); } - if let Err(error) = publish_file_atomically(staging_file, target_file) { - let rollback_result = publish_file_atomically(&backup_file, target_file) + if let Err(error) = run_replace_file_test_hook(ReplaceFileTestPoint::PublishStage) + .and_then(|()| publish_file_atomically(staging_file, target_file)) + { + let rollback_result = run_replace_file_test_hook(ReplaceFileTestPoint::RestoreBackup) + .and_then(|()| publish_file_atomically(&backup_file, target_file)) .and_then(|()| best_effort_fsync_dir(parent)); - return Err(with_rollback_context( + return Err(replace_file_rollback_error( error, - rollback_result.err(), + rollback_result, "failed to publish staged artifact file", + ReplaceFileFailureState::Restored, )); } @@ -567,10 +638,11 @@ pub fn replace_file_atomically( let rollback_result = std::fs::rename(target_file, staging_file) .and_then(|()| publish_file_atomically(&backup_file, target_file)) .and_then(|()| best_effort_fsync_dir(parent)); - return Err(with_rollback_context( + return Err(replace_file_rollback_error( error, - rollback_result.err(), + rollback_result, "failed to fsync parent after publishing staged artifact file", + ReplaceFileFailureState::Restored, )); } @@ -595,9 +667,31 @@ pub fn replace_file_atomically( } else { Some(warnings.join("; ")) }, + previous_target_present: true, }) } +fn replace_file_rollback_error( + error: std::io::Error, + rollback_result: std::io::Result<()>, + context: &str, + restored_state: ReplaceFileFailureState, +) -> ReplaceFileError { + match rollback_result { + Ok(()) => ReplaceFileError::new( + std::io::Error::new(error.kind(), format!("{context}: {error}")), + restored_state, + ), + Err(rollback_error) => ReplaceFileError::new( + std::io::Error::new( + error.kind(), + format!("{context}: {error}; rollback failed: {rollback_error}"), + ), + ReplaceFileFailureState::Uncertain, + ), + } +} + fn with_rollback_context( error: std::io::Error, rollback_error: Option, @@ -617,10 +711,11 @@ mod tests { #[cfg(windows)] use super::replace_dir_atomically; use super::{ - acquire_advisory_lock, advisory_lock_owner_id, publish_file_atomically, - publish_file_atomically_impl, read_advisory_lock_metadata, remove_path_if_exists, + acquire_advisory_lock, advisory_lock_owner_id, advisory_system_lock_path, + publish_file_atomically, publish_file_atomically_impl, read_advisory_lock_metadata, + remove_path_if_exists, replace_file_atomically, replace_file_rollback_error, try_acquire_advisory_lock, try_acquire_advisory_lock_with_hook, AdvisoryLockMetadata, - TOOL_NAME, + ReplaceFileFailureState, ReplaceFileTestPoint, REPLACE_FILE_TEST_HOOK, TOOL_NAME, }; use std::fs; use std::io::ErrorKind; @@ -657,6 +752,63 @@ mod tests { assert_eq!(metadata.owner_id, advisory_lock_owner_id(&guard)); } + #[test] + fn released_advisory_lock_keeps_system_file_and_can_be_reacquired() { + let dir = tempdir().expect("tempdir"); + let lock_path = dir.path().join("persistent.lock"); + let first = acquire_advisory_lock(&lock_path).expect("first lock"); + drop(first); + + assert!(!lock_path.exists()); + assert!(advisory_system_lock_path(&lock_path) + .expect("system lock path") + .is_file()); + let second = try_acquire_advisory_lock(&lock_path).expect("second lock"); + assert!(!advisory_lock_owner_id(&second).is_empty()); + } + + #[test] + fn dead_legacy_lock_metadata_is_fail_closed() { + let dir = tempdir().expect("tempdir"); + let lock_path = dir.path().join("stale.lock"); + let stale = AdvisoryLockMetadata { + tool: TOOL_NAME.to_owned(), + pid: i32::MAX as u32, + owner_id: "stale-owner".to_owned(), + created_at: chrono::Utc::now(), + }; + fs::write( + &lock_path, + serde_json::to_vec_pretty(&stale).expect("metadata"), + ) + .expect("stale lock"); + + let error = try_acquire_advisory_lock(&lock_path).expect_err("legacy lock remains busy"); + + assert_eq!(error.kind(), ErrorKind::AlreadyExists); + assert!(error.to_string().contains("remove this file manually")); + assert_eq!( + read_advisory_lock_metadata(&lock_path) + .expect("stale metadata") + .owner_id, + "stale-owner" + ); + } + + #[test] + fn blocking_acquisition_fails_fast_for_legacy_owner_lock() { + let dir = tempdir().expect("tempdir"); + let lock_path = dir.path().join("legacy.lock"); + fs::write(&lock_path, b"legacy owner").expect("legacy lock"); + let started = std::time::Instant::now(); + + let error = acquire_advisory_lock(&lock_path).expect_err("legacy lock must fail fast"); + + assert_eq!(error.kind(), ErrorKind::AlreadyExists); + assert!(started.elapsed() < Duration::from_secs(1)); + assert!(error.to_string().contains("remove this file manually")); + } + #[test] fn advisory_lock_serializes_blocking_waiters() { let dir = tempdir().expect("tempdir"); @@ -727,16 +879,143 @@ mod tests { } #[test] - fn stale_corrupt_lock_file_can_be_recovered() { + fn publish_file_atomically_reports_when_publish_and_rollback_both_fail() { + let dir = tempdir().expect("tempdir"); + let temp = dir.path().join("temp.json"); + let destination = dir.path().join("dest.json"); + fs::write(&temp, "new").expect("temp"); + fs::write(&destination, "old").expect("dest"); + + let calls = AtomicUsize::new(0); + let rename = |from: &Path, to: &Path| { + let count = calls.fetch_add(1, Ordering::SeqCst); + if count > 0 { + return Err(std::io::Error::new( + ErrorKind::PermissionDenied, + if count == 1 { + "simulated publish failure" + } else { + "simulated rollback failure" + }, + )); + } + fs::rename(from, to) + }; + + let error = publish_file_atomically_impl(&temp, &destination, &rename, &|path| { + remove_path_if_exists(path) + }) + .expect_err("publish and rollback must fail"); + + let message = error.to_string(); + assert!(message.contains("simulated publish failure")); + assert!(message.contains("rollback failed")); + assert!(message.contains("simulated rollback failure")); + assert!(!destination.exists(), "target needs manual inspection"); + } + + #[test] + fn replace_file_rollback_failure_is_typed_as_uncertain() { + let error = replace_file_rollback_error( + std::io::Error::new(ErrorKind::PermissionDenied, "publish failed"), + Err(std::io::Error::new( + ErrorKind::PermissionDenied, + "rollback failed", + )), + "failed to publish staged artifact file", + ReplaceFileFailureState::Restored, + ); + + assert_eq!(error.target_state, ReplaceFileFailureState::Uncertain); + assert!(error.to_string().contains("rollback failed")); + } + + #[test] + fn successful_replace_file_rollback_is_typed_as_restored() { + let error = replace_file_rollback_error( + std::io::Error::new(ErrorKind::PermissionDenied, "publish failed"), + Ok(()), + "failed to publish staged artifact file", + ReplaceFileFailureState::Restored, + ); + + assert_eq!(error.target_state, ReplaceFileFailureState::Restored); + assert!(!error.to_string().contains("rollback failed")); + } + + #[test] + fn replace_file_restores_original_bytes_when_stage_disappeared() { + let dir = tempdir().expect("tempdir"); + let target = dir.path().join("target.cf"); + let missing_stage = dir.path().join("missing-stage.cf"); + fs::write(&target, "original").expect("target"); + + let error = replace_file_atomically(&missing_stage, &target, "run-1", "identity") + .expect_err("publish must fail"); + + assert_eq!(error.target_state, ReplaceFileFailureState::Restored); + assert_eq!( + fs::read_to_string(&target).expect("restored target"), + "original" + ); + } + + #[test] + fn replace_file_reports_uncertain_and_retains_backup_when_rollback_fails() { + struct HookReset; + impl Drop for HookReset { + fn drop(&mut self) { + REPLACE_FILE_TEST_HOOK.with(|hook| *hook.borrow_mut() = None); + } + } + + let dir = tempdir().expect("tempdir"); + let target = dir.path().join("target.cf"); + let stage = dir.path().join("stage.cf"); + let backup = dir.path().join(".target.cf.backup-run-1"); + fs::write(&target, "original").expect("target"); + fs::write(&stage, "replacement").expect("stage"); + REPLACE_FILE_TEST_HOOK.with(|hook| { + *hook.borrow_mut() = Some(Box::new(|point| { + Err(std::io::Error::new( + ErrorKind::PermissionDenied, + match point { + ReplaceFileTestPoint::PublishStage => "injected publish failure", + ReplaceFileTestPoint::RestoreBackup => "injected rollback failure", + }, + )) + })); + }); + let _reset = HookReset; + + let error = replace_file_atomically(&stage, &target, "run-1", "identity") + .expect_err("publish and rollback must fail"); + + assert_eq!(error.target_state, ReplaceFileFailureState::Uncertain); + assert!(!target.exists()); + assert_eq!( + fs::read_to_string(&backup).expect("retained backup"), + "original" + ); + assert_eq!( + fs::read_to_string(&stage).expect("retained stage"), + "replacement" + ); + assert!(error.to_string().contains("rollback failed")); + } + + #[test] + fn fresh_corrupt_lock_file_cannot_be_stolen() { let dir = tempdir().expect("tempdir"); let lock_path = dir.path().join("corrupt.lock"); let original = b"{not valid json".to_vec(); fs::write(&lock_path, &original).expect("lock"); - let guard = try_acquire_advisory_lock(&lock_path).expect("recovered lock"); + let error = + try_acquire_advisory_lock(&lock_path).expect_err("fresh malformed lock is busy"); - assert_eq!(advisory_lock_owner_id(&guard).len(), 36); - assert_ne!(fs::read(&lock_path).expect("lock"), original); + assert_eq!(error.kind(), ErrorKind::AlreadyExists); + assert_eq!(fs::read(&lock_path).expect("lock"), original); } #[test] @@ -757,7 +1036,7 @@ mod tests { let error = try_acquire_advisory_lock(&lock_path).expect_err("busy lock"); - assert_eq!(error.kind(), ErrorKind::WouldBlock); + assert_eq!(error.kind(), ErrorKind::AlreadyExists); assert_eq!( read_advisory_lock_metadata(&lock_path) .expect("metadata") @@ -767,7 +1046,7 @@ mod tests { } #[test] - fn concurrent_acquisition_cannot_steal_lock_during_initial_publish() { + fn concurrent_acquisition_cannot_enter_during_metadata_write() { let dir = tempdir().expect("tempdir"); let lock_path = dir.path().join("publish.lock"); let (hook_ready_tx, hook_ready_rx) = mpsc::channel(); @@ -779,22 +1058,57 @@ mod tests { hook_ready_tx.send(()).expect("signal hook"); release_rx.recv().expect("release hook"); }; - try_acquire_advisory_lock_with_hook(&lock_path_clone, hook).expect("first lock"); + try_acquire_advisory_lock_with_hook(&lock_path_clone, hook) }); hook_ready_rx.recv().expect("hook reached"); - let contender = thread::spawn({ - let lock_path = lock_path.clone(); - move || try_acquire_advisory_lock(&lock_path) + let contender = try_acquire_advisory_lock(&lock_path).expect_err("lock remains held"); + assert_eq!(contender.kind(), ErrorKind::WouldBlock); + release_tx.send(()).expect("release hook"); + + let first_guard = handle.join().expect("join first").expect("first lock"); + let published = read_advisory_lock_metadata(&lock_path).expect("complete metadata"); + assert_eq!(published.owner_id, advisory_lock_owner_id(&first_guard)); + } + + #[test] + fn legacy_writer_can_win_without_being_overwritten_by_new_protocol() { + let dir = tempdir().expect("tempdir"); + let lock_path = dir.path().join("legacy-race.lock"); + let (hook_ready_tx, hook_ready_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let lock_path_clone = lock_path.clone(); + + let handle = thread::spawn(move || { + let hook = move || { + hook_ready_tx.send(()).expect("signal hook"); + release_rx.recv().expect("release hook"); + }; + try_acquire_advisory_lock_with_hook(&lock_path_clone, hook) }); - thread::sleep(Duration::from_millis(100)); + hook_ready_rx.recv().expect("hook reached"); + let legacy = AdvisoryLockMetadata { + tool: TOOL_NAME.to_owned(), + pid: std::process::id(), + owner_id: "legacy-owner".to_owned(), + created_at: chrono::Utc::now(), + }; + fs::write( + &lock_path, + serde_json::to_vec_pretty(&legacy).expect("legacy metadata"), + ) + .expect("legacy lock"); release_tx.send(()).expect("release hook"); - handle.join().expect("join first"); - - let second_result = contender.join().expect("join second"); - assert!(matches!(second_result, Err(error) if error.kind() == ErrorKind::WouldBlock)); + let result = handle.join().expect("join new protocol"); + assert!(matches!(result, Err(error) if error.kind() == ErrorKind::AlreadyExists)); + assert_eq!( + read_advisory_lock_metadata(&lock_path) + .expect("legacy metadata") + .owner_id, + "legacy-owner" + ); } #[test] @@ -856,10 +1170,4 @@ mod tests { "payload" ); } - - #[cfg(windows)] - #[test] - fn windows_reports_missing_process_as_not_live() { - assert!(!super::lock_holder_is_live(u32::MAX)); - } } diff --git a/src/support/logging.rs b/src/support/logging.rs index 18e382c26..346e0f0cc 100644 --- a/src/support/logging.rs +++ b/src/support/logging.rs @@ -30,11 +30,44 @@ pub fn init_action_logging( color_enabled: bool, work_path: &Path, ) -> Result, LoggingInitError> { + init_action_logging_impl(level, output_format, color_enabled, work_path, false) +} + +pub fn init_action_logging_deferred( + level: &str, + output_format: &str, + color_enabled: bool, + work_path: &Path, +) -> Result, LoggingInitError> { + init_action_logging_impl(level, output_format, color_enabled, work_path, true) +} + +fn init_action_logging_impl( + level: &str, + output_format: &str, + color_enabled: bool, + work_path: &Path, + defer_file_open: bool, +) -> Result, LoggingInitError> { + let log_path = resolve_action_log_path(output_format, work_path); let writer = ActionLogMakeWriter { stdout_enabled: output_format == "text", - file: open_log_file(resolve_action_log_path(output_format, work_path).as_deref())?, + file: if defer_file_open { + None + } else { + open_log_file(log_path.as_deref())? + }, + deferred_file: if defer_file_open { + log_path.as_ref().map(|path| { + Arc::new(DeferredActionLog { + path: path.clone(), + file: Mutex::new(None), + }) + }) + } else { + None + }, }; - let log_path = resolve_action_log_path(output_format, work_path); let ansi_enabled = output_format == "text" && color_enabled; let env_filter = env_filter_with_live_progress(level); @@ -113,11 +146,18 @@ fn open_log_file(path: Option<&Path>) -> Result>>, Loggin struct ActionLogMakeWriter { stdout_enabled: bool, file: Option>>, + deferred_file: Option>, } struct ActionLogWriter { stdout_enabled: bool, file: Option>>, + deferred_file: Option>, +} + +struct DeferredActionLog { + path: PathBuf, + file: Mutex>, } struct UtcTimer; @@ -152,6 +192,7 @@ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for ActionLogMakeWriter { ActionLogWriter { stdout_enabled: self.stdout_enabled, file: self.file.clone(), + deferred_file: self.deferred_file.clone(), } } } @@ -490,6 +531,9 @@ impl IoWrite for ActionLogWriter { file.write_all(buf)?; file.flush()?; } + if let Some(deferred) = &self.deferred_file { + deferred.write_all(buf)?; + } Ok(buf.len()) } @@ -505,11 +549,53 @@ impl IoWrite for ActionLogWriter { .map_err(|_| io::Error::other("action log mutex poisoned"))?; file.flush()?; } + if let Some(deferred) = &self.deferred_file { + deferred.flush()?; + } Ok(()) } } +impl DeferredActionLog { + fn with_file(&self, operation: impl FnOnce(&mut File) -> io::Result) -> io::Result { + let mut file = self + .file + .lock() + .map_err(|_| io::Error::other("deferred action log mutex poisoned"))?; + if file.is_none() { + if let Some(parent) = self.path.parent() { + std::fs::create_dir_all(parent)?; + } + *file = Some( + OpenOptions::new() + .create(true) + .append(true) + .open(&self.path)?, + ); + } + operation(file.as_mut().expect("deferred action log was opened")) + } + + fn write_all(&self, buf: &[u8]) -> io::Result<()> { + self.with_file(|file| { + file.write_all(buf)?; + file.flush() + }) + } + + fn flush(&self) -> io::Result<()> { + let mut file = self + .file + .lock() + .map_err(|_| io::Error::other("deferred action log mutex poisoned"))?; + match file.as_mut() { + Some(file) => file.flush(), + None => Ok(()), + } + } +} + #[cfg(test)] mod tests { use std::io; diff --git a/src/support/path.rs b/src/support/path.rs index 7467b5db2..4ada84248 100644 --- a/src/support/path.rs +++ b/src/support/path.rs @@ -2,6 +2,91 @@ use std::path::{Component, Path, PathBuf}; use sha2::{Digest, Sha256}; +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FilesystemObjectIdentity { + #[cfg(unix)] + Unix { device: u64, inode: u64 }, + #[cfg(windows)] + Windows { volume_serial: u32, file_index: u64 }, + #[cfg(not(any(unix, windows)))] + Portable { + canonical_path: PathBuf, + created: Option, + }, +} + +pub fn filesystem_object_identity(path: &Path) -> std::io::Result { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let metadata = std::fs::metadata(path)?; + Ok(FilesystemObjectIdentity::Unix { + device: metadata.dev(), + inode: metadata.ino(), + }) + } + #[cfg(windows)] + { + windows_filesystem_object_identity(path) + } + #[cfg(not(any(unix, windows)))] + { + let metadata = std::fs::metadata(path)?; + Ok(FilesystemObjectIdentity::Portable { + canonical_path: std::fs::canonicalize(path)?, + created: metadata.created().ok(), + }) + } +} + +#[cfg(windows)] +fn windows_filesystem_object_identity(path: &Path) -> std::io::Result { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, + FILE_FLAG_BACKUP_SEMANTICS, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, + FILE_SHARE_WRITE, OPEN_EXISTING, + }; + + let wide_path = path + .as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect::>(); + let handle = unsafe { + CreateFileW( + wide_path.as_ptr(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + std::ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return Err(std::io::Error::last_os_error()); + } + let mut information = BY_HANDLE_FILE_INFORMATION::default(); + let success = unsafe { GetFileInformationByHandle(handle, &mut information) }; + let query_error = if success == 0 { + Some(std::io::Error::last_os_error()) + } else { + None + }; + unsafe { + CloseHandle(handle); + } + if let Some(error) = query_error { + return Err(error); + } + Ok(FilesystemObjectIdentity::Windows { + volume_serial: information.dwVolumeSerialNumber, + file_index: ((information.nFileIndexHigh as u64) << 32) | information.nFileIndexLow as u64, + }) +} + /// Returns true when `value` can be safely used as a single file/path segment. pub fn is_safe_path_segment(value: &str) -> bool { if value.is_empty() { @@ -72,7 +157,14 @@ pub fn nearest_existing_canonical_path(path: &Path) -> std::io::Result pub fn stable_path_identity(path: &Path) -> String { let mut hasher = Sha256::new(); - hasher.update(path.to_string_lossy().as_bytes()); + let path = path.to_string_lossy(); + #[cfg(any(windows, target_os = "macos"))] + let path = { + use unicode_casefold::UnicodeCaseFold; + use unicode_normalization::UnicodeNormalization; + path.nfd().case_fold().nfd().collect::() + }; + hasher.update(path.as_bytes()); let digest = hasher.finalize(); digest[..16] .iter() @@ -113,7 +205,7 @@ pub fn normalize_windows_verbatim_path(path: &Path) -> PathBuf { #[cfg(test)] mod tests { use super::{ - hashed_lock_path, is_filesystem_root, is_safe_path_segment, + filesystem_object_identity, hashed_lock_path, is_filesystem_root, is_safe_path_segment, nearest_existing_canonical_path, normalize_windows_verbatim_path, stable_path_identity, strip_windows_verbatim_prefix, }; @@ -167,6 +259,20 @@ mod tests { .is_some_and(|name| name.starts_with(".dump-") && name.ends_with(".lock"))); } + #[test] + fn filesystem_object_identity_changes_when_directory_is_replaced() { + let dir = tempdir().expect("tempdir"); + let observed = dir.path().join("observed"); + fs::create_dir(&observed).expect("observed"); + let before = filesystem_object_identity(&observed).expect("before"); + + fs::rename(&observed, dir.path().join("original")).expect("move original"); + fs::create_dir(&observed).expect("replace observed"); + let after = filesystem_object_identity(&observed).expect("after"); + + assert_ne!(before, after); + } + #[test] fn filesystem_root_detection_matches_non_root_paths() { let dir = tempdir().expect("tempdir"); diff --git a/src/use_cases/artifacts.rs b/src/use_cases/artifacts.rs index e4d7649bf..80b71e415 100644 --- a/src/use_cases/artifacts.rs +++ b/src/use_cases/artifacts.rs @@ -1,7 +1,5 @@ use std::path::{Path, PathBuf}; -use std::time::{Duration, Instant}; - -use chrono::Utc; +use std::time::Instant; use tracing::debug; use crate::config::model::{ @@ -20,10 +18,7 @@ use crate::platform::process::ProcessRunner; use crate::platform::result::PlatformCommandResult; use crate::platform::utilities::PlatformUtilities; use crate::support::error::AppError; -use crate::support::fs::{ - acquire_advisory_lock, is_known_tool_name, metadata_sidecar_path, read_temp_dir_metadata, - remove_path_if_exists, write_temp_dir_metadata, TempDirKind, TempDirMetadata, -}; +use crate::support::fs::{acquire_advisory_lock, write_temp_dir_metadata, TempDirKind}; use crate::support::path::{ hashed_lock_path, is_filesystem_root, nearest_existing_canonical_path, stable_path_identity, }; @@ -45,11 +40,12 @@ use crate::use_cases::request::{ArtifactsModeRequest, ArtifactsRequest}; use crate::use_cases::result::{UseCaseFailure, UseCaseResult}; use crate::use_cases::source_inventory::SourceSetInventory; -use super::staged_publication::{interruption_before_publish, StagedPublication}; +use super::staged_publication::{ + cleanup_owned_orphan_files, interruption_before_publish, StagedPublication, +}; const SUPPORTED_ARTIFACTS_ERROR: &str = "artifacts currently supports only builder=DESIGNER with designer backend profile"; -const ORPHAN_TTL: Duration = Duration::from_secs(24 * 60 * 60); const ARTIFACTS_BACKUP_PREFIX: &str = ".artifacts-backup"; pub fn execute( @@ -921,90 +917,16 @@ fn cleanup_orphan_files(resolved: &ResolvedArtifactsTarget) -> Result<(), AppErr if resolved.is_directory_output { scan_roots.push(resolved.output_path.clone()); } - scan_roots.sort(); - scan_roots.dedup(); - - for root in scan_roots { - if !root.exists() { - continue; - } - for entry in std::fs::read_dir(&root) - .map_err(|error| AppError::Runtime(format!("failed to read output dir: {error}")))? - { - let entry = entry - .map_err(|error| AppError::Runtime(format!("failed to read dir entry: {error}")))?; - let path = entry.path(); - let (temp_path, metadata_path) = orphan_cleanup_paths(&path); - let Some(file_name) = path.file_name().and_then(|value| value.to_str()) else { - continue; - }; - if !file_name.starts_with(".artifacts-stage-") - && !file_name.starts_with(ARTIFACTS_BACKUP_PREFIX) - && !file_name.contains(".backup-") - { - continue; - } - let Ok(metadata) = read_orphan_metadata(&temp_path, &metadata_path) else { - continue; - }; - if !is_known_tool_name(&metadata.tool) - || metadata.target_identity != resolved.target_identity - { - continue; - } - if (Utc::now() - metadata.created_at) - .to_std() - .unwrap_or_default() - < ORPHAN_TTL - { - continue; - } - - remove_path_if_exists(&temp_path).map_err(|error| { - AppError::Runtime(format!( - "failed to remove stale artifact temp '{}': {error}", - temp_path.display() - )) - })?; - remove_path_if_exists(&metadata_path).map_err(|error| { - AppError::Runtime(format!( - "failed to remove stale artifact metadata '{}': {error}", - metadata_path.display() - )) - })?; - } - } - Ok(()) -} - -fn orphan_cleanup_paths(path: &Path) -> (PathBuf, PathBuf) { - let Some(file_name) = path.file_name().and_then(|value| value.to_str()) else { - return (path.to_path_buf(), metadata_sidecar_path(path)); - }; - let Some(temp_name) = file_name.strip_suffix(".meta.json") else { - return (path.to_path_buf(), metadata_sidecar_path(path)); - }; - ( - path.parent() - .unwrap_or_else(|| Path::new(".")) - .join(temp_name), - path.to_path_buf(), + cleanup_owned_orphan_files( + &scan_roots, + &resolved.output_path, + &resolved.target_identity, + &[".artifacts-stage-"], + &[ARTIFACTS_BACKUP_PREFIX], + resolved.is_directory_output, ) } -fn read_orphan_metadata( - temp_path: &Path, - metadata_path: &Path, -) -> std::io::Result { - if metadata_path == metadata_sidecar_path(temp_path) { - return read_temp_dir_metadata(temp_path); - } - - let raw = std::fs::read(metadata_path)?; - serde_json::from_slice(&raw) - .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error)) -} - fn build_designer_dsl<'a>( context: &ExecutionContext, config: &AppConfig, @@ -1813,7 +1735,7 @@ mod tests { let dir = tempdir().expect("tempdir"); let output = dir.path().join("dist/external"); fs::create_dir_all(&output).expect("output"); - let stale = output.join(".artifacts-stage-old.epf"); + let stale = output.join(".artifacts-stage-run-1.epf"); fs::create_dir_all(&stale).expect("stale"); write_temp_dir_metadata( &stale, @@ -1857,7 +1779,7 @@ mod tests { let stage_dir = output .parent() .expect("parent") - .join(".artifacts-stage-old"); + .join(".artifacts-stage-run-1"); fs::create_dir_all(&stage_dir).expect("stage"); write_temp_dir_metadata(&stage_dir, TempDirKind::Stage, "run-1", &output, "identity") .expect("metadata"); @@ -1897,7 +1819,7 @@ mod tests { let stage_file = output .parent() .expect("parent") - .join(".artifacts-stage-orphan.cf"); + .join(".artifacts-stage-run-1.cf"); write_temp_dir_metadata( &stage_file, TempDirKind::Stage, @@ -1942,7 +1864,7 @@ mod tests { let backup_dir = output .parent() .expect("parent") - .join(".artifacts-backup-old"); + .join(".artifacts-backup-run-1"); fs::create_dir_all(&backup_dir).expect("backup"); write_temp_dir_metadata( &backup_dir, @@ -1988,7 +1910,7 @@ mod tests { let recent = output .parent() .expect("parent") - .join(".artifacts-stage-recent"); + .join(".artifacts-stage-run-1"); fs::create_dir_all(&recent).expect("stage"); write_temp_dir_metadata(&recent, TempDirKind::Stage, "run-1", &output, "identity") .expect("metadata"); @@ -2020,7 +1942,7 @@ mod tests { let foreign = output .parent() .expect("parent") - .join(".artifacts-backup-foreign"); + .join(".artifacts-backup-run-1"); fs::create_dir_all(&foreign).expect("backup"); write_temp_dir_metadata(&foreign, TempDirKind::Backup, "run-1", &output, "identity") .expect("metadata"); diff --git a/src/use_cases/context.rs b/src/use_cases/context.rs index c274aa80d..ad5404576 100644 --- a/src/use_cases/context.rs +++ b/src/use_cases/context.rs @@ -15,6 +15,8 @@ pub enum CommandName { Load, Test, Dump, + InfobaseConfigurationExport, + InfobaseDump, Convert, Artifacts, Syntax, @@ -33,6 +35,8 @@ impl CommandName { Self::Load => "load", Self::Test => "test", Self::Dump => "dump", + Self::InfobaseConfigurationExport => "infobase.configuration.export", + Self::InfobaseDump => "infobase.dump", Self::Convert => "convert", Self::Artifacts => "make", Self::Syntax => "syntax", diff --git a/src/use_cases/convert_sources.rs b/src/use_cases/convert_sources.rs index d22d34c37..60fc8a79e 100644 --- a/src/use_cases/convert_sources.rs +++ b/src/use_cases/convert_sources.rs @@ -936,36 +936,7 @@ fn discover_edt_external_projects( child.display(), source_set_name )), - AppError::ValidationIbcmd(error) => AppError::ValidationIbcmd(error), - AppError::ValidationIbcmdContext { context, source } => { - AppError::ValidationIbcmdContext { context, source } - } - AppError::Runtime(message) => AppError::Runtime(message), - AppError::Platform(message) => AppError::Platform(message), - AppError::PlatformDesigner(error) => AppError::PlatformDesigner(error), - AppError::PlatformDesignerContext { context, source } => { - AppError::PlatformDesignerContext { context, source } - } - AppError::PlatformLocator(error) => AppError::PlatformLocator(error), - AppError::PlatformProcess(error) => AppError::PlatformProcess(error), - AppError::PlatformLocatorContext { context, source } => { - AppError::PlatformLocatorContext { context, source } - } - AppError::PlatformProcessContext { context, source } => { - AppError::PlatformProcessContext { context, source } - } - AppError::PlatformEdt(error) => AppError::PlatformEdt(error), - AppError::PlatformEdtContext { context, source } => { - AppError::PlatformEdtContext { context, source } - } - AppError::PlatformEdtSession(error) => AppError::PlatformEdtSession(error), - AppError::PlatformEdtSessionContext { context, source } => { - AppError::PlatformEdtSessionContext { context, source } - } - AppError::Config(error) => AppError::Config(error), - AppError::ConfigContext { context, source } => { - AppError::ConfigContext { context, source } - } + other => other, })?; if descriptor.artifact_type != expected_kind { return Err(AppError::Validation(format!( diff --git a/src/use_cases/dump_config.rs b/src/use_cases/dump_config.rs index b80a7210f..783b25ab7 100644 --- a/src/use_cases/dump_config.rs +++ b/src/use_cases/dump_config.rs @@ -183,8 +183,9 @@ fn run_full_dump_designer( return Err(publication.cleanup_failure(error)); } - let publish_phase = - publication.publish_dir(context, DUMP_BACKUP_PREFIX, "failed to publish staged dump")?; + let publish_phase = publication + .publish_dir(context, DUMP_BACKUP_PREFIX, "failed to publish staged dump") + .map_err(|error| publication.cleanup_failure(error))?; debug!(target = %resolved.platform_target_path.display(), "published staged dump"); Ok(( @@ -258,8 +259,9 @@ fn run_full_dump_ibcmd( return Err(publication.cleanup_failure(error)); } - let publish_phase = - publication.publish_dir(context, DUMP_BACKUP_PREFIX, "failed to publish staged dump")?; + let publish_phase = publication + .publish_dir(context, DUMP_BACKUP_PREFIX, "failed to publish staged dump") + .map_err(|error| publication.cleanup_failure(error))?; debug!(target = %resolved.platform_target_path.display(), "published staged dump"); Ok(( @@ -599,8 +601,9 @@ fn finalize_edt_dump( return Err(publication.cleanup_failure(error)); } - let publish_phase = - publication.publish_dir(context, DUMP_BACKUP_PREFIX, "failed to publish staged dump")?; + let publish_phase = publication + .publish_dir(context, DUMP_BACKUP_PREFIX, "failed to publish staged dump") + .map_err(|error| publication.cleanup_failure(error))?; Ok(( platform_result, diff --git a/src/use_cases/infobase_export.rs b/src/use_cases/infobase_export.rs new file mode 100644 index 000000000..bd2b0cf1e --- /dev/null +++ b/src/use_cases/infobase_export.rs @@ -0,0 +1,1532 @@ +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; +use std::thread; +use std::time::{Duration, Instant}; + +use crate::config::model::{AppConfig, BuilderBackend}; +use crate::domain::execution::{ExecutionError, ExecutionOutcome, ExecutionStatus, StepResult}; +use crate::domain::infobase_export::{ + ConfigurationState, ConfigurationSubject, ExportConfigurationPackageRequest, + ExportConfigurationPackageResult, ExportInfobaseSnapshotRequest, ExportInfobaseSnapshotResult, + ExportPhase, ExportProvider, ExportProviderDecision, ExportTargetState, ProviderCandidate, + ProviderEvidence, ProviderImplementation, ProviderReadiness, +}; +use crate::platform::designer::DesignerDsl; +use crate::platform::ibcmd::{IbcmdConnection, IbcmdDsl}; +use crate::platform::locator::UtilityType; +use crate::platform::process::{ProcessError, ProcessInterruptionReason}; +use crate::platform::result::PlatformCommandResult; +use crate::platform::utilities::PlatformUtilities; +use crate::support::error::AppError; +use crate::support::fs::try_acquire_advisory_lock; +use crate::support::path::{ + filesystem_object_identity, hashed_lock_path, nearest_existing_canonical_path, + stable_path_identity, FilesystemObjectIdentity, +}; +use crate::support::temp::platform_logs_dir; +use crate::use_cases::context::{ExecutionContext, InterruptionSafetyClass}; +use crate::use_cases::result::{UseCaseError, UseCaseErrorKind}; +use crate::use_cases::result::{UseCaseFailure, UseCaseResult}; + +use super::interruption::{ + command_interruption_details, deferred_command_interruption_details, + deferred_process_interruption_details, deferred_process_interruption_warning, + process_interruption_details, +}; +use super::staged_publication::{ + cleanup_owned_orphan_files, interruption_before_publish, PublicationFailureState, + StagedPublication, +}; + +const CONFIGURATION_COMMAND: &str = "infobase.configuration.export"; +const SNAPSHOT_COMMAND: &str = "infobase.dump"; + +#[derive(Debug, Clone)] +pub struct PreparedExportProvider { + selection: ExportProviderDecision, + provider: ExportProvider, + executable: PathBuf, +} + +impl PreparedExportProvider { + pub fn selection(&self) -> &ExportProviderDecision { + &self.selection + } +} + +#[allow(clippy::result_large_err)] // Failure payload preserves the typed AI-facing result. +pub fn execute_configuration_export( + context: &ExecutionContext, + config: &AppConfig, + request: &ExportConfigurationPackageRequest, + prepared: &PreparedExportProvider, +) -> UseCaseResult { + let mut result = + ExportConfigurationPackageResult::new(request.clone(), prepared.selection.clone()); + if let Err(error) = validate_configuration_request(request) { + return Err(configuration_failure( + context, + error, + result, + ExportPhase::Validation, + )); + } + let provider = prepared.provider; + + let output = resolve_output(config, &request.output).map_err(|error| { + configuration_failure(context, error, result.clone(), ExportPhase::ResolveTarget) + })?; + result.output = output.target.clone(); + let _target_lock = acquire_target_lock(context, &output.lock_path, CONFIGURATION_COMMAND) + .map_err(|error| { + configuration_failure(context, error, result.clone(), ExportPhase::TargetLock) + })?; + let output_observation = observe_locked_output(&output).map_err(|error| { + configuration_failure(context, error, result.clone(), ExportPhase::ResolveTarget) + })?; + cleanup_export_orphans(&output, &[".infobase-config-stage-"]).map_err(|error| { + configuration_failure(context, error, result.clone(), ExportPhase::OrphanCleanup) + })?; + let publication = StagedPublication::prepare_file( + &output.target, + &output.identity, + ".infobase-config-stage", + request.subject.artifact_kind().file_extension(), + ) + .map_err(|error| { + configuration_failure(context, error, result.clone(), ExportPhase::PrepareStaging) + })?; + + let provider_started = Instant::now(); + let platform_result = match run_configuration_provider( + context, + config, + provider, + &prepared.executable, + request.state, + &request.subject, + publication.staging_path(), + ) { + Ok(platform_result) => platform_result, + Err(error) => { + return Err(configuration_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::ProviderCommand, + )) + } + }; + if let Err(error) = validate_platform_success(&platform_result) { + return Err(configuration_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::ProviderCommand, + )); + } + result.steps.push( + StepResult::succeeded( + ExportPhase::ProviderCommand.as_str(), + ExportPhase::ProviderCommand.kind(), + provider_started.elapsed().as_millis() as u64, + ) + .with_target(publication.staging_path().display().to_string()), + ); + if let Err(error) = validate_platform_artifact(publication.staging_path()) { + return Err(configuration_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::ValidateProviderOutput, + )); + } + record_deferred_process_interruption( + &platform_result, + "provider command", + "configuration export", + &mut result.execution, + &mut result.warnings, + ); + if let Some(error) = interruption_before_publish(context, "configuration package publication") { + return Err(configuration_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::BeforePublication, + )); + } + revalidate_before_publish(&output, &output_observation, &publication).map_err(|error| { + configuration_failure( + context, + error, + result.clone(), + ExportPhase::PublishTargetRevalidation, + ) + })?; + let publication_started = Instant::now(); + let publication_outcome = publication + .publish_file_with_state(context, "failed to publish configuration package") + .map_err(|mut failure| { + failure.error = publication.cleanup_failure(failure.error); + result.target_state = export_failure_state(failure.target_state); + record_uncertain_target_warning(&mut result.warnings, result.target_state); + configuration_failure( + context, + failure.error, + result.clone(), + ExportPhase::Publication, + ) + })?; + result.steps.push( + StepResult::succeeded( + ExportPhase::Publication.as_str(), + ExportPhase::Publication.kind(), + publication_started.elapsed().as_millis() as u64, + ) + .with_target(result.output.display().to_string()), + ); + result.published = true; + result.target_state = if publication_outcome.previous_target_present { + ExportTargetState::Replaced + } else { + ExportTargetState::Created + }; + result.mark_succeeded(); + if let Some(warning) = publication_outcome.cleanup_warning { + result.warnings.push(warning); + } + if let Some(interruption) = publication_outcome.deferred_interruption { + let message = "interruption was deferred until configuration publication completed"; + result.warnings.push(message.to_owned()); + result + .execution + .interruptions + .push(deferred_command_interruption_details( + interruption, + "publication", + message, + )); + } + Ok(result) +} + +#[allow(clippy::result_large_err)] // Failure payload preserves the typed AI-facing result. +pub fn execute_infobase_snapshot( + context: &ExecutionContext, + config: &AppConfig, + request: &ExportInfobaseSnapshotRequest, + prepared: &PreparedExportProvider, +) -> UseCaseResult { + let mut result = ExportInfobaseSnapshotResult::new(request.clone(), prepared.selection.clone()); + if let Err(error) = validate_snapshot_output(&request.output) { + return Err(snapshot_failure( + context, + error, + result, + ExportPhase::Validation, + )); + } + let provider = prepared.provider; + + let output = resolve_output(config, &request.output).map_err(|error| { + snapshot_failure(context, error, result.clone(), ExportPhase::ResolveTarget) + })?; + result.output = output.target.clone(); + let _target_lock = + acquire_target_lock(context, &output.lock_path, SNAPSHOT_COMMAND).map_err(|error| { + snapshot_failure(context, error, result.clone(), ExportPhase::TargetLock) + })?; + let output_observation = observe_locked_output(&output).map_err(|error| { + snapshot_failure(context, error, result.clone(), ExportPhase::ResolveTarget) + })?; + cleanup_export_orphans(&output, &[".infobase-dt-stage-"]).map_err(|error| { + snapshot_failure(context, error, result.clone(), ExportPhase::OrphanCleanup) + })?; + let publication = StagedPublication::prepare_file( + &output.target, + &output.identity, + ".infobase-dt-stage", + "dt", + ) + .map_err(|error| { + snapshot_failure(context, error, result.clone(), ExportPhase::PrepareStaging) + })?; + + let provider_started = Instant::now(); + let platform_result = match run_snapshot_provider( + context, + config, + provider, + &prepared.executable, + publication.staging_path(), + ) { + Ok(platform_result) => platform_result, + Err(error) => { + return Err(snapshot_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::ProviderCommand, + )) + } + }; + if let Err(error) = validate_platform_success(&platform_result) { + return Err(snapshot_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::ProviderCommand, + )); + } + result.steps.push( + StepResult::succeeded( + ExportPhase::ProviderCommand.as_str(), + ExportPhase::ProviderCommand.kind(), + provider_started.elapsed().as_millis() as u64, + ) + .with_target(publication.staging_path().display().to_string()), + ); + if let Err(error) = validate_platform_artifact(publication.staging_path()) { + return Err(snapshot_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::ValidateProviderOutput, + )); + } + record_deferred_process_interruption( + &platform_result, + "provider command", + "infobase DT export", + &mut result.execution, + &mut result.warnings, + ); + if let Some(error) = interruption_before_publish(context, "infobase DT publication") { + return Err(snapshot_failure( + context, + publication.cleanup_failure(error), + result, + ExportPhase::BeforePublication, + )); + } + revalidate_before_publish(&output, &output_observation, &publication).map_err(|error| { + snapshot_failure( + context, + error, + result.clone(), + ExportPhase::PublishTargetRevalidation, + ) + })?; + let publication_started = Instant::now(); + let publication_outcome = publication + .publish_file_with_state(context, "failed to publish infobase DT") + .map_err(|mut failure| { + failure.error = publication.cleanup_failure(failure.error); + result.target_state = export_failure_state(failure.target_state); + record_uncertain_target_warning(&mut result.warnings, result.target_state); + snapshot_failure( + context, + failure.error, + result.clone(), + ExportPhase::Publication, + ) + })?; + result.steps.push( + StepResult::succeeded( + ExportPhase::Publication.as_str(), + ExportPhase::Publication.kind(), + publication_started.elapsed().as_millis() as u64, + ) + .with_target(result.output.display().to_string()), + ); + result.published = true; + result.target_state = if publication_outcome.previous_target_present { + ExportTargetState::Replaced + } else { + ExportTargetState::Created + }; + result.mark_succeeded(); + if let Some(warning) = publication_outcome.cleanup_warning { + result.warnings.push(warning); + } + if let Some(interruption) = publication_outcome.deferred_interruption { + let message = "interruption was deferred until DT publication completed"; + result.warnings.push(message.to_owned()); + result + .execution + .interruptions + .push(deferred_command_interruption_details( + interruption, + "publication", + message, + )); + } + Ok(result) +} + +pub(crate) fn validate_configuration_output( + subject: &ConfigurationSubject, + output: &Path, +) -> Result<(), AppError> { + validate_output_suffix(output, subject.artifact_kind().file_extension()) +} + +pub(crate) fn validate_snapshot_output(output: &Path) -> Result<(), AppError> { + validate_output_suffix(output, "dt") +} + +pub(crate) fn validate_configuration_request( + request: &ExportConfigurationPackageRequest, +) -> Result<(), AppError> { + if let ConfigurationSubject::Extension { name } = &request.subject { + if !valid_platform_identifier(name) { + return Err(AppError::Validation( + "--extension must be a non-empty 1C identifier".to_owned(), + )); + } + } + validate_configuration_output(&request.subject, &request.output) +} + +fn validate_output_suffix(output: &Path, expected: &str) -> Result<(), AppError> { + let actual = output.extension().and_then(|value| value.to_str()); + if actual.is_some_and(|value| value.eq_ignore_ascii_case(expected)) { + return Ok(()); + } + Err(AppError::Validation(format!( + "output '{}' must have .{expected} suffix", + output.display() + ))) +} + +fn export_failure_state(state: PublicationFailureState) -> ExportTargetState { + match state { + PublicationFailureState::Unchanged => ExportTargetState::Unchanged, + PublicationFailureState::Restored => ExportTargetState::Restored, + PublicationFailureState::Uncertain => ExportTargetState::Uncertain, + } +} + +fn record_uncertain_target_warning(warnings: &mut Vec, state: ExportTargetState) { + if state == ExportTargetState::Uncertain { + warnings.push( + "publication rollback failed; the output target requires manual inspection".to_owned(), + ); + } +} + +fn valid_platform_identifier(value: &str) -> bool { + let mut chars = value.chars(); + chars + .next() + .is_some_and(|first| first == '_' || first.is_alphabetic()) + && chars.all(|ch| ch == '_' || ch.is_alphanumeric()) +} + +pub fn prepare_configuration_export( + context: &ExecutionContext, + config: &AppConfig, + request: &ExportConfigurationPackageRequest, +) -> Result> { + if let Err(error) = validate_configuration_request(request) { + let decision = ExportProviderDecision::unavailable( + "provider selection was not attempted because the request is invalid", + Vec::new(), + ); + let result = ExportConfigurationPackageResult::new(request.clone(), decision); + return Err(configuration_failure( + context, + error, + result, + ExportPhase::Validation, + )); + } + + match select_provider(context, config, ExportIntent::Configuration) { + Ok(prepared) => Ok(prepared), + Err((error, decision)) => { + let result = ExportConfigurationPackageResult::new(request.clone(), decision); + Err(configuration_failure( + context, + error, + result, + ExportPhase::ProviderSelection, + )) + } + } +} + +pub fn prepare_infobase_snapshot( + context: &ExecutionContext, + config: &AppConfig, + request: &ExportInfobaseSnapshotRequest, +) -> Result> { + if let Err(error) = validate_snapshot_output(&request.output) { + let decision = ExportProviderDecision::unavailable( + "provider selection was not attempted because the request is invalid", + Vec::new(), + ); + let result = ExportInfobaseSnapshotResult::new(request.clone(), decision); + return Err(snapshot_failure( + context, + error, + result, + ExportPhase::Validation, + )); + } + + match select_provider(context, config, ExportIntent::Snapshot) { + Ok(prepared) => Ok(prepared), + Err((error, decision)) => { + let result = ExportInfobaseSnapshotResult::new(request.clone(), decision); + Err(snapshot_failure( + context, + error, + result, + ExportPhase::ProviderSelection, + )) + } + } +} + +#[derive(Debug, Clone, Copy)] +enum ExportIntent { + Configuration, + Snapshot, +} + +fn select_provider( + context: &ExecutionContext, + config: &AppConfig, + intent: ExportIntent, +) -> Result { + let providers = match config.builder { + BuilderBackend::Designer => [ExportProvider::DesignerBatch, ExportProvider::IbcmdProcess], + BuilderBackend::Ibcmd => [ExportProvider::IbcmdProcess, ExportProvider::DesignerBatch], + }; + let mut utilities = PlatformUtilities::from_config(config); + let mut candidates = Vec::new(); + let mut selected = None; + + for provider in providers { + if let Some(interruption) = context.interruption() { + let reason = format!( + "{} during provider selection", + interruption.message(context.command()) + ); + let decision = ExportProviderDecision::unavailable(reason.clone(), candidates); + let error = match interruption { + crate::use_cases::context::ExecutionInterruption::Cancelled => { + AppError::Cancelled(reason) + } + crate::use_cases::context::ExecutionInterruption::TimedOut => { + AppError::TimedOut(reason) + } + }; + return Err((error, decision)); + } + let (implementation, evidence, implementation_reason) = capability(intent, provider); + if selected.is_some() || implementation != ProviderImplementation::Implemented { + candidates.push(ProviderCandidate::new( + provider, + implementation, + ProviderReadiness::NotChecked, + evidence, + implementation_reason, + )); + continue; + } + + let utility = provider_utility(provider); + match readiness(config, &mut utilities, provider, utility) { + Ok(executable) => { + candidates.push(ProviderCandidate::new( + provider, + implementation, + ProviderReadiness::Ready, + evidence, + format!( + "{}; '{}' resolved without starting a provider process", + implementation_reason, + executable.display() + ), + )); + selected = Some((provider, executable)); + } + Err(reason) => candidates.push(ProviderCandidate::new( + provider, + implementation, + ProviderReadiness::Unavailable, + evidence, + format!("{implementation_reason}; {reason}"), + )), + } + } + + if let Some((provider, executable)) = selected { + let reason = format!( + "selected {} before dispatch from the operation-specific candidate order", + provider.as_str() + ); + let selection = ExportProviderDecision::selected(provider, reason, candidates); + return Ok(PreparedExportProvider { + selection, + provider, + executable, + }); + } + + let has_implemented = candidates + .iter() + .any(|candidate| candidate.implementation == ProviderImplementation::Implemented); + let reason = candidates + .iter() + .map(|candidate| format!("{}: {}", candidate.provider.as_str(), candidate.reason)) + .collect::>() + .join("; "); + let decision = ExportProviderDecision::unavailable(reason.clone(), candidates); + let error = if has_implemented { + AppError::EnvironmentUnavailable(reason) + } else { + AppError::CapabilityUnavailable(reason) + }; + Err((error, decision)) +} + +fn capability( + intent: ExportIntent, + provider: ExportProvider, +) -> (ProviderImplementation, ProviderEvidence, &'static str) { + match (intent, provider) { + (ExportIntent::Configuration, ExportProvider::DesignerBatch) => ( + ProviderImplementation::Implemented, + ProviderEvidence::ArgvTested, + "Designer CF/CFE adapter is implemented from the documented batch contract", + ), + (ExportIntent::Configuration, ExportProvider::IbcmdProcess) => ( + ProviderImplementation::Implemented, + ProviderEvidence::ArgvTested, + "IBCMD CF/CFE adapter is implemented from the documented config-save contract", + ), + (ExportIntent::Snapshot, ExportProvider::DesignerBatch) => ( + ProviderImplementation::Implemented, + ProviderEvidence::ArgvTested, + "Designer DT adapter is implemented from the documented batch contract", + ), + (ExportIntent::Snapshot, ExportProvider::IbcmdProcess) => ( + ProviderImplementation::Experimental, + ProviderEvidence::Documented, + "IBCMD DT export is disabled until an exclusive-access preflight is implemented", + ), + } +} + +fn provider_utility(provider: ExportProvider) -> UtilityType { + match provider { + ExportProvider::DesignerBatch => UtilityType::V8, + ExportProvider::IbcmdProcess => UtilityType::Ibcmd, + } +} + +fn readiness( + config: &AppConfig, + utilities: &mut PlatformUtilities, + provider: ExportProvider, + utility: UtilityType, +) -> Result { + validate_file_infobase_readiness(config)?; + if provider == ExportProvider::IbcmdProcess { + IbcmdConnection::from_infobase(&config.infobase) + .map_err(|error| format!("connection is not ready for IBCMD: {error}"))?; + } + utilities + .locate(utility) + .map(|location| location.path) + .map_err(|error| format!("environment is not ready: {error}")) +} + +fn validate_file_infobase_readiness(config: &AppConfig) -> Result<(), String> { + let connection = config.v8_connection(); + if !connection.has_supported_shape() { + return Err( + "infobase connection is not ready: expected non-empty File=..., Srvr=...;Ref=..., or /S server\\ref" + .to_owned(), + ); + } + let Some(file_path) = connection.file_path() else { + return Ok(()); + }; + let database_file = Path::new(file_path).join("1Cv8.1CD"); + if database_file.is_file() { + return Ok(()); + } + Err(format!( + "file infobase is not ready: '{}' is missing or is not a file", + database_file.display() + )) +} + +#[derive(Debug)] +struct ResolvedOutput { + requested: PathBuf, + target: PathBuf, + identity: String, + lock_path: PathBuf, +} + +#[derive(Debug)] +struct OutputObservation { + parent: FilesystemObjectIdentity, + target: Option, +} + +#[derive(Debug, PartialEq, Eq)] +struct TargetObjectObservation { + identity: FilesystemObjectIdentity, + len: u64, + modified: Option, +} + +fn configuration_failure( + context: &ExecutionContext, + error: AppError, + mut result: ExportConfigurationPackageResult, + phase: ExportPhase, +) -> UseCaseFailure { + record_execution_failure(context, &error, phase, &mut result.execution); + result.steps.push(failed_step(phase, &error)); + UseCaseFailure::with_payload(infobase_use_case_error(error), result) +} + +fn snapshot_failure( + context: &ExecutionContext, + error: AppError, + mut result: ExportInfobaseSnapshotResult, + phase: ExportPhase, +) -> UseCaseFailure { + record_execution_failure(context, &error, phase, &mut result.execution); + result.steps.push(failed_step(phase, &error)); + UseCaseFailure::with_payload(infobase_use_case_error(error), result) +} + +fn infobase_use_case_error(error: AppError) -> UseCaseError { + let kind = match process_error(&error) { + Some(ProcessError::Cancelled { .. }) => Some(UseCaseErrorKind::Cancelled), + Some(ProcessError::TimedOut { .. }) => Some(UseCaseErrorKind::TimedOut), + _ => None, + }; + match kind { + Some(kind) => UseCaseError::new(kind, error.to_string()), + None => error.into(), + } +} + +fn failed_step(phase: ExportPhase, error: &AppError) -> StepResult { + StepResult::failed(phase.as_str(), phase.kind(), 0).with_message(error.to_string()) +} + +fn record_execution_failure( + _context: &ExecutionContext, + error: &AppError, + phase: ExportPhase, + execution: &mut ExecutionOutcome<()>, +) { + let message = error.to_string(); + let mut interruption_details = None; + let (status, code) = match process_error(error) { + Some(ProcessError::Cancelled { .. }) => { + interruption_details = Some(process_interruption_details( + ProcessInterruptionReason::Cancelled, + phase.as_str(), + false, + &message, + )); + (ExecutionStatus::Cancelled, "cancelled") + } + Some(ProcessError::TimedOut { .. }) => { + interruption_details = Some(process_interruption_details( + ProcessInterruptionReason::TimedOut, + phase.as_str(), + false, + &message, + )); + (ExecutionStatus::TimedOut, "timed_out") + } + _ => match error { + AppError::Cancelled(_) => { + interruption_details = Some(command_interruption_details( + crate::use_cases::context::ExecutionInterruption::Cancelled, + phase.as_str(), + &message, + )); + (ExecutionStatus::Cancelled, "cancelled") + } + AppError::TimedOut(_) => { + interruption_details = Some(command_interruption_details( + crate::use_cases::context::ExecutionInterruption::TimedOut, + phase.as_str(), + &message, + )); + (ExecutionStatus::TimedOut, "timed_out") + } + AppError::CapabilityUnavailable(_) => { + (ExecutionStatus::Failed, "capability_unavailable") + } + AppError::EnvironmentUnavailable(_) => { + (ExecutionStatus::Failed, "environment_unavailable") + } + AppError::WorkspaceBusy(_) => (ExecutionStatus::Failed, "workspace_busy"), + AppError::InvalidOutput(_) => (ExecutionStatus::InvalidOutput, "invalid_output"), + _ => (ExecutionStatus::Failed, execution_error_code(error)), + }, + }; + execution.status = status; + execution.errors.push(ExecutionError::new(code, message)); + if let Some(details) = interruption_details { + execution.interruptions.push(details); + } +} + +fn process_error(error: &AppError) -> Option<&ProcessError> { + match error { + AppError::PlatformProcess(error) + | AppError::PlatformProcessContext { source: error, .. } => Some(error), + _ => None, + } +} + +fn execution_error_code(error: &AppError) -> &'static str { + match error { + AppError::Validation(_) + | AppError::ValidationIbcmd(_) + | AppError::ValidationIbcmdContext { .. } + | AppError::Config(_) + | AppError::ConfigContext { .. } => "invalid_argument", + AppError::CapabilityUnavailable(_) => "capability_unavailable", + AppError::EnvironmentUnavailable(_) => "environment_unavailable", + AppError::WorkspaceBusy(_) => "workspace_busy", + AppError::Cancelled(_) => "cancelled", + AppError::TimedOut(_) => "timed_out", + AppError::InvalidOutput(_) => "invalid_output", + AppError::Runtime(_) => "runtime_failure", + _ => "platform_failure", + } +} + +fn record_deferred_process_interruption( + platform_result: &PlatformCommandResult, + phase: &str, + completed_action: &str, + execution: &mut ExecutionOutcome<()>, + warnings: &mut Vec, +) { + if let Some(details) = + deferred_process_interruption_details(phase, completed_action, platform_result) + { + execution.interruptions.push(details); + } + if let Some(warning) = deferred_process_interruption_warning(completed_action, platform_result) + { + warnings.push(warning); + } +} + +fn resolve_output(config: &AppConfig, requested: &Path) -> Result { + let requested = if requested.is_absolute() { + requested.to_path_buf() + } else { + config.base_path.join(requested) + }; + let canonical = nearest_existing_canonical_path(&requested).map_err(|error| { + AppError::Runtime(format!( + "failed to canonicalize output '{}': {error}", + requested.display() + )) + })?; + if canonical.is_dir() { + return Err(AppError::Validation(format!( + "output '{}' is a directory", + requested.display() + ))); + } + let identity = stable_path_identity(&canonical); + let lock_path = hashed_lock_path(&canonical, "infobase-export").map_err(|error| { + AppError::Runtime(format!("failed to resolve output lock path: {error}")) + })?; + Ok(ResolvedOutput { + requested, + target: canonical, + identity, + lock_path, + }) +} + +fn revalidate_output_identity(output: &ResolvedOutput) -> Result<(), AppError> { + let canonical = nearest_existing_canonical_path(&output.requested).map_err(|error| { + AppError::Runtime(format!( + "failed to revalidate output '{}': {error}", + output.requested.display() + )) + })?; + let current_identity = stable_path_identity(&canonical); + if current_identity != output.identity { + return Err(AppError::Runtime(format!( + "output identity changed before publication: expected '{}', resolved '{}'", + output.identity, current_identity + ))); + } + Ok(()) +} + +fn observe_locked_output(output: &ResolvedOutput) -> Result { + revalidate_output_identity(output)?; + let parent = output.target.parent().ok_or_else(|| { + AppError::Runtime(format!( + "output path has no parent: {}", + output.target.display() + )) + })?; + let parent = filesystem_object_identity(parent).map_err(|error| { + AppError::Runtime(format!( + "failed to observe output parent '{}': {error}", + parent.display() + )) + })?; + let target = match observe_target_object(&output.target) { + Ok(identity) => Some(identity), + Err(error) if error.kind() == ErrorKind::NotFound => None, + Err(error) => { + return Err(AppError::Runtime(format!( + "failed to observe output '{}': {error}", + output.target.display() + ))) + } + }; + Ok(OutputObservation { parent, target }) +} + +fn observe_target_object(path: &Path) -> std::io::Result { + let metadata = std::fs::metadata(path)?; + Ok(TargetObjectObservation { + identity: filesystem_object_identity(path)?, + len: metadata.len(), + modified: metadata.modified().ok(), + }) +} + +fn revalidate_output_observation( + output: &ResolvedOutput, + observation: &OutputObservation, +) -> Result<(), AppError> { + revalidate_output_identity(output)?; + let parent = output.target.parent().ok_or_else(|| { + AppError::Runtime(format!( + "output path has no parent: {}", + output.target.display() + )) + })?; + let current_parent = filesystem_object_identity(parent).map_err(|error| { + AppError::Runtime(format!( + "failed to revalidate output parent '{}': {error}", + parent.display() + )) + })?; + if current_parent != observation.parent { + return Err(AppError::Runtime(format!( + "output parent changed before publication: '{}'", + parent.display() + ))); + } + let current_target = match observe_target_object(&output.target) { + Ok(identity) => Some(identity), + Err(error) if error.kind() == ErrorKind::NotFound => None, + Err(error) => { + return Err(AppError::Runtime(format!( + "failed to revalidate output '{}': {error}", + output.target.display() + ))) + } + }; + if current_target != observation.target { + return Err(AppError::Runtime(format!( + "output target changed before publication: '{}'", + output.target.display() + ))); + } + Ok(()) +} + +fn revalidate_before_publish( + output: &ResolvedOutput, + observation: &OutputObservation, + publication: &StagedPublication, +) -> Result<(), AppError> { + revalidate_output_observation(output, observation) + .map_err(|error| publication.cleanup_failure(error)) +} + +fn cleanup_export_orphans( + output: &ResolvedOutput, + stage_prefixes: &[&str], +) -> Result<(), AppError> { + let roots = output + .target + .parent() + .map(|parent| vec![parent.to_path_buf()]) + .unwrap_or_default(); + cleanup_owned_orphan_files( + &roots, + &output.target, + &output.identity, + stage_prefixes, + &[], + false, + ) +} + +fn acquire_target_lock( + context: &ExecutionContext, + lock_path: &Path, + command: &str, +) -> Result { + loop { + match try_acquire_advisory_lock(lock_path) { + Ok(guard) => return Ok(guard), + Err(error) if error.kind() == ErrorKind::WouldBlock => { + if let Some(interruption) = context.interruption() { + let message = format!( + "{} while waiting for {command} output lock '{}'", + interruption.message(context.command()), + lock_path.display() + ); + return Err(match interruption { + crate::use_cases::context::ExecutionInterruption::Cancelled => { + AppError::Cancelled(message) + } + crate::use_cases::context::ExecutionInterruption::TimedOut => { + AppError::TimedOut(message) + } + }); + } + let delay = context + .remaining_budget() + .map(|remaining| remaining.min(Duration::from_millis(25))) + .unwrap_or(Duration::from_millis(25)); + if delay.is_zero() { + continue; + } + thread::sleep(delay); + } + Err(error) => { + return Err(AppError::Runtime(format!( + "failed to acquire {command} output lock '{}': {error}", + lock_path.display() + ))) + } + } + } +} + +fn run_configuration_provider( + context: &ExecutionContext, + config: &AppConfig, + provider: ExportProvider, + executable: &Path, + state: ConfigurationState, + subject: &ConfigurationSubject, + staging_path: &Path, +) -> Result { + let extension = match subject { + ConfigurationSubject::Main => None, + ConfigurationSubject::Extension { name } => Some(name.as_str()), + }; + let runner = crate::platform::process::ProcessExecutor; + let result = match provider { + ExportProvider::DesignerBatch => { + let log = provider_log_path(config, "configuration-export")?; + let dsl = DesignerDsl::new( + executable.to_path_buf(), + config.v8_connection(), + &runner, + Some(log), + ) + .with_execution_policy( + context.process_policy(InterruptionSafetyClass::GracefulThenKill, None), + ); + match state { + ConfigurationState::Working => dsl.dump_cfg(staging_path, extension), + ConfigurationState::Database => dsl.dump_db_cfg(staging_path, extension), + } + .map_err(AppError::from)? + } + ExportProvider::IbcmdProcess => { + let connection = + IbcmdConnection::from_infobase(&config.infobase).map_err(AppError::from)?; + let data_path = config.work_path.join("ibcmd-data"); + std::fs::create_dir_all(&data_path).map_err(|error| { + AppError::Runtime(format!( + "failed to create IBCMD data directory '{}': {error}", + data_path.display() + )) + })?; + IbcmdDsl::new(executable.to_path_buf(), connection, &runner) + .with_data_path(data_path) + .with_execution_policy( + context.process_policy(InterruptionSafetyClass::GracefulThenKill, None), + ) + .config_save( + staging_path, + state == ConfigurationState::Database, + extension, + ) + .map_err(AppError::from)? + } + }; + Ok(result) +} + +fn run_snapshot_provider( + context: &ExecutionContext, + config: &AppConfig, + provider: ExportProvider, + executable: &Path, + staging_path: &Path, +) -> Result { + match provider { + ExportProvider::DesignerBatch => { + let runner = crate::platform::process::ProcessExecutor; + let log = provider_log_path(config, "infobase-dump")?; + DesignerDsl::new( + executable.to_path_buf(), + config.v8_connection(), + &runner, + Some(log), + ) + .with_execution_policy( + context.process_policy(InterruptionSafetyClass::GracefulThenKill, None), + ) + .dump_infobase(staging_path) + .map_err(AppError::from) + } + ExportProvider::IbcmdProcess => Err(AppError::CapabilityUnavailable( + "IBCMD DT export is experimental and cannot be dispatched".to_owned(), + )), + } +} + +fn provider_log_path(config: &AppConfig, stem: &str) -> Result { + platform_logs_dir(&config.work_path) + .map(|dir| dir.join(format!("{stem}.log"))) + .map_err(|error| AppError::Runtime(format!("failed to create platform logs dir: {error}"))) +} + +fn validate_platform_success(result: &PlatformCommandResult) -> Result<(), AppError> { + if result.process.exit_code != 0 { + let mut details = vec![format!( + "platform export failed with exit code {}", + result.process.exit_code + )]; + append_platform_diagnostic(&mut details, "stdout", &result.process.stdout); + append_platform_diagnostic(&mut details, "stderr", &result.process.stderr); + if let Some(log) = result.platform_log.as_deref() { + append_platform_diagnostic(&mut details, "platform log", log); + } + if let Some(error) = result.platform_log_read_error.as_deref() { + append_platform_diagnostic(&mut details, "platform log read error", error); + } + if let Some(path) = result.platform_log_path.as_deref() { + details.push(format!("platform log path: {}", path.display())); + } + return Err(AppError::Platform(details.join("; "))); + } + Ok(()) +} + +fn append_platform_diagnostic(details: &mut Vec, label: &str, value: &str) { + let value = value.trim(); + if !value.is_empty() { + details.push(format!("{label}: {value}")); + } +} + +fn validate_platform_artifact(staging_path: &Path) -> Result<(), AppError> { + let metadata = std::fs::symlink_metadata(staging_path).map_err(|error| { + AppError::InvalidOutput(format!( + "provider did not produce export file '{}': {error}", + staging_path.display() + )) + })?; + if !metadata.file_type().is_file() || metadata.len() == 0 { + return Err(AppError::InvalidOutput(format!( + "provider export '{}' is not a non-empty regular file", + staging_path.display() + ))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + use crate::config::model::{ + AppConfig, BuildConfig, BuilderBackend, InfobaseConfig, McpConfig, SourceFormat, + TestsConfig, ToolsConfig, + }; + use crate::domain::execution::{ExecutionOutcome, ExecutionStatus}; + use crate::domain::infobase_export::{ + ConfigurationSubject, ExportProvider, ProviderImplementation, + }; + use crate::platform::process::ProcessError; + use crate::support::error::AppError; + use crate::use_cases::context::ExecutionContext; + use crate::use_cases::result::UseCaseErrorKind; + + use super::{ + acquire_target_lock, capability, cleanup_export_orphans, observe_locked_output, + record_execution_failure, resolve_output, revalidate_before_publish, + revalidate_output_observation, validate_configuration_output, validate_snapshot_output, + ExportIntent, ExportPhase, SNAPSHOT_COMMAND, + }; + + fn config(base: &Path, work: &Path) -> AppConfig { + AppConfig { + base_path: base.to_path_buf(), + work_path: work.to_path_buf(), + execution_timeout: 300_000, + format: SourceFormat::Designer, + builder: BuilderBackend::Designer, + infobase: InfobaseConfig::file("File=/tmp/ib"), + source_sets: Vec::new(), + build: BuildConfig::default(), + tools: ToolsConfig::default(), + mcp: McpConfig::default(), + tests: TestsConfig::default(), + } + } + + #[test] + fn configuration_output_suffix_is_derived_from_subject() { + assert!(validate_configuration_output( + &ConfigurationSubject::Main, + Path::new("dist/main.cf") + ) + .is_ok()); + assert!(validate_configuration_output( + &ConfigurationSubject::Extension { + name: "Sales".to_owned(), + }, + Path::new("dist/sales.cfe") + ) + .is_ok()); + assert!(validate_configuration_output( + &ConfigurationSubject::Main, + Path::new("dist/main.cfe") + ) + .is_err()); + } + + #[test] + fn snapshot_output_is_dt_and_ibcmd_remains_experimental() { + assert!(validate_snapshot_output(Path::new("dist/base.dt")).is_ok()); + assert!(validate_snapshot_output(Path::new("dist/base.backup")).is_err()); + + let (designer, _, _) = capability(ExportIntent::Snapshot, ExportProvider::DesignerBatch); + assert_eq!(designer, ProviderImplementation::Implemented); + let (ibcmd, _, _) = capability(ExportIntent::Snapshot, ExportProvider::IbcmdProcess); + assert_eq!(ibcmd, ProviderImplementation::Experimental); + } + + #[test] + fn different_workspaces_resolve_one_output_to_one_serializing_target_lock() { + let dir = tempfile::tempdir().expect("tempdir"); + let output = dir.path().join("shared/base.dt"); + std::fs::create_dir_all(output.parent().expect("parent")).expect("output parent"); + let first = config(&dir.path().join("one"), &dir.path().join("work-one")); + let second = config(&dir.path().join("two"), &dir.path().join("work-two")); + let first_target = resolve_output(&first, &output).expect("first target"); + let second_target = resolve_output(&second, &output).expect("second target"); + assert_eq!(first_target.lock_path, second_target.lock_path); + + let first_guard = crate::support::fs::acquire_advisory_lock(&first_target.lock_path) + .expect("first target lock"); + let lock_path = second_target.lock_path.clone(); + let (tx, rx) = mpsc::channel(); + let waiter = std::thread::spawn(move || { + let _guard = + crate::support::fs::acquire_advisory_lock(&lock_path).expect("second target lock"); + tx.send(()).expect("send acquired"); + }); + assert!(rx.recv_timeout(Duration::from_millis(100)).is_err()); + drop(first_guard); + rx.recv_timeout(Duration::from_secs(2)) + .expect("second workspace acquires after release"); + waiter.join().expect("waiter"); + } + + #[cfg(any(windows, target_os = "macos"))] + #[test] + fn case_aliases_for_absent_output_share_one_target_lock() { + let dir = tempfile::tempdir().expect("tempdir"); + let output_dir = dir.path().join("shared"); + std::fs::create_dir_all(&output_dir).expect("output parent"); + let config = config(&dir.path().join("base"), &dir.path().join("work")); + + let lower = resolve_output(&config, &output_dir.join("base.dt")).expect("lower target"); + let upper = resolve_output(&config, &output_dir.join("BASE.DT")).expect("upper target"); + + assert_eq!(lower.lock_path, upper.lock_path); + } + + #[cfg(target_os = "macos")] + #[test] + fn unicode_normalization_aliases_for_absent_output_share_one_target_lock() { + let dir = tempfile::tempdir().expect("tempdir"); + let output_dir = dir.path().join("shared"); + std::fs::create_dir_all(&output_dir).expect("output parent"); + let config = config(&dir.path().join("base"), &dir.path().join("work")); + + let nfc = resolve_output(&config, &output_dir.join("caf\u{e9}.dt")).expect("NFC target"); + let nfd = resolve_output(&config, &output_dir.join("cafe\u{301}.dt")).expect("NFD target"); + + assert_eq!(nfc.lock_path, nfd.lock_path); + } + + #[cfg(target_os = "macos")] + #[test] + fn full_unicode_casefold_aliases_for_absent_output_share_one_target_lock() { + let dir = tempfile::tempdir().expect("tempdir"); + let output_dir = dir.path().join("shared"); + std::fs::create_dir_all(&output_dir).expect("output parent"); + let config = config(&dir.path().join("base"), &dir.path().join("work")); + + for (first, second) in [ + ("Stra\u{df}e.dt", "STRASSE.DT"), + ("\u{fb00}.dt", "ff.dt"), + ("\u{3c2}.dt", "\u{3c3}.dt"), + ] { + let first = resolve_output(&config, &output_dir.join(first)).expect("first target"); + let second = resolve_output(&config, &output_dir.join(second)).expect("second target"); + assert_eq!(first.lock_path, second.lock_path); + } + } + + #[test] + fn target_lock_wait_observes_the_command_deadline() { + let dir = tempfile::tempdir().expect("tempdir"); + let lock_path = dir.path().join("target.lock"); + let _guard = crate::support::fs::acquire_advisory_lock(&lock_path).expect("held lock"); + let context = ExecutionContext::cli(crate::use_cases::context::CommandName::InfobaseDump) + .with_deadline(Some(Instant::now() + Duration::from_millis(30))); + let started = Instant::now(); + + let error = acquire_target_lock(&context, &lock_path, SNAPSHOT_COMMAND) + .expect_err("deadline must stop lock wait"); + + assert!(matches!(error, AppError::TimedOut(_))); + assert!(started.elapsed() < Duration::from_millis(250)); + } + + #[test] + fn target_lock_wait_reports_typed_cancellation() { + let dir = tempfile::tempdir().expect("tempdir"); + let lock_path = dir.path().join("target.lock"); + let _guard = crate::support::fs::acquire_advisory_lock(&lock_path).expect("held lock"); + let cancellation = tokio_util::sync::CancellationToken::new(); + cancellation.cancel(); + let context = ExecutionContext::cli(crate::use_cases::context::CommandName::InfobaseDump) + .with_cancellation(cancellation); + + let error = acquire_target_lock(&context, &lock_path, SNAPSHOT_COMMAND) + .expect_err("cancellation must stop lock wait"); + + assert!(matches!(error, AppError::Cancelled(_))); + } + + #[test] + fn provider_selection_observes_the_shared_command_deadline() { + let dir = tempfile::tempdir().expect("tempdir"); + let base = dir.path().join("base"); + let work = dir.path().join("work"); + std::fs::create_dir_all(&base).expect("base"); + let config = config(&base, &work); + let request = crate::domain::infobase_export::ExportInfobaseSnapshotRequest { + output: base.join("base.dt"), + }; + let context = ExecutionContext::cli(crate::use_cases::context::CommandName::InfobaseDump) + .with_deadline(Some(Instant::now() - Duration::from_millis(1))); + + let failure = super::prepare_infobase_snapshot(&context, &config, &request) + .expect_err("expired deadline"); + + assert_eq!(failure.error.kind(), UseCaseErrorKind::TimedOut); + let result = failure.payload.expect("typed payload"); + assert_eq!(result.execution.status, ExecutionStatus::TimedOut); + assert_eq!(result.execution.errors[0].code, "timed_out"); + } + + #[test] + fn orphan_cleanup_removes_only_owned_stale_export_files() { + use crate::support::fs::{ + metadata_sidecar_path, read_temp_dir_metadata, write_temp_dir_metadata, TempDirKind, + }; + + let dir = tempfile::tempdir().expect("tempdir"); + let base = dir.path().join("base"); + let work = dir.path().join("work"); + std::fs::create_dir_all(&base).expect("base"); + let config = config(&base, &work); + let output = base.join("dist/main.cf"); + std::fs::create_dir_all(output.parent().expect("parent")).expect("output parent"); + let resolved = resolve_output(&config, &output).expect("resolved"); + let stage = output + .parent() + .expect("parent") + .join(".infobase-config-stage-old-run.cf"); + std::fs::write(&stage, "payload").expect("stage"); + write_temp_dir_metadata( + &stage, + TempDirKind::Stage, + "old-run", + &resolved.target, + &resolved.identity, + ) + .expect("metadata"); + let metadata_path = metadata_sidecar_path(&stage); + let mut metadata = read_temp_dir_metadata(&stage).expect("read metadata"); + metadata.created_at -= chrono::Duration::days(2); + std::fs::write(&metadata_path, serde_json::to_vec(&metadata).expect("json")) + .expect("rewrite metadata"); + + cleanup_export_orphans(&resolved, &[".infobase-config-stage-"]).expect("cleanup"); + + assert!(!stage.exists()); + assert!(!metadata_path.exists()); + } + + #[test] + fn cancelled_process_is_not_collapsed_into_generic_failure() { + let context = ExecutionContext::cli( + crate::use_cases::context::CommandName::InfobaseConfigurationExport, + ); + let mut execution = ExecutionOutcome::new(ExecutionStatus::Failed); + let error = AppError::PlatformProcess(ProcessError::Cancelled { + cmd: "1cv8 DESIGNER".to_owned(), + }); + + record_execution_failure( + &context, + &error, + ExportPhase::ProviderCommand, + &mut execution, + ); + + assert_eq!(execution.status, ExecutionStatus::Cancelled); + assert_eq!(execution.errors[0].code, "cancelled"); + assert!(!execution.errors[0].retryable); + assert_eq!(execution.interruptions.len(), 1); + } + + #[test] + fn unrelated_failure_is_not_reclassified_by_an_expired_deadline() { + let context = ExecutionContext::cli( + crate::use_cases::context::CommandName::InfobaseConfigurationExport, + ) + .with_deadline(Some(Instant::now() - Duration::from_millis(1))); + let mut execution = ExecutionOutcome::new(ExecutionStatus::Failed); + let error = AppError::Runtime("publication failed".to_owned()); + + record_execution_failure(&context, &error, ExportPhase::Publication, &mut execution); + + assert_eq!(execution.status, ExecutionStatus::Failed); + assert_eq!(execution.errors[0].code, "runtime_failure"); + assert!(execution.interruptions.is_empty()); + } + + #[cfg(unix)] + #[test] + fn publication_rejects_target_identity_change_after_provider_execution() { + use std::os::unix::fs::symlink; + + let dir = tempfile::tempdir().expect("tempdir"); + let original_parent = dir.path().join("real-a"); + let replacement_parent = dir.path().join("real-b"); + let alias = dir.path().join("output"); + std::fs::create_dir_all(&original_parent).expect("original parent"); + std::fs::create_dir_all(&replacement_parent).expect("replacement parent"); + symlink(&original_parent, &alias).expect("initial alias"); + let config = config(dir.path(), &dir.path().join("work")); + let output = resolve_output(&config, &alias.join("main.cf")).expect("output"); + let observation = observe_locked_output(&output).expect("observation"); + let publication = crate::use_cases::staged_publication::StagedPublication::prepare_file( + &output.target, + &output.identity, + ".infobase-config-stage", + "cf", + ) + .expect("publication"); + std::fs::write(publication.staging_path(), "payload").expect("stage"); + let stage = publication.staging_path().to_path_buf(); + let sidecar = crate::support::fs::metadata_sidecar_path(&stage); + + std::fs::remove_file(&alias).expect("remove old alias"); + symlink(&replacement_parent, &alias).expect("retarget alias"); + + let error = revalidate_before_publish(&output, &observation, &publication) + .expect_err("identity change"); + assert!(error.to_string().contains("identity changed")); + assert!(!stage.exists()); + assert!(!sidecar.exists()); + } + + #[test] + fn publication_rejects_target_created_after_locked_observation() { + let dir = tempfile::tempdir().expect("tempdir"); + let config = config(dir.path(), &dir.path().join("work")); + let output = resolve_output(&config, &dir.path().join("main.cf")).expect("output"); + let observation = observe_locked_output(&output).expect("observation"); + let publication = crate::use_cases::staged_publication::StagedPublication::prepare_file( + &output.target, + &output.identity, + ".infobase-config-stage", + "cf", + ) + .expect("publication"); + std::fs::write(publication.staging_path(), "payload").expect("stage"); + let stage = publication.staging_path().to_path_buf(); + let sidecar = crate::support::fs::metadata_sidecar_path(&stage); + std::fs::write(&output.target, "external target").expect("external target"); + + let error = revalidate_before_publish(&output, &observation, &publication) + .expect_err("target appearance"); + + assert!(error.to_string().contains("target changed")); + assert_eq!( + std::fs::read_to_string(&output.target).expect("target"), + "external target" + ); + assert!(!stage.exists()); + assert!(!sidecar.exists()); + } + + #[cfg(unix)] + #[test] + fn output_observation_detects_parent_replacement_at_the_same_path() { + let dir = tempfile::tempdir().expect("tempdir"); + let parent = dir.path().join("output"); + std::fs::create_dir(&parent).expect("parent"); + let config = config(dir.path(), &dir.path().join("work")); + let output = resolve_output(&config, &parent.join("main.cf")).expect("output"); + let observation = observe_locked_output(&output).expect("observation"); + + std::fs::rename(&parent, dir.path().join("moved-output")).expect("move parent"); + std::fs::create_dir(&parent).expect("replacement parent"); + + let error = + revalidate_output_observation(&output, &observation).expect_err("parent replacement"); + assert!(error.to_string().contains("output parent changed")); + } +} diff --git a/src/use_cases/mod.rs b/src/use_cases/mod.rs index 57e904cf5..3c2ec415d 100644 --- a/src/use_cases/mod.rs +++ b/src/use_cases/mod.rs @@ -26,6 +26,7 @@ pub mod extension_identity; pub mod external_artifacts; /// Shared formatting helpers for IBCMD diagnostics. pub mod ibcmd_diagnostics; +pub mod infobase_export; /// Init orchestration use case. pub mod init_project; /// Shared command interruption status, metadata and message vocabulary. diff --git a/src/use_cases/result.rs b/src/use_cases/result.rs index 3ab7b86c9..ebcc8e584 100644 --- a/src/use_cases/result.rs +++ b/src/use_cases/result.rs @@ -9,6 +9,12 @@ const PLATFORM_EXIT_CODE: i32 = 4; /// Stable use-case error class used by transport adapters. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum UseCaseErrorKind { + Capability, + Environment, + WorkspaceBusy, + InvalidOutput, + Cancelled, + TimedOut, Validation, Runtime, Platform, @@ -18,6 +24,10 @@ impl UseCaseErrorKind { /// Maps the error kind to the CLI exit code. pub const fn exit_code(self) -> i32 { match self { + Self::Capability => VALIDATION_EXIT_CODE, + Self::Environment => VALIDATION_EXIT_CODE, + Self::WorkspaceBusy => RUNTIME_EXIT_CODE, + Self::InvalidOutput | Self::Cancelled | Self::TimedOut => PLATFORM_EXIT_CODE, Self::Validation => VALIDATION_EXIT_CODE, Self::Runtime => RUNTIME_EXIT_CODE, Self::Platform => PLATFORM_EXIT_CODE, @@ -26,6 +36,12 @@ impl UseCaseErrorKind { const fn label(self) -> &'static str { match self { + Self::Capability => "capability unavailable", + Self::Environment => "environment unavailable", + Self::WorkspaceBusy => "workspace busy", + Self::InvalidOutput => "invalid output", + Self::Cancelled => "cancelled", + Self::TimedOut => "timed out", Self::Validation => "validation error", Self::Runtime => "runtime error", Self::Platform => "platform error", @@ -74,6 +90,16 @@ impl fmt::Display for UseCaseError { impl From for UseCaseError { fn from(value: AppError) -> Self { match value { + AppError::CapabilityUnavailable(message) => { + Self::new(UseCaseErrorKind::Capability, message) + } + AppError::EnvironmentUnavailable(message) => { + Self::new(UseCaseErrorKind::Environment, message) + } + AppError::WorkspaceBusy(message) => Self::new(UseCaseErrorKind::WorkspaceBusy, message), + AppError::Cancelled(message) => Self::new(UseCaseErrorKind::Cancelled, message), + AppError::TimedOut(message) => Self::new(UseCaseErrorKind::TimedOut, message), + AppError::InvalidOutput(message) => Self::new(UseCaseErrorKind::InvalidOutput, message), AppError::Validation(message) => Self::new(UseCaseErrorKind::Validation, message), AppError::ValidationIbcmd(error) => { Self::new(UseCaseErrorKind::Validation, error.to_string()) @@ -161,6 +187,12 @@ mod tests { #[test] fn use_case_error_kinds_keep_stable_cli_exit_codes() { + assert_eq!(UseCaseErrorKind::Capability.exit_code(), 2); + assert_eq!(UseCaseErrorKind::Environment.exit_code(), 2); + assert_eq!(UseCaseErrorKind::WorkspaceBusy.exit_code(), 3); + assert_eq!(UseCaseErrorKind::InvalidOutput.exit_code(), 4); + assert_eq!(UseCaseErrorKind::Cancelled.exit_code(), 4); + assert_eq!(UseCaseErrorKind::TimedOut.exit_code(), 4); assert_eq!(UseCaseErrorKind::Validation.exit_code(), 2); assert_eq!(UseCaseErrorKind::Runtime.exit_code(), 3); assert_eq!(UseCaseErrorKind::Platform.exit_code(), 4); @@ -179,6 +211,16 @@ mod tests { assert!(error.message().contains("1cv8c ENTERPRISE")); } + #[test] + fn generic_process_timeout_keeps_the_existing_platform_error_kind() { + let error = UseCaseError::from(AppError::PlatformProcess(ProcessError::TimedOut { + cmd: "1cv8 DESIGNER".to_owned(), + timeout_ms: 100, + })); + + assert_eq!(error.kind(), UseCaseErrorKind::Platform); + } + #[test] fn contextual_config_errors_stay_validation_errors() { let app_error = AppError::Config(ConfigLoadError::NotFound("v8project.yaml".to_owned())) diff --git a/src/use_cases/staged_publication.rs b/src/use_cases/staged_publication.rs index dcf59e2be..8bcf9aaf0 100644 --- a/src/use_cases/staged_publication.rs +++ b/src/use_cases/staged_publication.rs @@ -1,27 +1,46 @@ use std::path::{Path, PathBuf}; +use std::time::Duration; use chrono::Utc; use crate::support::error::AppError; use crate::support::fs::{ - ensure_dir, metadata_sidecar_path, remove_path_if_exists, replace_dir_atomically, - replace_file_atomically, write_temp_dir_metadata, TempDirKind, + ensure_dir, is_known_tool_name, metadata_sidecar_path, read_temp_dir_metadata, + remove_path_if_exists, replace_dir_atomically, replace_file_atomically, + write_temp_dir_metadata, ReplaceFileFailureState, TempDirKind, TempDirMetadata, }; use crate::use_cases::context::{ExecutionContext, ExecutionInterruption}; use crate::use_cases::interruption; +const ORPHAN_TTL: Duration = Duration::from_secs(24 * 60 * 60); + #[derive(Debug, Clone)] pub(super) struct StagedPublication { staging_path: PathBuf, target_path: PathBuf, run_id: String, target_identity: String, + previous_target_present: bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct StagedPublicationOutcome { pub cleanup_warning: Option, pub deferred_interruption: Option, + pub previous_target_present: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum PublicationFailureState { + Unchanged, + Restored, + Uncertain, +} + +#[derive(Debug)] +pub(super) struct StagedPublicationError { + pub error: AppError, + pub target_state: PublicationFailureState, } impl StagedPublication { @@ -110,6 +129,9 @@ impl StagedPublication { backup_prefix: &str, error_prefix: &str, ) -> Result { + if let Some(error) = interruption_before_publish(context, "staged directory publication") { + return Err(error); + } let publish_phase = context.run_no_process_critical_phase(|| { replace_dir_atomically( &self.staging_path, @@ -123,6 +145,7 @@ impl StagedPublication { Ok(StagedPublicationOutcome { cleanup_warning: publish_phase.value.cleanup_warning, deferred_interruption: publish_phase.deferred_interruption, + previous_target_present: self.previous_target_present, }) } @@ -131,6 +154,22 @@ impl StagedPublication { context: &ExecutionContext, error_prefix: &str, ) -> Result { + self.publish_file_with_state(context, error_prefix) + .map_err(|failure| failure.error) + } + + #[allow(clippy::result_large_err)] // Typed rollback state must stay attached to the publication error. + pub fn publish_file_with_state( + &self, + context: &ExecutionContext, + error_prefix: &str, + ) -> Result { + if let Some(error) = interruption_before_publish(context, "staged file publication") { + return Err(StagedPublicationError { + error, + target_state: PublicationFailureState::Unchanged, + }); + } let publish_phase = context.run_no_process_critical_phase(|| { replace_file_atomically( &self.staging_path, @@ -138,11 +177,19 @@ impl StagedPublication { &self.run_id, &self.target_identity, ) - .map_err(|error| AppError::Runtime(format!("{error_prefix}: {error}"))) + .map_err(|error| StagedPublicationError { + target_state: match error.target_state { + ReplaceFileFailureState::Unchanged => PublicationFailureState::Unchanged, + ReplaceFileFailureState::Restored => PublicationFailureState::Restored, + ReplaceFileFailureState::Uncertain => PublicationFailureState::Uncertain, + }, + error: AppError::Runtime(format!("{error_prefix}: {error}")), + }) })?; Ok(StagedPublicationOutcome { cleanup_warning: publish_phase.value.cleanup_warning, deferred_interruption: publish_phase.deferred_interruption, + previous_target_present: publish_phase.value.previous_target_present, }) } @@ -157,6 +204,7 @@ impl StagedPublication { target_path: target_path.to_path_buf(), run_id, target_identity: target_identity.to_owned(), + previous_target_present: target_path.exists(), } } @@ -179,6 +227,140 @@ pub(super) fn cleanup_staging_path(staging_path: &Path, error: AppError) -> AppE error } +/// Reintroduction guard: this is the single scanner for stale staged/backup +/// files published through [`StagedPublication`]. Callers supply only naming +/// policy; metadata ownership and target identity remain centralized here. +pub(super) fn cleanup_owned_orphan_files( + scan_roots: &[PathBuf], + target_path: &Path, + target_identity: &str, + stage_prefixes: &[&str], + backup_prefixes: &[&str], + allow_descendant_targets: bool, +) -> Result<(), AppError> { + let mut roots = scan_roots.to_vec(); + roots.sort(); + roots.dedup(); + + for root in roots { + if !root.exists() { + continue; + } + for entry in std::fs::read_dir(&root) + .map_err(|error| AppError::Runtime(format!("failed to read output dir: {error}")))? + { + let entry = entry + .map_err(|error| AppError::Runtime(format!("failed to read dir entry: {error}")))?; + let path = entry.path(); + let (temp_path, metadata_path) = orphan_cleanup_paths(&path); + let Ok(metadata) = read_orphan_metadata(&temp_path, &metadata_path) else { + continue; + }; + let Some(temp_name) = temp_path.file_name().and_then(|value| value.to_str()) else { + continue; + }; + let target_matches = metadata.target_path == target_path + || (allow_descendant_targets && metadata.target_path.starts_with(target_path)); + if !is_known_tool_name(&metadata.tool) + || !target_matches + || metadata.target_identity != target_identity + || !orphan_name_matches_contract( + temp_name, + target_path, + &metadata, + stage_prefixes, + backup_prefixes, + ) + { + continue; + } + if (Utc::now() - metadata.created_at) + .to_std() + .unwrap_or_default() + < ORPHAN_TTL + { + continue; + } + + remove_path_if_exists(&temp_path).map_err(|error| { + AppError::Runtime(format!( + "failed to remove stale publication temp '{}': {error}", + temp_path.display() + )) + })?; + remove_path_if_exists(&metadata_path).map_err(|error| { + AppError::Runtime(format!( + "failed to remove stale publication metadata '{}': {error}", + metadata_path.display() + )) + })?; + } + } + Ok(()) +} + +fn orphan_name_matches_contract( + file_name: &str, + target_path: &Path, + metadata: &TempDirMetadata, + stage_prefixes: &[&str], + backup_prefixes: &[&str], +) -> bool { + match metadata.kind { + TempDirKind::Stage => { + stage_prefixes + .iter() + .any(|prefix| file_name.starts_with(prefix)) + && file_name.contains(&metadata.run_id) + } + TempDirKind::Backup => { + let named_backup = backup_prefixes + .iter() + .any(|prefix| file_name.starts_with(prefix)) + && file_name.contains(&metadata.run_id); + let file_backup = target_path + .file_name() + .map(|target_name| { + file_name + == format!( + ".{}.backup-{}", + target_name.to_string_lossy(), + metadata.run_id + ) + }) + .unwrap_or(false); + named_backup || file_backup + } + } +} + +fn orphan_cleanup_paths(path: &Path) -> (PathBuf, PathBuf) { + let Some(file_name) = path.file_name().and_then(|value| value.to_str()) else { + return (path.to_path_buf(), metadata_sidecar_path(path)); + }; + let Some(temp_name) = file_name.strip_suffix(".meta.json") else { + return (path.to_path_buf(), metadata_sidecar_path(path)); + }; + ( + path.parent() + .unwrap_or_else(|| Path::new(".")) + .join(temp_name), + path.to_path_buf(), + ) +} + +fn read_orphan_metadata( + temp_path: &Path, + metadata_path: &Path, +) -> std::io::Result { + if metadata_path == metadata_sidecar_path(temp_path) { + return read_temp_dir_metadata(temp_path); + } + let raw = std::fs::read(metadata_path)?; + serde_json::from_slice(&raw) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error)) +} + pub(super) fn interruption_before_publish( context: &ExecutionContext, safe_point: impl Into, @@ -199,10 +381,26 @@ mod tests { use tokio_util::sync::CancellationToken; use crate::support::error::AppError; - use crate::support::fs::{metadata_sidecar_path, read_temp_dir_metadata}; - use crate::use_cases::context::{CommandName, ExecutionContext, ExecutionInterruption}; - - use super::{cleanup_staging_path, interruption_before_publish, StagedPublication}; + use crate::support::fs::{ + metadata_sidecar_path, read_temp_dir_metadata, write_temp_dir_metadata, TempDirKind, + }; + use crate::use_cases::context::{CommandName, ExecutionContext}; + + use super::{ + cleanup_owned_orphan_files, cleanup_staging_path, interruption_before_publish, + StagedPublication, + }; + + fn make_stale(path: &std::path::Path) { + let metadata_path = metadata_sidecar_path(path); + let mut metadata = read_temp_dir_metadata(path).expect("metadata"); + metadata.created_at -= chrono::Duration::days(2); + fs::write( + metadata_path, + serde_json::to_vec_pretty(&metadata).expect("json"), + ) + .expect("stale metadata"); + } #[test] fn prepare_dir_creates_stage_dir_and_metadata_then_publishes() { @@ -251,7 +449,7 @@ mod tests { StagedPublication::prepare_file(&target, "identity", ".stage", "cf").expect("prepare"); fs::write(publication.staging_path(), "package").expect("stage"); - publication + let outcome = publication .publish_file( &ExecutionContext::cli(CommandName::Artifacts), "failed to publish staged test file", @@ -259,6 +457,27 @@ mod tests { .expect("publish"); assert_eq!(fs::read_to_string(target).expect("target"), "package"); + assert!(!outcome.previous_target_present); + } + + #[test] + fn file_publication_observes_target_presence_at_commit_time() { + let dir = tempdir().expect("tempdir"); + let target = dir.path().join("target.cf"); + let publication = + StagedPublication::prepare_file(&target, "identity", ".stage", "cf").expect("prepare"); + fs::write(publication.staging_path(), "package").expect("stage"); + fs::write(&target, "existing").expect("target created after prepare"); + + let outcome = publication + .publish_file( + &ExecutionContext::cli(CommandName::Artifacts), + "failed to publish staged test file", + ) + .expect("publish"); + + assert!(outcome.previous_target_present); + assert_eq!(fs::read_to_string(target).expect("target"), "package"); } #[test] @@ -279,6 +498,60 @@ mod tests { assert!(!metadata.exists()); } + #[test] + fn orphan_cleanup_requires_exact_target_kind_and_run_name_contract() { + let dir = tempdir().expect("tempdir"); + let target = dir.path().join("target.cf"); + let wrong_target = dir.path().join("other.cf"); + let wrong_target_stage = dir.path().join(".stage-wrong-target.cf"); + let wrong_kind_stage = dir.path().join(".stage-wrong-kind.cf"); + let unrelated_backup = dir.path().join("unrelated.backup-backup-run"); + fs::write(&wrong_target_stage, "stage").expect("stage"); + fs::write(&wrong_kind_stage, "stage").expect("stage"); + fs::write(&unrelated_backup, "backup").expect("backup"); + write_temp_dir_metadata( + &wrong_target_stage, + TempDirKind::Stage, + "wrong-target", + &wrong_target, + "identity", + ) + .expect("wrong target metadata"); + write_temp_dir_metadata( + &wrong_kind_stage, + TempDirKind::Backup, + "wrong-kind", + &target, + "identity", + ) + .expect("wrong kind metadata"); + write_temp_dir_metadata( + &unrelated_backup, + TempDirKind::Backup, + "backup-run", + &target, + "identity", + ) + .expect("unrelated backup metadata"); + make_stale(&wrong_target_stage); + make_stale(&wrong_kind_stage); + make_stale(&unrelated_backup); + + cleanup_owned_orphan_files( + &[dir.path().to_path_buf()], + &target, + "identity", + &[".stage-"], + &[], + false, + ) + .expect("cleanup"); + + assert!(wrong_target_stage.exists()); + assert!(wrong_kind_stage.exists()); + assert!(unrelated_backup.exists()); + } + #[test] fn interruption_check_reports_command_safe_point() { let cancellation = CancellationToken::new(); @@ -293,22 +566,50 @@ mod tests { } #[test] - fn publish_reports_deferred_interruption_from_critical_phase() { + fn cancelled_directory_publication_does_not_enter_critical_phase() { let dir = tempdir().expect("tempdir"); let target = dir.path().join("target"); let publication = StagedPublication::prepare_dir(&target, "identity", ".stage").expect("prepare"); + fs::write(publication.staging_path().join("payload.txt"), "payload").expect("payload"); + let staging_path = publication.staging_path().to_path_buf(); let cancellation = CancellationToken::new(); cancellation.cancel(); let context = ExecutionContext::cli(CommandName::Dump).with_cancellation(cancellation); - let outcome = publication + let error = publication .publish_dir(&context, ".backup", "failed to publish staged test dir") - .expect("publish"); + .expect_err("cancelled publication"); + + assert!(error + .to_string() + .contains("before entering staged directory publication safe point")); + assert!(!target.exists()); + assert!(staging_path.exists()); + } + + #[test] + fn cancelled_file_publication_reports_unchanged_target() { + let dir = tempdir().expect("tempdir"); + let target = dir.path().join("target.cf"); + fs::write(&target, "original").expect("target"); + let publication = + StagedPublication::prepare_file(&target, "identity", ".stage", "cf").expect("prepare"); + fs::write(publication.staging_path(), "replacement").expect("stage"); + let staging_path = publication.staging_path().to_path_buf(); + let cancellation = CancellationToken::new(); + cancellation.cancel(); + let context = ExecutionContext::cli(CommandName::Artifacts).with_cancellation(cancellation); + + let failure = publication + .publish_file_with_state(&context, "failed to publish staged test file") + .expect_err("cancelled publication"); assert_eq!( - outcome.deferred_interruption, - Some(ExecutionInterruption::Cancelled) + failure.target_state, + super::PublicationFailureState::Unchanged ); + assert_eq!(fs::read_to_string(target).expect("target"), "original"); + assert!(staging_path.exists()); } } diff --git a/src/use_cases/transport.rs b/src/use_cases/transport.rs index 718d3f310..da5fe4df6 100644 --- a/src/use_cases/transport.rs +++ b/src/use_cases/transport.rs @@ -5,6 +5,12 @@ use crate::use_cases::result::UseCaseError; use crate::use_cases::result::UseCaseFailure; use crate::use_cases::workspace_lock::acquire_workspace_lock; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WorkspaceBusyPolicy { + LegacyRuntime, + Typed, +} + /// Runs an adapter dispatch under the shared workspace-lock policy. pub fn dispatch_with_workspace_lock( config: &AppConfig, @@ -12,8 +18,36 @@ pub fn dispatch_with_workspace_lock( before_dispatch: impl FnOnce() -> Result<(), UseCaseError>, run: impl FnOnce() -> TResult, ) -> Result { - let _workspace_lock = - acquire_workspace_lock(config, command.as_str()).map_err(UseCaseError::from)?; + dispatch_with_workspace_lock_policy( + config, + command, + WorkspaceBusyPolicy::LegacyRuntime, + before_dispatch, + run, + ) +} + +/// Runs the single workspace-lock policy while allowing new commands to opt into a typed +/// contention code without changing the established contract of existing commands. +pub(crate) fn dispatch_with_workspace_lock_policy( + config: &AppConfig, + command: CommandName, + busy_policy: WorkspaceBusyPolicy, + before_dispatch: impl FnOnce() -> Result<(), UseCaseError>, + run: impl FnOnce() -> TResult, +) -> Result { + let _workspace_lock = acquire_workspace_lock(config, command.as_str()) + .map_err(UseCaseError::from) + .map_err(|error| match (busy_policy, error.kind()) { + ( + WorkspaceBusyPolicy::LegacyRuntime, + crate::use_cases::result::UseCaseErrorKind::WorkspaceBusy, + ) => UseCaseError::new( + crate::use_cases::result::UseCaseErrorKind::Runtime, + error.message(), + ), + _ => error, + })?; before_dispatch()?; Ok(run()) } diff --git a/src/use_cases/workspace_lock.rs b/src/use_cases/workspace_lock.rs index c09414e89..272f2cd6d 100644 --- a/src/use_cases/workspace_lock.rs +++ b/src/use_cases/workspace_lock.rs @@ -53,11 +53,14 @@ pub(crate) fn acquire_workspace_lock( let sidecar_path = workspace_lock_sidecar_path(&canonical_work_path); let lock = try_acquire_advisory_lock(&lock_path).map_err(|error| match error.kind() { - ErrorKind::WouldBlock => AppError::Runtime(render_busy_message( - command_name, - &canonical_work_path, - &lock_path, - &sidecar_path, + ErrorKind::WouldBlock | ErrorKind::AlreadyExists => AppError::WorkspaceBusy(format!( + "{}; {error}", + render_busy_message( + command_name, + &canonical_work_path, + &lock_path, + &sidecar_path, + ) )), _ => AppError::Runtime(format!( "failed to acquire {command_name} workspace lock '{}': {error}", diff --git a/tests/architecture_guardrails.rs b/tests/architecture_guardrails.rs index 1f5e76643..fe83c6a76 100644 --- a/tests/architecture_guardrails.rs +++ b/tests/architecture_guardrails.rs @@ -136,6 +136,8 @@ fn public_command_adapters_keep_workspace_lock_boundary() { "execute_test", "execute_load", "execute_dump", + "execute_infobase_configuration_export", + "execute_infobase_dump", "execute_convert", "execute_artifacts", "execute_syntax", @@ -143,7 +145,8 @@ fn public_command_adapters_keep_workspace_lock_boundary() { ] { let window = free_function_tokens(repo_path("src/cli/execute.rs").as_path(), function); assert!( - window.contains("with_cli_workspace_lock("), + window.contains("with_cli_workspace_lock(") + || window.contains("with_cli_workspace_lock_observed("), "{function} must keep the CLI workspace-lock boundary" ); } diff --git a/tests/cli_help.rs b/tests/cli_help.rs index 72977755e..2a485f654 100644 --- a/tests/cli_help.rs +++ b/tests/cli_help.rs @@ -189,3 +189,33 @@ fn convert_help_uses_output_target_root_name() { assert!(stdout.contains("--source-set ")); assert!(stdout.contains("--json-message")); } + +#[test] +fn infobase_configuration_export_help_fixes_the_exact_grammar() { + let output = v8_runner_command() + .args(["infobase", "configuration", "export", "--help"]) + .output() + .expect("run command"); + + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("--state ")); + assert!(stdout.contains("[possible values: working, database]")); + assert!(stdout.contains("--extension ")); + assert!(stdout.contains("--output ")); + assert!(!stdout.contains("--provider")); + assert!(!stdout.contains("--engine")); +} + +#[test] +fn infobase_dump_help_calls_dt_a_transfer_file_not_a_backup() { + let output = v8_runner_command() + .args(["infobase", "dump", "--help"]) + .output() + .expect("run command"); + + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("--output ")); + assert!(stdout.contains("not a backup")); +} diff --git a/tests/cli_infobase.rs b/tests/cli_infobase.rs new file mode 100644 index 000000000..1e9e8977a --- /dev/null +++ b/tests/cli_infobase.rs @@ -0,0 +1,1191 @@ +#![cfg(unix)] + +mod support; + +use std::fs; +use std::path::{Path, PathBuf}; + +use serde_json::Value; +use support::{temp_workspace, v8_runner_command, write_shell_script}; + +fn write_designer(path: &Path, calls: &Path) { + write_shell_script( + path, + &format!( + r#"printf '%s\n' "$*" >> "{}" +previous='' +out='' +for argument in "$@"; do + case "$previous" in + /DumpCfg|/DumpDBCfg|/DumpIB) printf 'payload' > "$argument" ;; + /Out) out="$argument" ;; + esac + previous="$argument" +done +if [ -n "$out" ]; then printf 'platform log' > "$out"; fi +exit 0"#, + calls.display() + ), + ); +} + +fn write_ibcmd(path: &Path, calls: &Path) { + write_shell_script( + path, + &format!( + r#"printf '%s\n' "$*" >> "{}" +last='' +for argument in "$@"; do last="$argument"; done +printf 'payload' > "$last" +exit 0"#, + calls.display() + ), + ); +} + +fn write_config(path: &Path, base: &Path, work: &Path, builder: &str, platform: &Path) { + fs::create_dir_all(base.join("main")).expect("base"); + fs::create_dir_all(work).expect("work"); + let infobase = base.join("ib"); + fs::create_dir_all(&infobase).expect("infobase"); + fs::write(infobase.join("1Cv8.1CD"), "database").expect("infobase file"); + fs::write( + path, + format!( + "workPath: '{}'\nformat: DESIGNER\nbuilder: {}\ninfobase:\n connection: 'File={}'\nsource-set:\n - name: main\n type: CONFIGURATION\n path: project/main\ntools:\n platform:\n path: '{}'\n", + work.display(), + builder, + infobase.display(), + platform.display(), + ), + ) + .expect("config"); +} + +#[test] +fn missing_file_infobase_is_unavailable_before_designer_dispatch() { + let (_dir, config, base, calls) = setup("DESIGNER"); + fs::remove_file(base.join("ib/1Cv8.1CD")).expect("remove infobase file"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "environment_unavailable"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "unavailable" + ); + assert!(envelope["data"]["selection"]["candidates"][0]["reason"] + .as_str() + .is_some_and(|reason| reason.contains("1Cv8.1CD"))); + assert!(!calls.exists()); + assert!(!output.exists()); +} + +#[test] +fn malformed_server_connection_is_unavailable_before_provider_dispatch() { + let (dir, config, base, calls) = setup("DESIGNER"); + let yaml = fs::read_to_string(&config).expect("config"); + fs::write( + &config, + yaml.replace( + &format!("File={}", base.join("ib").display()), + "not a connection", + ), + ) + .expect("malformed connection config"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "environment_unavailable"); + assert!(envelope["data"]["selection"]["candidates"][0]["reason"] + .as_str() + .is_some_and(|reason| reason.contains("expected non-empty File="))); + assert!(!calls.exists()); + assert!(!output.exists()); + assert!(!dir.path().join("work/logs/mcp/actions.log").exists()); +} + +#[test] +fn malformed_config_keeps_the_typed_infobase_failure_payload() { + let dir = temp_workspace(); + let config = dir.path().join("v8project.yaml"); + fs::write(&config, "workPath: [unterminated").expect("malformed config"); + let output = dir.path().join("main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["command"], "infobase.configuration.export"); + assert_eq!(envelope["data"]["selection"]["provider"], Value::Null); + assert_eq!( + envelope["data"]["selection"]["candidates"] + .as_array() + .map(Vec::len), + Some(0) + ); + assert_eq!(envelope["data"]["published"], false); + assert_eq!(envelope["data"]["target_state"], "unchanged"); + assert_eq!(envelope["data"]["execution"]["status"], "failed"); + assert_eq!(envelope["steps"][0]["name"], "configuration load"); + assert!(!output.exists()); +} + +fn hold_workspace_lock(work: &Path) { + fs::create_dir_all(work).expect("work"); + fs::write( + work.join(".v8-runner.workspace.lock"), + format!( + "{{\"tool\":\"v8-runner\",\"pid\":{},\"owner_id\":\"test-owner\",\"created_at\":\"2026-09-02T00:00:00Z\"}}", + std::process::id() + ), + ) + .expect("workspace lock"); +} + +fn setup(builder: &str) -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let binary = dir + .path() + .join(if builder == "IBCMD" { "ibcmd" } else { "1cv8" }); + let calls = dir.path().join("calls.log"); + if builder == "IBCMD" { + write_ibcmd(&binary, &calls); + } else { + write_designer(&binary, &calls); + } + write_config(&config, &base, &work, builder, &binary); + (dir, config, base, calls) +} + +#[test] +fn designer_exports_database_extension_to_cfe_with_typed_json() { + let (dir, config, base, calls) = setup("DESIGNER"); + let output = base.join("dist/sales.cfe"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--log-level", + "debug", + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "database", + "--extension", + "SalesAddon", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["command"], "infobase.configuration.export"); + assert_eq!(envelope["data"]["state"], "database"); + assert_eq!(envelope["data"]["subject"]["kind"], "extension"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(envelope["data"]["artifact_kind"], "cfe"); + assert_eq!(envelope["data"]["published"], true); + assert_eq!(envelope["data"]["target_state"], "created"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["implementation"], + "implemented" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "ready" + ); + assert_eq!(envelope["data"]["execution"]["status"], "succeeded"); + assert_eq!(envelope["steps"].as_array().map(Vec::len), Some(2)); + assert_eq!(fs::read(&output).expect("published cfe"), b"payload"); + let argv = fs::read_to_string(calls).expect("calls"); + assert!(argv.contains("/DumpDBCfg")); + assert!(argv.contains("-Extension SalesAddon")); + let action_log = + fs::read_to_string(dir.path().join("work/logs/mcp/actions.log")).expect("action log"); + assert!(action_log.contains("starting command under workspace lock")); + assert!(!action_log.contains("command finished successfully")); +} + +#[test] +fn designer_dumps_dt_and_labels_it_as_transfer_snapshot() { + let (_dir, config, base, calls) = setup("DESIGNER"); + let output = base.join("dist/base.dt"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "dump", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run dump"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["command"], "infobase.dump"); + assert_eq!(envelope["data"]["subject"]["kind"], "infobase"); + assert_eq!(envelope["data"]["artifact_kind"], "dt"); + assert_eq!(envelope["data"]["published"], true); + assert_eq!(fs::read(&output).expect("published dt"), b"payload"); + assert!(fs::read_to_string(calls) + .expect("calls") + .contains("/DumpIB")); +} + +#[test] +fn dt_uses_designer_when_ibcmd_is_preferred_but_not_implemented() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_ibcmd(&platform.join("ibcmd"), &calls); + write_designer(&platform.join("1cv8"), &calls); + write_config(&config, &base, &work, "IBCMD", &platform); + let output = base.join("dist/base.dt"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "dump", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run dump"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["command"], "infobase.dump"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(envelope["data"]["published"], true); + let argv = fs::read_to_string(calls).expect("calls"); + assert!(argv.contains("/DumpIB")); + assert!(!argv.contains("infobase dump")); +} + +#[test] +fn missing_preferred_ibcmd_falls_back_to_ready_designer_before_dispatch() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_designer(&platform.join("1cv8"), &calls); + write_config(&config, &base, &work, "IBCMD", &platform); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["provider"], + "ibcmd-process" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "unavailable" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][1]["readiness"], + "ready" + ); + assert!(fs::read_to_string(calls) + .expect("calls") + .contains("/DumpCfg")); +} + +#[test] +fn missing_preferred_designer_falls_back_to_ready_ibcmd_before_dispatch() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_ibcmd(&platform.join("ibcmd"), &calls); + write_config(&config, &base, &work, "DESIGNER", &platform); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!(command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "ibcmd-process"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["provider"], + "designer-batch" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "unavailable" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][1]["readiness"], + "ready" + ); + assert!(fs::read_to_string(calls) + .expect("calls") + .contains("config save")); +} + +#[test] +fn ibcmd_only_environment_cannot_dump_dt_until_capability_is_implemented() { + let (_dir, config, base, calls) = setup("IBCMD"); + let output = base.join("dist/base.dt"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "dump", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run dump"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "environment_unavailable"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["implementation"], + "experimental" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "not_checked" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][1]["readiness"], + "unavailable" + ); + assert!(!calls.exists()); + assert!(!output.exists()); +} + +#[test] +fn thin_client_alone_is_not_reported_as_designer_ready() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_designer(&platform.join("1cv8c"), &calls); + write_config(&config, &base, &work, "DESIGNER", &platform); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "environment_unavailable"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "unavailable" + ); + assert!(!calls.exists()); + assert!(!output.exists()); +} + +#[test] +fn incomplete_ibcmd_server_contract_does_not_block_ready_designer_alternate() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&base).expect("base"); + fs::create_dir_all(&work).expect("work"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_ibcmd(&platform.join("ibcmd"), &calls); + write_designer(&platform.join("1cv8"), &calls); + fs::write( + &config, + format!( + "workPath: '{}'\nformat: DESIGNER\nbuilder: IBCMD\ninfobase:\n connection: 'Srvr=localhost;Ref=demo'\nsource-set: []\ntools:\n platform:\n path: '{}'\n", + work.display(), + platform.display(), + ), + ) + .expect("config"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!( + envelope["data"]["selection"]["candidates"][0]["readiness"], + "unavailable" + ); + assert_eq!( + envelope["data"]["selection"]["candidates"][1]["readiness"], + "ready" + ); + let argv = fs::read_to_string(calls).expect("calls"); + assert!(argv.contains("/DumpCfg")); + assert!(!argv.contains("config save")); +} + +#[test] +fn complete_server_dbms_contract_is_dispatched_to_ibcmd() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&base).expect("base"); + fs::create_dir_all(&work).expect("work"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_ibcmd(&platform.join("ibcmd"), &calls); + fs::write( + &config, + format!( + "workPath: '{}'\nformat: DESIGNER\nbuilder: IBCMD\ninfobase:\n connection: 'Srvr=cluster;Ref=demo'\n dbms:\n kind: PostgreSQL\n server: db.example.test\n name: demo_data\nsource-set: []\ntools:\n platform:\n path: '{}'\n", + work.display(), + platform.display(), + ), + ) + .expect("config"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "database", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!(command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "ibcmd-process"); + let argv = fs::read_to_string(calls).expect("calls"); + assert!(argv.contains("--dbms PostgreSQL")); + assert!(argv.contains("--database-server db.example.test")); + assert!(argv.contains("--database-name demo_data")); + assert!(argv.contains("config save")); + assert!(argv.split_whitespace().any(|argument| argument == "--db")); +} + +#[test] +fn ibcmd_exports_working_configuration_without_designer_fallback() { + let (_dir, config, base, calls) = setup("IBCMD"); + let output = base.join("dist/main.cf"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "ibcmd-process"); + assert_eq!(envelope["data"]["state"], "working"); + assert_eq!(envelope["data"]["published"], true); + assert_eq!(fs::read(&output).expect("published cf"), b"payload"); + let argv = fs::read_to_string(calls).expect("calls"); + assert!(argv.contains("config save")); + assert!(!argv.split_whitespace().any(|argument| argument == "--db")); + assert!(!argv.contains("DESIGNER")); +} + +#[test] +fn invalid_suffix_is_rejected_before_workspace_lock_and_provider_dispatch() { + let (_dir, config, base, calls) = setup("DESIGNER"); + hold_workspace_lock(&base.join("../work")); + let output = base.join("dist/main.cfe"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run invalid export"); + + assert_eq!(command.status.code(), Some(2)); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["command"], "infobase.configuration.export"); + assert_eq!(envelope["error"]["kind"], "validation"); + assert_eq!(envelope["error"]["code"], "invalid_argument"); + assert_eq!(envelope["data"]["subject"]["kind"], "main"); + assert_eq!(envelope["data"]["selection"]["provider"], Value::Null); + assert_eq!( + envelope["data"]["selection"]["candidates"] + .as_array() + .map(Vec::len), + Some(0) + ); + assert_eq!(envelope["data"]["target_state"], "unchanged"); + assert_eq!(envelope["data"]["execution"]["status"], "failed"); + assert_eq!( + envelope["data"]["execution"]["errors"][0]["code"], + "invalid_argument" + ); + assert!( + !calls.exists(), + "invalid request must not dispatch a provider" + ); +} + +#[test] +fn clean_before_failure_is_reported_as_workspace_preparation() { + let (dir, config, base, calls) = setup("DESIGNER"); + fs::write(dir.path().join("work/logs"), "blocks log directory").expect("log blocker"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "--clean-before-execution", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert_eq!(command.status.code(), Some(3)); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "runtime_failure"); + assert_eq!(envelope["steps"][0]["name"], "workspace preparation"); + assert_eq!(envelope["steps"][0]["kind"], "prepare_workspace"); + assert!(!calls.exists()); + assert!(!output.exists()); +} + +#[test] +fn workspace_lock_io_failure_is_reported_as_lock_acquisition() { + let (dir, config, base, calls) = setup("DESIGNER"); + fs::remove_dir_all(dir.path().join("work")).expect("remove work directory"); + fs::write(dir.path().join("work"), "not a directory").expect("work path blocker"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert_eq!(command.status.code(), Some(3)); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "runtime_failure"); + assert_eq!(envelope["steps"][0]["name"], "workspace lock"); + assert_eq!(envelope["steps"][0]["kind"], "prepare_workspace"); + assert!(!calls.exists()); + assert!(!output.exists()); +} + +#[test] +fn ready_provider_reports_workspace_busy_without_dispatch() { + let (dir, config, base, calls) = setup("DESIGNER"); + hold_workspace_lock(&base.join("../work")); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run busy export"); + + assert_eq!(command.status.code(), Some(3)); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "workspace_busy"); + assert_eq!(envelope["error"]["kind"], "workspace"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(envelope["data"]["target_state"], "unchanged"); + assert_eq!(envelope["data"]["execution"]["status"], "failed"); + assert_eq!( + envelope["data"]["execution"]["errors"][0]["code"], + "workspace_busy" + ); + assert!(!calls.exists()); + assert!(!output.exists()); + assert!(!dir.path().join("work/logs/mcp/actions.log").exists()); +} + +#[test] +fn text_output_uses_the_same_canonical_provider_name_as_json() { + let (_dir, config, base, _calls) = setup("DESIGNER"); + let output = base.join("dist/base.dt"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "infobase", + "dump", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run text dump"); + + assert!(command.status.success()); + let stdout = String::from_utf8_lossy(&command.stdout); + assert!(stdout.contains("command: infobase.dump")); + assert!(stdout.contains("Infobase DT export")); + assert!(stdout.contains("provider: designer-batch")); + assert!(!stdout.contains("DesignerBatch")); + assert!(stdout.contains("published: true")); + assert!(stdout.contains("subject: infobase")); + assert!(stdout.contains("implementation: implemented")); + assert!(stdout.contains("readiness: ready")); + assert!(stdout.contains("artifact kind: dt")); + assert!(stdout.contains("execution status: succeeded")); +} + +#[test] +fn text_output_explains_unavailable_preference_and_ready_alternate() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_designer(&platform.join("1cv8"), &calls); + write_config(&config, &base, &work, "IBCMD", &platform); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run text export"); + + assert!(command.status.success()); + let stdout = String::from_utf8_lossy(&command.stdout); + assert!(stdout.contains("provider: designer-batch")); + assert!(stdout.contains("evidence: argv_tested")); + assert!(stdout.contains("candidate ibcmd-process:")); + assert!(stdout.contains("implementation=implemented, readiness=unavailable")); + assert!(stdout.contains("candidate designer-batch:")); + assert!(stdout.contains("implementation=implemented, readiness=ready")); +} + +#[test] +fn provider_failure_preserves_an_existing_target() { + let (dir, config, base, calls) = setup("DESIGNER"); + let output = base.join("dist/main.cf"); + fs::create_dir_all(output.parent().expect("parent")).expect("output parent"); + fs::write(&output, "old package").expect("old target"); + write_shell_script( + &dir.path().join("1cv8"), + &format!( + "printf '%s\\n' \"$*\" >> '{}'; printf 'provider stderr' >&2; exit 19", + calls.display() + ), + ); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run failed export"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(envelope["data"]["published"], false); + assert_eq!(envelope["data"]["target_state"], "unchanged"); + assert_eq!(envelope["data"]["execution"]["status"], "failed"); + assert_eq!( + envelope["data"]["execution"]["errors"][0]["code"], + "platform_failure" + ); + assert!(envelope["data"]["execution"]["errors"][0]["message"] + .as_str() + .is_some_and(|message| message.contains("provider stderr"))); + let provider_steps = envelope["steps"] + .as_array() + .expect("steps") + .iter() + .filter(|step| step["name"] == "provider command") + .collect::>(); + assert_eq!(provider_steps.len(), 1); + assert_eq!(provider_steps[0]["status"], "failed"); + assert_eq!( + fs::read_to_string(&output).expect("preserved target"), + "old package" + ); + assert_eq!( + fs::read_to_string(calls) + .expect("single provider call") + .lines() + .count(), + 1 + ); +} + +#[test] +fn provider_failure_never_dispatches_a_ready_alternate_after_spawn() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("platform"); + fs::create_dir_all(&platform).expect("platform"); + let calls = dir.path().join("calls.log"); + write_shell_script( + &platform.join("1cv8"), + &format!( + "printf 'designer-failed\\n' >> '{}'; exit 19", + calls.display() + ), + ); + write_ibcmd(&platform.join("ibcmd"), &calls); + write_config(&config, &base, &work, "DESIGNER", &platform); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run failed export"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(envelope["data"]["published"], false); + assert_eq!( + fs::read_to_string(calls).expect("single provider call"), + "designer-failed\n" + ); + assert!(!output.exists()); +} + +#[test] +fn successful_overwrite_reports_replaced_target_state() { + let (_dir, config, base, _calls) = setup("DESIGNER"); + let output = base.join("dist/main.cf"); + fs::create_dir_all(output.parent().expect("parent")).expect("output parent"); + fs::write(&output, "old package").expect("old target"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run overwrite"); + + assert!(command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["target_state"], "replaced"); + assert_eq!(fs::read(&output).expect("target"), b"payload"); +} + +#[test] +fn infobase_export_does_not_require_project_source_sets() { + let (dir, config, base, calls) = setup("DESIGNER"); + let yaml = fs::read_to_string(&config).expect("config"); + let source_set = + "source-set:\n - name: main\n type: CONFIGURATION\n path: project/main\n"; + fs::write(&config, yaml.replace(source_set, "source-set: []\n")).expect("source-free config"); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run source-free export"); + + assert!( + command.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&command.stdout), + String::from_utf8_lossy(&command.stderr) + ); + assert_eq!(fs::read(&output).expect("published cf"), b"payload"); + assert!(fs::read_to_string(calls) + .expect("calls") + .contains("/DumpCfg")); + drop(dir); +} + +#[test] +fn missing_provider_artifact_has_invalid_output_terminal_status() { + let (dir, config, base, _calls) = setup("DESIGNER"); + write_shell_script(&dir.path().join("1cv8"), "exit 0"); + let output = base.join("dist/main.cf"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run invalid provider output"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["execution"]["status"], "invalid_output"); + assert_eq!( + envelope["data"]["execution"]["errors"][0]["code"], + "invalid_output" + ); + assert_eq!(envelope["error"]["code"], "invalid_output"); + assert_eq!(envelope["error"]["kind"], "invalid_output"); + assert_eq!(envelope["data"]["published"], false); + assert_eq!(envelope["data"]["target_state"], "unchanged"); +} + +#[test] +fn provider_timeout_has_timed_out_terminal_status_and_is_not_retryable() { + let (dir, config, base, _calls) = setup("DESIGNER"); + let yaml = fs::read_to_string(&config).expect("config"); + fs::write( + &config, + yaml.replacen("workPath:", "execution_timeout: 50\nworkPath:", 1), + ) + .expect("short timeout config"); + write_shell_script(&dir.path().join("1cv8"), "sleep 1"); + let output = base.join("dist/main.cf"); + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run timed out provider"); + + assert!(!command.status.success()); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["data"]["execution"]["status"], "timed_out"); + assert_eq!( + envelope["data"]["execution"]["errors"][0]["code"], + "timed_out" + ); + assert!(envelope["data"]["execution"]["errors"][0]["retryable"].is_null()); + assert_eq!(envelope["steps"][0]["status"], "failed"); + assert_eq!(envelope["data"]["published"], false); + assert_eq!(envelope["data"]["target_state"], "unchanged"); + assert_eq!(envelope["error"]["code"], "timed_out"); + assert_eq!(envelope["error"]["kind"], "interruption"); +} + +#[test] +fn no_ready_provider_wins_over_workspace_contention_without_side_effects() { + let dir = temp_workspace(); + let base = dir.path().join("project"); + let work = dir.path().join("work"); + let config = dir.path().join("v8project.yaml"); + let platform = dir.path().join("empty-platform"); + fs::create_dir_all(&base).expect("base"); + fs::create_dir_all(&platform).expect("platform"); + fs::write( + &config, + format!( + "workPath: '{}'\nformat: DESIGNER\nbuilder: IBCMD\ninfobase:\n connection: 'File=/tmp/ib'\nsource-set: []\ntools:\n platform:\n path: '{}'\n strict: true\n version: '8.3.27'\n", + work.display(), + platform.display() + ), + ) + .expect("config"); + hold_workspace_lock(&work); + let output = base.join("dist/main.cf"); + + let command = v8_runner_command() + .args([ + "--config", + &config.display().to_string(), + "--json-message", + "infobase", + "configuration", + "export", + "--state", + "working", + "--output", + &output.display().to_string(), + ]) + .output() + .expect("run export"); + + assert_eq!(command.status.code(), Some(2)); + let envelope: Value = serde_json::from_slice(&command.stdout).expect("json envelope"); + assert_eq!(envelope["error"]["code"], "environment_unavailable"); + assert_eq!(envelope["error"]["kind"], "environment"); + assert!(!output.parent().expect("output parent").exists()); + assert!(!work.join("platform-logs").exists()); + assert!( + !work.join("logs/mcp/actions.log").exists(), + "selection failure must not create the JSON action log" + ); +} diff --git a/tests/cli_infobase_cross_platform.rs b/tests/cli_infobase_cross_platform.rs new file mode 100644 index 000000000..68c0ce65c --- /dev/null +++ b/tests/cli_infobase_cross_platform.rs @@ -0,0 +1,178 @@ +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +use serde_json::Value; +use tempfile::tempdir; + +fn compile_fake_designer(target_dir: &Path) -> PathBuf { + fs::create_dir_all(target_dir).expect("platform dir"); + let target = target_dir.join(format!("1cv8{}", std::env::consts::EXE_SUFFIX)); + let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/fake_platform.rs"); + let compile = Command::new("rustc") + .arg("--edition=2021") + .arg(&source) + .arg("-o") + .arg(&target) + .output() + .expect("run rustc for fake platform"); + assert!( + compile.status.success(), + "failed to compile {}: {}", + source.display(), + String::from_utf8_lossy(&compile.stderr) + ); + + target +} + +fn write_config(root: &Path, platform: &Path) -> PathBuf { + let project = root.join("project"); + let work = root.join("work"); + let infobase = root.join("ib"); + fs::create_dir_all(&project).expect("project"); + fs::create_dir_all(&work).expect("work"); + fs::create_dir_all(&infobase).expect("infobase"); + fs::write(infobase.join("1Cv8.1CD"), "database").expect("infobase file"); + let config = root.join("v8project.yaml"); + fs::write( + &config, + format!( + "workPath: '{}'\nformat: DESIGNER\nbuilder: DESIGNER\ninfobase:\n connection: 'File={}'\nsource-set: []\ntools:\n platform:\n path: '{}'\n", + work.display(), + infobase.display(), + platform.display(), + ), + ) + .expect("config"); + config +} + +fn run_json(config: &Path, arguments: &[&str]) -> Value { + let output = Command::new(env!("CARGO_BIN_EXE_v8-runner")) + .arg("--config") + .arg(config) + .arg("--json-message") + .args(arguments) + .output() + .expect("run v8-runner"); + assert!( + output.status.success(), + "stdout={} stderr={}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("JSON envelope") +} + +fn wait_for_file(path: &Path) { + let deadline = Instant::now() + Duration::from_secs(10); + while !path.is_file() { + assert!( + Instant::now() < deadline, + "timed out waiting for {}", + path.display() + ); + thread::sleep(Duration::from_millis(25)); + } +} + +#[test] +fn designer_configuration_and_dt_exports_publish_through_native_cli() { + let root = tempdir().expect("tempdir"); + let platform = compile_fake_designer(&root.path().join("platform")); + let config = write_config(root.path(), &platform); + let cfe = root.path().join("project/dist/sales.cfe"); + let dt = root.path().join("project/dist/base.dt"); + + let cfe_json = run_json( + &config, + &[ + "infobase", + "configuration", + "export", + "--state", + "database", + "--extension", + "Sales", + "--output", + cfe.to_str().expect("cfe path"), + ], + ); + assert_eq!(cfe_json["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(cfe_json["data"]["artifact_kind"], "cfe"); + assert_eq!(cfe_json["data"]["published"], true); + assert_eq!(fs::read(&cfe).expect("published CFE"), b"payload"); + + let dt_json = run_json( + &config, + &[ + "infobase", + "dump", + "--output", + dt.to_str().expect("dt path"), + ], + ); + assert_eq!(dt_json["data"]["selection"]["provider"], "designer-batch"); + assert_eq!(dt_json["data"]["artifact_kind"], "dt"); + assert_eq!(dt_json["data"]["published"], true); + assert_eq!(fs::read(&dt).expect("published DT"), b"payload"); +} + +#[test] +fn concurrent_native_cli_processes_observe_the_workspace_lock() { + let root = tempdir().expect("tempdir"); + let platform = compile_fake_designer(&root.path().join("platform")); + let config = write_config(root.path(), &platform); + let ready = root.path().join("first-platform.ready"); + let release = root.path().join("first-platform.release"); + let first_dt = root.path().join("project/dist/first.dt"); + let second_dt = root.path().join("project/dist/second.dt"); + + let first = Command::new(env!("CARGO_BIN_EXE_v8-runner")) + .arg("--config") + .arg(&config) + .arg("--json-message") + .args(["infobase", "dump", "--output"]) + .arg(&first_dt) + .env("V8_RUNNER_FAKE_PLATFORM_READY", &ready) + .env("V8_RUNNER_FAKE_PLATFORM_RELEASE", &release) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn first v8-runner"); + wait_for_file(&ready); + + let second = Command::new(env!("CARGO_BIN_EXE_v8-runner")) + .arg("--config") + .arg(&config) + .arg("--json-message") + .args(["infobase", "dump", "--output"]) + .arg(&second_dt) + .output() + .expect("run contending v8-runner"); + fs::write(&release, b"release").expect("release first fake platform"); + assert!(!second.status.success(), "contender unexpectedly succeeded"); + let contender: Value = serde_json::from_slice(&second.stdout).unwrap_or_else(|error| { + panic!( + "invalid contender JSON ({error}): stdout={} stderr={}", + String::from_utf8_lossy(&second.stdout), + String::from_utf8_lossy(&second.stderr) + ) + }); + assert_eq!(contender["error"]["code"], "workspace_busy"); + assert_eq!(contender["steps"][0]["name"], "workspace lock"); + assert_eq!(contender["steps"][0]["kind"], "prepare_workspace"); + assert!(!second_dt.exists()); + + let first_output = first.wait_with_output().expect("wait for first v8-runner"); + assert!( + first_output.status.success(), + "first v8-runner failed: stdout={} stderr={}", + String::from_utf8_lossy(&first_output.stdout), + String::from_utf8_lossy(&first_output.stderr) + ); + assert_eq!(fs::read(first_dt).expect("first DT"), b"payload"); +} diff --git a/tests/support/fake_platform.rs b/tests/support/fake_platform.rs new file mode 100644 index 000000000..12a141c64 --- /dev/null +++ b/tests/support/fake_platform.rs @@ -0,0 +1,49 @@ +use std::path::Path; +use std::time::{Duration, Instant}; + +fn main() { + let arguments = std::env::args_os().skip(1).collect::>(); + let mut output = None; + let mut platform_log = None; + + for pair in arguments.windows(2) { + let option = pair[0].to_string_lossy(); + if matches!(option.as_ref(), "/DumpCfg" | "/DumpDBCfg" | "/DumpIB") { + output = Some(pair[1].as_os_str()); + } else if option == "/Out" { + platform_log = Some(pair[1].as_os_str()); + } + } + + let Some(output) = output else { + eprintln!("fake platform did not receive a supported export target"); + std::process::exit(2); + }; + + if let Some(ready_path) = std::env::var_os("V8_RUNNER_FAKE_PLATFORM_READY") { + write_artifact(Path::new(&ready_path), b"ready"); + } + if let Some(release_path) = std::env::var_os("V8_RUNNER_FAKE_PLATFORM_RELEASE") { + let release_path = Path::new(&release_path); + let deadline = Instant::now() + Duration::from_secs(30); + while !release_path.is_file() { + assert!( + Instant::now() < deadline, + "timed out waiting for fake platform release at {}", + release_path.display() + ); + std::thread::sleep(Duration::from_millis(10)); + } + } + write_artifact(Path::new(output), b"payload"); + if let Some(platform_log) = platform_log { + write_artifact(Path::new(platform_log), b"platform log"); + } +} + +fn write_artifact(path: &Path, contents: &[u8]) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create artifact parent"); + } + std::fs::write(path, contents).expect("write fake platform artifact"); +}