diff --git a/.gitea/actions/kaniko-push/Dockerfile b/.gitea/actions/kaniko-push/Dockerfile new file mode 100644 index 0000000..f43c97c --- /dev/null +++ b/.gitea/actions/kaniko-push/Dockerfile @@ -0,0 +1,4 @@ +FROM ghcr.io/osscontainertools/kaniko:v1.28.5-debug@sha256:c73ca67a3b494bce79a8fb6090c4f73c18997ab272d80bffc460a62343aeb412 +COPY release-build.sh /usr/local/bin/release-build +COPY validate-destination.sh /usr/local/bin/validate-destination.sh +ENTRYPOINT ["/busybox/sh", "/usr/local/bin/release-build"] diff --git a/.gitea/actions/kaniko-push/action.yml b/.gitea/actions/kaniko-push/action.yml new file mode 100644 index 0000000..e98525b --- /dev/null +++ b/.gitea/actions/kaniko-push/action.yml @@ -0,0 +1,23 @@ +name: Publish a pinned Akyldash image +description: Build and push one commit-tagged image with pinned rootless Kaniko +inputs: + workspace: + description: Checked out source directory + required: true + dockerfile: + description: Dockerfile path relative to workspace + required: true + destination: + description: Commit-specific OCI tag + required: true + digest_file: + description: Workspace path for Kaniko's resulting digest + required: true +runs: + using: docker + image: Dockerfile + args: + - ${{ inputs.workspace }} + - ${{ inputs.dockerfile }} + - ${{ inputs.destination }} + - ${{ inputs.digest_file }} diff --git a/.gitea/actions/kaniko-push/release-build.sh b/.gitea/actions/kaniko-push/release-build.sh new file mode 100644 index 0000000..bc56aeb --- /dev/null +++ b/.gitea/actions/kaniko-push/release-build.sh @@ -0,0 +1,22 @@ +#!/busybox/sh +set -eu + +workspace=$1 +dockerfile=$2 +destination=$3 +digest_file=$4 +: "${REGISTRY_USERNAME:?registry username secret is required}" +: "${REGISTRY_PASSWORD:?registry password secret is required}" +/busybox/sh /usr/local/bin/validate-destination.sh "$dockerfile" "$destination" + +mkdir -p /kaniko/.docker "$(dirname "$digest_file")" +auth=$(printf '%s:%s' "$REGISTRY_USERNAME" "$REGISTRY_PASSWORD" | base64 | tr -d '\n') +umask 077 +printf '{"auths":{"git.vakanaut.ru":{"auth":"%s"}}}\n' "$auth" > /kaniko/.docker/config.json +unset auth REGISTRY_USERNAME REGISTRY_PASSWORD +/kaniko/executor \ + --context="dir://${workspace}" \ + --dockerfile="${workspace}/${dockerfile}" \ + --destination="$destination" \ + --digest-file="$digest_file" \ + --no-push-cache diff --git a/.gitea/actions/kaniko-push/validate-destination.sh b/.gitea/actions/kaniko-push/validate-destination.sh new file mode 100644 index 0000000..8650f41 --- /dev/null +++ b/.gitea/actions/kaniko-push/validate-destination.sh @@ -0,0 +1,49 @@ +#!/bin/sh +set -eu + +if [ "$#" -ne 2 ]; then + echo 'ERROR: expected Dockerfile path and image destination' >&2 + exit 2 +fi + +dockerfile=$1 +destination=$2 +case "$dockerfile" in + deploy/production/Dockerfile.backend) + repository=git.vakanaut.ru/admin/akyldash/backend + ;; + deploy/production/Dockerfile.opensearch) + repository=git.vakanaut.ru/admin/akyldash/opensearch + ;; + *) + echo 'ERROR: Dockerfile is outside the approved production image set' >&2 + exit 2 + ;; +esac + +case "$destination" in + "$repository":*) tag=${destination#"$repository":} ;; + *) + echo 'ERROR: destination is outside the approved registry repository' >&2 + exit 2 + ;; +esac + +commit=${tag%%-*} +run_id=${tag#*-} +case "$commit" in + ''|*[!0123456789abcdef]*) + echo 'ERROR: destination commit must be a lowercase Git SHA-1' >&2 + exit 2 + ;; +esac +if [ "${#commit}" -ne 40 ] || [ "$run_id" = "$tag" ]; then + echo 'ERROR: destination tag must contain a 40-character commit and run ID' >&2 + exit 2 +fi +case "$run_id" in + ''|*[!0123456789]*) + echo 'ERROR: destination run ID must be numeric' >&2 + exit 2 + ;; +esac diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 2bd50f4..6638e57 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -44,6 +44,7 @@ jobs: infra/bootstrap/verify.sh infra/bootstrap/verify-helper.sh infra/bootstrap/audit-host.sh \ infra/deploy/install-helper.sh infra/deploy/compose-helper.sh infra/deploy/test-compose-helper.sh \ infra/deploy/prepare-production-config.sh infra/deploy/test-production-config-guard.sh \ + .gitea/actions/kaniko-push/release-build.sh \ infra/bootstrap/test-audit-host.sh infra/bootstrap/test-root-guard.sh \ infra/bootstrap/test-verify-helper.sh infra/test/run-as-unprivileged.sh \ infra/runner/install-runner.sh infra/runner/install-runner-lib.sh \ @@ -52,6 +53,12 @@ jobs: infra/runner/test-ci-container-builds.sh python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/runner/secure-runner-image.py').read_text())" python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/validate_release.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/deploy_release.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/create_release_manifest.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/release_handoff.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/release_refs.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/release_state.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/deployment_lock.py').read_text())" - name: Run deployment contract and rollback tests run: python3 -m unittest discover -s infra/deploy -p 'test_*.py' -v - name: Validate production Compose and Caddyfile @@ -75,3 +82,14 @@ jobs: workspace: ${{ github.workspace }} dockerfile: deploy/production/Dockerfile.opensearch destination: akyldash-opensearch:ci + - name: Prepare a synthetic artifact compatibility marker + run: | + mkdir -p artifact-smoke + printf 'Gitea artifact upload smoke test; no release data.\n' > artifact-smoke/marker.txt + - name: Verify Gitea runtime artifact upload + uses: https://gitea.com/actions/gitea-upload-artifact@055b8b3f04a4a7ed853f2c6ab04256f83e4874dc + with: + name: artifact-smoke-${{ github.run_id }} + path: artifact-smoke/marker.txt + if-no-files-found: error + retention-days: 1 diff --git a/.gitea/workflows/deploy-handoff.yaml b/.gitea/workflows/deploy-handoff.yaml new file mode 100644 index 0000000..b187581 --- /dev/null +++ b/.gitea/workflows/deploy-handoff.yaml @@ -0,0 +1,64 @@ +name: Production handoff status (not deployed) + +on: + workflow_run: + workflows: ["Release production images"] + branches: [main] + types: [completed] + +jobs: + deployment-status: + name: NOT DEPLOYED - handoff status only + if: >- + gitea.event.workflow_run.conclusion == 'success' && + gitea.event.workflow_run.event == 'workflow_run' && + gitea.event.workflow_run.head_branch == 'main' + runs-on: akyldash-ci + steps: + - uses: actions/checkout@v4 + with: + ref: main + - name: Verify source release identity before artifact lookup + env: + SOURCE_WORKFLOW: ${{ gitea.event.workflow.name }} + SOURCE_WORKFLOW_PATH: ${{ gitea.event.workflow_run.path }} + SOURCE_EVENT: ${{ gitea.event.workflow_run.event }} + SOURCE_CONCLUSION: ${{ gitea.event.workflow_run.conclusion }} + SOURCE_BRANCH: ${{ gitea.event.workflow_run.head_branch }} + SOURCE_RUN_ID: ${{ gitea.event.workflow_run.id }} + SOURCE_SHA: ${{ gitea.event.workflow_run.head_sha }} + SOURCE_REPOSITORY: ${{ gitea.event.repository.full_name }} + run: python3 infra/deploy/release_handoff.py validate-handoff-source + - name: Read artifact metadata with the installed Gitea helper when available + env: + GITEA_URL: ${{ gitea.server_url }} + GITEA_TOKEN: ${{ gitea.token }} + SOURCE_RUN_ID: ${{ gitea.event.workflow_run.id }} + SOURCE_WORKFLOW: ${{ gitea.event.workflow.name }} + SOURCE_WORKFLOW_PATH: ${{ gitea.event.workflow_run.path }} + SOURCE_EVENT: ${{ gitea.event.workflow_run.event }} + SOURCE_CONCLUSION: ${{ gitea.event.workflow_run.conclusion }} + SOURCE_BRANCH: ${{ gitea.event.workflow_run.head_branch }} + SOURCE_SHA: ${{ gitea.event.workflow_run.head_sha }} + SOURCE_REPOSITORY: ${{ gitea.event.repository.full_name }} + run: | + if ! command -v gitea-api >/dev/null 2>&1; then + echo 'DRY-RUN only: gitea-api is unavailable in this job; artifact metadata and host handoff are not verified.' + python3 infra/deploy/release_handoff.py dry-run + exit 0 + fi + if [[ -z ${GITEA_TOKEN:-} ]]; then + echo 'DRY-RUN only: GITEA_TOKEN is unavailable; artifact metadata and host handoff are not verified.' + python3 infra/deploy/release_handoff.py dry-run + exit 0 + fi + metadata=$(mktemp) + trap 'rm -f "$metadata"' EXIT + gitea-api GET "/repos/admin/akyldash/actions/runs/${SOURCE_RUN_ID}/artifacts" > "$metadata" + python3 infra/deploy/release_handoff.py dry-run --artifact-metadata "$metadata" + - name: State that no deployment was performed + run: | + echo 'DEPLOYMENT STATUS: NOT DEPLOYED' + echo 'This workflow checks source provenance and may inspect artifact metadata only.' + echo 'It does not download the descriptor ZIP, open SSH, or invoke the Windows receiver.' + echo 'No Windows execution runner or automatic runtime binding has been verified.' diff --git a/.gitea/workflows/release-images.yaml b/.gitea/workflows/release-images.yaml new file mode 100644 index 0000000..866e4f9 --- /dev/null +++ b/.gitea/workflows/release-images.yaml @@ -0,0 +1,90 @@ +name: Release production images + +on: + workflow_run: + workflows: ["CI"] + branches: [main] + types: [completed] + +jobs: + publish-images: + if: >- + gitea.event.workflow_run.conclusion == 'success' && + gitea.event.workflow_run.event == 'push' && + gitea.event.workflow_run.head_branch == 'main' + runs-on: akyldash-ci + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ gitea.event.workflow_run.head_sha }} + - name: Verify successful CI source before using registry credentials + env: + SOURCE_WORKFLOW: ${{ gitea.event.workflow.name }} + SOURCE_WORKFLOW_PATH: ${{ gitea.event.workflow_run.path }} + SOURCE_EVENT: ${{ gitea.event.workflow_run.event }} + SOURCE_CONCLUSION: ${{ gitea.event.workflow_run.conclusion }} + SOURCE_BRANCH: ${{ gitea.event.workflow_run.head_branch }} + SOURCE_RUN_ID: ${{ gitea.event.workflow_run.id }} + SOURCE_SHA: ${{ gitea.event.workflow_run.head_sha }} + SOURCE_REPOSITORY: ${{ gitea.event.repository.full_name }} + run: python3 infra/deploy/release_handoff.py validate-ci-source + - name: Require explicitly configured Gitea registry credentials + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + run: | + test -n "$REGISTRY_USERNAME" || { echo 'REGISTRY_USERNAME repository secret is required'; exit 1; } + test -n "$REGISTRY_PASSWORD" || { echo 'REGISTRY_PASSWORD repository secret is required'; exit 1; } + - name: Build and publish backend image + uses: ./.gitea/actions/kaniko-push + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + with: + workspace: ${{ github.workspace }} + dockerfile: deploy/production/Dockerfile.backend + destination: git.vakanaut.ru/admin/akyldash/backend:${{ gitea.event.workflow_run.head_sha }}-${{ gitea.run_id }} + digest_file: ${{ github.workspace }}/release/backend.digest + - name: Build and publish OpenSearch image + uses: ./.gitea/actions/kaniko-push + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + with: + workspace: ${{ github.workspace }} + dockerfile: deploy/production/Dockerfile.opensearch + destination: git.vakanaut.ru/admin/akyldash/opensearch:${{ gitea.event.workflow_run.head_sha }}-${{ gitea.run_id }} + digest_file: ${{ github.workspace }}/release/opensearch.digest + - name: Create and validate release descriptor + run: | + python3 infra/deploy/create_release_manifest.py \ + --repository admin/akyldash \ + --commit '${{ gitea.event.workflow_run.head_sha }}' \ + --run-id '${{ gitea.run_id }}' \ + --source-run-id '${{ gitea.event.workflow_run.id }}' \ + --backend-digest release/backend.digest \ + --opensearch-digest release/opensearch.digest \ + --output release/release-manifest.json + python3 infra/deploy/validate_release.py release/release-manifest.json \ + --policy infra/deploy/release-policy.json + (cd release && sha256sum release-manifest.json > release-manifest.json.sha256) + - id: descriptor + name: Record release descriptor digest + run: | + (cd release && sha256sum -c release-manifest.json.sha256) + digest=$(sha256sum release/release-manifest.json) + digest=${digest%% *} + printf 'descriptor_sha256=%s\n' "$digest" >> "$GITEA_OUTPUT" + - name: Upload verified release descriptor + uses: https://gitea.com/actions/gitea-upload-artifact@055b8b3f04a4a7ed853f2c6ab04256f83e4874dc + with: + name: release-descriptor-${{ gitea.run_id }}-${{ steps.descriptor.outputs.descriptor_sha256 }} + path: | + release/release-manifest.json + release/release-manifest.json.sha256 + if-no-files-found: error + retention-days: 90 + - name: Confirm uploaded release descriptor + run: | + (cd release && sha256sum -c release-manifest.json.sha256) + echo 'Release descriptor and checksum are available as this run artifact.' diff --git a/AGENTS.md b/AGENTS.md index 57bd1a1..0c36664 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,11 @@ # Акылдаш — инструкции для агента Проект: юридическая информационно-аналитическая платформа; Search API на -Python, SQLite и OpenSearch. Production пока не развернут. +Python, SQLite и OpenSearch. На 2026-10-25 публичный `/review` и прямой origin +отвечают HTTP 200; состав production-контейнеров, готовность индекса и +проверенность backup/restore не подтверждены. Сверяй актуальное состояние с +[`CURRENT_STATE.md`](docs/operations/CURRENT_STATE.md), не считай HTTP 200 +доказательством готовности поиска. - Начинай с [инфраструктурного состояния](docs/operations/CURRENT_STATE.md) и [правил доступа](docs/operations/ACCESS.md). Не запрашивай доступы повторно. diff --git a/CHANGELOG.md b/CHANGELOG.md index c9b3ac1..ba995b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ ## Не выпущено +- Успешный CI на `push` в `main` запускает release workflow: при настроенных + registry secrets он собирает образы rootless Kaniko, публикует digest + references и сохраняет schema-v4 descriptor с SHA-256 в Gitea artifact; + sidecar проверяется после извлечения из корня. Следующий workflow проверяет + source-run identity и, при доступном `gitea-api`, метаданные артефакта только + в dry-run и явно сообщает `NOT DEPLOYED`: ZIP не скачивается, SSH и host + apply не выполняются. Добавлена отдельная root-verified status→fixed-tuple→ + Windows `--once` привязка через строгий SSH dispatcher; она не использует + Gitea/PR runner и не требует Gitea token на Windows. Config и Task Scheduler + template выключены, задача не зарегистрирована и production CD не активирован. + Зелёный handoff не означает деплой. Подготовлены owner-run cutover и rollback с + проверкой backup, image IDs, RU/KY canaries и recovery journal; CI проверяет + synthetic artifact и завершается ошибкой при отсутствии файлов. Windows + receiver прошёл 17 synthetic client checks, 8 protocol checks и проверку + private owner ACL на disposable real-NTFS fixture. Inert Windows argv probe + подтвердил передачу пути скрипта с пробелами; Task Scheduler COM проверил + XML с `TASK_VALIDATE_ONLY` — задачу не регистрировали, не обновляли и не + запускали. Production D: path, SSH, установка на VPS и полный backup/restore + не проверены; cutover остаётся заблокирован до отдельного restore-теста и + owner bootstrap. Принимаются только завершённые успешные Gitea runs; pending + recovery journal записывается до остановки + сервисов, повторно применённый release отклоняется до простоя, а проверка + `main` использует явно заданный production checkout. Windows preflight + проверяет owner ACL и требует свободное место под максимальный допустимый + архив. - Frontend `0.3.3` / Backend `0.13.2`: управление пользователями отображается согласно правам аккаунта, подписи ролей локализованы, повторяющиеся действия кабинета убраны, а знак лаборатории приведён к основному бренду. diff --git a/backend/README.md b/backend/README.md index 0aae543..d7e7e88 100644 --- a/backend/README.md +++ b/backend/README.md @@ -171,16 +171,31 @@ python3 backend/search/minjust_opensearch.py \ После проверки production-индекса следует переключать alias, чтобы удалённые фрагменты не оставались в поиске. -Чтобы переключить alias атомарно только после успешной полной загрузки, -передайте `--alias`: +Alias переключается только после refresh, точного сравнения полного fragment +count с inventory, обеих языковых canary-проверок и совпадения ожидаемого +текущего индекса. Перед cutover обязательно укажите RU/KY запросы и точное имя +старого target: ```bash python3 backend/search/minjust_opensearch.py \ --url http://127.0.0.1:9200 \ --index akyldash-fragments-v2 \ - --alias akyldash-fragments-current + --alias akyldash-fragments-current \ + --expected-old-index akyldash-fragments-v1 \ + --canary-ru 'утверждённый русский запрос' \ + --canary-ky 'бекитилген кыргызча суроо' ``` +Wildcard removal, пустой индекс и alias с несколькими target запрещены. Если +старый target успел измениться после проверки, OpenSearch отклонит атомарную +операцию удаления точного старого alias. `--resume` повторно проверяет весь +ожидаемый inventory, а не только количество документов текущего запуска. +Если ответ на alias request потерян после успешного переключения или процесс +остановился до записи завершённого checkpoint, повторный запуск проверит +фактическую цель alias. Уже опубликованный candidate оставляется на месте, и +checkpoint завершается; старый target позволяет безопасно повторить cutover, +а любой другой target останавливает операцию. + После каждого принятого Bulk-пакета загрузчик атомарно сохраняет checkpoint и печатает код безопасного возобновления. При временных HTTP 429/5xx, timeout и обрыве соединения запрос повторяется автоматически. Прерванную загрузку можно diff --git a/backend/search/minjust_opensearch.py b/backend/search/minjust_opensearch.py index 078fa57..0e67b8d 100644 --- a/backend/search/minjust_opensearch.py +++ b/backend/search/minjust_opensearch.py @@ -17,7 +17,7 @@ from typing import Iterator from search.catalog import authority_codes, legal_force_code, source_code -APP_VERSION = "0.13.2" +APP_VERSION = "0.13.3" LANGUAGES = {"ru", "ky"} DEFAULT_MAPPING = Path(__file__).with_name("minjust-fragments-index.json") @@ -342,10 +342,17 @@ def load_bulk( resume: bool = False, checkpoint: Path = Path("data/opensearch/minjust-fragments.checkpoint.json"), alias: str | None = None, + expected_old_index: str | None = None, + canary_ru: str | None = None, + canary_ky: str | None = None, ) -> tuple[int, int]: base = url.rstrip("/") if alias is not None and (not alias or alias == index): raise ValueError("--alias must differ from --index") + if alias is not None and (not expected_old_index or expected_old_index == index): + raise ValueError("alias publication requires an exact --expected-old-index") + if alias is not None and (not canary_ru or not canary_ky): + raise ValueError("alias publication requires both Russian and Kyrgyz canary queries") index_url = f"{base}/{urllib.parse.quote(index, safe='')}" if resume: cluster_uuid, index_uuid = opensearch_identity(base, index, index_url) @@ -364,6 +371,7 @@ def load_bulk( alias, ) documents = document_count(input_root, limit, start_at) + expected_fragments = sum(1 for _ in bulk_pairs(input_root, index, limit)) if alias else None if not resume: write_json_atomic(checkpoint, state) fragments = 0 @@ -398,27 +406,100 @@ def load_bulk( write_json_atomic(checkpoint, state) print(f"checkpoint={last_code} fragments={fragments}", flush=True) if alias: - switch_alias(base, index, alias) + if not expected_fragments: + raise ValueError("refusing to publish an index with an empty expected fragment inventory") + validate_candidate_index(base, index, expected_fragments, canary_ru, canary_ky) + switch_alias(base, index, alias, expected_old_index) state["complete"] = True write_json_atomic(checkpoint, state) return documents, fragments -def switch_alias(base: str, index: str, alias: str) -> None: +def alias_target(base: str, alias: str) -> str: + alias_url = f"{base.rstrip('/')}/_alias/{urllib.parse.quote(alias, safe='')}" + try: + result = request_json(alias_url, "GET", None, "application/json") + except RuntimeError as error: + if "failed with HTTP 404:" in str(error): + raise ValueError(f"alias {alias} has no current target; explicit bootstrap is required") from error + raise + if not isinstance(result, dict) or len(result) != 1: + raise ValueError(f"alias {alias} must point to exactly one index") + target, definition = next(iter(result.items())) + if not isinstance(definition, dict) or alias not in definition.get("aliases", {}): + raise ValueError(f"alias {alias} response is malformed") + return target + + +def validate_candidate_index( + base: str, index: str, expected_fragments: int, canary_ru: str, canary_ky: str +) -> None: + if expected_fragments <= 0: + raise ValueError("expected fragment count must be positive") + encoded_index = urllib.parse.quote(index, safe='') + refreshed = request_json(f"{base.rstrip('/')}/{encoded_index}/_refresh", "POST", None, "application/json") + shards = refreshed.get("_shards", {}) + if not isinstance(shards, dict) or shards.get("failed") != 0: + raise RuntimeError(f"refresh failed for candidate index {index}") + count_result = request_json(f"{base.rstrip('/')}/{encoded_index}/_count", "GET", None, "application/json") + if count_result.get("count") != expected_fragments: + raise RuntimeError( + f"candidate index {index} has {count_result.get('count')} fragments; expected {expected_fragments}" + ) + for language, query in (("ru", canary_ru), ("ky", canary_ky)): + payload = json.dumps({"size": 1, "query": {"match": {f"text_{language}": query}}}).encode() + result = request_json( + f"{base.rstrip('/')}/{encoded_index}/_search", "POST", payload, "application/json" + ) + hits = result.get("hits", {}).get("hits", []) + if not hits or not isinstance(hits[0].get("_source", {}).get(f"text_{language}"), str): + raise RuntimeError(f"candidate index {index} failed the {language} canary query") + + +def switch_alias(base: str, index: str, alias: str, expected_old_index: str) -> None: if not alias or alias == index: raise ValueError("--alias must differ from --index") - result = request_json( - f"{base.rstrip('/')}/_aliases", - "POST", - json.dumps({ - "actions": [ - {"remove": {"index": "*", "alias": alias, "must_exist": False}}, - {"add": {"index": index, "alias": alias}}, - ] - }).encode(), - "application/json", - ) - if result.get("acknowledged") is not True: + if not expected_old_index or expected_old_index == index: + raise ValueError("--expected-old-index must name the exact previous index") + actual_old_index = alias_target(base, alias) + if actual_old_index == index: + return + if actual_old_index != expected_old_index: + raise ValueError( + f"alias {alias} currently targets {actual_old_index}, expected {expected_old_index}; refusing cutover" + ) + try: + result = request_json( + f"{base.rstrip('/')}/_aliases", + "POST", + json.dumps({ + "actions": [ + {"remove": {"index": expected_old_index, "alias": alias, "must_exist": True}}, + {"add": {"index": index, "alias": alias}}, + ] + }).encode(), + "application/json", + ) + except Exception as error: + try: + current = alias_target(base, alias) + except Exception: + raise RuntimeError(f"alias switch outcome is unknown; inspect {alias} before resuming") from error + if current == index: + return + if current != expected_old_index: + raise ValueError( + f"alias {alias} now targets unexpected index {current}; refusing to retry publication" + ) from error + raise RuntimeError(f"alias switch failed; {alias} still targets {expected_old_index}") from error + if not isinstance(result, dict) or result.get("acknowledged") is not True: + current = alias_target(base, alias) + if current == index: + return + if current != expected_old_index: + raise ValueError( + f"alias {alias} now targets unexpected index {current}; refusing to retry publication" + ) raise RuntimeError(f"OpenSearch did not acknowledge alias switch: {alias}") @@ -430,6 +511,9 @@ def main() -> int: parser.add_argument("--limit", type=int) parser.add_argument("--url", help="create the index and stream bounded Bulk requests instead of writing a file") parser.add_argument("--alias", help="atomically point this alias at --index after a successful load") + parser.add_argument("--expected-old-index", help="exact current alias target required for guarded cutover") + parser.add_argument("--canary-ru", help="approved Russian query that must match the candidate index") + parser.add_argument("--canary-ky", help="approved Kyrgyz query that must match the candidate index") parser.add_argument("--mapping", type=Path, default=DEFAULT_MAPPING) parser.add_argument("--batch-mb", type=int, default=25) parser.add_argument("--resume", action="store_true", help="load into an existing index") @@ -460,6 +544,9 @@ def main() -> int: arguments.resume, checkpoint, arguments.alias, + arguments.expected_old_index, + arguments.canary_ru, + arguments.canary_ky, ) destination = arguments.url else: diff --git a/backend/search/review.html b/backend/search/review.html index 4caffca..d38c2c4 100644 --- a/backend/search/review.html +++ b/backend/search/review.html @@ -657,7 +657,7 @@

Документ

Выберите документ в выдаче, чтобы открыть текст.

Содержание
- +

Черновик появится после поиска.

Вход в Акылдаш

Введите учетные данные, выданные администратором.

Создайте новый пароль

Для продолжения замените временный пароль. Используйте не менее 12 символов.

@@ -675,7 +675,7 @@

Документ

Источники документов

Поиск выполняется по документам, подготовленным из правовых источников Кыргызской Республики. Для каждого результата доступная редакция и ссылка на официальный источник показываются в панели документа.

Официальный источник: Централизованный банк данных правовой информации Министерства юстиции Кыргызской Республики.

Короткое знакомство

- +