From 1b8c6d87590be1a16120069bd551811f1d09e338 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Tue, 17 Nov 2026 11:51:11 +0100 Subject: [PATCH 1/9] feat: add infrahubctl storage encrypt for files stored before encryption was enabled Files stored before storage encryption was enabled stay in plaintext, and an operator has no way to encrypt them. The new command encrypts them through the storage routes of the Infrahub server, which holds the key. The key never reaches the machine that runs the command. The command lists the stored objects, counts them, and sends them in batches of 50 with an adaptive number of batches in flight. It shows done out of total, the percentage and the time remaining. It waits on 429 answers, retries network errors, and keeps a state file, so a run stopped with Ctrl-C, SIGTERM or a kill resumes where it stopped. Objects that were not encrypted are listed in a report file. It needs an Infrahub server that has the storage encryption routes, so it targets infrahub-develop. Signed-off-by: Simon AURA--SCUSSEL --- changelog/+storage-encrypt.added.md | 1 + dev/knowledge/cli-architecture.md | 2 +- docs/docs/infrahubctl/infrahubctl-storage.mdx | 74 + infrahub_sdk/ctl/cli_commands.py | 2 + infrahub_sdk/ctl/storage/__init__.py | 11 + infrahub_sdk/ctl/storage/encrypt.py | 343 ++++ infrahub_sdk/ctl/storage/migration.py | 756 +++++++ infrahub_sdk/ctl/storage/progress.py | 136 ++ tests/unit/ctl/test_storage_app.py | 739 +++++++ tests/unit/ctl/test_storage_migration.py | 1766 +++++++++++++++++ tests/unit/ctl/test_storage_progress.py | 204 ++ 11 files changed, 4033 insertions(+), 1 deletion(-) create mode 100644 changelog/+storage-encrypt.added.md create mode 100644 docs/docs/infrahubctl/infrahubctl-storage.mdx create mode 100644 infrahub_sdk/ctl/storage/__init__.py create mode 100644 infrahub_sdk/ctl/storage/encrypt.py create mode 100644 infrahub_sdk/ctl/storage/migration.py create mode 100644 infrahub_sdk/ctl/storage/progress.py create mode 100644 tests/unit/ctl/test_storage_app.py create mode 100644 tests/unit/ctl/test_storage_migration.py create mode 100644 tests/unit/ctl/test_storage_progress.py diff --git a/changelog/+storage-encrypt.added.md b/changelog/+storage-encrypt.added.md new file mode 100644 index 000000000..7c8225a59 --- /dev/null +++ b/changelog/+storage-encrypt.added.md @@ -0,0 +1 @@ +Added `infrahubctl storage encrypt`, which encrypts the files that an Infrahub server stored before storage encryption was enabled. Before it encrypts, the command lists the files still to process, so the progress line shows the number done out of the total, the percentage, the remaining time at the recent rate and the bytes done out of the total; `--no-count` skips that listing on very large installations. The command pages through the stored files, asks the server to encrypt them in batches, adapts the number of requests in flight to the server and waits when the server answers HTTP 429, and logs in again when a login with a username and password expires during a long run. It saves its position, so that a run stopped with Ctrl-C (exit code 130), SIGTERM (exit code 143) or an error can resume, and it writes a report of the files the server left unchanged. diff --git a/dev/knowledge/cli-architecture.md b/dev/knowledge/cli-architecture.md index eb3a7e6f1..0f50bb15e 100644 --- a/dev/knowledge/cli-architecture.md +++ b/dev/knowledge/cli-architecture.md @@ -11,7 +11,7 @@ The main Typer app lives in `infrahub_sdk/ctl/cli_commands.py`. It is re-exporte Commands are organized in two tiers: - **Root commands** are registered directly on the main app with `app.command()`. These are standalone operations that don't belong to a logical group (e.g. `dump`, `load`, `check`, `render`, `run`, `transform`, `protocols`, `version`, `info`). -- **Subcommand groups** are separate `AsyncTyper()` instances registered with `app.add_typer(sub_app, name="group")`. Each group lives in its own module under `infrahub_sdk/ctl/`. Current groups: `branch`, `schema`, `validate`, `repository`, `menu`, `object`, `graphql`, `task`. +- **Subcommand groups** are separate `AsyncTyper()` instances registered with `app.add_typer(sub_app, name="group")`. Each group lives in its own module under `infrahub_sdk/ctl/`. Current groups: `branch`, `schema`, `validate`, `repository`, `menu`, `object`, `graphql`, `task`, `storage`. ## Adding a new command diff --git a/docs/docs/infrahubctl/infrahubctl-storage.mdx b/docs/docs/infrahubctl/infrahubctl-storage.mdx new file mode 100644 index 000000000..c5b722bd7 --- /dev/null +++ b/docs/docs/infrahubctl/infrahubctl-storage.mdx @@ -0,0 +1,74 @@ +# `infrahubctl storage` + +Manage the files that an Infrahub server stores. + +**Usage**: + +```console +$ infrahubctl storage [OPTIONS] COMMAND [ARGS]... +``` + +**Options**: + +* `--install-completion`: Install completion for the current shell. +* `--show-completion`: Show completion for the current shell, to copy it or customize the installation. +* `--help`: Show this message and exit. + +**Commands**: + +* `encrypt`: Encrypt the stored files that were written... + +## `infrahubctl storage encrypt` + +Encrypt the stored files that were written before storage encryption was enabled. + +The command lists the stored objects page by page and asks the server, which holds the storage key, to encrypt them. + +It keeps several batches in flight, lowers that number when the server slows down, and waits when it answers HTTP 429. + +The token needs the super admin permission, and storage encryption must be enabled on the server. + +The command does its own retries, not those of the SDK client: network errors and HTTP 502, 503 and 504, up to --max-retries. + +Before it encrypts, the command lists the objects still to process, to show the total, the percent done and the remaining time. +Use --no-count to skip this pass on a very large installation; the progress then shows no total. + +The state file records the position after every page. After an error, Ctrl-C or SIGTERM, run the same command again to resume. + +Objects that the server leaves unchanged are listed in the report file, which every run appends to. +A run that resumes does not retry them, nor the objects that failed, because the saved position is past them. +A new full pass, which starts after a pass has finished, or --restart, tries them again. + +Exit codes: + 0 Every object is encrypted, was already encrypted, or was skipped by the server + 1 The server could not encrypt at least one object, or the command failed before the run + (for example on a login error, a file error or an unexpected error) + 2 The run stopped on an error from the server or on a state file or report that cannot be used + 130 The run stopped on Ctrl-C (SIGINT) + 143 The run stopped on SIGTERM + +**Usage**: + +```console +$ infrahubctl storage encrypt [OPTIONS] +``` + +**Options**: + +* `--concurrency INTEGER RANGE`: Most batches in flight at once (at most 64); the command starts lower and adapts [default: 8; 1<=x<=64] +* `--batch-size INTEGER RANGE`: Stored objects in each request to encrypt [default: 50; 1<=x<=500] +* `--page-size INTEGER RANGE`: Stored objects in each listing request [default: 5000; 1<=x<=5000] +* `--rate FLOAT RANGE`: Most requests per second (default: no maximum) [x>=0.001] +* `--priority TEXT`: Priority of the requests: high, medium or low [default: low] +* `--before [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%dT%H:%M:%S%z]`: Leave the objects modified after this time (ISO 8601; no offset means UTC) +* `--dry-run`: Only list: count the objects and their size +* `--limit INTEGER RANGE`: Stop after this number of objects [x>=1] +* `--allow-unverified`: Also encrypt the objects that no node records a checksum for +* `--state-file PATH`: Keeps the position in the listing, so a rerun resumes [default: infrahub-storage-encrypt.state.json] +* `--report PATH`: Receives one JSON line for each object that was not encrypted [default: infrahub-storage-encrypt.report.jsonl] +* `--max-retries INTEGER RANGE`: Retries of one request after a network error or HTTP 502, 503, 504 [default: 10; x>=0] +* `--timeout INTEGER RANGE`: Seconds before one request times out [default: 300; x>=1] +* `--restart`: Ignore the state file and list from the first object +* `--no-count`: Do not list the objects first to count them; the progress shows no total, percent or remaining time +* `--config-file TEXT`: [env var: INFRAHUBCTL_CONFIG; default: infrahubctl.toml] +* `--help`: Show this message and exit. diff --git a/infrahub_sdk/ctl/cli_commands.py b/infrahub_sdk/ctl/cli_commands.py index 94c1f4a80..804e4e95a 100644 --- a/infrahub_sdk/ctl/cli_commands.py +++ b/infrahub_sdk/ctl/cli_commands.py @@ -35,6 +35,7 @@ from ..ctl.repository import app as repository_app from ..ctl.repository import find_repository_config_file, get_repository_config from ..ctl.schema import app as schema_app +from ..ctl.storage import app as storage_app from ..ctl.task import app as task_app from ..ctl.telemetry import app as telemetry_app from ..ctl.transform import list_transforms @@ -81,6 +82,7 @@ app.add_typer(graphql_app, name="graphql") app.add_typer(task_app, name="task") app.add_typer(marketplace_app, name="marketplace") +app.add_typer(storage_app, name="storage") app.add_typer(telemetry_app, name="telemetry") app.add_typer(troubleshooting_app, name="troubleshooting") diff --git a/infrahub_sdk/ctl/storage/__init__.py b/infrahub_sdk/ctl/storage/__init__.py new file mode 100644 index 000000000..32340364f --- /dev/null +++ b/infrahub_sdk/ctl/storage/__init__.py @@ -0,0 +1,11 @@ +from infrahub_sdk.async_typer import AsyncTyper +from infrahub_sdk.ctl.storage.encrypt import encrypt_command + +app = AsyncTyper() + +app.command(name="encrypt")(encrypt_command) + + +@app.callback() +def callback() -> None: + """Manage the files that an Infrahub server stores.""" diff --git a/infrahub_sdk/ctl/storage/encrypt.py b/infrahub_sdk/ctl/storage/encrypt.py new file mode 100644 index 000000000..b4fe8b1b9 --- /dev/null +++ b/infrahub_sdk/ctl/storage/encrypt.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +import asyncio +import contextlib +import signal +import time +from datetime import datetime, timezone +from pathlib import Path + +import httpx +import typer +from rich.console import Console +from rich.live import Live +from rich.markup import escape +from rich.table import Table + +from ...constants import Priority +from ..client import initialize_client +from ..parameters import CONFIG_PARAM +from ..utils import catch_exception +from .migration import ( + BATCH_MAX_SIZE, + OUTCOME_FAILED, + PAGE_MAX_SIZE, + MigrationError, + Options, + StorageEncryptor, +) +from .progress import ( + ProgressView, + RateTracker, + format_bytes, + format_number, + format_percent, + progress_line, +) + +console = Console() + +DEFAULT_STATE_FILE = Path("infrahub-storage-encrypt.state.json") +DEFAULT_REPORT_FILE = Path("infrahub-storage-encrypt.report.jsonl") +CONCURRENCY_MAX = 64 +EXIT_OBJECTS_FAILED = 1 +EXIT_STOPPED = 2 +EXIT_INTERRUPTED = 130 +EXIT_TERMINATED = 143 +STOP_SIGNALS = ((signal.SIGINT, "Ctrl-C"), (signal.SIGTERM, "SIGTERM")) +PROGRESS_LINE_SECONDS = 5.0 +PROGRESS_LIVE_SECONDS = 0.5 + + +def _check_priority(value: str) -> str: + try: + return Priority(value).value + except ValueError: + raise typer.BadParameter(f"must be one of {', '.join(item.value for item in Priority)}") from None + + +def _view(encryptor: StorageEncryptor, rate: float | None) -> ProgressView: + dry = encryptor.options.dry_run + totals = encryptor.totals + return ProgressView( + done_objects=totals.objects_listed if dry else encryptor.done_objects, + total_objects=None if dry else encryptor.total_objects, + done_bytes=totals.bytes_listed if dry else encryptor.done_bytes, + total_bytes=None if dry else encryptor.total_bytes, + rate=rate, + limit=encryptor.limit.limit, + limit_maximum=encryptor.limit.maximum, + shed_429=totals.shed_429, + retries=totals.retries, + ) + + +def _done_objects(encryptor: StorageEncryptor) -> int: + return encryptor.totals.objects_listed if encryptor.options.dry_run else encryptor.done_objects + + +def _done_text(encryptor: StorageEncryptor) -> str: + """Return `done / total objects (percent)` when the total is known, otherwise the number done.""" + done = _done_objects(encryptor) + total = None if encryptor.options.dry_run else encryptor.total_objects + if total is None: + return f"{format_number(done)} objects" + return f"{format_number(done)} / {format_number(total)} objects ({format_percent(done=done, total=total)})" + + +class _Progress: + """Builds the progress line from counters, with the recent rate for the remaining time.""" + + def __init__(self, encryptor: StorageEncryptor) -> None: + self._encryptor = encryptor + self._tracker = RateTracker() + + def line(self) -> str: + encryptor = self._encryptor + if encryptor.counting: + self._tracker = RateTracker() + return f"Counting the objects to process: {format_number(encryptor.counted_objects)} so far" + self._tracker.record(now=time.monotonic(), done=_done_objects(encryptor)) + return progress_line(_view(encryptor, rate=self._tracker.rate())) + + +async def _show_progress(encryptor: StorageEncryptor) -> None: + progress = _Progress(encryptor) + if console.is_terminal: + with Live(console=console, transient=True, refresh_per_second=2) as live: + while True: + live.update(progress.line()) + await asyncio.sleep(PROGRESS_LIVE_SECONDS) + # Sample the counters twice per second so the rate has data, and print a line every PROGRESS_LINE_SECONDS. + next_print = time.monotonic() + PROGRESS_LINE_SECONDS + while True: + line = progress.line() + if time.monotonic() >= next_print: + console.print(line, highlight=False, soft_wrap=True) + next_print += PROGRESS_LINE_SECONDS + await asyncio.sleep(PROGRESS_LIVE_SECONDS) + + +async def _run_until_stopped(encryptor: StorageEncryptor, http: httpx.AsyncClient) -> str | None: + """Run the encryption; return the name of the signal that stopped it, after its work in flight was cancelled. + + Ctrl-C (SIGINT) and SIGTERM, which a container or a job runner sends, stop the run in the same way. + + Raises: + MigrationError: If the run cannot continue. + + """ + loop = asyncio.get_running_loop() + stop = asyncio.Event() + received: list[str] = [] + + def request_stop(name: str) -> None: + received.append(name) + stop.set() + + installed: list[signal.Signals] = [] + for number, name in STOP_SIGNALS: + with contextlib.suppress(NotImplementedError, RuntimeError, ValueError): + loop.add_signal_handler(number, request_stop, name) + installed.append(number) + work = asyncio.create_task(encryptor.run(http)) + waiter = asyncio.create_task(stop.wait()) + progress = asyncio.create_task(_show_progress(encryptor)) + try: + await asyncio.wait({work, waiter}, return_when=asyncio.FIRST_COMPLETED) + finally: + for number in installed: + loop.remove_signal_handler(number) + for task in (waiter, progress): + task.cancel() + if not work.done(): + work.cancel() + await asyncio.gather(waiter, progress, work, return_exceptions=True) + if work.cancelled(): + return received[0] if received else "Ctrl-C" + work.result() + return None + + +def _announce_count(encryptor: StorageEncryptor) -> None: + console.print( + f"To process: {format_number(encryptor.remaining_objects or 0)} objects " + f"({format_bytes(encryptor.remaining_bytes or 0)})", + highlight=False, + ) + if encryptor.handled_before: + console.print( + f"Already handled in earlier runs: {format_number(encryptor.handled_before)} objects", highlight=False + ) + + +def _summary_table(encryptor: StorageEncryptor, options: Options) -> Table: + totals = encryptor.totals + seconds = encryptor.seconds_this_run + handled = encryptor.handled_this_run + table = Table(show_header=False, title="Storage encryption" + (" (dry run)" if options.dry_run else "")) + table.add_row("Objects listed", str(totals.objects_listed)) + if options.dry_run: + table.add_row("Objects that would be sent", str(totals.objects_listed - totals.skipped_newer)) + table.add_row( + "Bytes that would be sent", f"{encryptor.selected_bytes} ({format_bytes(encryptor.selected_bytes)})" + ) + elif encryptor.total_objects is not None: + table.add_row("Objects to process at the start of this run", format_number(encryptor.remaining_objects or 0)) + table.add_row("Handled in earlier runs", format_number(encryptor.handled_before)) + table.add_row("Done in total", _done_text(encryptor)) + table.add_row( + "Bytes done in total", f"{format_bytes(encryptor.done_bytes)} / {format_bytes(encryptor.total_bytes or 0)}" + ) + table.add_row("Seconds counting", f"{encryptor.count_seconds_this_run:.1f}") + for outcome, count in sorted(totals.counts.items()): + table.add_row(outcome, str(count)) + if options.before: + table.add_row("Skipped, modified after --before", str(totals.skipped_newer)) + table.add_row("Bytes listed", str(totals.bytes_listed)) + table.add_row("Bytes encrypted", str(totals.bytes_encrypted)) + table.add_row("Requests", f"{totals.requests} ({totals.encrypt_requests} to encrypt a batch)") + table.add_row("Retries after errors", str(totals.retries)) + table.add_row("Answers 429", f"{totals.shed_429} ({totals.shed_429_admission} with the admission marker)") + table.add_row( + "In flight limit", + f"final {encryptor.limit.limit} of {encryptor.limit.maximum}, " + f"{encryptor.limit.decreases} decreases, {encryptor.limit.increases} increases", + ) + table.add_row("Seconds in this run", f"{seconds:.1f}") + if not options.dry_run and seconds > 0: + table.add_row("Objects per second", f"{handled / seconds:.1f}") + table.add_row("Pass finished", "yes" if encryptor.completed else "no") + return table + + +@catch_exception(console=console) +async def encrypt_command( + concurrency: int = typer.Option( + 8, + min=1, + max=CONCURRENCY_MAX, + help="Most batches in flight at once (at most 64); the command starts lower and adapts", + ), + batch_size: int = typer.Option(50, min=1, max=BATCH_MAX_SIZE, help="Stored objects in each request to encrypt"), + page_size: int = typer.Option( + PAGE_MAX_SIZE, min=1, max=PAGE_MAX_SIZE, help="Stored objects in each listing request" + ), + rate: float | None = typer.Option(None, min=0.001, help="Most requests per second (default: no maximum)"), + priority: str = typer.Option("low", callback=_check_priority, help="Priority of the requests: high, medium or low"), + before: datetime | None = typer.Option( + None, + help="Leave the objects modified after this time (ISO 8601; no offset means UTC)", + formats=["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S%z"], + ), + dry_run: bool = typer.Option(False, "--dry-run", help="Only list: count the objects and their size"), + limit: int | None = typer.Option(None, min=1, help="Stop after this number of objects"), + allow_unverified: bool = typer.Option( + False, "--allow-unverified", help="Also encrypt the objects that no node records a checksum for" + ), + state_file: Path = typer.Option(DEFAULT_STATE_FILE, help="Keeps the position in the listing, so a rerun resumes"), + report: Path = typer.Option( + DEFAULT_REPORT_FILE, help="Receives one JSON line for each object that was not encrypted" + ), + max_retries: int = typer.Option( + 10, min=0, help="Retries of one request after a network error or HTTP 502, 503, 504" + ), + timeout: int = typer.Option(300, min=1, help="Seconds before one request times out"), + restart: bool = typer.Option(False, "--restart", help="Ignore the state file and list from the first object"), + no_count: bool = typer.Option( + False, + "--no-count", + help="Do not list the objects first to count them; the progress shows no total, percent or remaining time", + ), + _: str = CONFIG_PARAM, +) -> None: + """Encrypt the stored files that were written before storage encryption was enabled. + + The command lists the stored objects page by page and asks the server, which holds the storage key, to encrypt them. + + It keeps several batches in flight, lowers that number when the server slows down, and waits when it answers HTTP 429. + + The token needs the super admin permission, and storage encryption must be enabled on the server. + + The command does its own retries, not those of the SDK client: network errors and HTTP 502, 503 and 504, up to --max-retries. + + Before it encrypts, the command lists the objects still to process, to show the total, the percent done and the remaining time. + Use --no-count to skip this pass on a very large installation; the progress then shows no total. + + The state file records the position after every page. After an error, Ctrl-C or SIGTERM, run the same command again to resume. + + Objects that the server leaves unchanged are listed in the report file, which every run appends to. + A run that resumes does not retry them, nor the objects that failed, because the saved position is past them. + A new full pass, which starts after a pass has finished, or --restart, tries them again. + + \b + Exit codes: + 0 Every object is encrypted, was already encrypted, or was skipped by the server + 1 The server could not encrypt at least one object, or the command failed before the run + (for example on a login error, a file error or an unexpected error) + 2 The run stopped on an error from the server or on a state file or report that cannot be used + 130 The run stopped on Ctrl-C (SIGINT) + 143 The run stopped on SIGTERM + """ + options = Options( + concurrency=concurrency, + batch_size=batch_size, + page_size=page_size, + rate=rate, + priority=priority, + before=before.replace(tzinfo=timezone.utc) if before and before.tzinfo is None else before, + dry_run=dry_run, + limit=limit, + allow_unverified=allow_unverified, + state_file=state_file, + report=report, + max_retries=max_retries, + restart=restart, + count=not no_count, + ) + client = initialize_client(timeout=timeout) + await client.login() + encryptor = StorageEncryptor(options=options, address=client.address) + encryptor.on_counted = lambda: _announce_count(encryptor) + encryptor.on_notice = lambda message: console.print(escape(message), highlight=False) + if client.config.password_authentication: + + async def renew_login(http: httpx.AsyncClient) -> None: + await client.login(refresh=True) + http.headers["Authorization"] = client.headers["Authorization"] + + encryptor.refresh_login = renew_login + async with httpx.AsyncClient( + base_url=client.address, + headers=client._merge_request_headers({"X-Priority": priority}), + timeout=client._build_timeout(timeout), + verify=client.config.tls_context, + **client._build_proxy_config(), + ) as http: + try: + stopped_by = await _run_until_stopped(encryptor, http) + except MigrationError as exc: + console.print(f"[red]Error: {escape(str(exc))}") + console.print(f"Done before the error: {_done_text(encryptor)}.", highlight=False) + if not dry_run and state_file.exists(): + console.print(f"Progress is saved in {escape(str(state_file))}; run the same command again to resume.") + console.print(_summary_table(encryptor, options)) + raise typer.Exit(code=EXIT_STOPPED) from exc + + console.print(_summary_table(encryptor, options)) + if dry_run and stopped_by is None: + console.print( + f"To process: {format_number(encryptor.selected_objects)} objects ({format_bytes(encryptor.selected_bytes)})", + highlight=False, + ) + if stopped_by is not None: + console.print(f"Stopped by {stopped_by}. Done: {_done_text(encryptor)}.", highlight=False) + if not dry_run and state_file.exists(): + console.print(f"Run the same command again to resume from {escape(str(state_file))}.") + else: + console.print("Nothing was saved to resume from; run the same command again to start again.") + raise typer.Exit(code=EXIT_TERMINATED if stopped_by == "SIGTERM" else EXIT_INTERRUPTED) + if not dry_run and encryptor.totals.counts: + console.print(f"Objects that were not encrypted are listed in {escape(str(report))}.") + if encryptor.totals.counts.get(OUTCOME_FAILED, 0): + raise typer.Exit(code=EXIT_OBJECTS_FAILED) diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py new file mode 100644 index 000000000..dfdf0e3e5 --- /dev/null +++ b/infrahub_sdk/ctl/storage/migration.py @@ -0,0 +1,756 @@ +from __future__ import annotations + +import asyncio +import contextlib +import json +import math +import os +import random +import time +from dataclasses import asdict, dataclass, field, fields +from datetime import datetime, timezone +from typing import TYPE_CHECKING, Any, TextIO + +import httpx + +from ...client import _should_refresh_token +from ...exceptions import Error +from ...rate_limit import RateLimitRetryHandler + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + from pathlib import Path + +LIST_PATH = "/api/storage/objects" +BATCH_PATH = "/api/storage/objects/encrypt" +OUTCOME_ENCRYPTED = "encrypted" +OUTCOME_FAILED = "failed" +RETRYABLE_STATUS_CODES = frozenset({502, 503, 504}) +HTTP_OK = 200 +HTTP_UNAUTHORIZED = 401 +HTTP_FORBIDDEN = 403 +HTTP_NOT_FOUND = 404 +HTTP_CONFLICT = 409 +HTTP_TOO_MANY_REQUESTS = 429 +ADMISSION_HEADER = "X-Infrahub-Admission" +BACKOFF_BASE_SECONDS = 0.5 +BACKOFF_MAX_SECONDS = 30.0 +BACKOFF_JITTER = 0.25 +BACKOFF_MAX_EXPONENT = 63 +RETRY_AFTER_MAX_SECONDS = 300.0 +UNANSWERED_MAX_RETRIES = 3 +SMALL_OBJECT_BYTES = 65536 +BATCH_MAX_SIZE = 500 +PAGE_MAX_SIZE = 5000 + + +class MigrationError(Exception): + """The run cannot continue: the server refused the request, or stayed unreachable.""" + + +@dataclass +class Totals: + """Counters of a run; a state file keeps them, so they add up over the runs that resume it.""" + + counts: dict[str, int] = field(default_factory=dict) + bytes_encrypted: int = 0 + bytes_listed: int = 0 + objects_listed: int = 0 + skipped_newer: int = 0 + requests: int = 0 + encrypt_requests: int = 0 + shed_429: int = 0 + shed_429_admission: int = 0 + retries: int = 0 + elapsed_seconds: float = 0.0 + limit_decreases: int = 0 + limit_increases: int = 0 + limit_final: int = 0 + bytes_handled: int = 0 + count_seconds: float = 0.0 + count_requests: int = 0 + + +@dataclass +class Options: + concurrency: int = 8 + batch_size: int = 50 + page_size: int = 5000 + rate: float | None = None + priority: str = "low" + before: datetime | None = None + dry_run: bool = False + limit: int | None = None + allow_unverified: bool = False + state_file: Path | None = None + report: Path | None = None + max_retries: int = 10 + restart: bool = False + min_concurrency: int = 1 + slow_factor: float = 2.0 + count: bool = False + + +class Pacer: + """Space the requests of every worker by the configured rate, and hold them all while the server sheds.""" + + def __init__( + self, rate: float | None, clock: Callable[[], float], sleep: Callable[[float], Awaitable[None]] + ) -> None: + self._interval = 1.0 / rate if rate else 0.0 + self._clock = clock + self._sleep = sleep + self._next_slot = 0.0 + self._paused_until = 0.0 + + async def wait(self) -> None: + """Return when the caller may send one request.""" + while True: + now = self._clock() + if now < self._paused_until: + await self._sleep(self._paused_until - now) + continue + slot = max(now, self._next_slot) + self._next_slot = slot + self._interval + if slot > now: + await self._sleep(slot - now) + if self._clock() >= self._paused_until: + return + + def pause(self, seconds: float) -> None: + """Hold every request for `seconds` from now.""" + self._paused_until = max(self._paused_until, self._clock() + seconds) + + +class AdaptiveLimit: + """Number of requests kept in flight, lowered when the server slows down or answers 429. + + The signal is the latency per unit of work of the batches, compared with the lowest smoothed value seen so + far. A signal above `slow_factor` times that floor, or a 429 answer, halves the limit (at most once per + cooldown). Otherwise the limit rises by one after every `limit` quiet requests, up to the maximum. + """ + + SMOOTHING = 0.2 + COOLDOWN_SECONDS = 2.0 + FLOOR_DRIFT_PER_SECOND = 0.005 + + def __init__(self, maximum: int, minimum: int, slow_factor: float, clock: Callable[[], float]) -> None: + self.maximum = maximum + self.minimum = max(1, min(minimum, maximum)) + self.limit = max(self.minimum, maximum // 2) + self.slow_factor = slow_factor + self._clock = clock + self._in_flight = 0 + self._condition = asyncio.Condition() + self._smoothed: float | None = None + self._floor = 0.0 + self._floor_at = 0.0 + self._quiet = 0 + self._last_decrease = float("-inf") + self.decreases = 0 + self.increases = 0 + + async def acquire(self) -> None: + async with self._condition: + await self._condition.wait_for(lambda: self._in_flight < self.limit) + self._in_flight += 1 + + async def release(self) -> None: + async with self._condition: + self._in_flight -= 1 + self._condition.notify_all() + + def _decrease(self) -> None: + now = self._clock() + if now - self._last_decrease < self.COOLDOWN_SECONDS or self.limit <= self.minimum: + return + self.limit = max(self.minimum, self.limit // 2) + self._last_decrease = now + self._quiet = 0 + self.decreases += 1 + + def shed(self) -> None: + """The server answered 429.""" + self._decrease() + + def observe(self, seconds: float) -> None: + """Record the latency per unit of work of one batch and adapt the limit.""" + if seconds <= 0: + return # A coarse clock can read 0.0; as the first sample it would set the floor to 0 for ever. + now = self._clock() + if self._smoothed is None: + self._smoothed = seconds + self._floor = seconds + else: + self._smoothed += self.SMOOTHING * (seconds - self._smoothed) + # The floor rises slowly, so one lucky sample does not make every later request look slow for ever. + drift = 1 + self.FLOOR_DRIFT_PER_SECOND * (now - self._floor_at) + self._floor = min(self._floor * drift, self._smoothed) + self._floor_at = now + if self._smoothed > self.slow_factor * self._floor: + self._decrease() + return + self._quiet += 1 + if self._quiet >= self.limit and self.limit < self.maximum: + self.limit += 1 + self._quiet = 0 + self.increases += 1 + + +def backoff_delay(attempt: int, rng: random.Random) -> float: + """Return the delay before retry number `attempt` (1 for the first): exponential, capped, with jitter.""" + delay = min(BACKOFF_MAX_SECONDS, BACKOFF_BASE_SECONDS * 2 ** min(attempt - 1, BACKOFF_MAX_EXPONENT)) + return delay * (1 + BACKOFF_JITTER * rng.random()) + + +_RETRY_AFTER_PARSER = RateLimitRetryHandler(max_retries=0, backoff_base=0.0, backoff_max=RETRY_AFTER_MAX_SECONDS) + + +def parse_retry_after(value: str | None) -> float: + """Return the seconds a `Retry-After` header asks for (delta-seconds or HTTP-date); 0 when absent or unusable.""" + if value is None: + return 0.0 + try: + seconds = float(value) + except ValueError: + return _RETRY_AFTER_PARSER.parse_retry_after(value) or 0.0 + return max(0.0, seconds) if math.isfinite(seconds) else 0.0 + + +def parse_timestamp(value: str) -> datetime: + """Parse an ISO 8601 timestamp; one without an offset is read as UTC.""" + text = value[:-1] + "+00:00" if value.endswith(("Z", "z")) else value + parsed = datetime.fromisoformat(text) + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + +class StorageEncryptor: + """Page through the stored objects and have the server encrypt them in batches, at a pace the server accepts. + + The requests go through one `httpx.AsyncClient`, so every request reuses a pooled connection. The client + answers 429 itself, without the retries of the SDK client, so that every 429 reaches the adaptive limit. + """ + + def __init__( + self, + options: Options, + address: str, + clock: Callable[[], float] = time.monotonic, + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + rng: random.Random | None = None, + on_counted: Callable[[], None] | None = None, + on_notice: Callable[[str], None] | None = None, + refresh_login: Callable[[httpx.AsyncClient], Awaitable[None]] | None = None, + ) -> None: + self.options = options + self.on_counted = on_counted + self.on_notice = on_notice + self.refresh_login = refresh_login + self.address = address + self.totals = Totals() + self.start_after: str | None = None + self.completed = False + self.resumed = False + self._clock = clock + self._sleep = sleep + self._rng = rng or random.Random() + self._pacer = Pacer(rate=options.rate, clock=clock, sleep=sleep) + self._started_at = clock() + self._elapsed_before = 0.0 + self._answered = False + self._auth_generation = 0 + self._auth_lock = asyncio.Lock() + self._handled_at_start = 0 + self._bytes_at_start = 0 + self.objects_confirmed = 0 + self.bytes_confirmed = 0 + self.selected_objects = 0 + self.selected_bytes = 0 + self.remaining_objects: int | None = None + self.remaining_bytes: int | None = None + self.counting = False + self.counted_objects = 0 + self.count_seconds_this_run = 0.0 + self._count_requests_before = 0 + self.limit = AdaptiveLimit( + maximum=options.concurrency, + minimum=options.min_concurrency, + slow_factor=options.slow_factor, + clock=clock, + ) + + def check_output_files(self) -> None: + """Check that the state file and the report can be written, before any object is changed. + + A dry run writes neither file, so it checks nothing. + + Raises: + MigrationError: If the directory of a file is missing or not writable, or an existing file is not writable. + + """ + if self.options.dry_run: + return + for option, path in (("--state-file", self.options.state_file), ("--report", self.options.report)): + if path is None: + continue + directory = path.parent + if not directory.is_dir(): + raise MigrationError( + f"The directory of {option} {path} does not exist. Create it, or use another path." + ) + if not os.access(directory, os.W_OK | os.X_OK): + raise MigrationError(f"The directory of {option} {path} is not writable. Use another path.") + if path.is_dir() or (path.exists() and not os.access(path, os.W_OK)): + raise MigrationError(f"The file {path} given to {option} cannot be written. Use another path.") + + def load_state(self) -> None: + path = self.options.state_file + if path is None or self.options.restart or not path.exists(): + return + try: + state = json.loads(path.read_text(encoding="utf-8")) + if state["address"] != self.address: + raise MigrationError( + f"The state file {path} belongs to {state['address']}, not to {self.address}. " + "Use another --state-file, or --restart to discard it." + ) + start_after = state["start_after"] + completed = bool(state["completed"]) + saved = dict(state["totals"]) + known = {item.name for item in fields(Totals)} + totals = Totals(**{name: value for name, value in saved.items() if name in known}) + if "bytes_handled" not in saved: + # A state file of an earlier version did not record the bytes of every outcome. + totals.bytes_handled = totals.bytes_encrypted + except (OSError, ValueError, KeyError, TypeError) as exc: + raise MigrationError( + f"The state file {path} cannot be read ({type(exc).__name__}: {exc}). " + "Delete it or use --restart to start again." + ) from exc + if completed: + return + self.start_after = start_after + self.resumed = start_after is not None + if self.options.dry_run: + return + self.totals = totals + self._elapsed_before = totals.elapsed_seconds + self._handled_at_start = sum(totals.counts.values()) + self._bytes_at_start = totals.bytes_handled + + def save_state(self) -> None: + path = self.options.state_file + if path is None or self.options.dry_run: + return + self._update_totals() + state = { + "version": 1, + "address": self.address, + "start_after": self.start_after, + "completed": self.completed, + "totals": asdict(self.totals), + } + if self.total_objects is not None: + state["plan"] = {"objects_total": self.total_objects, "bytes_total": self.total_bytes} + temporary = path.with_name(f"{path.name}.tmp") + with temporary.open("w", encoding="utf-8") as output: + json.dump(state, output) + output.flush() + os.fsync(output.fileno()) + temporary.replace(path) + + @property + def handled_this_run(self) -> int: + return sum(self.totals.counts.values()) - self._handled_at_start + + @property + def seconds_this_run(self) -> float: + return self._clock() - self._started_at + + @property + def handled_before(self) -> int: + """Objects that earlier runs of the same pass handled, from the state file.""" + return self._handled_at_start + + @property + def done_objects(self) -> int: + return self._handled_at_start + self.objects_confirmed + + @property + def done_bytes(self) -> int: + return self._bytes_at_start + self.bytes_confirmed + + @property + def total_objects(self) -> int | None: + """Objects of the whole pass: those earlier runs handled plus those still to do; None without a count.""" + return None if self.remaining_objects is None else self._handled_at_start + self.remaining_objects + + @property + def total_bytes(self) -> int | None: + return None if self.remaining_bytes is None else self._bytes_at_start + self.remaining_bytes + + def _update_totals(self) -> None: + self.totals.elapsed_seconds = self._elapsed_before + (self._clock() - self._started_at) + self.totals.limit_decreases = self.limit.decreases + self.totals.limit_increases = self.limit.increases + self.totals.limit_final = self.limit.limit + + def _check_retries(self, failures: int, path: str, cause: str) -> None: + allowed = self.options.max_retries if self._answered else min(self.options.max_retries, UNANSWERED_MAX_RETRIES) + if failures > allowed: + if self._answered: + raise MigrationError(f"{path} still fails after {self.options.max_retries} retries: {cause}") + raise MigrationError( + f"The server cannot be reached ({cause}), and nothing answered after {allowed} retries." + ) + self.totals.retries += 1 + + async def _request( + self, + http: httpx.AsyncClient, + method: str, + path: str, + params: dict[str, Any], + body: dict[str, Any] | None = None, + ) -> httpx.Response: + """Send one request until the server answers it, waiting out 429 responses and transient failures. + + Raises: + MigrationError: If the failures other than 429 outnumber the retries allowed. + + """ + failures = 0 + sheds = 0 + refreshed = False + while True: + await self._pacer.wait() + self.totals.requests += 1 + generation = self._auth_generation + try: + response = await http.request(method, path, params=params, json=body) + except httpx.TransportError as exc: + failures += 1 + self._check_retries(failures=failures, path=path, cause=f"{type(exc).__name__}: {exc}") + await self._sleep(backoff_delay(attempt=failures, rng=self._rng)) + continue + self._answered = True + if response.status_code == HTTP_TOO_MANY_REQUESTS: + sheds += 1 + self.totals.shed_429 += 1 + if ADMISSION_HEADER in response.headers: + self.totals.shed_429_admission += 1 + self.limit.shed() + asked = parse_retry_after(response.headers.get("Retry-After")) + if asked > RETRY_AFTER_MAX_SECONDS: + self._notify( + f"The server asked for a pause of {asked:.0f} seconds; the command waits " + f"{RETRY_AFTER_MAX_SECONDS:.0f} seconds at most, then tries again." + ) + asked = RETRY_AFTER_MAX_SECONDS + self._pacer.pause(max(asked, backoff_delay(attempt=sheds, rng=self._rng))) + continue + if response.status_code in RETRYABLE_STATUS_CODES: + failures += 1 + self._check_retries(failures=failures, path=path, cause=f"HTTP {response.status_code}") + await self._sleep(backoff_delay(attempt=failures, rng=self._rng)) + continue + if ( + response.status_code == HTTP_UNAUTHORIZED + and self.refresh_login is not None + and not refreshed + and _should_refresh_token(response=response) + ): + refreshed = True + await self._renew_login(http, self.refresh_login, seen_generation=generation) + continue + return response + + def _notify(self, message: str) -> None: + if self.on_notice is not None: + self.on_notice(message) + + async def _renew_login( + self, + http: httpx.AsyncClient, + refresh_login: Callable[[httpx.AsyncClient], Awaitable[None]], + seen_generation: int, + ) -> None: + """Log in again after a 401, once for all the requests that got a 401 with the same token. + + Raises: + MigrationError: If the new login fails. + + """ + async with self._auth_lock: + if self._auth_generation != seen_generation: + return + try: + await refresh_login(http) + except (httpx.HTTPError, Error) as exc: + raise MigrationError( + f"The access token expired and the new login failed ({type(exc).__name__}: {exc})." + ) from exc + self._auth_generation += 1 + + async def _list_page(self, http: httpx.AsyncClient) -> tuple[list[dict[str, Any]], str | None]: + return await self._fetch_listing(http, start_after=self.start_after, limit=self.options.page_size) + + async def _fetch_listing( + self, http: httpx.AsyncClient, start_after: str | None, limit: int + ) -> tuple[list[dict[str, Any]], str | None]: + params: dict[str, Any] = {"limit": limit} + if start_after: + params["start_after"] = start_after + response = await self._request(http, "GET", LIST_PATH, params) + if response.status_code != HTTP_OK: + raise MigrationError(refusal_message(response=response, what="The listing of the stored objects")) + body = answer_body(response, what="The listing of the stored objects") + try: + return body["objects"], body["next_start_after"] + except (KeyError, TypeError) as exc: + raise MigrationError(f"The listing of the stored objects has an unexpected shape: {exc!r}") from exc + + @staticmethod + def _check_progress(start_after: str | None, next_start_after: str | None) -> None: + """Stop when the server points back at the position it was asked to continue after. + + Raises: + MigrationError: If `next_start_after` equals `start_after`, since the same page would be listed again. + + """ + if next_start_after is not None and next_start_after == start_after: + raise MigrationError( + f"The listing of the stored objects does not advance: asked to continue after {start_after!r}, " + f"the server answered with the same position. The command stops instead of listing the same page " + "again. The server may be faulty." + ) + + async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, Any]]) -> list[dict[str, Any]]: + body = { + "identifiers": [item["identifier"] for item in stored], + "allow_unverified": self.options.allow_unverified, + } + await self.limit.acquire() + started = self._clock() + try: + response = await self._request(http, "POST", BATCH_PATH, {}, body) + finally: + await self.limit.release() + seconds = self._clock() - started + self.totals.encrypt_requests += 1 + if response.status_code != HTTP_OK: + raise MigrationError(refusal_message(response=response, what="The request to encrypt a batch")) + # A batch is compared per unit of work: one unit per object plus one per `SMALL_OBJECT_BYTES` of content. + batch_bytes = sum(item["size"] for item in stored) + units = len(stored) + batch_bytes / SMALL_OBJECT_BYTES + self.limit.observe(seconds / units) + body = answer_body(response, what="The request to encrypt a batch") + try: + results: list[dict[str, Any]] = body["results"] + except (KeyError, TypeError) as exc: + raise MigrationError( + f"The request to encrypt a batch has an answer of an unexpected shape: {exc!r}" + ) from exc + self.objects_confirmed += len(results) + self.bytes_confirmed += batch_bytes + return results + + def _record(self, result: dict[str, Any], report: TextIO | None) -> None: + outcome = result["outcome"] + self.totals.counts[outcome] = self.totals.counts.get(outcome, 0) + 1 + if outcome == OUTCOME_ENCRYPTED: + self.totals.bytes_encrypted += result["size"] + elif report is not None: + report.write(json.dumps(result) + "\n") + + def _select(self, objects: list[dict[str, Any]], remaining: int | None) -> tuple[list[dict[str, Any]], bool]: + """Return the objects of a page to work on, and whether the limit of the run cut the page short.""" + selected: list[dict[str, Any]] = [] + for stored in objects: + if remaining is not None and len(selected) >= remaining: + return selected, True + self.start_after = stored["identifier"] + self.totals.objects_listed += 1 + self.totals.bytes_listed += stored["size"] + if self.options.before and parse_timestamp(stored["last_modified"]) > self.options.before: + self.totals.skipped_newer += 1 + continue + selected.append(stored) + self.selected_objects += 1 + self.selected_bytes += stored["size"] + return selected, False + + async def _encrypt_page( + self, http: httpx.AsyncClient, selected: list[dict[str, Any]], report: TextIO | None + ) -> None: + queue: asyncio.Queue[list[dict[str, Any]]] = asyncio.Queue() + size = self.options.batch_size + for start in range(0, len(selected), size): + queue.put_nowait(selected[start : start + size]) + results: list[dict[str, Any]] = [] + + async def worker() -> None: + while True: + try: + batch = queue.get_nowait() + except asyncio.QueueEmpty: + return + results.extend(await self._encrypt_batch(http, batch)) + + workers = [asyncio.create_task(worker()) for _ in range(min(self.options.concurrency, queue.qsize()))] + try: + await asyncio.gather(*workers) + finally: + for task in workers: + task.cancel() + await asyncio.gather(*workers, return_exceptions=True) + # A page counts only once it is complete, so an interrupted page is redone and never counted twice. + for result in results: + self._record(result=result, report=report) + self.totals.bytes_handled += sum(item["size"] for item in selected) + + async def _count_pass(self, http: httpx.AsyncClient) -> None: + """List the objects the run will send, from the saved position, and record how many and how large. + + The pass only reads. It applies `--before` and `--limit` as the run does, and uses the largest page size, + so it neither changes which objects are sent nor needs the page size of the run. The seconds and requests + it takes are kept apart from the encryption, so the throughput of the run stays comparable. + + Raises: + MigrationError: If the server refuses the listing or stays unreachable. + + """ + started = self._clock() + requests_before = self.totals.requests + self.counting = True + objects = 0 + total_bytes = 0 + start_after = self.start_after + limit = self.options.limit + try: + while limit is None or objects < limit: + page, next_start_after = await self._fetch_listing(http, start_after=start_after, limit=PAGE_MAX_SIZE) + self._check_progress(start_after=start_after, next_start_after=next_start_after) + for item in page: + if self.options.before and parse_timestamp(item["last_modified"]) > self.options.before: + continue + if limit is not None and objects >= limit: + break + objects += 1 + total_bytes += item["size"] + self.counted_objects = objects + if next_start_after is None: + break + start_after = next_start_after + finally: + self.counting = False + self.count_seconds_this_run = self._clock() - started + self.totals.count_requests += self.totals.requests - requests_before + self.totals.requests = requests_before + self.remaining_objects = objects + self.remaining_bytes = total_bytes + self.totals.count_seconds += self.count_seconds_this_run + # The time of the count pass is not part of the time of the run, so objects per second stay comparable. + self._started_at = self._clock() + if self.on_counted is not None: + self.on_counted() + + async def run(self, http: httpx.AsyncClient) -> None: + """Walk the listing from the saved position and encrypt every selected object. + + Raises: + MigrationError: If the server refuses the run or stays unreachable. + + """ + self.check_output_files() + self.load_state() + if self.options.count and not self.options.dry_run: + await self._count_pass(http) + processed = 0 + with contextlib.ExitStack() as stack: + report: TextIO | None = None + if self.options.report is not None and not self.options.dry_run: + report = stack.enter_context(self.options.report.open("a", encoding="utf-8")) + while True: + remaining = None if self.options.limit is None else self.options.limit - processed + if remaining is not None and remaining <= 0: + break + position = self.start_after + objects, next_start_after = await self._list_page(http) + self._check_progress(start_after=position, next_start_after=next_start_after) + selected, cut_short = self._select(objects=objects, remaining=remaining) + if not self.options.dry_run: + try: + await self._encrypt_page(http, selected, report) + except BaseException: + self.start_after = position + raise + if not cut_short and next_start_after is not None: + # The cursor is the last name the server scanned; it can be past the last listed object. + self.start_after = next_start_after + processed += len(selected) + if report is not None: + report.flush() + if not cut_short and next_start_after is None: + self.completed = True + self.save_state() + if cut_short or next_start_after is None: + break + self._update_totals() + + +def answer_body(response: httpx.Response, what: str) -> Any: + """Return the JSON body of an answer. + + Raises: + MigrationError: If the body is not JSON. + + """ + try: + return response.json() + except ValueError as exc: + raise MigrationError( + f"{what} was answered with HTTP {response.status_code} and a body that is not JSON." + ) from exc + + +def refusal_message(response: httpx.Response, what: str) -> str: + """Return a message that says what a refused request means for the person who runs the command.""" + status = response.status_code + detail = server_detail(response) + suffix = f" Server answer: {detail}" if detail else "" + if status == HTTP_UNAUTHORIZED: + return f"{what} was refused with HTTP 401: the server does not accept the token or credentials.{suffix}" + if status == HTTP_FORBIDDEN: + return ( + f"{what} was refused with HTTP 403: the account of this token does not have the super admin permission " + f"that encrypting stored objects needs.{suffix}" + ) + if status == HTTP_NOT_FOUND: + return ( + f"{what} was refused with HTTP 404: this server does not have the storage encryption routes " + f"({LIST_PATH}). It runs an Infrahub version without them, or another address is meant.{suffix}" + ) + if status == HTTP_CONFLICT: + return ( + f"{what} was refused with HTTP 409: storage encryption is not enabled on the server, or the server " + f"has no storage key.{suffix}" + ) + return f"{what} was refused with HTTP {status}.{suffix}" + + +def server_detail(response: httpx.Response) -> str: + """Return the message a server error carries, or the start of its body.""" + try: + body = response.json() + except ValueError: + return response.text[:300] + if isinstance(body, dict): + if isinstance(body.get("detail"), str): + return str(body["detail"])[:300] + errors = body.get("errors") + if isinstance(errors, list): + messages = [str(item["message"]) for item in errors if isinstance(item, dict) and "message" in item] + if messages: + return "; ".join(messages)[:300] + return response.text[:300] diff --git a/infrahub_sdk/ctl/storage/progress.py b/infrahub_sdk/ctl/storage/progress.py new file mode 100644 index 000000000..b653caf86 --- /dev/null +++ b/infrahub_sdk/ctl/storage/progress.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import math +from collections import deque +from dataclasses import dataclass + +RATE_WINDOW_SECONDS = 30.0 +RATE_MINIMUM_SPAN_SECONDS = 4.0 +MINIMUM_SAMPLES = 2 +BYTES_PER_UNIT = 1000 +BYTE_UNITS = ("B", "kB", "MB", "GB", "TB", "PB") +SECONDS_PER_MINUTE = 60 +SECONDS_PER_HOUR = 3600 +SECONDS_PER_DAY = 86400 +LONGEST_DURATION_DAYS = 99 + + +class RateTracker: + """Rate of progress over the last `window` seconds, so the remaining time follows the current speed. + + The caller records `(time, done)` once per progress refresh, which costs two numbers per refresh. The rate + stays unknown until the recorded samples span `minimum_span` seconds. + """ + + def __init__(self, window: float = RATE_WINDOW_SECONDS, minimum_span: float = RATE_MINIMUM_SPAN_SECONDS) -> None: + self._window = window + self._minimum_span = minimum_span + self._samples: deque[tuple[float, int]] = deque() + + def record(self, now: float, done: int) -> None: + self._samples.append((now, done)) + # Keep one sample at or before the start of the window, so the window is always fully covered. + while len(self._samples) > MINIMUM_SAMPLES and self._samples[1][0] <= now - self._window: + self._samples.popleft() + + def rate(self) -> float | None: + """Return objects per second over the window, or None while there is too little data.""" + if len(self._samples) < MINIMUM_SAMPLES: + return None + first_time, first_done = self._samples[0] + last_time, last_done = self._samples[-1] + span = last_time - first_time + if span < self._minimum_span: + return None + return max(0.0, (last_done - first_done) / span) + + +@dataclass +class ProgressView: + """What the progress line shows; `total_objects` is None when the count pass was skipped.""" + + done_objects: int + total_objects: int | None + done_bytes: int + total_bytes: int | None + rate: float | None + limit: int + limit_maximum: int + shed_429: int + retries: int + + +def format_number(value: int) -> str: + return f"{value:,}" + + +def format_bytes(value: int) -> str: + """Return `value` bytes in decimal units with one decimal, for example `23.4 GB`.""" + size = float(max(0, value)) + unit = 0 + while size >= BYTES_PER_UNIT and unit < len(BYTE_UNITS) - 1: + size /= BYTES_PER_UNIT + unit += 1 + return f"{int(size)} B" if unit == 0 else f"{size:.1f} {BYTE_UNITS[unit]}" + + +def format_duration(seconds: float) -> str: + """Return a time span as `45s`, `3m 05s`, `2h 07m` or `3d 04h`; more than 99 days is `>99d`.""" + if math.isnan(seconds) or math.isinf(seconds) or seconds < 0: + return "unknown" + whole = round(seconds) + days, rest = divmod(whole, SECONDS_PER_DAY) + if days > LONGEST_DURATION_DAYS: + return f">{LONGEST_DURATION_DAYS}d" + hours, rest = divmod(rest, SECONDS_PER_HOUR) + minutes, secs = divmod(rest, SECONDS_PER_MINUTE) + if days: + return f"{days}d {hours:02d}h" + if hours: + return f"{hours}h {minutes:02d}m" + if minutes: + return f"{minutes}m {secs:02d}s" + return f"{secs}s" + + +def format_percent(done: int, total: int) -> str: + """Return the share done, rounded down to one decimal and never above 100%, so 100.0% means finished.""" + if total <= 0: + return "100.0%" + return f"{min(100.0, math.floor(done * 1000 / total) / 10):.1f}%" + + +def remaining_seconds(view: ProgressView) -> float | None: + """Return the seconds left at the recent rate, or None when the rate or the total is unknown or zero.""" + if view.total_objects is None or view.rate is None or view.rate <= 0: + return None + return max(0, view.total_objects - view.done_objects) / view.rate + + +def remaining_text(view: ProgressView) -> str: + if view.total_objects is not None and view.done_objects >= view.total_objects: + return "finishing" + if view.rate is None: + return "estimating" + seconds = remaining_seconds(view) + return "unknown" if seconds is None else format_duration(seconds) + + +def progress_line(view: ProgressView) -> str: + """Return the progress line: done / total, percent, rate, remaining time, bytes, limit, 429 answers, retries.""" + rate = "estimating" if view.rate is None else f"{view.rate:,.0f} objects/s" + parts: list[str] = [] + if view.total_objects is None: + parts.extend([f"{format_number(view.done_objects)} objects", rate, format_bytes(view.done_bytes)]) + else: + percent = format_percent(done=view.done_objects, total=view.total_objects) + parts.extend( + [ + f"{format_number(view.done_objects)} / {format_number(view.total_objects)} objects ({percent})", + rate, + f"remaining {remaining_text(view)}", + f"{format_bytes(view.done_bytes)} / {format_bytes(view.total_bytes or 0)}", + ] + ) + parts.extend([f"limit {view.limit}/{view.limit_maximum}", f"429: {view.shed_429}", f"retries: {view.retries}"]) + return " | ".join(parts) diff --git a/tests/unit/ctl/test_storage_app.py b/tests/unit/ctl/test_storage_app.py new file mode 100644 index 000000000..598fa2d51 --- /dev/null +++ b/tests/unit/ctl/test_storage_app.py @@ -0,0 +1,739 @@ +from __future__ import annotations + +import asyncio +import json +import os +import signal +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import httpx +import pytest +from typer.testing import CliRunner + +from infrahub_sdk.ctl import config +from infrahub_sdk.ctl.storage import app +from infrahub_sdk.ctl.storage import encrypt as encrypt_module +from infrahub_sdk.ctl.storage import migration as migration_module +from infrahub_sdk.ctl.storage.migration import Options, StorageEncryptor + +if TYPE_CHECKING: + from pathlib import Path + + from click.testing import Result + from pytest_httpx import HTTPXMock + +pytestmark = pytest.mark.httpx_mock(can_send_already_matched_responses=True) + +runner = CliRunner() + +BASE = "http://mock" +LIST_URL = f"{BASE}/api/storage/objects" +BATCH_URL = f"{BASE}/api/storage/objects/encrypt" +OLD = "2026-01-01T00:00:00Z" + + +def page(*identifiers: str, next_start_after: str | None = None) -> dict[str, Any]: + objects = [{"identifier": i, "size": 100, "last_modified": OLD} for i in identifiers] + return {"objects": objects, "next_start_after": next_start_after} + + +def answer(*identifiers: str, outcome: str = "encrypted", reason: str | None = None) -> dict[str, Any]: + return {"results": [{"identifier": i, "outcome": outcome, "size": 100, "reason": reason} for i in identifiers]} + + +@pytest.fixture +def files(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]: + monkeypatch.setattr(migration_module, "BACKOFF_BASE_SECONDS", 0.0) + return ["--state-file", str(tmp_path / "state.json"), "--report", str(tmp_path / "report.jsonl")] + + +def invoke(files: list[str], *args: str) -> Result: + return runner.invoke(app=app, args=["encrypt", "--no-count", *files, *args]) + + +def invoke_counting(files: list[str], *args: str) -> Result: + return runner.invoke(app=app, args=["encrypt", *files, *args]) + + +def test_a_run_prints_a_summary_and_exits_0(httpx_mock: HTTPXMock, files: list[str], tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert "Storage encryption" in result.stdout + assert "Objects listed" in result.stdout + assert "encrypted" in result.stdout + assert "Answers 429" in result.stdout + assert "In flight limit" in result.stdout + assert "Pass finished" in result.stdout + assert json.loads((tmp_path / "state.json").read_text())["completed"] is True + + +def test_objects_the_server_skips_do_not_fail_the_run_and_are_reported( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", outcome="skipped_unverified", reason="x")) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert "skipped_unverified" in result.stdout + assert json.loads((tmp_path / "report.jsonl").read_text())["identifier"] == "a" + + +def test_an_object_that_failed_makes_the_exit_code_1(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", outcome="failed", reason="disk full")) + + result = invoke(files) + + assert result.exit_code == 1, result.stdout + assert "failed" in result.stdout + + +def test_the_requests_carry_the_token_and_the_priority( + httpx_mock: HTTPXMock, files: list[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config.SETTINGS.active, "api_token", "secret-token") + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + + result = invoke(files, "--priority", "medium") + + assert result.exit_code == 0, result.stdout + for request in httpx_mock.get_requests(): + assert request.headers["X-INFRAHUB-KEY"] == "secret-token" + assert request.headers["X-Priority"] == "medium" + + +def test_the_priority_is_read_in_any_case(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + + result = invoke(files, "--priority", "HIGH") + + assert result.exit_code == 0, result.stdout + assert {r.headers["X-Priority"] for r in httpx_mock.get_requests()} == {"high"} + + +def test_the_default_priority_is_low(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + + invoke(files) + + assert {r.headers["X-Priority"] for r in httpx_mock.get_requests()} == {"low"} + + +def test_the_options_reach_the_requests(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=3", json=page("a", "b", "c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + + result = invoke(files, "--page-size", "3", "--batch-size", "2", "--allow-unverified", "--concurrency", "1") + + assert result.exit_code == 0, result.stdout + bodies = [json.loads(r.content) for r in httpx_mock.get_requests(method="POST")] + assert bodies == [ + {"identifiers": ["a", "b"], "allow_unverified": True}, + {"identifiers": ["c"], "allow_unverified": True}, + ] + + +def test_a_dry_run_only_lists(httpx_mock: HTTPXMock, files: list[str], tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + + result = invoke(files, "--dry-run") + + assert result.exit_code == 0, result.stdout + assert httpx_mock.get_requests(method="POST") == [] + assert "dry run" in result.stdout + assert "Objects that would be sent" in result.stdout + assert not (tmp_path / "state.json").exists() + + +def test_a_second_run_resumes_from_the_state_file(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + assert invoke(files, "--page-size", "2", "--limit", "2").exit_code == 0 + + result = invoke(files, "--page-size", "2") + + assert result.exit_code == 0, result.stdout + listings = [r.url.query for r in httpx_mock.get_requests(method="GET")] + assert listings == [b"limit=2", b"limit=2&start_after=b"] + assert "3" in result.stdout + + +@dataclass +class ErrorCase: + name: str + listing_status: int + batch_status: int | None + body: dict[str, Any] + expected: str + + +ERROR_CASES = [ + ErrorCase( + name="no-routes", + listing_status=404, + batch_status=None, + body={"detail": "Not Found"}, + expected="does not have the storage encryption routes", + ), + ErrorCase( + name="no-super-admin", + listing_status=403, + batch_status=None, + body={"detail": "Forbidden"}, + expected="does not have the super admin permission", + ), + ErrorCase( + name="token-rejected", + listing_status=401, + batch_status=None, + body={"detail": "Unauthorized"}, + expected="does not accept the token", + ), + ErrorCase( + name="encryption-disabled", + listing_status=200, + batch_status=409, + body={"detail": "Storage encryption is not enabled."}, + expected="storage encryption is not enabled on the server", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in ERROR_CASES]) +def test_a_refusal_prints_its_meaning_and_exits_2( + case: ErrorCase, httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + if case.batch_status is None: + httpx_mock.add_response(method="GET", status_code=case.listing_status, json=case.body) + else: + httpx_mock.add_response(method="GET", json=page("a")) + httpx_mock.add_response(method="POST", status_code=case.batch_status, json=case.body) + + result = invoke(files) + + assert result.exit_code == 2, result.stdout + assert case.expected in result.stdout.replace("\n", " ") + assert "Traceback" not in result.stdout + assert "Progress is saved" not in result.stdout + assert not (tmp_path / "state.json").exists() + + +def test_an_error_after_a_complete_page_says_where_to_resume( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", status_code=403, json={"detail": "no"}) + + result = invoke(files, "--page-size", "2") + + assert result.exit_code == 2, result.stdout + assert "Progress is saved in" in result.stdout.replace("\n", " ") + assert "run the same command again to resume" in result.stdout.replace("\n", " ") + assert json.loads((tmp_path / "state.json").read_text())["start_after"] == "b" + + +def test_the_message_of_the_server_is_printed_without_markup_loss(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(method="GET", status_code=409, json={"detail": "No key [storage] is set"}) + + result = invoke(files) + + assert result.exit_code == 2 + assert "No key [storage] is set" in result.stdout.replace("\n", " ") + + +def test_a_server_that_cannot_be_reached_exits_2_with_the_cause(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_exception(httpx.ConnectError("connection refused"), is_reusable=True) + + result = invoke(files) + + assert result.exit_code == 2, result.stdout + text = result.stdout.replace("\n", " ") + assert "cannot be reached" in text + assert "ConnectError: connection refused" in text + + +def test_a_state_file_of_another_server_exits_2(httpx_mock: HTTPXMock, files: list[str], tmp_path: Path) -> None: + (tmp_path / "state.json").write_text( + json.dumps({"address": "http://other", "start_after": None, "completed": False, "totals": {}}) + ) + + result = invoke(files) + + assert result.exit_code == 2 + assert "belongs to http://other" in result.stdout.replace("\n", " ") + + +@dataclass +class OptionCase: + name: str + args: list[str] + + +OPTION_CASES = [ + OptionCase(name="priority", args=["--priority", "urgent"]), + OptionCase(name="batch-size-too-large", args=["--batch-size", "501"]), + OptionCase(name="page-size-too-large", args=["--page-size", "5001"]), + OptionCase(name="concurrency-zero", args=["--concurrency", "0"]), + OptionCase(name="concurrency-too-large", args=["--concurrency", "65"]), + OptionCase(name="rate-zero", args=["--rate", "0"]), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in OPTION_CASES]) +def test_an_invalid_option_is_refused_before_any_request( + case: OptionCase, httpx_mock: HTTPXMock, files: list[str] +) -> None: + result = invoke(files, *case.args) + + assert result.exit_code == 2 + assert "Invalid value for" in result.output + assert httpx_mock.get_requests() == [] + + +def test_ctrl_c_stops_the_run_and_keeps_the_state(httpx_mock: HTTPXMock, files: list[str], tmp_path: Path) -> None: + async def interrupt(request: httpx.Request) -> httpx.Response: + os.kill(os.getpid(), signal.SIGINT) + await asyncio.sleep(30) + raise AssertionError("not reached") + + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_callback(interrupt, url=f"{LIST_URL}?limit=2&start_after=b") + + result = invoke(files, "--page-size", "2") + + assert result.exit_code == 130, result.stdout + assert "Stopped" in result.stdout + assert "Run the same command again" in result.stdout.replace("\n", " ") + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + assert state["completed"] is False + assert state["totals"]["counts"] == {"encrypted": 2} + + +def text_of(result: Result) -> str: + return result.stdout.replace("\n", " ") + + +def test_a_server_that_repeats_the_position_it_was_given_exits_2_with_a_message( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + pages = {None: page("a", next_start_after="a"), "a": page(next_start_after="a")} + asked: list[str | None] = [] + + def listing(request: httpx.Request) -> httpx.Response: + asked.append(request.url.params.get("start_after")) + if len(asked) > 20: + return httpx.Response(400, json={"detail": "listing asked too often"}) + return httpx.Response(200, json=pages[asked[-1]]) + + httpx_mock.add_callback(listing, method="GET") + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + + result = invoke(files) + + assert result.exit_code == 2, result.stdout + assert "does not advance" in text_of(result) + assert asked == [None, "a"] + assert json.loads((tmp_path / "state.json").read_text())["start_after"] == "a" + + +def mock_three_objects(httpx_mock: HTTPXMock) -> None: + """Three objects: counted with one request of 5000, listed by the run in pages of 2.""" + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b"), match_json=None) + + +def test_a_run_counts_first_prints_the_total_and_ends_with_done_over_total( + httpx_mock: HTTPXMock, files: list[str] +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + + result = invoke_counting(files) + + assert result.exit_code == 0, result.stdout + assert "To process: 2 objects (200 B)" in result.stdout + assert "Already handled in earlier runs" not in result.stdout + assert "2 / 2 objects (100.0%)" in result.stdout + assert "Bytes done in total" in result.stdout + assert "Seconds counting" in result.stdout + assert result.stdout.index("To process") < result.stdout.index("Storage encryption") + + +def test_the_count_pass_uses_the_largest_page_size_and_the_priority_and_token_of_the_run( + httpx_mock: HTTPXMock, files: list[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config.SETTINGS.active, "api_token", "secret-token") + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + + result = invoke_counting(files, "--page-size", "2", "--priority", "medium") + + assert result.exit_code == 0, result.stdout + listings = httpx_mock.get_requests(method="GET") + assert [r.url.query for r in listings] == [b"limit=5000", b"limit=2"] + for request in listings: + assert request.headers["X-Priority"] == "medium" + assert request.headers["X-INFRAHUB-KEY"] == "secret-token" + + +def test_a_run_with_no_count_prints_no_total_and_lists_once(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert "To process" not in result.stdout + assert "Seconds counting" not in result.stdout + assert "Done in total" not in result.stdout + assert len(httpx_mock.get_requests(method="GET")) == 1 + + +def test_a_resumed_run_prints_what_earlier_runs_handled_and_the_total_of_the_whole_pass( + httpx_mock: HTTPXMock, files: list[str] +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + assert invoke(files, "--page-size", "2", "--limit", "2").exit_code == 0 + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) + + result = invoke_counting(files, "--page-size", "2") + + assert result.exit_code == 0, result.stdout + assert "To process: 1 objects (100 B)" in result.stdout + assert "Already handled in earlier runs: 2 objects" in result.stdout + assert "3 / 3 objects (100.0%)" in result.stdout + + +def test_a_dry_run_prints_the_total_it_found_and_does_not_count_first(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + + result = invoke_counting(files, "--dry-run") + + assert result.exit_code == 0, result.stdout + assert "To process: 2 objects (200 B)" in result.stdout + assert "Bytes that would be sent" in result.stdout + assert len(httpx_mock.get_requests()) == 1 + + +def test_a_dry_run_with_before_and_limit_totals_only_the_objects_it_would_send( + httpx_mock: HTTPXMock, files: list[str] +) -> None: + objects = [ + {"identifier": "old1", "size": 100, "last_modified": OLD}, + {"identifier": "new", "size": 900, "last_modified": "2026-06-01T00:00:00Z"}, + {"identifier": "old2", "size": 100, "last_modified": OLD}, + {"identifier": "old3", "size": 100, "last_modified": OLD}, + ] + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json={"objects": objects, "next_start_after": None}) + + result = invoke(files, "--dry-run", "--before", "2026-03-01", "--limit", "2") + + assert result.exit_code == 0, result.stdout + assert "To process: 2 objects (200 B)" in result.stdout + + +def test_the_total_follows_before_and_limit(httpx_mock: HTTPXMock, files: list[str]) -> None: + objects = [ + {"identifier": "old1", "size": 100, "last_modified": OLD}, + {"identifier": "new", "size": 900, "last_modified": "2026-06-01T00:00:00Z"}, + {"identifier": "old2", "size": 100, "last_modified": OLD}, + {"identifier": "old3", "size": 100, "last_modified": OLD}, + ] + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json={"objects": objects, "next_start_after": None}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("old1", "old2")) + + result = invoke_counting(files, "--before", "2026-03-01", "--limit", "2") + + assert result.exit_code == 0, result.stdout + assert "To process: 2 objects (200 B)" in result.stdout + assert "2 / 2 objects (100.0%)" in result.stdout + + +def test_an_error_during_the_run_prints_done_over_total(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", status_code=409, json={"detail": "Storage encryption is not enabled."}) + + result = invoke_counting(files) + + assert result.exit_code == 2, result.stdout + assert "Done before the error: 0 / 2 objects (0.0%)." in text_of(result) + + +def test_a_refusal_during_the_count_stops_the_run_with_a_clear_message_and_sends_nothing( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(method="GET", status_code=403, json={"detail": "no"}) + + result = invoke_counting(files) + + assert result.exit_code == 2, result.stdout + assert "does not have the super admin permission" in text_of(result) + assert "To process" not in result.stdout + assert httpx_mock.get_requests(method="POST") == [] + assert not (tmp_path / "state.json").exists() + + +def test_a_server_that_cannot_be_reached_during_the_count_exits_2(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_exception(httpx.ConnectError("connection refused"), is_reusable=True) + + result = invoke_counting(files) + + assert result.exit_code == 2, result.stdout + assert "ConnectError: connection refused" in text_of(result) + assert httpx_mock.get_requests(method="POST") == [] + assert len(httpx_mock.get_requests()) == migration_module.UNANSWERED_MAX_RETRIES + 1 + + +@dataclass +class StopCase: + name: str + signal_number: int + exit_code: int + stopped_by: str + + +STOP_CASES = [ + StopCase(name="ctrl-c", signal_number=signal.SIGINT, exit_code=130, stopped_by="Ctrl-C"), + StopCase(name="sigterm", signal_number=signal.SIGTERM, exit_code=143, stopped_by="SIGTERM"), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in STOP_CASES]) +def test_a_stop_signal_cancels_the_work_saves_the_state_and_prints_done_over_total_then_resumes( + case: StopCase, httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + async def stop(request: httpx.Request) -> httpx.Response: + os.kill(os.getpid(), case.signal_number) + await asyncio.sleep(30) + raise AssertionError("not reached") + + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_callback(stop, url=f"{LIST_URL}?limit=2&start_after=b") + + result = invoke_counting(files, "--page-size", "2") + + assert result.exit_code == case.exit_code, result.stdout + assert f"Stopped by {case.stopped_by}. Done: 2 / 3 objects (66.6%)." in text_of(result) + assert "Run the same command again to resume" in text_of(result) + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + assert state["completed"] is False + assert state["totals"]["counts"] == {"encrypted": 2} + + httpx_mock.reset() + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + resumed = invoke_counting(files, "--page-size", "2") + + assert resumed.exit_code == 0, resumed.stdout + assert "Already handled in earlier runs: 2 objects" in resumed.stdout + assert "To process: 1 objects (100 B)" in resumed.stdout + assert "3 / 3 objects (100.0%)" in resumed.stdout + assert [json.loads(r.content)["identifiers"] for r in httpx_mock.get_requests(method="POST")] == [["c"]] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in STOP_CASES]) +def test_a_stop_signal_during_the_count_saves_nothing_and_says_so( + case: StopCase, httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + async def stop(request: httpx.Request) -> httpx.Response: + os.kill(os.getpid(), case.signal_number) + await asyncio.sleep(30) + raise AssertionError("not reached") + + httpx_mock.add_callback(stop, url=f"{LIST_URL}?limit=5000") + + result = invoke_counting(files) + + assert result.exit_code == case.exit_code, result.stdout + assert f"Stopped by {case.stopped_by}." in text_of(result) + assert "Nothing was saved to resume from" in text_of(result) + assert httpx_mock.get_requests(method="POST") == [] + assert not (tmp_path / "state.json").exists() + + +def test_a_failed_object_still_gives_exit_code_1_when_the_run_counted(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", outcome="failed", reason="disk full")) + + assert invoke_counting(files).exit_code == 1 + + +def make_encryptor(tmp_path: Path, *, dry_run: bool = False) -> StorageEncryptor: + options = Options(state_file=tmp_path / "state.json", report=tmp_path / "report.jsonl", dry_run=dry_run) + return StorageEncryptor(options=options, address=BASE) + + +async def test_the_progress_line_printed_when_the_output_is_not_a_terminal_shows_total_percent_and_remaining_time( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setattr(encrypt_module, "PROGRESS_LINE_SECONDS", 0.3) + monkeypatch.setattr(encrypt_module, "PROGRESS_LIVE_SECONDS", 0.02) + clock = {"now": 0.0} + + class FakeClockModule: + @staticmethod + def monotonic() -> float: + return clock["now"] + + monkeypatch.setattr(encrypt_module, "time", FakeClockModule) + encryptor = make_encryptor(tmp_path) + encryptor.remaining_objects = 1000 + encryptor.remaining_bytes = 100_000 + + async def advance() -> None: + # 100 objects/s: 0.1 s of the fake clock for each 10 objects. + for _ in range(60): + clock["now"] += 0.1 + encryptor.objects_confirmed += 10 + encryptor.bytes_confirmed += 1000 + await asyncio.sleep(0.01) + + with encrypt_module.console.capture() as capture: + task = asyncio.create_task(encrypt_module._show_progress(encryptor)) + await advance() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + lines = [line for line in capture.get().splitlines() if "objects" in line] + assert lines, capture.get() + last = lines[-1] + assert "/ 1,000 objects (" in last + assert "estimating" not in last + assert " objects/s | remaining " in last + assert "%)" in last + assert "remaining" in last + assert " / 100.0 kB" in last + assert "limit " in last + assert "429: 0" in last + assert "retries: 0" in last + + +async def test_the_progress_line_while_counting_shows_the_objects_counted_so_far(tmp_path: Path) -> None: + encryptor = make_encryptor(tmp_path) + encryptor.counting = True + encryptor.counted_objects = 12345 + + line = encrypt_module._Progress(encryptor).line() + + assert line == "Counting the objects to process: 12,345 so far" + + +async def test_the_progress_line_without_a_total_shows_no_percent(tmp_path: Path) -> None: + encryptor = make_encryptor(tmp_path) + encryptor.objects_confirmed = 40 + + line = encrypt_module._Progress(encryptor).line() + + assert line.startswith("40 objects | estimating | ") + assert "%" not in line + assert "remaining" not in line + + +async def test_the_progress_line_of_a_dry_run_counts_the_objects_listed(tmp_path: Path) -> None: + encryptor = make_encryptor(tmp_path, dry_run=True) + encryptor.totals.objects_listed = 7 + encryptor.totals.bytes_listed = 7000 + + line = encrypt_module._Progress(encryptor).line() + + assert line.startswith("7 objects | estimating | 7.0 kB | ") + + +def test_a_missing_directory_for_the_state_file_exits_2_before_any_request( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + files = ["--state-file", str(tmp_path / "missing" / "state.json"), *files[2:]] + + result = invoke_counting(files) + + assert result.exit_code == 2 + assert "directory of --state-file" in result.stdout.replace("\n", " ") + assert httpx_mock.get_requests() == [] + + +def test_a_missing_directory_for_the_report_exits_2_before_the_count( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + files = [*files[:2], "--report", str(tmp_path / "missing" / "report.jsonl")] + + result = invoke_counting(files) + + assert result.exit_code == 2 + assert "directory of --report" in result.stdout.replace("\n", " ") + assert httpx_mock.get_requests() == [] + + +def test_a_dry_run_needs_neither_directory(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + missing = ["--state-file", str(tmp_path / "x" / "s.json"), "--report", str(tmp_path / "y" / "r.jsonl")] + + result = invoke(missing, "--dry-run") + + assert result.exit_code == 0, result.stdout + + +def test_a_run_with_a_username_renews_an_expired_token_and_goes_on( + httpx_mock: HTTPXMock, files: list[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("INFRAHUB_USERNAME", "admin") + monkeypatch.setenv("INFRAHUB_PASSWORD", "secret") + expired = {"errors": [{"message": "Expired Signature", "extensions": {"code": 401}}]} + httpx_mock.add_response( + method="POST", + url=f"{BASE}/api/auth/login", + json={"access_token": "old", "refresh_token": "refresh"}, + ) + httpx_mock.add_response(method="POST", url=f"{BASE}/api/auth/refresh", json={"access_token": "new"}) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response( + method="POST", url=BATCH_URL, status_code=401, json=expired, match_headers={"Authorization": "Bearer old"} + ) + httpx_mock.add_response( + method="POST", url=BATCH_URL, json=answer("a"), match_headers={"Authorization": "Bearer new"} + ) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert len(httpx_mock.get_requests(url=f"{BASE}/api/auth/refresh")) == 1 + + +def test_a_run_with_an_api_token_stops_on_a_401_with_the_clear_message( + httpx_mock: HTTPXMock, files: list[str], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config.SETTINGS.active, "api_token", "secret-token") + expired = {"errors": [{"message": "Expired Signature", "extensions": {"code": 401}}]} + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=401, json=expired) + + result = invoke(files) + + assert result.exit_code == 2 + assert "does not accept the token or credentials" in result.stdout.replace("\n", " ") + assert len(httpx_mock.get_requests(method="POST", url=BATCH_URL)) == 1 diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py new file mode 100644 index 000000000..023b0b63a --- /dev/null +++ b/tests/unit/ctl/test_storage_migration.py @@ -0,0 +1,1766 @@ +from __future__ import annotations + +import asyncio +import json +import os +import random +import re +import threading +import time +from dataclasses import dataclass +from email.utils import formatdate +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import TYPE_CHECKING, Any, cast + +import httpx +import pytest + +from infrahub_sdk.ctl.storage.migration import ( + BATCH_MAX_SIZE, + RETRY_AFTER_MAX_SECONDS, + UNANSWERED_MAX_RETRIES, + AdaptiveLimit, + MigrationError, + Options, + StorageEncryptor, + backoff_delay, + parse_retry_after, + parse_timestamp, +) + +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + + from pytest_httpx import HTTPXMock + +pytestmark = pytest.mark.httpx_mock(can_send_already_matched_responses=True) + +BASE = "http://mock" +LIST_URL = f"{BASE}/api/storage/objects" +BATCH_URL = f"{BASE}/api/storage/objects/encrypt" +OLD = "2026-01-01T00:00:00Z" + + +class FakeTime: + """A clock that advances only when the code under test sleeps.""" + + def __init__(self) -> None: + self.now = 1000.0 + self.sleeps: list[float] = [] + + def clock(self) -> float: + return self.now + + async def sleep(self, seconds: float) -> None: + self.sleeps.append(seconds) + self.now += seconds + await asyncio.sleep(0) + + +def stored(identifier: str, size: int = 100, modified: str = OLD) -> dict[str, Any]: + return {"identifier": identifier, "size": size, "last_modified": modified} + + +def page(*identifiers: str, next_start_after: str | None = None) -> dict[str, Any]: + return {"objects": [stored(identifier) for identifier in identifiers], "next_start_after": next_start_after} + + +def answer(*identifiers: str, outcome: str = "encrypted", size: int = 100) -> dict[str, Any]: + return {"results": [{"identifier": i, "outcome": outcome, "size": size, "reason": None} for i in identifiers]} + + +def make( + tmp_path: Path, + *, + fake: FakeTime | None = None, + address: str = BASE, + **overrides: Any, # noqa: ANN401 +) -> tuple[StorageEncryptor, FakeTime]: + fake = fake or FakeTime() + settings: dict[str, Any] = { + "state_file": tmp_path / "state.json", + "report": tmp_path / "report.jsonl", + "concurrency": 4, + "batch_size": 2, + } + settings.update(overrides) + encryptor = StorageEncryptor( + options=Options(**settings), address=address, clock=fake.clock, sleep=fake.sleep, rng=random.Random(1) + ) + return encryptor, fake + + +async def run(encryptor: StorageEncryptor, headers: dict[str, str] | None = None) -> None: + async with httpx.AsyncClient(base_url=BASE, headers=headers) as http: + await encryptor.run(http) + + +def sent_bodies(httpx_mock: HTTPXMock) -> list[dict[str, Any]]: + return [json.loads(r.content) for r in httpx_mock.get_requests(method="POST", url=BATCH_URL)] + + +def sent_listing_params(httpx_mock: HTTPXMock) -> list[dict[str, str]]: + return [dict(r.url.params) for r in httpx_mock.get_requests(method="GET") if r.url.path == "/api/storage/objects"] + + +async def test_pages_through_the_listing_and_sends_batches_of_the_given_size( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=3", json=page("a", "b", "c", next_start_after="c")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=3&start_after=c", json=page("d", "e")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + httpx_mock.add_response( + method="POST", url=BATCH_URL, json=answer("c"), match_json={"identifiers": ["c"], "allow_unverified": False} + ) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("d", "e"), + match_json={"identifiers": ["d", "e"], "allow_unverified": False}, + ) + encryptor, _ = make(tmp_path, page_size=3) + + await run(encryptor) + + assert encryptor.totals.counts == {"encrypted": 5} + assert encryptor.totals.objects_listed == 5 + assert encryptor.totals.encrypt_requests == 3 + assert encryptor.completed is True + + +async def test_allow_unverified_is_sent_to_the_server(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path, allow_unverified=True, page_size=5000) + + await run(encryptor) + + assert sent_bodies(httpx_mock) == [{"identifiers": ["a"], "allow_unverified": True}] + + +async def test_counts_every_outcome_and_reports_the_objects_that_were_not_encrypted( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d")) + results = [ + {"identifier": "a", "outcome": "encrypted", "size": 10, "reason": None}, + {"identifier": "b", "outcome": "already_encrypted", "size": 20, "reason": None}, + {"identifier": "c", "outcome": "skipped_unverified", "size": 30, "reason": "no checksum"}, + {"identifier": "d", "outcome": "failed", "size": 0, "reason": "disk full"}, + ] + httpx_mock.add_response(method="POST", url=BATCH_URL, json={"results": results[:2]}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json={"results": results[2:]}) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.totals.counts == {"encrypted": 1, "already_encrypted": 1, "skipped_unverified": 1, "failed": 1} + assert encryptor.totals.bytes_encrypted == 10 + lines = [json.loads(line) for line in (tmp_path / "report.jsonl").read_text().splitlines()] + assert sorted(line["identifier"] for line in lines) == ["b", "c", "d"] + assert next(line for line in lines if line["identifier"] == "c")["reason"] == "no checksum" + + +async def test_dry_run_sends_no_batch_and_writes_no_state_or_report(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + encryptor, _ = make(tmp_path, dry_run=True) + + await run(encryptor) + + assert httpx_mock.get_requests(method="POST") == [] + assert encryptor.totals.objects_listed == 2 + assert encryptor.totals.bytes_listed == 200 + assert encryptor.totals.counts == {} + assert not (tmp_path / "state.json").exists() + assert not (tmp_path / "report.jsonl").exists() + + +async def test_objects_modified_after_before_are_not_sent(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + objects = [stored("old", modified="2026-01-01T00:00:00Z"), stored("new", modified="2026-06-01T12:00:00Z")] + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json={"objects": objects, "next_start_after": None}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("old")) + encryptor, _ = make(tmp_path, before=parse_timestamp("2026-03-01T00:00:00")) + + await run(encryptor) + + assert sent_bodies(httpx_mock) == [{"identifiers": ["old"], "allow_unverified": False}] + assert encryptor.totals.skipped_newer == 1 + assert encryptor.totals.objects_listed == 2 + + +async def test_limit_stops_the_run_after_that_many_objects(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", next_start_after="c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + encryptor, _ = make(tmp_path, limit=2) + + await run(encryptor) + + assert sent_bodies(httpx_mock) == [{"identifiers": ["a", "b"], "allow_unverified": False}] + assert encryptor.completed is False + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + + +@dataclass +class TimestampCase: + name: str + text: str + expected: str + + +TIMESTAMP_CASES = [ + TimestampCase(name="z-suffix", text="2026-11-14T10:00:00Z", expected="2026-11-14T10:00:00+00:00"), + TimestampCase(name="offset", text="2026-11-14T10:00:00+01:00", expected="2026-11-14T10:00:00+01:00"), + TimestampCase(name="no-offset-is-utc", text="2026-11-14T10:00:00", expected="2026-11-14T10:00:00+00:00"), + TimestampCase( + name="microseconds-z", text="2026-11-14T10:00:00.123456Z", expected="2026-11-14T10:00:00.123456+00:00" + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in TIMESTAMP_CASES]) +def test_parse_timestamp(case: TimestampCase) -> None: + assert parse_timestamp(case.text).isoformat() == case.expected + + +def test_parse_retry_after_reads_seconds_and_a_date_and_ignores_anything_else() -> None: + assert parse_retry_after("7") == pytest.approx(7.0) + assert parse_retry_after("2.5") == pytest.approx(2.5) + assert parse_retry_after(None) == pytest.approx(0.0) + assert parse_retry_after("Wed, 21 Oct 2026 07:28:00 GMT") == pytest.approx(0.0) + assert parse_retry_after("-3") == pytest.approx(0.0) + assert parse_retry_after("not a number") == pytest.approx(0.0) + + +@pytest.mark.parametrize("value", ["inf", "-inf", "nan", "1e999"]) +def test_parse_retry_after_ignores_a_value_that_is_not_finite(value: str) -> None: + assert parse_retry_after(value) == pytest.approx(0.0) + + +def test_parse_retry_after_reads_an_http_date_in_the_future() -> None: + value = formatdate(time.time() + 60, usegmt=True) + + assert 50.0 < parse_retry_after(value) <= 60.0 + + +# State file + + +async def test_state_file_records_the_position_after_every_page(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + encryptor, _ = make(tmp_path, page_size=2) + + await run(encryptor) + + state = json.loads((tmp_path / "state.json").read_text()) + assert state["address"] == BASE + assert state["start_after"] == "c" + assert state["completed"] is True + assert state["totals"]["counts"] == {"encrypted": 3} + assert not (tmp_path / "state.json.tmp").exists() + + +async def test_a_rerun_resumes_after_the_saved_position_and_adds_up_the_counters( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + first, _ = make(tmp_path, page_size=2, limit=2) + await run(first) + httpx_mock.add_response( + method="POST", url=BATCH_URL, json=answer("c"), match_json={"identifiers": ["c"], "allow_unverified": False} + ) + + second, _ = make(tmp_path, page_size=2) + await run(second) + + assert second.resumed is True + assert sent_listing_params(httpx_mock) == [{"limit": "2"}, {"limit": "2", "start_after": "b"}] + assert second.totals.counts == {"encrypted": 3} + assert second.handled_this_run == 1 + assert second.completed is True + + +async def test_a_finished_pass_is_not_resumed_and_the_next_run_starts_again( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + await run(make(tmp_path)[0]) + + again, _ = make(tmp_path) + await run(again) + + assert sent_listing_params(httpx_mock) == [{"limit": "5000"}, {"limit": "5000"}] + assert again.resumed is False + assert again.totals.counts == {"encrypted": 1} + + +async def test_restart_ignores_the_state_file(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + (tmp_path / "state.json").write_text( + json.dumps({"address": BASE, "start_after": "m", "completed": False, "totals": {"counts": {"encrypted": 9}}}) + ) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path, restart=True) + + await run(encryptor) + + assert sent_listing_params(httpx_mock) == [{"limit": "5000"}] + assert encryptor.totals.counts == {"encrypted": 1} + + +async def test_a_dry_run_starts_at_the_saved_position_without_loading_the_counters( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + (tmp_path / "state.json").write_text( + json.dumps({"address": BASE, "start_after": "m", "completed": False, "totals": {"counts": {"encrypted": 9}}}) + ) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=m", json=page("n")) + encryptor, _ = make(tmp_path, dry_run=True) + + await run(encryptor) + + assert encryptor.totals.counts == {} + assert encryptor.totals.objects_listed == 1 + + +async def test_a_state_file_of_another_server_is_refused(tmp_path: Path) -> None: + (tmp_path / "state.json").write_text( + json.dumps({"address": "http://other", "start_after": "m", "completed": False, "totals": {}}) + ) + encryptor, _ = make(tmp_path) + + with pytest.raises(MigrationError, match=r"belongs to http://other, not to http://mock"): + await run(encryptor) + + +@pytest.mark.parametrize("content", ["not json", "{}", '{"address": "http://mock"}']) +async def test_an_unreadable_state_file_is_refused(tmp_path: Path, content: str) -> None: + (tmp_path / "state.json").write_text(content) + encryptor, _ = make(tmp_path) + + with pytest.raises(MigrationError, match=r"state file .* cannot be read"): + await run(encryptor) + + +async def test_a_failed_page_leaves_the_state_at_the_last_complete_page(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c", "d")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + status_code=403, + json={"detail": "no"}, + match_json={"identifiers": ["c", "d"], "allow_unverified": False}, + ) + encryptor, _ = make(tmp_path, page_size=2) + + with pytest.raises(MigrationError, match="HTTP 403"): + await run(encryptor) + + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + assert state["totals"]["counts"] == {"encrypted": 2} + assert encryptor.start_after == "b" + + +async def test_cancelling_the_run_keeps_the_state_of_the_last_complete_page( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + async def never_answers(request: httpx.Request) -> httpx.Response: + await asyncio.sleep(3600) + raise AssertionError("not reached") + + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c", "d")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + httpx_mock.add_callback( + never_answers, method="POST", url=BATCH_URL, match_json={"identifiers": ["c", "d"], "allow_unverified": False} + ) + encryptor, _ = make(tmp_path, page_size=2) + + task = asyncio.create_task(run(encryptor)) + for _ in range(200): + await asyncio.sleep(0.01) + if len(httpx_mock.get_requests(method="POST")) == 2: + break + task.cancel() + with pytest.raises(asyncio.CancelledError, match=r"^$"): + await task + + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + assert state["totals"]["counts"] == {"encrypted": 2} + assert encryptor.totals.counts == {"encrypted": 2} + + +# 429 answers + + +async def test_a_429_answer_holds_the_requests_for_retry_after_and_lowers_the_limit( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "7"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path, concurrency=8) + assert encryptor.limit.limit == 4 + + await run(encryptor) + + assert encryptor.totals.shed_429 == 1 + assert encryptor.totals.shed_429_admission == 0 + assert encryptor.limit.limit == 2 + assert encryptor.limit.decreases == 1 + assert fake.sleeps[0] == pytest.approx(7.0) + assert encryptor.totals.counts == {"encrypted": 1} + + +async def test_a_429_answer_without_retry_after_waits_the_backoff(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + + await run(encryptor) + + assert 0.5 <= fake.sleeps[0] <= 0.5 * 1.25 + + +async def test_the_admission_marker_is_counted_apart(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"X-Infrahub-Admission": "shed"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.totals.shed_429 == 2 + assert encryptor.totals.shed_429_admission == 1 + + +async def test_it_waits_out_more_429_answers_than_the_sdk_client_would(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + for _ in range(25): + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "1"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.totals.shed_429 == 25 + assert encryptor.totals.counts == {"encrypted": 1} + + +async def test_a_retry_after_longer_than_the_backoff_cap_is_honoured(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "120"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + + await run(encryptor) + + assert fake.sleeps[0] == pytest.approx(120.0) + + +async def test_the_backoff_after_repeated_429_answers_grows_and_stops_at_its_cap( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + for _ in range(9): + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + + await run(encryptor) + + waits = fake.sleeps[:9] + assert waits[0] < waits[1] < waits[2] < waits[3] + assert all(wait <= 30.0 * 1.25 for wait in waits) + assert waits[-1] >= 30.0 + + +async def test_the_limit_halves_at_most_once_per_cooldown(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "0"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "0"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path, concurrency=16) + + await run(encryptor) + + assert encryptor.limit.decreases == 1 + assert encryptor.limit.limit == 4 + + +# Adaptive limit + + +def test_the_limit_starts_at_half_the_maximum_and_never_below_the_minimum() -> None: + fake = FakeTime() + + assert AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock).limit == 4 + assert AdaptiveLimit(maximum=1, minimum=1, slow_factor=2.0, clock=fake.clock).limit == 1 + assert AdaptiveLimit(maximum=8, minimum=6, slow_factor=2.0, clock=fake.clock).limit == 6 + + +def test_the_limit_rises_by_one_after_as_many_quiet_requests_as_the_limit() -> None: + fake = FakeTime() + limit = AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) + + for _ in range(3): + limit.observe(0.01) + assert limit.limit == 4 + limit.observe(0.01) + assert limit.limit == 5 + assert limit.increases == 1 + for _ in range(100): + limit.observe(0.01) + assert limit.limit == 8 + + +def test_a_slow_signal_halves_the_limit_and_the_limit_rises_again_when_it_is_quiet() -> None: + fake = FakeTime() + limit = AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) + for _ in range(4): + limit.observe(0.01) + assert limit.limit == 5 + + for _ in range(10): + limit.observe(0.5) + assert limit.limit == 2 + assert limit.decreases >= 1 + + fake.now += 10_000 + for _ in range(40): + limit.observe(0.5) + assert limit.limit > 2 + + +def test_the_limit_does_not_fall_below_the_minimum() -> None: + fake = FakeTime() + limit = AdaptiveLimit(maximum=8, minimum=3, slow_factor=2.0, clock=fake.clock) + + for _ in range(5): + limit.shed() + fake.now += 10 + + assert limit.limit == 3 + + +def test_a_second_decrease_inside_the_cooldown_is_ignored() -> None: + fake = FakeTime() + limit = AdaptiveLimit(maximum=16, minimum=1, slow_factor=2.0, clock=fake.clock) + + limit.shed() + limit.shed() + assert limit.limit == 4 + fake.now += 2.5 + limit.shed() + assert limit.limit == 2 + + +async def test_no_more_requests_are_in_flight_than_the_limit_allows() -> None: + fake = FakeTime() + limit = AdaptiveLimit(maximum=4, minimum=1, slow_factor=2.0, clock=fake.clock) + assert limit.limit == 2 + await limit.acquire() + await limit.acquire() + + with pytest.raises(asyncio.TimeoutError, match=r"^$"): + await asyncio.wait_for(limit.acquire(), timeout=0.05) + await limit.release() + await asyncio.wait_for(limit.acquire(), timeout=1) + + +# Transient errors + + +async def test_a_503_answer_is_retried_after_a_backoff(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=503) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=502) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + + await run(encryptor) + + assert encryptor.totals.retries == 2 + assert encryptor.totals.counts == {"encrypted": 1} + assert 0.5 <= fake.sleeps[0] <= 0.5 * 1.25 + assert 1.0 <= fake.sleeps[1] <= 1.0 * 1.25 + + +async def test_a_connection_error_during_the_run_is_retried(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_exception(httpx.ReadError("connection reset"), method="POST", url=BATCH_URL) + httpx_mock.add_exception(httpx.ConnectError("refused"), method="POST", url=BATCH_URL) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.totals.retries == 2 + assert encryptor.totals.counts == {"encrypted": 1} + + +async def test_retries_stop_after_max_retries(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + for _ in range(4): + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=503) + encryptor, _ = make(tmp_path, max_retries=3) + + with pytest.raises(MigrationError, match=r"still fails after 3 retries: HTTP 503"): + await run(encryptor) + + assert encryptor.totals.retries == 3 + + +async def test_a_500_answer_is_not_retried(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=500, text="boom") + + with pytest.raises(MigrationError, match=r"HTTP 500"): + await run(make(tmp_path)[0]) + + assert len(httpx_mock.get_requests(method="POST")) == 1 + + +async def test_a_server_that_never_answers_fails_after_a_few_retries(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_exception(httpx.ConnectError("refused"), is_reusable=True) + encryptor, _ = make(tmp_path, max_retries=10) + + with pytest.raises( + MigrationError, match=rf"cannot be reached .*ConnectError.*after {UNANSWERED_MAX_RETRIES} retries" + ): + await run(encryptor) + + assert encryptor.totals.retries == UNANSWERED_MAX_RETRIES + + +async def test_a_server_that_went_away_after_answering_gets_the_full_retries( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_exception(httpx.ConnectError("refused"), method="POST", url=BATCH_URL, is_reusable=True) + encryptor, _ = make(tmp_path, max_retries=6) + + with pytest.raises(MigrationError, match=r"still fails after 6 retries"): + await run(encryptor) + + assert encryptor.totals.retries == 6 + + +# Refusals + + +@dataclass +class RefusalCase: + name: str + method: str + status: int + body: dict[str, Any] | str + expected: str + + +REFUSAL_CASES = [ + RefusalCase( + name="token-rejected", + method="GET", + status=401, + body={"detail": "bad token"}, + expected="HTTP 401: the server does not accept the token", + ), + RefusalCase( + name="no-super-admin-listing", + method="GET", + status=403, + body={"detail": "no"}, + expected="HTTP 403: the account of this token does not have the super admin permission", + ), + RefusalCase( + name="no-super-admin-batch", + method="POST", + status=403, + body={"errors": [{"message": "Permission denied"}]}, + expected="Server answer: Permission denied", + ), + RefusalCase( + name="no-routes", + method="GET", + status=404, + body={"detail": "Not Found"}, + expected="does not have the storage encryption routes (/api/storage/objects)", + ), + RefusalCase( + name="not-enabled", + method="POST", + status=409, + body={"detail": "Storage encryption is not enabled"}, + expected="HTTP 409: storage encryption is not enabled on the server, or the server has no storage key", + ), + RefusalCase( + name="invalid-batch", + method="POST", + status=422, + body={"detail": "An identifier is listed twice."}, + expected="HTTP 422. Server answer: An identifier is listed twice.", + ), + RefusalCase( + name="plain-text-body", + method="GET", + status=400, + body="gateway says no", + expected="HTTP 400. Server answer: gateway says no", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in REFUSAL_CASES]) +async def test_a_refusal_is_explained(case: RefusalCase, httpx_mock: HTTPXMock, tmp_path: Path) -> None: + body: dict[str, Any] = {"json": case.body} if isinstance(case.body, dict) else {"text": case.body} + if case.method == "GET": + httpx_mock.add_response(method="GET", status_code=case.status, **body) + else: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=case.status, **body) + encryptor, _ = make(tmp_path) + + with pytest.raises(MigrationError, match=re.escape(case.expected)): + await run(encryptor) + + +async def test_the_server_text_of_a_refusal_is_part_of_the_message(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(method="GET", status_code=409, json={"detail": "No storage key is set"}) + + with pytest.raises(MigrationError, match=r"Server answer: No storage key is set"): + await run(make(tmp_path)[0]) + + +# Connections + + +class _CountingServer(ThreadingHTTPServer): + connections = 0 + + +class _Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def setup(self) -> None: + super().setup() + cast("_CountingServer", self.server).connections += 1 + + def log_message(self, format: str, *args: object) -> None: + return + + def _send(self, body: dict[str, Any]) -> None: + raw = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def do_GET(self) -> None: + self._send(page(*[f"id{i:03d}" for i in range(40)])) + + def do_POST(self) -> None: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + self._send(answer(*body["identifiers"])) + + +@pytest.fixture +def local_server() -> Iterator[_CountingServer]: + server = _CountingServer(("127.0.0.1", 0), _Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield server + server.shutdown() + server.server_close() + thread.join() + + +@pytest.mark.httpx_mock(assert_all_responses_were_requested=False) +async def test_every_request_of_a_run_reuses_the_pooled_connection( + local_server: _CountingServer, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + address = f"http://127.0.0.1:{local_server.server_address[1]}" + original = httpx.AsyncClient + + def real_client(**kwargs: Any) -> httpx.AsyncClient: # noqa: ANN401 + return original(transport=httpx.AsyncHTTPTransport(), **kwargs) + + monkeypatch.setattr(httpx, "AsyncClient", real_client) + encryptor, _ = make(tmp_path, address=address, concurrency=1, batch_size=4) + + async with httpx.AsyncClient(base_url=address) as http: + await encryptor.run(http) + + assert encryptor.totals.encrypt_requests == 10 + assert encryptor.totals.requests == 11 + assert local_server.connections == 1 + + +def test_the_batch_limit_matches_the_server() -> None: + assert BATCH_MAX_SIZE == 500 + + +async def test_an_answer_that_is_not_json_stops_the_run_with_a_message(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", text="proxy page") + + with pytest.raises( + MigrationError, match=r"listing of the stored objects was answered with HTTP 200 and a body that is not JSON" + ): + await run(make(tmp_path)[0]) + + +async def test_a_batch_answer_that_is_not_json_stops_the_run_with_a_message( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, text="not json") + + with pytest.raises(MigrationError, match=r"encrypt a batch was answered with HTTP 200 and a body that is not JSON"): + await run(make(tmp_path)[0]) + + +@pytest.mark.parametrize("body", [{"objects": []}, ["x"]]) +async def test_a_listing_of_an_unexpected_shape_stops_the_run( + httpx_mock: HTTPXMock, tmp_path: Path, body: object +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=body) + + with pytest.raises(MigrationError, match=r"listing of the stored objects has an unexpected shape"): + await run(make(tmp_path)[0]) + + +async def test_a_batch_answer_of_an_unexpected_shape_stops_the_run(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json={"unexpected": True}) + + with pytest.raises(MigrationError, match=r"answer of an unexpected shape"): + await run(make(tmp_path)[0]) + + +# Count pass + + +def old_state(**overrides: Any) -> dict[str, Any]: # noqa: ANN401 + """A state file as the version without the count pass wrote it.""" + state: dict[str, Any] = { + "version": 1, + "address": BASE, + "start_after": "b", + "completed": False, + "totals": { + "counts": {"encrypted": 2}, + "bytes_encrypted": 200, + "bytes_listed": 200, + "objects_listed": 2, + "skipped_newer": 0, + "requests": 3, + "encrypt_requests": 1, + "shed_429": 0, + "shed_429_admission": 0, + "retries": 0, + "elapsed_seconds": 4.0, + "limit_decreases": 0, + "limit_increases": 0, + "limit_final": 4, + }, + } + state.update(overrides) + return state + + +def mock_count_and_run_of_three(httpx_mock: HTTPXMock) -> None: + """Three objects of 100 bytes each, counted in two requests of 5000 and listed by the run in pages of 2.""" + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + httpx_mock.add_response( + method="POST", url=BATCH_URL, json=answer("c"), match_json={"identifiers": ["c"], "allow_unverified": False} + ) + + +async def test_the_count_pass_lists_with_the_largest_page_size_before_any_batch_is_sent( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + mock_count_and_run_of_three(httpx_mock) + encryptor, _ = make(tmp_path, page_size=2, count=True) + + await run(encryptor) + + requests = httpx_mock.get_requests() + assert (requests[0].method, dict(requests[0].url.params)) == ("GET", {"limit": "5000"}) + assert [r.method for r in requests].index("POST") > 1 + assert encryptor.remaining_objects == 3 + assert encryptor.remaining_bytes == 300 + + +async def test_the_count_pass_follows_the_pages_and_adds_up_objects_and_bytes( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response( + url=f"{LIST_URL}?limit=5000&start_after=b", + json={"objects": [stored("c", size=300)], "next_start_after": None}, + ) + encryptor, _ = make(tmp_path, count=True) + + async with httpx.AsyncClient(base_url=BASE) as http: + await encryptor._count_pass(http) + + assert encryptor.remaining_objects == 3 + assert encryptor.remaining_bytes == 500 + assert sent_listing_params(httpx_mock) == [{"limit": "5000"}, {"limit": "5000", "start_after": "b"}] + assert encryptor.total_objects == 3 + assert encryptor.total_bytes == 500 + + +async def test_the_count_matches_the_objects_that_are_sent(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + mock_count_and_run_of_three(httpx_mock) + encryptor, _ = make(tmp_path, page_size=2, count=True) + + await run(encryptor) + + assert sum(len(body["identifiers"]) for body in sent_bodies(httpx_mock)) == encryptor.total_objects == 3 + assert encryptor.done_objects == 3 + assert encryptor.done_bytes == encryptor.total_bytes == 300 + + +async def test_the_count_pass_does_not_change_which_objects_are_sent(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + mock_count_and_run_of_three(httpx_mock) + (tmp_path / "a").mkdir() + (tmp_path / "b").mkdir() + counted, _ = make(tmp_path / "a", page_size=2, count=True) + await run(counted) + with_count = sent_bodies(httpx_mock) + uncounted, _ = make(tmp_path / "b", page_size=2, count=False) + + await run(uncounted) + + assert sent_bodies(httpx_mock)[len(with_count) :] == with_count + + +async def test_the_count_pass_leaves_out_objects_modified_after_before(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + objects = [stored("old", modified="2026-01-01T00:00:00Z"), stored("new", size=500, modified="2026-06-01T12:00:00Z")] + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json={"objects": objects, "next_start_after": None}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("old")) + encryptor, _ = make(tmp_path, before=parse_timestamp("2026-03-01T00:00:00"), count=True) + + await run(encryptor) + + assert encryptor.remaining_objects == 1 + assert encryptor.remaining_bytes == 100 + assert encryptor.done_objects == 1 + + +async def test_the_count_pass_stops_at_the_limit_and_requests_no_more_pages( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + encryptor, _ = make(tmp_path, limit=2, count=True) + + await run(encryptor) + + assert encryptor.remaining_objects == 2 + assert encryptor.total_objects == 2 + assert sent_listing_params(httpx_mock) == [{"limit": "5000"}, {"limit": "5000"}] + + +async def test_the_count_pass_cuts_the_last_page_at_the_limit(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d", next_start_after="d")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + encryptor, _ = make(tmp_path, limit=3, count=True) + + await run(encryptor) + + assert encryptor.remaining_objects == 3 + assert encryptor.remaining_bytes == 300 + assert encryptor.done_objects == 3 + + +async def test_a_resumed_count_starts_at_the_saved_position_and_adds_the_objects_of_earlier_runs( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + (tmp_path / "state.json").write_text(json.dumps(old_state())) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + encryptor, _ = make(tmp_path, page_size=2, count=True) + + await run(encryptor) + + assert sent_listing_params(httpx_mock)[0] == {"limit": "5000", "start_after": "b"} + assert encryptor.handled_before == 2 + assert encryptor.remaining_objects == 1 + assert encryptor.total_objects == 3 + assert encryptor.total_bytes == 300 + assert encryptor.done_objects == 3 + assert encryptor.done_bytes == 300 + + +async def test_a_resumed_run_counts_again_and_does_not_trust_the_total_of_the_state_file( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + state = old_state(plan={"objects_total": 10, "bytes_total": 1000}) + (tmp_path / "state.json").write_text(json.dumps(state)) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c", "d")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c", "d")) + encryptor, _ = make(tmp_path, count=True) + + await run(encryptor) + + assert encryptor.total_objects == 4 + assert encryptor.total_objects != 10 + plan = json.loads((tmp_path / "state.json").read_text())["plan"] + assert plan == {"objects_total": 4, "bytes_total": 400} + + +async def test_a_state_file_of_the_version_without_the_count_pass_is_read_and_resumed( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + (tmp_path / "state.json").write_text(json.dumps(old_state())) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.resumed is True + assert encryptor.totals.counts == {"encrypted": 3} + assert encryptor.handled_before == 2 + # The old file has no bytes of every outcome; the bytes of the encrypted objects are the nearest figure. + assert encryptor.totals.bytes_handled == 300 + assert encryptor.total_objects is None + + +async def test_the_state_file_keeps_the_total_and_the_count_figures(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + mock_count_and_run_of_three(httpx_mock) + encryptor, _ = make(tmp_path, page_size=2, count=True) + + await run(encryptor) + + state = json.loads((tmp_path / "state.json").read_text()) + assert state["plan"] == {"objects_total": 3, "bytes_total": 300} + assert state["totals"]["bytes_handled"] == 300 + assert state["totals"]["count_requests"] == 2 + assert state["totals"]["count_seconds"] == pytest.approx(0.0) + assert state["version"] == 1 + + +async def test_a_state_file_with_a_field_this_version_does_not_know_is_still_read( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + state = old_state() + state["totals"]["field_of_a_later_version"] = 7 + (tmp_path / "state.json").write_text(json.dumps(state)) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.totals.counts == {"encrypted": 3} + + +async def test_without_the_count_pass_there_is_no_total_and_no_count_request( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path, count=False) + + await run(encryptor) + + assert sent_listing_params(httpx_mock) == [{"limit": "5000"}] + assert encryptor.total_objects is None + assert encryptor.total_bytes is None + assert "plan" not in json.loads((tmp_path / "state.json").read_text()) + + +async def test_a_dry_run_lists_once_and_totals_what_it_would_send(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + objects = [stored("old"), stored("new", size=500, modified="2026-06-01T12:00:00Z")] + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json={"objects": objects, "next_start_after": None}) + encryptor, _ = make(tmp_path, dry_run=True, count=True, before=parse_timestamp("2026-03-01T00:00:00")) + + await run(encryptor) + + assert sent_listing_params(httpx_mock) == [{"limit": "5000"}] + assert encryptor.selected_objects == 1 + assert encryptor.selected_bytes == 100 + assert encryptor.totals.skipped_newer == 1 + + +async def test_the_count_pass_is_kept_apart_from_the_requests_and_the_time_of_the_run( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + fake = FakeTime() + + def slow_count(request: httpx.Request) -> httpx.Response: + fake.now += 10 + return httpx.Response(200, json=page("a", "b")) + + httpx_mock.add_callback(slow_count, url=f"{LIST_URL}?limit=5000") + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + encryptor, _ = make(tmp_path, fake=fake, page_size=2, count=True) + + await run(encryptor) + + assert encryptor.count_seconds_this_run == pytest.approx(10.0) + assert encryptor.totals.count_seconds == pytest.approx(10.0) + assert encryptor.totals.elapsed_seconds == pytest.approx(0.0) + assert encryptor.totals.count_requests == 1 + assert encryptor.totals.requests == 2 + + +async def test_more_objects_than_counted_are_still_sent_and_done_passes_the_total( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", "c")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) + encryptor, _ = make(tmp_path, page_size=2, count=True) + + await run(encryptor) + + assert encryptor.total_objects == 2 + assert encryptor.done_objects == 3 + assert encryptor.completed is True + + +async def test_the_callback_runs_once_after_the_count(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + mock_count_and_run_of_three(httpx_mock) + seen: list[int | None] = [] + encryptor, _ = make(tmp_path, page_size=2, count=True) + encryptor.on_counted = lambda: seen.append(encryptor.remaining_objects) + + await run(encryptor) + + assert seen == [3] + + +async def test_a_429_answer_during_the_count_is_waited_out_and_counted(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", status_code=429, headers={"Retry-After": "3"}) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path, page_size=5000, count=True) + + await run(encryptor) + + assert encryptor.totals.shed_429 >= 1 + assert max(fake.sleeps) >= 3.0 + assert encryptor.remaining_objects == 1 + + +@dataclass +class CountRefusalCase: + name: str + status: int + body: dict[str, Any] + expected: str + + +COUNT_REFUSAL_CASES = [ + CountRefusalCase( + name="token-rejected", status=401, body={"detail": "bad"}, expected="HTTP 401: the server does not accept" + ), + CountRefusalCase( + name="no-super-admin", status=403, body={"detail": "no"}, expected="does not have the super admin permission" + ), + CountRefusalCase( + name="no-routes", + status=404, + body={"detail": "Not Found"}, + expected="does not have the storage encryption routes", + ), + CountRefusalCase( + name="not-enabled", + status=409, + body={"detail": "Storage encryption is not enabled"}, + expected="storage encryption is not enabled on the server", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in COUNT_REFUSAL_CASES]) +async def test_a_refusal_during_the_count_stops_the_run_with_the_same_message_as_during_the_run( + case: CountRefusalCase, httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(method="GET", status_code=case.status, json=case.body) + encryptor, _ = make(tmp_path, count=True) + + with pytest.raises(MigrationError, match=re.escape(case.expected)) as raised: + await run(encryptor) + + assert "The listing of the stored objects was refused" in str(raised.value) + assert httpx_mock.get_requests(method="POST") == [] + assert len(httpx_mock.get_requests()) == 1 + assert not (tmp_path / "state.json").exists() + assert encryptor.counting is False + assert encryptor.total_objects is None + + +async def test_a_refusal_on_a_later_page_of_the_count_stops_the_run_before_any_batch( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", next_start_after="a")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=a", status_code=403, json={"detail": "no"}) + encryptor, _ = make(tmp_path, count=True) + + with pytest.raises(MigrationError, match="super admin"): + await run(encryptor) + + assert httpx_mock.get_requests(method="POST") == [] + + +async def test_a_server_that_cannot_be_reached_during_the_count_stops_the_run_with_the_cause( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_exception(httpx.ConnectError("connection refused"), is_reusable=True) + encryptor, _ = make(tmp_path, count=True) + + with pytest.raises(MigrationError, match=r"cannot be reached \(ConnectError: connection refused\)"): + await run(encryptor) + + assert len(httpx_mock.get_requests()) == UNANSWERED_MAX_RETRIES + 1 + assert encryptor.totals.requests == 0 + assert not (tmp_path / "state.json").exists() + + +@pytest.mark.parametrize("body", ["not json", '{"unexpected": 1}'], ids=["not-json", "unexpected-shape"]) +async def test_an_unreadable_count_listing_stops_the_run_with_a_message( + body: str, httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(method="GET", text=body) + encryptor, _ = make(tmp_path, count=True) + + with pytest.raises(MigrationError, match="listing of the stored objects"): + await run(encryptor) + + assert httpx_mock.get_requests(method="POST") == [] + + +async def test_cancelling_the_run_during_the_count_saves_nothing_and_ends_the_count( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + async def never_answers(request: httpx.Request) -> httpx.Response: + await asyncio.sleep(30) + raise AssertionError("not reached") + + httpx_mock.add_callback(never_answers, url=f"{LIST_URL}?limit=5000") + encryptor, _ = make(tmp_path, count=True) + task = asyncio.create_task(run(encryptor)) + for _ in range(50): + if encryptor.counting: + break + await asyncio.sleep(0.01) + assert encryptor.counting is True + + task.cancel() + with pytest.raises(asyncio.CancelledError, match=r"^$"): + await task + + assert encryptor.counting is False + assert not (tmp_path / "state.json").exists() + assert encryptor.totals.requests == 0 + + +# Retry-After and backoff limits + + +def test_the_backoff_does_not_overflow_for_a_very_high_attempt() -> None: + delay = backoff_delay(attempt=5000, rng=random.Random(1)) + + assert 30.0 <= delay <= 30.0 * 1.25 + + +async def test_a_retry_after_beyond_the_maximum_pause_is_cut_and_said(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "100000"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + notices: list[str] = [] + encryptor.on_notice = notices.append + + await run(encryptor) + + assert fake.sleeps[0] == pytest.approx(RETRY_AFTER_MAX_SECONDS) + assert len(notices) == 1 + assert "asked for a pause of 100000 seconds" in notices[0] + + +async def test_a_retry_after_that_is_not_finite_waits_the_backoff_only(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "inf"}) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + + await run(encryptor) + + assert fake.sleeps[0] < 1.0 + assert encryptor.totals.counts == {"encrypted": 1} + + +async def test_a_retry_after_given_as_a_date_is_honoured(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + status_code=429, + headers={"Retry-After": formatdate(time.time() + 60, usegmt=True)}, + ) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, fake = make(tmp_path) + + await run(encryptor) + + assert 50.0 < fake.sleeps[0] <= 60.0 + + +def test_a_first_latency_sample_of_zero_does_not_set_the_floor_to_zero() -> None: + fake = FakeTime() + limit = AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) + + limit.observe(0.0) + limit.observe(0.01) + limit.observe(0.01) + + assert limit.decreases == 0 + + +# Expired login + + +EXPIRED = {"errors": [{"message": "Expired Signature", "extensions": {"code": 401}}]} + + +class Login: + """Stands for the new login of the command: it sets a new token on the client of the run.""" + + def __init__(self, delay: float = 0.0) -> None: + self.calls = 0 + self.delay = delay + + async def __call__(self, http: httpx.AsyncClient) -> None: + self.calls += 1 + await asyncio.sleep(self.delay) + http.headers["Authorization"] = "Bearer new" + + +def reject_the_old_token(request: httpx.Request) -> httpx.Response: + if request.headers.get("Authorization") == "Bearer old": + return httpx.Response(401, json=EXPIRED) + return httpx.Response(200, json=answer(*json.loads(request.content)["identifiers"])) + + +async def test_an_expired_token_is_renewed_and_the_request_is_sent_again(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_callback(reject_the_old_token, method="POST", url=BATCH_URL) + encryptor, _ = make(tmp_path) + login = Login() + encryptor.refresh_login = login + + await run(encryptor, headers={"Authorization": "Bearer old"}) + + assert login.calls == 1 + posts = httpx_mock.get_requests(method="POST") + assert [r.headers["Authorization"] for r in posts] == ["Bearer old", "Bearer new"] + assert encryptor.totals.counts == {"encrypted": 2} + + +async def test_a_token_that_cannot_be_renewed_stops_the_run_with_the_refusal( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=401, json=EXPIRED) + encryptor, _ = make(tmp_path) + + with pytest.raises(MigrationError, match=r"HTTP 401: the server does not accept the token or credentials"): + await run(encryptor, headers={"Authorization": "Bearer old"}) + + assert len(httpx_mock.get_requests(method="POST")) == 1 + + +async def test_a_401_that_does_not_say_the_token_expired_is_not_retried(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=401, json={"detail": "Not allowed"}) + encryptor, _ = make(tmp_path) + login = Login() + encryptor.refresh_login = login + + with pytest.raises(MigrationError, match=r"HTTP 401"): + await run(encryptor) + + assert login.calls == 0 + + +async def test_a_request_is_renewed_once_and_not_in_a_loop(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=401, json=EXPIRED) + encryptor, _ = make(tmp_path) + login = Login() + encryptor.refresh_login = login + + with pytest.raises(MigrationError, match=r"HTTP 401"): + await run(encryptor, headers={"Authorization": "Bearer old"}) + + assert login.calls == 1 + assert len(httpx_mock.get_requests(method="POST")) == 2 + + +async def test_two_requests_that_get_a_401_together_renew_the_login_once(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d")) + httpx_mock.add_callback(reject_the_old_token, method="POST", url=BATCH_URL) + encryptor, _ = make(tmp_path, concurrency=4) + assert encryptor.limit.limit == 2 + login = Login(delay=0.05) + encryptor.refresh_login = login + + await run(encryptor, headers={"Authorization": "Bearer old"}) + + assert login.calls == 1 + assert encryptor.totals.counts == {"encrypted": 4} + + +async def test_a_login_that_fails_stops_the_run_with_a_message(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + async def failing(http: httpx.AsyncClient) -> None: + raise httpx.ConnectError("connection refused") + + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=401, json=EXPIRED) + encryptor, _ = make(tmp_path) + encryptor.refresh_login = failing + + with pytest.raises(MigrationError, match=r"new login failed \(ConnectError: connection refused\)"): + await run(encryptor) + + +# Files checked before the run + + +def files_at(option: str, path: Path) -> dict[str, Any]: + return {option: path} + + +async def test_a_missing_directory_for_the_state_file_stops_the_run_before_any_request( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + encryptor, _ = make(tmp_path, state_file=tmp_path / "missing" / "state.json", count=True) + + with pytest.raises(MigrationError, match=r"directory of --state-file .* does not exist"): + await run(encryptor) + + assert httpx_mock.get_requests() == [] + + +async def test_a_missing_directory_for_the_report_stops_the_run_before_the_count( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + encryptor, _ = make(tmp_path, report=tmp_path / "missing" / "report.jsonl", count=True) + + with pytest.raises(MigrationError, match=r"directory of --report .* does not exist"): + await run(encryptor) + + assert httpx_mock.get_requests() == [] + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root can write anywhere") +@pytest.mark.parametrize("option", ["state_file", "report"]) +async def test_a_directory_that_cannot_be_written_stops_the_run_before_any_request( + httpx_mock: HTTPXMock, tmp_path: Path, option: str +) -> None: + locked = tmp_path / "locked" + locked.mkdir() + locked.chmod(0o500) + encryptor, _ = make(tmp_path, **files_at(option, locked / "file")) + + try: + with pytest.raises(MigrationError, match=r"is not writable"): + await run(encryptor) + finally: + locked.chmod(0o700) + + assert httpx_mock.get_requests() == [] + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root can write anywhere") +@pytest.mark.parametrize("option", ["state_file", "report"]) +async def test_a_file_that_cannot_be_written_stops_the_run_before_any_request( + httpx_mock: HTTPXMock, tmp_path: Path, option: str +) -> None: + path = tmp_path / "readonly" + path.write_text("{}") + path.chmod(0o400) + encryptor, _ = make(tmp_path, **files_at(option, path)) + + with pytest.raises(MigrationError, match=r"cannot be written"): + await run(encryptor) + + assert httpx_mock.get_requests() == [] + + +@pytest.mark.parametrize("option", ["state_file", "report"]) +async def test_a_directory_given_as_a_file_stops_the_run_before_any_request( + httpx_mock: HTTPXMock, tmp_path: Path, option: str +) -> None: + encryptor, _ = make(tmp_path, **files_at(option, tmp_path)) + + with pytest.raises(MigrationError, match=r"cannot be written"): + await run(encryptor) + + assert httpx_mock.get_requests() == [] + + +async def test_a_dry_run_does_not_need_the_state_file_or_the_report(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + encryptor, _ = make( + tmp_path, dry_run=True, state_file=tmp_path / "x" / "state.json", report=tmp_path / "y" / "report.jsonl" + ) + + await run(encryptor) + + assert encryptor.totals.objects_listed == 1 + + +# Runs cut short by --limit and runs that add to the report + + +def serve_objects(httpx_mock: HTTPXMock, identifiers: list[str]) -> list[str]: + """Serve the listing of `identifiers` after the `start_after` parameter, and record what is sent.""" + sent: list[str] = [] + + def listing(request: httpx.Request) -> httpx.Response: + after = request.url.params.get("start_after") + rest = identifiers[identifiers.index(after) + 1 :] if after else identifiers + return httpx.Response(200, json=page(*rest)) + + def encrypt(request: httpx.Request) -> httpx.Response: + batch = json.loads(request.content)["identifiers"] + sent.extend(batch) + return httpx.Response(200, json=answer(*batch)) + + httpx_mock.add_callback(listing, method="GET", url=re.compile(rf"{re.escape(LIST_URL)}\?.*")) + httpx_mock.add_callback(encrypt, method="POST", url=BATCH_URL) + return sent + + +async def test_runs_cut_by_limit_send_every_object_once_and_leave_the_position_at_the_last_sent( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + identifiers = [f"o{n}" for n in range(10)] + sent = serve_objects(httpx_mock, identifiers) + positions: list[tuple[str | None, bool]] = [] + + for _ in range(4): + encryptor, _ = make(tmp_path, limit=3) + await run(encryptor) + state = json.loads((tmp_path / "state.json").read_text()) + positions.append((state["start_after"], state["completed"])) + + assert sent == identifiers + assert positions == [("o2", False), ("o5", False), ("o8", False), ("o9", True)] + + +async def test_every_run_adds_to_the_report(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", outcome="skipped_unverified")) + + for _ in range(2): + encryptor, _ = make(tmp_path) + await run(encryptor) + + lines = (tmp_path / "report.jsonl").read_text().splitlines() + assert [json.loads(line)["identifier"] for line in lines] == ["a", "a"] + + +# Listings whose next position is not the last listed object + + +LISTING_REQUEST_LIMIT = 20 + + +def serve_pages( + httpx_mock: HTTPXMock, pages: dict[str | None, dict[str, Any]], refuse_batches: bool = False +) -> tuple[list[str | None], list[str]]: + """Serve each listing page by the `start_after` it is asked for, and record the positions asked and the objects sent. + + A server that is asked more than `LISTING_REQUEST_LIMIT` times answers 400, so a command that never advances + ends with an error instead of running for ever. + """ + asked: list[str | None] = [] + sent: list[str] = [] + + def listing(request: httpx.Request) -> httpx.Response: + asked.append(request.url.params.get("start_after")) + if len(asked) > LISTING_REQUEST_LIMIT: + return httpx.Response(400, json={"detail": "listing asked too often"}) + return httpx.Response(200, json=pages[asked[-1]]) + + def encrypt(request: httpx.Request) -> httpx.Response: + if refuse_batches: + return httpx.Response(403, json={"detail": "no"}) + batch = json.loads(request.content)["identifiers"] + sent.extend(batch) + return httpx.Response(200, json=answer(*batch)) + + httpx_mock.add_callback(listing, method="GET", url=re.compile(rf"{re.escape(LIST_URL)}\?.*")) + httpx_mock.add_callback(encrypt, method="POST", url=BATCH_URL, is_optional=True) + return asked, sent + + +async def test_an_empty_page_with_a_next_position_is_followed_and_never_listed_twice( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + asked, sent = serve_pages(httpx_mock, {None: page(next_start_after="b"), "b": page("c")}) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert asked == [None, "b"] + assert sent == ["c"] + assert encryptor.totals.objects_listed == 1 + assert encryptor.totals.counts == {"encrypted": 1} + assert encryptor.completed is True + state = json.loads((tmp_path / "state.json").read_text()) + assert (state["start_after"], state["completed"]) == ("c", True) + + +async def test_the_state_file_moves_to_the_next_position_of_an_empty_page( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + asked, _ = serve_pages(httpx_mock, {None: page(next_start_after="b"), "b": page("c")}, refuse_batches=True) + encryptor, _ = make(tmp_path) + + with pytest.raises(MigrationError, match="HTTP 403"): + await run(encryptor) + + assert asked == [None, "b"] + state = json.loads((tmp_path / "state.json").read_text()) + assert (state["start_after"], state["completed"]) == ("b", False) + assert encryptor.start_after == "b" + + +async def test_a_next_position_beyond_the_last_listed_object_is_the_new_position( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + asked, sent = serve_pages(httpx_mock, {None: page("a", "b", next_start_after="c"), "c": page("d")}) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert asked == [None, "c"] + assert sent == ["a", "b", "d"] + assert encryptor.totals.objects_listed == 3 + assert json.loads((tmp_path / "state.json").read_text())["start_after"] == "d" + + +async def test_a_server_that_repeats_the_position_it_was_given_stops_the_run( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + asked, sent = serve_pages(httpx_mock, {None: page("a", next_start_after="a"), "a": page(next_start_after="a")}) + encryptor, _ = make(tmp_path) + + with pytest.raises(MigrationError, match="does not advance"): + await run(encryptor) + + assert asked == [None, "a"] + assert sent == ["a"] + assert encryptor.completed is False + assert json.loads((tmp_path / "state.json").read_text())["start_after"] == "a" + + +async def test_a_server_that_repeats_the_position_stops_the_count_before_any_batch( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + asked, sent = serve_pages(httpx_mock, {None: page("a", next_start_after="a"), "a": page(next_start_after="a")}) + encryptor, _ = make(tmp_path, count=True) + + with pytest.raises(MigrationError, match="does not advance"): + await run(encryptor) + + assert asked == [None, "a"] + assert sent == [] + + +async def test_a_limit_that_cuts_a_page_keeps_the_last_sent_object_as_the_position( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + pages = {None: page("a", "b", "c", "d", next_start_after="e"), "b": page("c", "d", next_start_after="e")} + asked, sent = serve_pages(httpx_mock, pages) + encryptor, _ = make(tmp_path, limit=2) + + await run(encryptor) + + state = json.loads((tmp_path / "state.json").read_text()) + assert (state["start_after"], state["completed"]) == ("b", False) + assert sent == ["a", "b"] + + pages["b"] = page("c", "d") + again, _ = make(tmp_path, limit=2) + await run(again) + + assert asked == [None, "b"] + assert sent == ["a", "b", "c", "d"] + assert json.loads((tmp_path / "state.json").read_text())["completed"] is True + + +async def test_the_count_and_the_run_agree_on_pages_that_are_empty_or_end_beyond_their_last_object( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + pages = { + None: page(next_start_after="b"), + "b": page("c", "d", next_start_after="e"), + "e": page(next_start_after="f"), + "f": page("g"), + } + asked, sent = serve_pages(httpx_mock, pages) + encryptor, _ = make(tmp_path, count=True) + + await run(encryptor) + + assert sent == ["c", "d", "g"] + assert asked == [None, "b", "e", "f"] * 2 + assert encryptor.remaining_objects == encryptor.total_objects == encryptor.done_objects == 3 + assert encryptor.done_bytes == encryptor.total_bytes == 300 diff --git a/tests/unit/ctl/test_storage_progress.py b/tests/unit/ctl/test_storage_progress.py new file mode 100644 index 000000000..2bf07dc64 --- /dev/null +++ b/tests/unit/ctl/test_storage_progress.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import pytest + +from infrahub_sdk.ctl.storage.progress import ( + ProgressView, + RateTracker, + format_bytes, + format_duration, + format_number, + format_percent, + progress_line, + remaining_text, +) + + +def view(**overrides: float | None) -> ProgressView: + values: dict[str, int | float | None] = { + "done_objects": 1000, + "total_objects": 4000, + "done_bytes": 2_000_000_000, + "total_bytes": 8_000_000_000, + "rate": 100.0, + "limit": 6, + "limit_maximum": 8, + "shed_429": 2, + "retries": 1, + } + values.update(overrides) + return ProgressView(**values) # type: ignore[arg-type] + + +@dataclass +class FormatCase: + name: str + value: float + expected: str + + +BYTE_CASES = [ + FormatCase(name="zero", value=0, expected="0 B"), + FormatCase(name="below-a-kilobyte", value=999, expected="999 B"), + FormatCase(name="one-kilobyte", value=1000, expected="1.0 kB"), + FormatCase(name="gigabytes", value=23_400_000_000, expected="23.4 GB"), + FormatCase(name="petabytes", value=3 * 10**15, expected="3.0 PB"), + FormatCase(name="beyond-the-largest-unit", value=2 * 10**18, expected="2000.0 PB"), + FormatCase(name="negative-is-zero", value=-5, expected="0 B"), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in BYTE_CASES]) +def test_format_bytes(case: FormatCase) -> None: + assert format_bytes(int(case.value)) == case.expected + + +DURATION_CASES = [ + FormatCase(name="seconds", value=45, expected="45s"), + FormatCase(name="zero", value=0, expected="0s"), + FormatCase(name="minutes", value=185, expected="3m 05s"), + FormatCase(name="hours", value=7620, expected="2h 07m"), + FormatCase(name="days", value=3 * 86400 + 4 * 3600, expected="3d 04h"), + FormatCase(name="more-than-99-days", value=100 * 86400, expected=">99d"), + FormatCase(name="infinite", value=float("inf"), expected="unknown"), + FormatCase(name="not-a-number", value=float("nan"), expected="unknown"), + FormatCase(name="negative", value=-1, expected="unknown"), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in DURATION_CASES]) +def test_format_duration(case: FormatCase) -> None: + assert format_duration(case.value) == case.expected + + +def test_format_number_groups_thousands_for_very_large_numbers() -> None: + assert format_number(157_000) == "157,000" + assert format_number(12_345_678_901) == "12,345,678,901" + + +@dataclass +class PercentCase: + name: str + done: int + total: int + expected: str + + +PERCENT_CASES = [ + PercentCase(name="start", done=0, total=100, expected="0.0%"), + PercentCase(name="half", done=50, total=100, expected="50.0%"), + PercentCase(name="rounds-down-so-100-means-finished", done=9999, total=10000, expected="99.9%"), + PercentCase(name="finished", done=100, total=100, expected="100.0%"), + PercentCase(name="more-objects-than-counted", done=130, total=100, expected="100.0%"), + PercentCase(name="nothing-to-process", done=0, total=0, expected="100.0%"), + PercentCase(name="huge", done=10**12, total=4 * 10**12, expected="25.0%"), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in PERCENT_CASES]) +def test_format_percent(case: PercentCase) -> None: + assert format_percent(done=case.done, total=case.total) == case.expected + + +def test_the_rate_is_unknown_until_the_samples_span_enough_time() -> None: + tracker = RateTracker(window=30, minimum_span=4) + assert tracker.rate() is None + tracker.record(now=0, done=0) + assert tracker.rate() is None + tracker.record(now=3, done=300) + assert tracker.rate() is None + tracker.record(now=5, done=500) + assert tracker.rate() == pytest.approx(100.0) + + +def test_the_rate_follows_the_last_window_and_not_the_average_since_the_start() -> None: + tracker = RateTracker(window=30, minimum_span=4) + # 100 objects/s for 60 s, then 10 objects/s for 40 s. + for second in range(0, 101, 2): + done = second * 100 if second <= 60 else 6000 + (second - 60) * 10 + tracker.record(now=second, done=done) + average_since_start = 6400 / 100 + assert tracker.rate() == pytest.approx(10.0) + assert tracker.rate() != pytest.approx(average_since_start) + + +def test_the_rate_is_zero_when_nothing_progressed_in_the_window() -> None: + tracker = RateTracker(window=30, minimum_span=4) + tracker.record(now=0, done=500) + tracker.record(now=10, done=500) + assert tracker.rate() == pytest.approx(0.0) + + +def test_the_rate_is_never_negative() -> None: + tracker = RateTracker(window=30, minimum_span=4) + tracker.record(now=0, done=500) + tracker.record(now=10, done=400) + assert tracker.rate() == pytest.approx(0.0) + + +def test_the_progress_line_shows_done_total_percent_rate_remaining_bytes_limit_429_and_retries() -> None: + line = progress_line(view()) + + assert line == ( + "1,000 / 4,000 objects (25.0%) | 100 objects/s | remaining 30s | 2.0 GB / 8.0 GB | limit 6/8 | 429: 2 | retries: 1" + ) + + +def test_the_progress_line_says_estimating_until_there_is_a_rate() -> None: + line = progress_line(view(rate=None)) + + assert "| estimating |" in line + assert "remaining estimating" in line + + +def test_the_progress_line_with_a_rate_of_zero_does_not_divide_by_zero() -> None: + line = progress_line(view(rate=0.0)) + + assert "0 objects/s" in line + assert "remaining unknown" in line + + +def test_the_progress_line_with_nothing_to_process() -> None: + line = progress_line(view(done_objects=0, total_objects=0, done_bytes=0, total_bytes=0, rate=None)) + + assert line.startswith("0 / 0 objects (100.0%)") + assert "remaining finishing" in line + assert "0 B / 0 B" in line + + +def test_the_progress_line_when_more_objects_appeared_than_were_counted() -> None: + line = progress_line(view(done_objects=4200, total_objects=4000)) + + assert line.startswith("4,200 / 4,000 objects (100.0%)") + assert "remaining finishing" in line + + +def test_the_progress_line_without_a_total_shows_no_total_percent_or_remaining_time() -> None: + line = progress_line(view(total_objects=None, total_bytes=None)) + + assert line == "1,000 objects | 100 objects/s | 2.0 GB | limit 6/8 | 429: 2 | retries: 1" + assert "%" not in line + assert "remaining" not in line + assert "/ 4" not in line + + +def test_the_progress_line_with_very_large_numbers() -> None: + line = progress_line( + view( + done_objects=1_234_567_890, + total_objects=9_876_543_210, + done_bytes=5 * 10**15, + total_bytes=4 * 10**16, + rate=2_500_000.0, + ) + ) + + assert line.startswith("1,234,567,890 / 9,876,543,210 objects (12.4%) | 2,500,000 objects/s | remaining ") + assert "5.0 PB / 40.0 PB" in line + + +def test_the_remaining_time_is_the_objects_left_divided_by_the_recent_rate() -> None: + assert remaining_text(view(done_objects=0, total_objects=36_000, rate=10.0)) == "1h 00m" + assert remaining_text(view(done_objects=0, total_objects=36_000, rate=20.0)) == "30m 00s" From a3266e8ef72cf130d0c8ae8cfd698ab4659f863b Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Thu, 19 Nov 2026 13:42:11 +0100 Subject: [PATCH 2/9] fix: do not show a wrong remaining time after a freeze, and show what a stopped page confirmed After the process was frozen (SIGSTOP, a paused container), the rate window still held a sample from before the freeze, so the remaining time showed hours for about 30 seconds. The rate tracker now drops its samples when two samples are more than 5 seconds apart, so the line shows `estimating` for 4 seconds and then the right value. A stall of the server is not a gap: the refresh goes on and the rate falls. A stop in the middle of a page printed a table without the objects that the server had already confirmed in that page, because a page is counted only when it is complete. The table now lists them in separate rows marked `interrupted page, not saved`, and a note says that no position was saved and that a smaller `--page-size` saves it more often. The totals, the state file, the options and the exit codes are unchanged. Signed-off-by: Simon AURA--SCUSSEL --- infrahub_sdk/ctl/storage/encrypt.py | 25 +++- infrahub_sdk/ctl/storage/migration.py | 18 +++ infrahub_sdk/ctl/storage/progress.py | 16 ++- tests/unit/ctl/test_storage_app.py | 152 +++++++++++++++++++++++ tests/unit/ctl/test_storage_migration.py | 83 +++++++++++++ tests/unit/ctl/test_storage_progress.py | 54 +++++++- 6 files changed, 342 insertions(+), 6 deletions(-) diff --git a/infrahub_sdk/ctl/storage/encrypt.py b/infrahub_sdk/ctl/storage/encrypt.py index b4fe8b1b9..3287f2918 100644 --- a/infrahub_sdk/ctl/storage/encrypt.py +++ b/infrahub_sdk/ctl/storage/encrypt.py @@ -174,7 +174,7 @@ def _announce_count(encryptor: StorageEncryptor) -> None: def _summary_table(encryptor: StorageEncryptor, options: Options) -> Table: totals = encryptor.totals seconds = encryptor.seconds_this_run - handled = encryptor.handled_this_run + handled = encryptor.handled_this_run + sum(encryptor.interrupted_counts.values()) table = Table(show_header=False, title="Storage encryption" + (" (dry run)" if options.dry_run else "")) table.add_row("Objects listed", str(totals.objects_listed)) if options.dry_run: @@ -194,8 +194,12 @@ def _summary_table(encryptor: StorageEncryptor, options: Options) -> Table: table.add_row(outcome, str(count)) if options.before: table.add_row("Skipped, modified after --before", str(totals.skipped_newer)) + for outcome, count in sorted(encryptor.interrupted_counts.items()): + table.add_row(f"{outcome} (interrupted page, not saved)", str(count)) table.add_row("Bytes listed", str(totals.bytes_listed)) table.add_row("Bytes encrypted", str(totals.bytes_encrypted)) + if encryptor.interrupted_counts: + table.add_row("Bytes encrypted (interrupted page, not saved)", str(encryptor.interrupted_bytes_encrypted)) table.add_row("Requests", f"{totals.requests} ({totals.encrypt_requests} to encrypt a batch)") table.add_row("Retries after errors", str(totals.retries)) table.add_row("Answers 429", f"{totals.shed_429} ({totals.shed_429_admission} with the admission marker)") @@ -211,6 +215,23 @@ def _summary_table(encryptor: StorageEncryptor, options: Options) -> Table: return table +def _print_interrupted_page(encryptor: StorageEncryptor, state_file: Path) -> None: + """Say what the interrupted page left out of the table, and why no position was saved when none was.""" + if encryptor.interrupted_counts: + console.print( + "The rows marked 'interrupted page' are what the server confirmed in a page that was not complete. " + "They are not saved. Requests still in flight at the stop can have encrypted more. The rerun repeats " + "the page, and the server reports the objects it already encrypted as already_encrypted.", + highlight=False, + ) + if encryptor.page_interrupted and not state_file.exists(): + console.print( + "No page was complete, so no position was saved. With a smaller --page-size the position is saved " + "after every page.", + highlight=False, + ) + + @catch_exception(console=console) async def encrypt_command( concurrency: int = typer.Option( @@ -322,9 +343,11 @@ async def renew_login(http: httpx.AsyncClient) -> None: if not dry_run and state_file.exists(): console.print(f"Progress is saved in {escape(str(state_file))}; run the same command again to resume.") console.print(_summary_table(encryptor, options)) + _print_interrupted_page(encryptor, state_file) raise typer.Exit(code=EXIT_STOPPED) from exc console.print(_summary_table(encryptor, options)) + _print_interrupted_page(encryptor, state_file) if dry_run and stopped_by is None: console.print( f"To process: {format_number(encryptor.selected_objects)} objects ({format_bytes(encryptor.selected_bytes)})", diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py index dfdf0e3e5..7364934e5 100644 --- a/infrahub_sdk/ctl/storage/migration.py +++ b/infrahub_sdk/ctl/storage/migration.py @@ -264,6 +264,9 @@ def __init__( self._bytes_at_start = 0 self.objects_confirmed = 0 self.bytes_confirmed = 0 + self.page_interrupted = False + self.interrupted_counts: dict[str, int] = {} + self.interrupted_bytes_encrypted = 0 self.selected_objects = 0 self.selected_bytes = 0 self.remaining_objects: int | None = None @@ -563,6 +566,18 @@ def _record(self, result: dict[str, Any], report: TextIO | None) -> None: elif report is not None: report.write(json.dumps(result) + "\n") + def _keep_interrupted(self, results: list[dict[str, Any]]) -> None: + """Keep what the server confirmed in a page that did not complete, for the summary only. + + These results are not in `totals`, so the state file never counts them: the rerun repeats the page. + """ + self.page_interrupted = True + for result in results: + outcome = result["outcome"] + self.interrupted_counts[outcome] = self.interrupted_counts.get(outcome, 0) + 1 + if outcome == OUTCOME_ENCRYPTED: + self.interrupted_bytes_encrypted += result["size"] + def _select(self, objects: list[dict[str, Any]], remaining: int | None) -> tuple[list[dict[str, Any]], bool]: """Return the objects of a page to work on, and whether the limit of the run cut the page short.""" selected: list[dict[str, Any]] = [] @@ -600,6 +615,9 @@ async def worker() -> None: workers = [asyncio.create_task(worker()) for _ in range(min(self.options.concurrency, queue.qsize()))] try: await asyncio.gather(*workers) + except BaseException: + self._keep_interrupted(results) + raise finally: for task in workers: task.cancel() diff --git a/infrahub_sdk/ctl/storage/progress.py b/infrahub_sdk/ctl/storage/progress.py index b653caf86..d2a542189 100644 --- a/infrahub_sdk/ctl/storage/progress.py +++ b/infrahub_sdk/ctl/storage/progress.py @@ -6,6 +6,7 @@ RATE_WINDOW_SECONDS = 30.0 RATE_MINIMUM_SPAN_SECONDS = 4.0 +RATE_MAXIMUM_GAP_SECONDS = 5.0 MINIMUM_SAMPLES = 2 BYTES_PER_UNIT = 1000 BYTE_UNITS = ("B", "kB", "MB", "GB", "TB", "PB") @@ -20,14 +21,27 @@ class RateTracker: The caller records `(time, done)` once per progress refresh, which costs two numbers per refresh. The rate stays unknown until the recorded samples span `minimum_span` seconds. + + The refresh runs twice per second, so two samples more than `maximum_gap` seconds apart mean the process did + not run in between (for example after SIGSTOP). The samples before the gap are dropped, because a rate over a + span that holds the pause says nothing about the current speed. + A stall of the server does not make a gap: the refresh goes on and the rate falls. """ - def __init__(self, window: float = RATE_WINDOW_SECONDS, minimum_span: float = RATE_MINIMUM_SPAN_SECONDS) -> None: + def __init__( + self, + window: float = RATE_WINDOW_SECONDS, + minimum_span: float = RATE_MINIMUM_SPAN_SECONDS, + maximum_gap: float = RATE_MAXIMUM_GAP_SECONDS, + ) -> None: self._window = window self._minimum_span = minimum_span + self._maximum_gap = maximum_gap self._samples: deque[tuple[float, int]] = deque() def record(self, now: float, done: int) -> None: + if self._samples and now - self._samples[-1][0] > self._maximum_gap: + self._samples.clear() self._samples.append((now, done)) # Keep one sample at or before the start of the window, so the window is always fully covered. while len(self._samples) > MINIMUM_SAMPLES and self._samples[1][0] <= now - self._window: diff --git a/tests/unit/ctl/test_storage_app.py b/tests/unit/ctl/test_storage_app.py index 598fa2d51..a0157cd56 100644 --- a/tests/unit/ctl/test_storage_app.py +++ b/tests/unit/ctl/test_storage_app.py @@ -18,6 +18,7 @@ from infrahub_sdk.ctl.storage.migration import Options, StorageEncryptor if TYPE_CHECKING: + from collections.abc import Awaitable, Callable from pathlib import Path from click.testing import Result @@ -329,6 +330,10 @@ def text_of(result: Result) -> str: return result.stdout.replace("\n", " ") +def squeezed(result: Result) -> str: + return " ".join(result.stdout.split()) + + def test_a_server_that_repeats_the_position_it_was_given_exits_2_with_a_message( httpx_mock: HTTPXMock, files: list[str], tmp_path: Path ) -> None: @@ -557,6 +562,101 @@ async def stop(request: httpx.Request) -> httpx.Response: assert [json.loads(r.content)["identifiers"] for r in httpx_mock.get_requests(method="POST")] == [["c"]] +def encrypt_until( + trouble_at: str, trouble: Callable[[], Awaitable[httpx.Response]] +) -> Callable[..., Awaitable[httpx.Response]]: + """Answer every batch as encrypted, except the batch that holds `trouble_at`, which gets `trouble`.""" + + async def handler(request: httpx.Request) -> httpx.Response: + identifiers = json.loads(request.content)["identifiers"] + if trouble_at in identifiers: + return await trouble() + return httpx.Response(200, json=answer(*identifiers)) + + return handler + + +def stop_with(signal_number: int) -> Callable[[], Awaitable[httpx.Response]]: + async def stop() -> httpx.Response: + os.kill(os.getpid(), signal_number) + await asyncio.sleep(30) + raise AssertionError("not reached") + + return stop + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in STOP_CASES]) +def test_a_stop_in_a_single_page_shows_what_the_server_confirmed_in_it_and_says_no_position_was_saved( + case: StopCase, httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d")) + httpx_mock.add_callback(encrypt_until("c", stop_with(case.signal_number)), method="POST", url=BATCH_URL) + + result = invoke(files, "--batch-size", "2", "--concurrency", "1") + + output = squeezed(result) + assert result.exit_code == case.exit_code, result.stdout + assert "encrypted (interrupted page, not saved) │ 2" in output + assert "Bytes encrypted (interrupted page, not saved) │ 200" in output + assert "Bytes encrypted │ 0" in output + assert "Objects per second │ 0.0" not in output + assert "the server reports the objects it already encrypted as already_encrypted" in output + assert "No page was complete, so no position was saved" in output + assert f"Stopped by {case.stopped_by}. Done: 2 objects." in output + assert not (tmp_path / "state.json").exists() + + +def test_a_stop_in_a_later_page_keeps_the_saved_totals_and_shows_the_interrupted_page_apart( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c", "d", next_start_after="d")) + httpx_mock.add_callback(encrypt_until("d", stop_with(signal.SIGINT)), method="POST", url=BATCH_URL) + + result = invoke(files, "--page-size", "2", "--batch-size", "1", "--concurrency", "1") + + output = squeezed(result) + assert result.exit_code == 130, result.stdout + assert "│ encrypted │ 2 │" in output + assert "encrypted (interrupted page, not saved) │ 1" in output + assert "Bytes encrypted │ 200" in output + assert "Bytes encrypted (interrupted page, not saved) │ 100" in output + assert "No page was complete" not in output + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + assert state["totals"]["counts"] == {"encrypted": 2} + assert state["totals"]["bytes_encrypted"] == 200 + + +def test_an_error_in_a_page_shows_what_the_server_confirmed_before_it_and_exits_2( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + async def refuse() -> httpx.Response: + return httpx.Response(403, json={"detail": "no"}) + + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d")) + httpx_mock.add_callback(encrypt_until("c", refuse), method="POST", url=BATCH_URL) + + result = invoke(files, "--batch-size", "2", "--concurrency", "1") + + output = squeezed(result) + assert result.exit_code == 2, result.stdout + assert "encrypted (interrupted page, not saved) │ 2" in output + assert "No page was complete, so no position was saved" in output + assert not (tmp_path / "state.json").exists() + + +def test_a_complete_run_shows_no_interrupted_page_rows_and_no_note(httpx_mock: HTTPXMock, files: list[str]) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert "interrupted page" not in result.stdout + assert "No page was complete" not in result.stdout + + @pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in STOP_CASES]) def test_a_stop_signal_during_the_count_saves_nothing_and_says_so( case: StopCase, httpx_mock: HTTPXMock, files: list[str], tmp_path: Path @@ -634,6 +734,58 @@ async def advance() -> None: assert "retries: 0" in last +@dataclass +class FreezeCase: + name: str + frozen_seconds: int + + +FREEZE_CASES = [ + FreezeCase(name="one-minute", frozen_seconds=60), + FreezeCase(name="six-minutes", frozen_seconds=360), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in FREEZE_CASES]) +async def test_the_remaining_time_after_the_process_was_frozen_is_estimating_and_then_right( + case: FreezeCase, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + clock = {"now": 1000.0} + + class FakeClockModule: + @staticmethod + def monotonic() -> float: + return clock["now"] + + monkeypatch.setattr(encrypt_module, "time", FakeClockModule) + encryptor = make_encryptor(tmp_path) + encryptor.remaining_objects = 100_000 + encryptor.remaining_bytes = 10_000_000 + progress = encrypt_module._Progress(encryptor) + + def run(seconds: float) -> str: + """Run at 100 objects/s, with a progress line every 0.5 s; return the last line.""" + line = "" + for _ in range(int(seconds * 2)): + clock["now"] += 0.5 + encryptor.objects_confirmed += 50 + line = progress.line() + return line + + run(30) + # The process is stopped: the clock moves and the count does not; a batch that was in flight completes on resume. + clock["now"] += case.frozen_seconds + encryptor.objects_confirmed += 50 + assert "remaining estimating" in progress.line() + + line = run(5) + + shown = line.split("remaining ")[1].split(" | ")[0] + minutes, seconds = shown.rstrip("s").split("m ") + expected = (100_000 - encryptor.objects_confirmed) / 100 + assert int(minutes) * 60 + int(seconds) == pytest.approx(expected, rel=0.05) + + async def test_the_progress_line_while_counting_shows_the_objects_counted_so_far(tmp_path: Path) -> None: encryptor = make_encryptor(tmp_path) encryptor.counting = True diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py index 023b0b63a..ee403267d 100644 --- a/tests/unit/ctl/test_storage_migration.py +++ b/tests/unit/ctl/test_storage_migration.py @@ -421,6 +421,89 @@ async def never_answers(request: httpx.Request) -> httpx.Response: assert encryptor.totals.counts == {"encrypted": 2} +async def test_what_the_server_confirmed_in_an_interrupted_page_is_kept_apart_and_never_counted( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + async def never_answers(request: httpx.Request) -> httpx.Response: + await asyncio.sleep(3600) + raise AssertionError("not reached") + + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json={ + "results": [ + {"identifier": "a", "outcome": "encrypted", "size": 100, "reason": None}, + {"identifier": "b", "outcome": "already_encrypted", "size": 0, "reason": None}, + ] + }, + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + httpx_mock.add_callback( + never_answers, method="POST", url=BATCH_URL, match_json={"identifiers": ["c", "d"], "allow_unverified": False} + ) + encryptor, _ = make(tmp_path, concurrency=1) + + task = asyncio.create_task(run(encryptor)) + for _ in range(200): + await asyncio.sleep(0.01) + if len(httpx_mock.get_requests(method="POST")) == 2: + break + task.cancel() + with pytest.raises(asyncio.CancelledError, match=r"^$"): + await task + + assert encryptor.page_interrupted is True + assert encryptor.interrupted_counts == {"encrypted": 1, "already_encrypted": 1} + assert encryptor.interrupted_bytes_encrypted == 100 + assert encryptor.objects_confirmed == 2 + assert encryptor.totals.counts == {} + assert encryptor.totals.bytes_encrypted == 0 + assert not (tmp_path / "state.json").exists() + + +async def test_an_error_in_a_page_keeps_what_the_server_confirmed_before_it_apart( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b", "c", "d")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + status_code=403, + json={"detail": "no"}, + match_json={"identifiers": ["c", "d"], "allow_unverified": False}, + ) + encryptor, _ = make(tmp_path, concurrency=1) + + with pytest.raises(MigrationError, match="HTTP 403"): + await run(encryptor) + + assert encryptor.interrupted_counts == {"encrypted": 2} + assert encryptor.interrupted_bytes_encrypted == 200 + assert encryptor.totals.counts == {} + assert encryptor.start_after is None + + +async def test_a_complete_page_leaves_nothing_in_the_interrupted_figures(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + encryptor, _ = make(tmp_path) + + await run(encryptor) + + assert encryptor.page_interrupted is False + assert encryptor.interrupted_counts == {} + assert encryptor.interrupted_bytes_encrypted == 0 + assert encryptor.totals.counts == {"encrypted": 2} + + # 429 answers diff --git a/tests/unit/ctl/test_storage_progress.py b/tests/unit/ctl/test_storage_progress.py index 2bf07dc64..ff3da4e3d 100644 --- a/tests/unit/ctl/test_storage_progress.py +++ b/tests/unit/ctl/test_storage_progress.py @@ -1,6 +1,7 @@ from __future__ import annotations from dataclasses import dataclass +from itertools import pairwise import pytest @@ -126,18 +127,63 @@ def test_the_rate_follows_the_last_window_and_not_the_average_since_the_start() def test_the_rate_is_zero_when_nothing_progressed_in_the_window() -> None: tracker = RateTracker(window=30, minimum_span=4) - tracker.record(now=0, done=500) - tracker.record(now=10, done=500) + for now in range(0, 11, 2): + tracker.record(now=now, done=500) assert tracker.rate() == pytest.approx(0.0) def test_the_rate_is_never_negative() -> None: tracker = RateTracker(window=30, minimum_span=4) - tracker.record(now=0, done=500) - tracker.record(now=10, done=400) + for now in range(0, 11, 2): + tracker.record(now=now, done=500 - now * 10) assert tracker.rate() == pytest.approx(0.0) +def record_steady(tracker: RateTracker, start: float, stop: float, rate: float, done_at_start: int) -> int: + """Record a sample every 0.5 s from `start` to `stop` at `rate` objects/s; return the objects done at `stop`.""" + now = start + while now <= stop: + tracker.record(now=now, done=done_at_start + round((now - start) * rate)) + now += 0.5 + return done_at_start + round((stop - start) * rate) + + +@pytest.mark.parametrize("frozen_seconds", [60, 360]) +def test_the_rate_after_the_process_was_frozen_ignores_the_frozen_span(frozen_seconds: int) -> None: + tracker = RateTracker(window=30, minimum_span=4) + done = record_steady(tracker, start=0, stop=60, rate=100, done_at_start=0) + resumed_at = 60 + frozen_seconds + # The frozen process recorded nothing; the first sample after it holds the same count of objects. + tracker.record(now=resumed_at, done=done) + assert tracker.rate() is None + record_steady(tracker, start=resumed_at, stop=resumed_at + 4, rate=100, done_at_start=done) + assert tracker.rate() == pytest.approx(100.0) + + +def test_the_rate_of_a_pause_shorter_than_the_largest_gap_is_kept() -> None: + tracker = RateTracker(window=30, minimum_span=4, maximum_gap=5) + done = record_steady(tracker, start=0, stop=20, rate=100, done_at_start=0) + tracker.record(now=25, done=done) + assert tracker.rate() == pytest.approx(done / 25) + + +def test_the_rate_falls_while_the_process_runs_and_nothing_progresses() -> None: + tracker = RateTracker(window=30, minimum_span=4) + done = record_steady(tracker, start=0, stop=20, rate=100, done_at_start=0) + steady = tracker.rate() + assert steady is not None + assert steady == pytest.approx(100.0) + # A server that answers 429: the samples keep coming every 0.5 s and the count stays the same. + rates: list[float] = [] + for second in range(1, 41): + tracker.record(now=20 + second / 2, done=done) + rate = tracker.rate() + assert rate is not None + rates.append(rate) + assert all(earlier >= later for earlier, later in pairwise(rates)) + assert rates[-1] < 0.5 * steady + + def test_the_progress_line_shows_done_total_percent_rate_remaining_bytes_limit_429_and_retries() -> None: line = progress_line(view()) From 2bdc2887132c60cf2acab9c7fe50faa1f0ef2102 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Mon, 23 Nov 2026 11:16:06 +0100 Subject: [PATCH 3/9] fix: keep the pace of the command out of the latency that adapts the limit The latency of a batch included the wait for the pace, the pause after a 429 answer and the delay after a failure, so the adaptive limit could shrink while the server was not slow. The request now returns the time of the HTTP call that produced the answer, and the limit uses that. The text of a server error is printed with its control characters replaced by spaces, so that an escape sequence in an answer does not reach the terminal. Signed-off-by: Simon AURA--SCUSSEL --- infrahub_sdk/ctl/storage/migration.py | 30 +++++++---- tests/unit/ctl/test_storage_migration.py | 69 +++++++++++++++++++++++- 2 files changed, 87 insertions(+), 12 deletions(-) diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py index 7364934e5..70b14a438 100644 --- a/infrahub_sdk/ctl/storage/migration.py +++ b/infrahub_sdk/ctl/storage/migration.py @@ -415,9 +415,12 @@ async def _request( path: str, params: dict[str, Any], body: dict[str, Any] | None = None, - ) -> httpx.Response: + ) -> tuple[httpx.Response, float]: """Send one request until the server answers it, waiting out 429 responses and transient failures. + Returns the answer and the seconds that the HTTP call that produced it took, without the time spent + waiting for the pace, a pause after a 429 answer or a delay after a failure. + Raises: MigrationError: If the failures other than 429 outnumber the retries allowed. @@ -429,6 +432,7 @@ async def _request( await self._pacer.wait() self.totals.requests += 1 generation = self._auth_generation + call_started = self._clock() try: response = await http.request(method, path, params=params, json=body) except httpx.TransportError as exc: @@ -436,6 +440,7 @@ async def _request( self._check_retries(failures=failures, path=path, cause=f"{type(exc).__name__}: {exc}") await self._sleep(backoff_delay(attempt=failures, rng=self._rng)) continue + call_seconds = self._clock() - call_started self._answered = True if response.status_code == HTTP_TOO_MANY_REQUESTS: sheds += 1 @@ -466,7 +471,7 @@ async def _request( refreshed = True await self._renew_login(http, self.refresh_login, seen_generation=generation) continue - return response + return response, call_seconds def _notify(self, message: str) -> None: if self.on_notice is not None: @@ -504,7 +509,7 @@ async def _fetch_listing( params: dict[str, Any] = {"limit": limit} if start_after: params["start_after"] = start_after - response = await self._request(http, "GET", LIST_PATH, params) + response, _ = await self._request(http, "GET", LIST_PATH, params) if response.status_code != HTTP_OK: raise MigrationError(refusal_message(response=response, what="The listing of the stored objects")) body = answer_body(response, what="The listing of the stored objects") @@ -534,12 +539,10 @@ async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, A "allow_unverified": self.options.allow_unverified, } await self.limit.acquire() - started = self._clock() try: - response = await self._request(http, "POST", BATCH_PATH, {}, body) + response, seconds = await self._request(http, "POST", BATCH_PATH, {}, body) finally: await self.limit.release() - seconds = self._clock() - started self.totals.encrypt_requests += 1 if response.status_code != HTTP_OK: raise MigrationError(refusal_message(response=response, what="The request to encrypt a batch")) @@ -757,18 +760,23 @@ def refusal_message(response: httpx.Response, what: str) -> str: return f"{what} was refused with HTTP {status}.{suffix}" +def printable(text: str) -> str: + """Replace the characters that a terminal would act on, such as escape sequences, with spaces.""" + return "".join(char if char.isprintable() else " " for char in text) + + def server_detail(response: httpx.Response) -> str: - """Return the message a server error carries, or the start of its body.""" + """Return the message a server error carries, or the start of its body, safe to print.""" try: body = response.json() except ValueError: - return response.text[:300] + return printable(response.text[:300]) if isinstance(body, dict): if isinstance(body.get("detail"), str): - return str(body["detail"])[:300] + return printable(str(body["detail"])[:300]) errors = body.get("errors") if isinstance(errors, list): messages = [str(item["message"]) for item in errors if isinstance(item, dict) and "message" in item] if messages: - return "; ".join(messages)[:300] - return response.text[:300] + return printable("; ".join(messages)[:300]) + return printable(response.text[:300]) diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py index ee403267d..d89452082 100644 --- a/tests/unit/ctl/test_storage_migration.py +++ b/tests/unit/ctl/test_storage_migration.py @@ -26,10 +26,11 @@ backoff_delay, parse_retry_after, parse_timestamp, + server_detail, ) if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Callable, Iterator from pathlib import Path from pytest_httpx import HTTPXMock @@ -1847,3 +1848,69 @@ async def test_the_count_and_the_run_agree_on_pages_that_are_empty_or_end_beyond assert asked == [None, "b", "e", "f"] * 2 assert encryptor.remaining_objects == encryptor.total_objects == encryptor.done_objects == 3 assert encryptor.done_bytes == encryptor.total_bytes == 300 + + +class RecordingLimit(AdaptiveLimit): + """An adaptive limit that keeps the latency samples it is given.""" + + def __init__(self, maximum: int, minimum: int, slow_factor: float, clock: Callable[[], float]) -> None: + super().__init__(maximum=maximum, minimum=minimum, slow_factor=slow_factor, clock=clock) + self.observed: list[float] = [] + + def observe(self, seconds: float) -> None: + self.observed.append(seconds) + super().observe(seconds) + + +async def test_the_pace_of_the_command_is_not_counted_as_the_latency_of_the_server( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + identifiers = ["a", "b", "c", "d", "e", "f"] + encryptor, fake = make(tmp_path, concurrency=8, batch_size=1, rate=1.0) + encryptor.limit = RecordingLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) + + def server_that_takes_a_tenth_of_a_second(request: httpx.Request) -> httpx.Response: + fake.now += 0.1 + return httpx.Response(200, json=answer(*json.loads(request.content)["identifiers"])) + + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page(*identifiers)) + for _ in identifiers: + httpx_mock.add_callback(server_that_takes_a_tenth_of_a_second, method="POST", url=BATCH_URL) + + await run(encryptor) + + assert encryptor.totals.counts == {"encrypted": 6} + assert sum(fake.sleeps) > 4.0 + assert len(encryptor.limit.observed) == 6 + assert max(encryptor.limit.observed) < 0.11 + + +@dataclass +class ServerTextCase: + name: str + response: httpx.Response + expected: str + + +SERVER_TEXT_CASES = [ + ServerTextCase( + name="plain_text", + response=httpx.Response(500, text="boom \x1b[31mred\x07 end"), + expected="boom [31mred end", + ), + ServerTextCase( + name="detail", + response=httpx.Response(409, json={"detail": "refused\x1b]0;title\x07"}), + expected="refused ]0;title ", + ), + ServerTextCase( + name="graphql_errors", + response=httpx.Response(200, json={"errors": [{"message": "one\r\ntwo"}, {"message": "three\x9b"}]}), + expected="one two; three ", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in SERVER_TEXT_CASES]) +def test_the_text_of_a_server_error_has_no_control_characters(case: ServerTextCase) -> None: + assert server_detail(case.response) == case.expected From d5db04d909b6789415ec4bb7375805afb10ac736 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Mon, 23 Nov 2026 11:16:06 +0100 Subject: [PATCH 4/9] fix: point to the report only when it lists an object, show slow rates, fix the exit code help The line that points to the report was printed after every run that processed an object, also when all of them were encrypted and the report was empty. It is now printed when a result other than encrypted was counted, which is what the report lists. The progress line shows one decimal below 10 objects a second, so that a rate of 0.4 is not shown as 0 while the remaining time is computed from 0.4. The exit code help listed a file error under exit 1, but a state file or report that cannot be used exits 2. The generated page follows. Signed-off-by: Simon AURA--SCUSSEL --- docs/docs/infrahubctl/infrahubctl-storage.mdx | 2 +- infrahub_sdk/ctl/storage/encrypt.py | 5 ++-- infrahub_sdk/ctl/storage/progress.py | 7 +++++- tests/unit/ctl/test_storage_app.py | 25 +++++++++++++++++++ tests/unit/ctl/test_storage_progress.py | 22 +++++++++++++++- 5 files changed, 56 insertions(+), 5 deletions(-) diff --git a/docs/docs/infrahubctl/infrahubctl-storage.mdx b/docs/docs/infrahubctl/infrahubctl-storage.mdx index c5b722bd7..435bf1637 100644 --- a/docs/docs/infrahubctl/infrahubctl-storage.mdx +++ b/docs/docs/infrahubctl/infrahubctl-storage.mdx @@ -42,7 +42,7 @@ A new full pass, which starts after a pass has finished, or --restart, tries the Exit codes: 0 Every object is encrypted, was already encrypted, or was skipped by the server 1 The server could not encrypt at least one object, or the command failed before the run - (for example on a login error, a file error or an unexpected error) + (for example on a login error or an unexpected error) 2 The run stopped on an error from the server or on a state file or report that cannot be used 130 The run stopped on Ctrl-C (SIGINT) 143 The run stopped on SIGTERM diff --git a/infrahub_sdk/ctl/storage/encrypt.py b/infrahub_sdk/ctl/storage/encrypt.py index 3287f2918..8c189c905 100644 --- a/infrahub_sdk/ctl/storage/encrypt.py +++ b/infrahub_sdk/ctl/storage/encrypt.py @@ -20,6 +20,7 @@ from ..utils import catch_exception from .migration import ( BATCH_MAX_SIZE, + OUTCOME_ENCRYPTED, OUTCOME_FAILED, PAGE_MAX_SIZE, MigrationError, @@ -295,7 +296,7 @@ async def encrypt_command( Exit codes: 0 Every object is encrypted, was already encrypted, or was skipped by the server 1 The server could not encrypt at least one object, or the command failed before the run - (for example on a login error, a file error or an unexpected error) + (for example on a login error or an unexpected error) 2 The run stopped on an error from the server or on a state file or report that cannot be used 130 The run stopped on Ctrl-C (SIGINT) 143 The run stopped on SIGTERM @@ -360,7 +361,7 @@ async def renew_login(http: httpx.AsyncClient) -> None: else: console.print("Nothing was saved to resume from; run the same command again to start again.") raise typer.Exit(code=EXIT_TERMINATED if stopped_by == "SIGTERM" else EXIT_INTERRUPTED) - if not dry_run and encryptor.totals.counts: + if not dry_run and any(outcome != OUTCOME_ENCRYPTED for outcome in encryptor.totals.counts): console.print(f"Objects that were not encrypted are listed in {escape(str(report))}.") if encryptor.totals.counts.get(OUTCOME_FAILED, 0): raise typer.Exit(code=EXIT_OBJECTS_FAILED) diff --git a/infrahub_sdk/ctl/storage/progress.py b/infrahub_sdk/ctl/storage/progress.py index d2a542189..b2d374eee 100644 --- a/infrahub_sdk/ctl/storage/progress.py +++ b/infrahub_sdk/ctl/storage/progress.py @@ -130,9 +130,14 @@ def remaining_text(view: ProgressView) -> str: return "unknown" if seconds is None else format_duration(seconds) +def _format_rate(rate: float) -> str: + """Show one decimal below 10 objects per second, so that a slow rate is not shown as 0.""" + return f"{rate:,.1f}" if rate < 10 else f"{rate:,.0f}" + + def progress_line(view: ProgressView) -> str: """Return the progress line: done / total, percent, rate, remaining time, bytes, limit, 429 answers, retries.""" - rate = "estimating" if view.rate is None else f"{view.rate:,.0f} objects/s" + rate = "estimating" if view.rate is None else f"{_format_rate(view.rate)} objects/s" parts: list[str] = [] if view.total_objects is None: parts.extend([f"{format_number(view.done_objects)} objects", rate, format_bytes(view.done_bytes)]) diff --git a/tests/unit/ctl/test_storage_app.py b/tests/unit/ctl/test_storage_app.py index a0157cd56..6d571fc00 100644 --- a/tests/unit/ctl/test_storage_app.py +++ b/tests/unit/ctl/test_storage_app.py @@ -86,6 +86,31 @@ def test_objects_the_server_skips_do_not_fail_the_run_and_are_reported( assert json.loads((tmp_path / "report.jsonl").read_text())["identifier"] == "a" +def test_a_run_that_encrypts_every_object_does_not_point_to_the_report( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b")) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert "were not encrypted" not in result.stdout + assert (tmp_path / "report.jsonl").stat().st_size == 0 + + +def test_a_run_that_leaves_an_object_unchanged_points_to_the_report( + httpx_mock: HTTPXMock, files: list[str], tmp_path: Path +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", "b")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", "b", outcome="already_encrypted")) + + result = invoke(files) + + assert result.exit_code == 0, result.stdout + assert f"were not encrypted are listed in {tmp_path / 'report.jsonl'}" in result.stdout.replace("\n", " ") + + def test_an_object_that_failed_makes_the_exit_code_1(httpx_mock: HTTPXMock, files: list[str]) -> None: httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a", outcome="failed", reason="disk full")) diff --git a/tests/unit/ctl/test_storage_progress.py b/tests/unit/ctl/test_storage_progress.py index ff3da4e3d..67eb8d1e1 100644 --- a/tests/unit/ctl/test_storage_progress.py +++ b/tests/unit/ctl/test_storage_progress.py @@ -202,10 +202,30 @@ def test_the_progress_line_says_estimating_until_there_is_a_rate() -> None: def test_the_progress_line_with_a_rate_of_zero_does_not_divide_by_zero() -> None: line = progress_line(view(rate=0.0)) - assert "0 objects/s" in line + assert "0.0 objects/s" in line assert "remaining unknown" in line +@dataclass +class RateCase: + name: str + rate: float + expected: str + + +RATE_CASES = [ + RateCase(name="a_slow_rate_keeps_one_decimal", rate=0.4, expected="0.4 objects/s"), + RateCase(name="just_below_ten", rate=9.4, expected="9.4 objects/s"), + RateCase(name="ten_is_whole", rate=10.0, expected="10 objects/s"), + RateCase(name="a_fast_rate_has_a_thousands_separator", rate=1234.4, expected="1,234 objects/s"), +] + + +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in RATE_CASES]) +def test_the_progress_line_shows_one_decimal_for_a_rate_below_ten_objects_a_second(case: RateCase) -> None: + assert f"| {case.expected} |" in progress_line(view(rate=case.rate)) + + def test_the_progress_line_with_nothing_to_process() -> None: line = progress_line(view(done_objects=0, total_objects=0, done_bytes=0, total_bytes=0, rate=None)) From 7ec57a5409435f272aef9447d7d8d04470ea7bd7 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Mon, 23 Nov 2026 11:16:06 +0100 Subject: [PATCH 5/9] docs: list every subcommand group in the CLI architecture page The list of groups stopped at storage. It now has marketplace, telemetry and troubleshooting, which cli_commands.py also registers. Signed-off-by: Simon AURA--SCUSSEL --- dev/knowledge/cli-architecture.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/knowledge/cli-architecture.md b/dev/knowledge/cli-architecture.md index 0f50bb15e..3edfad09d 100644 --- a/dev/knowledge/cli-architecture.md +++ b/dev/knowledge/cli-architecture.md @@ -11,7 +11,7 @@ The main Typer app lives in `infrahub_sdk/ctl/cli_commands.py`. It is re-exporte Commands are organized in two tiers: - **Root commands** are registered directly on the main app with `app.command()`. These are standalone operations that don't belong to a logical group (e.g. `dump`, `load`, `check`, `render`, `run`, `transform`, `protocols`, `version`, `info`). -- **Subcommand groups** are separate `AsyncTyper()` instances registered with `app.add_typer(sub_app, name="group")`. Each group lives in its own module under `infrahub_sdk/ctl/`. Current groups: `branch`, `schema`, `validate`, `repository`, `menu`, `object`, `graphql`, `task`, `storage`. +- **Subcommand groups** are separate `AsyncTyper()` instances registered with `app.add_typer(sub_app, name="group")`. Each group lives in its own module under `infrahub_sdk/ctl/`. Current groups: `branch`, `schema`, `validate`, `repository`, `menu`, `object`, `graphql`, `task`, `marketplace`, `storage`, `telemetry`, `troubleshooting`. ## Adding a new command From 62483267819d12ab08e8e95260837b6a6a70551d Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Tue, 1 Dec 2026 15:02:20 +0100 Subject: [PATCH 6/9] fix: stop when the answer to a batch does not list every file sent The command moved its position past every file of a batch, even when the server answered for only some of them. A file left out of the answer stayed unencrypted, was not in the report, and the command exited 0. The command now compares the identifiers in the answer with the identifiers it sent. When a file has no result, a result names a file that was not sent, or a file has two results, it stops with exit code 2 before it saves its position, so the next run sends the page again. A result without a usable identifier stops the run as an answer of an unexpected shape. Signed-off-by: Simon AURA--SCUSSEL --- infrahub_sdk/ctl/storage/migration.py | 27 +++++- tests/unit/ctl/test_storage_migration.py | 118 +++++++++++++++++++++++ 2 files changed, 141 insertions(+), 4 deletions(-) diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py index 70b14a438..0bb9478e1 100644 --- a/infrahub_sdk/ctl/storage/migration.py +++ b/infrahub_sdk/ctl/storage/migration.py @@ -533,11 +533,28 @@ def _check_progress(start_after: str | None, next_start_after: str | None) -> No "again. The server may be faulty." ) + @staticmethod + def _check_answers(sent: list[str], results: list[dict[str, Any]], answered: set[Any]) -> None: + """Stop when the answer to a batch does not name each object sent exactly once. + + Raises: + MigrationError: If an object sent has no result, or a result names an object that was not sent, or + names one twice, since the position would otherwise move past objects that were never handled. + + """ + if len(results) == len(sent) and answered == set(sent): + return + missing = [identifier for identifier in sent if identifier not in answered] + unexpected = sorted(answered.difference(sent), key=repr) + raise MigrationError( + f"The server answered with {len(results)} results for the {len(sent)} objects sent in a batch " + f"(sent without a result: {missing[:3]!r}, not sent: {unexpected[:3]!r}). The command stops instead of " + "moving past objects that have no result. The server may be faulty." + ) + async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, Any]]) -> list[dict[str, Any]]: - body = { - "identifiers": [item["identifier"] for item in stored], - "allow_unverified": self.options.allow_unverified, - } + identifiers = [item["identifier"] for item in stored] + body = {"identifiers": identifiers, "allow_unverified": self.options.allow_unverified} await self.limit.acquire() try: response, seconds = await self._request(http, "POST", BATCH_PATH, {}, body) @@ -553,10 +570,12 @@ async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, A body = answer_body(response, what="The request to encrypt a batch") try: results: list[dict[str, Any]] = body["results"] + answered = {result["identifier"] for result in results} except (KeyError, TypeError) as exc: raise MigrationError( f"The request to encrypt a batch has an answer of an unexpected shape: {exc!r}" ) from exc + self._check_answers(sent=identifiers, results=results, answered=answered) self.objects_confirmed += len(results) self.bytes_confirmed += batch_bytes return results diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py index d89452082..64d9a10a9 100644 --- a/tests/unit/ctl/test_storage_migration.py +++ b/tests/unit/ctl/test_storage_migration.py @@ -955,6 +955,124 @@ async def test_a_batch_answer_of_an_unexpected_shape_stops_the_run(httpx_mock: H await run(make(tmp_path)[0]) +@pytest.mark.parametrize( + "result", + [ + pytest.param({"outcome": "encrypted", "size": 100, "reason": None}, id="no-identifier"), + pytest.param({"identifier": ["a"], "outcome": "encrypted", "size": 100, "reason": None}, id="list-identifier"), + ], +) +async def test_a_batch_result_without_a_usable_identifier_stops_the_run( + httpx_mock: HTTPXMock, tmp_path: Path, result: dict[str, Any] +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + httpx_mock.add_response(method="POST", url=BATCH_URL, json={"results": [result]}) + + with pytest.raises(MigrationError, match=r"answer of an unexpected shape"): + await run(make(tmp_path)[0]) + + +def two_pages(httpx_mock: HTTPXMock) -> None: + """List `a`, `b` on the first page and `c`, `d` on the second, and answer the first batch in full.""" + httpx_mock.add_response(url=f"{LIST_URL}?limit=2", json=page("a", "b", next_start_after="b")) + httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c", "d")) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer("a", "b"), + match_json={"identifiers": ["a", "b"], "allow_unverified": False}, + ) + + +@dataclass +class BatchAnswerCase: + name: str + answered: tuple[str, ...] + expected: str + + +BATCH_ANSWER_CASES = [ + BatchAnswerCase( + name="an-object-without-a-result", + answered=("c",), + expected="1 results for the 2 objects sent in a batch (sent without a result: ['d'], not sent: [])", + ), + BatchAnswerCase( + name="no-result", + answered=(), + expected="0 results for the 2 objects sent in a batch (sent without a result: ['c', 'd'], not sent: [])", + ), + BatchAnswerCase( + name="an-object-that-was-not-sent", + answered=("c", "x"), + expected="2 results for the 2 objects sent in a batch (sent without a result: ['d'], not sent: ['x'])", + ), + BatchAnswerCase( + name="an-extra-object", + answered=("c", "d", "e"), + expected="3 results for the 2 objects sent in a batch (sent without a result: [], not sent: ['e'])", + ), + BatchAnswerCase( + name="an-object-answered-twice", + answered=("c", "d", "d"), + expected="3 results for the 2 objects sent in a batch (sent without a result: [], not sent: [])", + ), +] + + +@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in BATCH_ANSWER_CASES]) +async def test_a_batch_answer_that_does_not_match_the_objects_sent_stops_before_the_position_moves( + httpx_mock: HTTPXMock, tmp_path: Path, case: BatchAnswerCase +) -> None: + two_pages(httpx_mock) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json=answer(*case.answered), + match_json={"identifiers": ["c", "d"], "allow_unverified": False}, + ) + encryptor, _ = make(tmp_path, page_size=2) + + with pytest.raises(MigrationError, match=re.escape(case.expected)): + await run(encryptor) + + state = json.loads((tmp_path / "state.json").read_text()) + assert state["start_after"] == "b" + assert state["completed"] is False + assert state["totals"]["counts"] == {"encrypted": 2} + assert encryptor.objects_confirmed == 2 + assert not (tmp_path / "report.jsonl").read_text() + + +async def test_a_rerun_after_a_batch_answer_without_every_object_sends_those_objects_again( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: + two_pages(httpx_mock) + match = {"identifiers": ["c", "d"], "allow_unverified": False} + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c"), match_json=match) + httpx_mock.add_response( + method="POST", + url=BATCH_URL, + json={ + "results": [ + {"identifier": "c", "outcome": "already_encrypted", "size": 0, "reason": None}, + {"identifier": "d", "outcome": "encrypted", "size": 100, "reason": None}, + ] + }, + match_json=match, + ) + first, _ = make(tmp_path, page_size=2) + with pytest.raises(MigrationError, match=r"sent without a result: \['d'\]"): + await run(first) + + second, _ = make(tmp_path, page_size=2) + await run(second) + + assert [body["identifiers"] for body in sent_bodies(httpx_mock)] == [["a", "b"], ["c", "d"], ["c", "d"]] + assert second.totals.counts == {"encrypted": 3, "already_encrypted": 1} + assert second.completed is True + + # Count pass From 3bcd8bf1dad426ac96c9aefc89f4efa59bad4400 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Tue, 1 Dec 2026 15:30:48 +0100 Subject: [PATCH 7/9] fix: show what the server confirmed in a batch answer that is incomplete When the answer to a batch did not name each file sent exactly once, the command stopped before it counted any result of that batch. The files the server confirmed in it were missing from the stop summary and from the number done before the error. The results that name a file sent, once, now go to the rows of the interrupted page and to the number done. The position and the state file do not change, so the rerun repeats the page. Signed-off-by: Simon AURA--SCUSSEL --- infrahub_sdk/ctl/storage/migration.py | 43 +++++++++++++++++++----- tests/unit/ctl/test_storage_migration.py | 12 ++++++- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py index 0bb9478e1..9bb8b907b 100644 --- a/infrahub_sdk/ctl/storage/migration.py +++ b/infrahub_sdk/ctl/storage/migration.py @@ -7,6 +7,7 @@ import os import random import time +from collections import Counter from dataclasses import asdict, dataclass, field, fields from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, TextIO @@ -48,6 +49,15 @@ class MigrationError(Exception): """The run cannot continue: the server refused the request, or stayed unreachable.""" +class IncompleteAnswerError(MigrationError): + """The answer to a batch does not name each object sent exactly once.""" + + def __init__(self, message: str, confirmed: list[dict[str, Any]]) -> None: + super().__init__(message) + self.confirmed = confirmed + """The results that name an object sent, and name it once.""" + + @dataclass class Totals: """Counters of a run; a state file keeps them, so they add up over the runs that resume it.""" @@ -538,18 +548,24 @@ def _check_answers(sent: list[str], results: list[dict[str, Any]], answered: set """Stop when the answer to a batch does not name each object sent exactly once. Raises: - MigrationError: If an object sent has no result, or a result names an object that was not sent, or - names one twice, since the position would otherwise move past objects that were never handled. + IncompleteAnswerError: If an object sent has no result, or a result names an object that was not sent, + or names one twice, since the position would otherwise move past objects that were never handled. """ - if len(results) == len(sent) and answered == set(sent): + expected = set(sent) + if len(results) == len(sent) and answered == expected: return missing = [identifier for identifier in sent if identifier not in answered] - unexpected = sorted(answered.difference(sent), key=repr) - raise MigrationError( + unexpected = sorted(answered.difference(expected), key=repr) + times = Counter(result["identifier"] for result in results) + confirmed = [ + result for result in results if result["identifier"] in expected and times[result["identifier"]] == 1 + ] + raise IncompleteAnswerError( f"The server answered with {len(results)} results for the {len(sent)} objects sent in a batch " f"(sent without a result: {missing[:3]!r}, not sent: {unexpected[:3]!r}). The command stops instead of " - "moving past objects that have no result. The server may be faulty." + "moving past objects that have no result. The server may be faulty.", + confirmed=confirmed, ) async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, Any]]) -> list[dict[str, Any]]: @@ -575,7 +591,13 @@ async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, A raise MigrationError( f"The request to encrypt a batch has an answer of an unexpected shape: {exc!r}" ) from exc - self._check_answers(sent=identifiers, results=results, answered=answered) + try: + self._check_answers(sent=identifiers, results=results, answered=answered) + except IncompleteAnswerError as exc: + confirmed = {result["identifier"] for result in exc.confirmed} + self.objects_confirmed += len(exc.confirmed) + self.bytes_confirmed += sum(item["size"] for item in stored if item["identifier"] in confirmed) + raise self.objects_confirmed += len(results) self.bytes_confirmed += batch_bytes return results @@ -632,7 +654,12 @@ async def worker() -> None: batch = queue.get_nowait() except asyncio.QueueEmpty: return - results.extend(await self._encrypt_batch(http, batch)) + try: + results.extend(await self._encrypt_batch(http, batch)) + except IncompleteAnswerError as exc: + # The page is not counted, but the summary shows what the server confirmed in it. + results.extend(exc.confirmed) + raise workers = [asyncio.create_task(worker()) for _ in range(min(self.options.concurrency, queue.qsize()))] try: diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py index 64d9a10a9..5079e4907 100644 --- a/tests/unit/ctl/test_storage_migration.py +++ b/tests/unit/ctl/test_storage_migration.py @@ -988,6 +988,7 @@ def two_pages(httpx_mock: HTTPXMock) -> None: class BatchAnswerCase: name: str answered: tuple[str, ...] + confirmed: tuple[str, ...] expected: str @@ -995,26 +996,31 @@ class BatchAnswerCase: BatchAnswerCase( name="an-object-without-a-result", answered=("c",), + confirmed=("c",), expected="1 results for the 2 objects sent in a batch (sent without a result: ['d'], not sent: [])", ), BatchAnswerCase( name="no-result", answered=(), + confirmed=(), expected="0 results for the 2 objects sent in a batch (sent without a result: ['c', 'd'], not sent: [])", ), BatchAnswerCase( name="an-object-that-was-not-sent", answered=("c", "x"), + confirmed=("c",), expected="2 results for the 2 objects sent in a batch (sent without a result: ['d'], not sent: ['x'])", ), BatchAnswerCase( name="an-extra-object", answered=("c", "d", "e"), + confirmed=("c", "d"), expected="3 results for the 2 objects sent in a batch (sent without a result: [], not sent: ['e'])", ), BatchAnswerCase( name="an-object-answered-twice", answered=("c", "d", "d"), + confirmed=("c",), expected="3 results for the 2 objects sent in a batch (sent without a result: [], not sent: [])", ), ] @@ -1040,8 +1046,12 @@ async def test_a_batch_answer_that_does_not_match_the_objects_sent_stops_before_ assert state["start_after"] == "b" assert state["completed"] is False assert state["totals"]["counts"] == {"encrypted": 2} - assert encryptor.objects_confirmed == 2 assert not (tmp_path / "report.jsonl").read_text() + # The results that name an object sent, once, are what the server confirmed in the interrupted page. + assert encryptor.interrupted_counts == ({"encrypted": len(case.confirmed)} if case.confirmed else {}) + assert encryptor.interrupted_bytes_encrypted == 100 * len(case.confirmed) + assert encryptor.objects_confirmed == 2 + len(case.confirmed) + assert encryptor.bytes_confirmed == 200 + 100 * len(case.confirmed) async def test_a_rerun_after_a_batch_answer_without_every_object_sends_those_objects_again( From 81c03446b41b72931569225e394e5dca97c77095 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Wed, 2 Dec 2026 08:35:13 +0100 Subject: [PATCH 8/9] fix: lower the limit on timeouts and busy answers, retry 500, drop the latency signal A timeout, or a 503 or 504 answer, now halves the number of requests in flight, as a 429 does. The server keeps working on a batch after its request times out, so sending it again at the same concurrency added load while the server was slowest. A 500 answer is retried like 502, 503 and 504, as the SDK does, because Infrahub reports some temporary database errors as 500. The limit no longer reacts to how long a batch takes. A batch of objects that are already encrypted is much faster than one to encrypt, so a resumed run looked like a slower server and the limit fell to 1 for minutes. The limit now halves once for all the requests sent before the last decrease, and rises by one after as many successful batches as the limit. Signed-off-by: Simon AURA--SCUSSEL --- docs/docs/infrahubctl/infrahubctl-storage.mdx | 7 +- infrahub_sdk/ctl/storage/encrypt.py | 7 +- infrahub_sdk/ctl/storage/migration.py | 95 +++----- tests/unit/ctl/test_storage_migration.py | 204 ++++++++++-------- 4 files changed, 154 insertions(+), 159 deletions(-) diff --git a/docs/docs/infrahubctl/infrahubctl-storage.mdx b/docs/docs/infrahubctl/infrahubctl-storage.mdx index 435bf1637..ced367f3f 100644 --- a/docs/docs/infrahubctl/infrahubctl-storage.mdx +++ b/docs/docs/infrahubctl/infrahubctl-storage.mdx @@ -24,11 +24,12 @@ Encrypt the stored files that were written before storage encryption was enabled The command lists the stored objects page by page and asks the server, which holds the storage key, to encrypt them. -It keeps several batches in flight, lowers that number when the server slows down, and waits when it answers HTTP 429. +It keeps several batches in flight, and halves that number when the server answers HTTP 429, 503 or 504 or a request times out. +It waits when the server answers HTTP 429. The token needs the super admin permission, and storage encryption must be enabled on the server. -The command does its own retries, not those of the SDK client: network errors and HTTP 502, 503 and 504, up to --max-retries. +The command does its own retries, not those of the SDK client: network errors and HTTP 500, 502, 503 and 504, up to --max-retries. Before it encrypts, the command lists the objects still to process, to show the total, the percent done and the remaining time. Use --no-count to skip this pass on a very large installation; the progress then shows no total. @@ -66,7 +67,7 @@ $ infrahubctl storage encrypt [OPTIONS] * `--allow-unverified`: Also encrypt the objects that no node records a checksum for * `--state-file PATH`: Keeps the position in the listing, so a rerun resumes [default: infrahub-storage-encrypt.state.json] * `--report PATH`: Receives one JSON line for each object that was not encrypted [default: infrahub-storage-encrypt.report.jsonl] -* `--max-retries INTEGER RANGE`: Retries of one request after a network error or HTTP 502, 503, 504 [default: 10; x>=0] +* `--max-retries INTEGER RANGE`: Retries of one request after a network error or HTTP 500, 502, 503, 504 [default: 10; x>=0] * `--timeout INTEGER RANGE`: Seconds before one request times out [default: 300; x>=1] * `--restart`: Ignore the state file and list from the first object * `--no-count`: Do not list the objects first to count them; the progress shows no total, percent or remaining time diff --git a/infrahub_sdk/ctl/storage/encrypt.py b/infrahub_sdk/ctl/storage/encrypt.py index 8c189c905..1ff8e8b19 100644 --- a/infrahub_sdk/ctl/storage/encrypt.py +++ b/infrahub_sdk/ctl/storage/encrypt.py @@ -262,7 +262,7 @@ async def encrypt_command( DEFAULT_REPORT_FILE, help="Receives one JSON line for each object that was not encrypted" ), max_retries: int = typer.Option( - 10, min=0, help="Retries of one request after a network error or HTTP 502, 503, 504" + 10, min=0, help="Retries of one request after a network error or HTTP 500, 502, 503, 504" ), timeout: int = typer.Option(300, min=1, help="Seconds before one request times out"), restart: bool = typer.Option(False, "--restart", help="Ignore the state file and list from the first object"), @@ -277,11 +277,12 @@ async def encrypt_command( The command lists the stored objects page by page and asks the server, which holds the storage key, to encrypt them. - It keeps several batches in flight, lowers that number when the server slows down, and waits when it answers HTTP 429. + It keeps several batches in flight, and halves that number when the server answers HTTP 429, 503 or 504 or a request times out. + It waits when the server answers HTTP 429. The token needs the super admin permission, and storage encryption must be enabled on the server. - The command does its own retries, not those of the SDK client: network errors and HTTP 502, 503 and 504, up to --max-retries. + The command does its own retries, not those of the SDK client: network errors and HTTP 500, 502, 503 and 504, up to --max-retries. Before it encrypts, the command lists the objects still to process, to show the total, the percent done and the remaining time. Use --no-count to skip this pass on a very large installation; the progress then shows no total. diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py index 9bb8b907b..515bc5a15 100644 --- a/infrahub_sdk/ctl/storage/migration.py +++ b/infrahub_sdk/ctl/storage/migration.py @@ -26,7 +26,9 @@ BATCH_PATH = "/api/storage/objects/encrypt" OUTCOME_ENCRYPTED = "encrypted" OUTCOME_FAILED = "failed" -RETRYABLE_STATUS_CODES = frozenset({502, 503, 504}) +RETRYABLE_STATUS_CODES = frozenset({500, 502, 503, 504}) +# Answers that say the server is too busy to answer in time; like a 429 or a timeout, they lower the limit. +OVERLOAD_STATUS_CODES = frozenset({503, 504}) HTTP_OK = 200 HTTP_UNAUTHORIZED = 401 HTTP_FORBIDDEN = 403 @@ -40,7 +42,6 @@ BACKOFF_MAX_EXPONENT = 63 RETRY_AFTER_MAX_SECONDS = 300.0 UNANSWERED_MAX_RETRIES = 3 -SMALL_OBJECT_BYTES = 65536 BATCH_MAX_SIZE = 500 PAGE_MAX_SIZE = 5000 @@ -97,7 +98,6 @@ class Options: max_retries: int = 10 restart: bool = False min_concurrency: int = 1 - slow_factor: float = 2.0 count: bool = False @@ -133,30 +133,21 @@ def pause(self, seconds: float) -> None: class AdaptiveLimit: - """Number of requests kept in flight, lowered when the server slows down or answers 429. + """Number of requests to encrypt kept in flight, lowered when the server says it is overloaded. - The signal is the latency per unit of work of the batches, compared with the lowest smoothed value seen so - far. A signal above `slow_factor` times that floor, or a 429 answer, halves the limit (at most once per - cooldown). Otherwise the limit rises by one after every `limit` quiet requests, up to the maximum. + The server says so with a 429 answer, a 503 or 504 answer, or no answer before the timeout. Each of these + halves the limit, once for all the requests sent before that decrease: they were in flight together and report + the same overload. After as many batches in a row succeed as the limit, the limit rises by one, up to the maximum. """ - SMOOTHING = 0.2 - COOLDOWN_SECONDS = 2.0 - FLOOR_DRIFT_PER_SECOND = 0.005 - - def __init__(self, maximum: int, minimum: int, slow_factor: float, clock: Callable[[], float]) -> None: + def __init__(self, maximum: int, minimum: int) -> None: self.maximum = maximum self.minimum = max(1, min(minimum, maximum)) self.limit = max(self.minimum, maximum // 2) - self.slow_factor = slow_factor - self._clock = clock + self.round = 0 self._in_flight = 0 self._condition = asyncio.Condition() - self._smoothed: float | None = None - self._floor = 0.0 - self._floor_at = 0.0 self._quiet = 0 - self._last_decrease = float("-inf") self.decreases = 0 self.increases = 0 @@ -170,36 +161,17 @@ async def release(self) -> None: self._in_flight -= 1 self._condition.notify_all() - def _decrease(self) -> None: - now = self._clock() - if now - self._last_decrease < self.COOLDOWN_SECONDS or self.limit <= self.minimum: + def overloaded(self, sent_in_round: int) -> None: + """A request sent in round `sent_in_round` got a 429, 503 or 504 answer, or none before the timeout.""" + self._quiet = 0 + if sent_in_round != self.round or self.limit <= self.minimum: return self.limit = max(self.minimum, self.limit // 2) - self._last_decrease = now - self._quiet = 0 + self.round += 1 self.decreases += 1 - def shed(self) -> None: - """The server answered 429.""" - self._decrease() - - def observe(self, seconds: float) -> None: - """Record the latency per unit of work of one batch and adapt the limit.""" - if seconds <= 0: - return # A coarse clock can read 0.0; as the first sample it would set the floor to 0 for ever. - now = self._clock() - if self._smoothed is None: - self._smoothed = seconds - self._floor = seconds - else: - self._smoothed += self.SMOOTHING * (seconds - self._smoothed) - # The floor rises slowly, so one lucky sample does not make every later request look slow for ever. - drift = 1 + self.FLOOR_DRIFT_PER_SECOND * (now - self._floor_at) - self._floor = min(self._floor * drift, self._smoothed) - self._floor_at = now - if self._smoothed > self.slow_factor * self._floor: - self._decrease() - return + def succeeded(self) -> None: + """A batch was encrypted without an overload answer.""" self._quiet += 1 if self._quiet >= self.limit and self.limit < self.maximum: self.limit += 1 @@ -285,12 +257,7 @@ def __init__( self.counted_objects = 0 self.count_seconds_this_run = 0.0 self._count_requests_before = 0 - self.limit = AdaptiveLimit( - maximum=options.concurrency, - minimum=options.min_concurrency, - slow_factor=options.slow_factor, - clock=clock, - ) + self.limit = AdaptiveLimit(maximum=options.concurrency, minimum=options.min_concurrency) def check_output_files(self) -> None: """Check that the state file and the report can be written, before any object is changed. @@ -425,11 +392,11 @@ async def _request( path: str, params: dict[str, Any], body: dict[str, Any] | None = None, - ) -> tuple[httpx.Response, float]: + ) -> httpx.Response: """Send one request until the server answers it, waiting out 429 responses and transient failures. - Returns the answer and the seconds that the HTTP call that produced it took, without the time spent - waiting for the pace, a pause after a 429 answer or a delay after a failure. + A 429, 503 or 504 answer, or a timeout, also lowers the limit of requests in flight: the server is + overloaded, and after a timeout it may still be working on the request that is sent again. Raises: MigrationError: If the failures other than 429 outnumber the retries allowed. @@ -442,22 +409,23 @@ async def _request( await self._pacer.wait() self.totals.requests += 1 generation = self._auth_generation - call_started = self._clock() + sent_in_round = self.limit.round try: response = await http.request(method, path, params=params, json=body) except httpx.TransportError as exc: + if isinstance(exc, httpx.TimeoutException): + self.limit.overloaded(sent_in_round=sent_in_round) failures += 1 self._check_retries(failures=failures, path=path, cause=f"{type(exc).__name__}: {exc}") await self._sleep(backoff_delay(attempt=failures, rng=self._rng)) continue - call_seconds = self._clock() - call_started self._answered = True if response.status_code == HTTP_TOO_MANY_REQUESTS: sheds += 1 self.totals.shed_429 += 1 if ADMISSION_HEADER in response.headers: self.totals.shed_429_admission += 1 - self.limit.shed() + self.limit.overloaded(sent_in_round=sent_in_round) asked = parse_retry_after(response.headers.get("Retry-After")) if asked > RETRY_AFTER_MAX_SECONDS: self._notify( @@ -468,6 +436,8 @@ async def _request( self._pacer.pause(max(asked, backoff_delay(attempt=sheds, rng=self._rng))) continue if response.status_code in RETRYABLE_STATUS_CODES: + if response.status_code in OVERLOAD_STATUS_CODES: + self.limit.overloaded(sent_in_round=sent_in_round) failures += 1 self._check_retries(failures=failures, path=path, cause=f"HTTP {response.status_code}") await self._sleep(backoff_delay(attempt=failures, rng=self._rng)) @@ -481,7 +451,7 @@ async def _request( refreshed = True await self._renew_login(http, self.refresh_login, seen_generation=generation) continue - return response, call_seconds + return response def _notify(self, message: str) -> None: if self.on_notice is not None: @@ -519,7 +489,7 @@ async def _fetch_listing( params: dict[str, Any] = {"limit": limit} if start_after: params["start_after"] = start_after - response, _ = await self._request(http, "GET", LIST_PATH, params) + response = await self._request(http, "GET", LIST_PATH, params) if response.status_code != HTTP_OK: raise MigrationError(refusal_message(response=response, what="The listing of the stored objects")) body = answer_body(response, what="The listing of the stored objects") @@ -573,16 +543,13 @@ async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, A body = {"identifiers": identifiers, "allow_unverified": self.options.allow_unverified} await self.limit.acquire() try: - response, seconds = await self._request(http, "POST", BATCH_PATH, {}, body) + response = await self._request(http, "POST", BATCH_PATH, {}, body) finally: await self.limit.release() self.totals.encrypt_requests += 1 if response.status_code != HTTP_OK: raise MigrationError(refusal_message(response=response, what="The request to encrypt a batch")) - # A batch is compared per unit of work: one unit per object plus one per `SMALL_OBJECT_BYTES` of content. - batch_bytes = sum(item["size"] for item in stored) - units = len(stored) + batch_bytes / SMALL_OBJECT_BYTES - self.limit.observe(seconds / units) + self.limit.succeeded() body = answer_body(response, what="The request to encrypt a batch") try: results: list[dict[str, Any]] = body["results"] @@ -599,7 +566,7 @@ async def _encrypt_batch(self, http: httpx.AsyncClient, stored: list[dict[str, A self.bytes_confirmed += sum(item["size"] for item in stored if item["identifier"] in confirmed) raise self.objects_confirmed += len(results) - self.bytes_confirmed += batch_bytes + self.bytes_confirmed += sum(item["size"] for item in stored) return results def _record(self, result: dict[str, Any], report: TextIO | None) -> None: diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py index 5079e4907..8d65a4fce 100644 --- a/tests/unit/ctl/test_storage_migration.py +++ b/tests/unit/ctl/test_storage_migration.py @@ -592,7 +592,9 @@ async def test_the_backoff_after_repeated_429_answers_grows_and_stops_at_its_cap assert waits[-1] >= 30.0 -async def test_the_limit_halves_at_most_once_per_cooldown(httpx_mock: HTTPXMock, tmp_path: Path) -> None: +async def test_a_429_to_a_request_sent_after_the_limit_was_lowered_lowers_it_again( + httpx_mock: HTTPXMock, tmp_path: Path +) -> None: httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "0"}) httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=429, headers={"Retry-After": "0"}) @@ -601,80 +603,107 @@ async def test_the_limit_halves_at_most_once_per_cooldown(httpx_mock: HTTPXMock, await run(encryptor) - assert encryptor.limit.decreases == 1 - assert encryptor.limit.limit == 4 + assert encryptor.limit.decreases == 2 + assert encryptor.limit.limit == 2 + + +async def test_batches_that_become_slower_do_not_lower_the_limit(httpx_mock: HTTPXMock, tmp_path: Path) -> None: + identifiers = [f"obj-{index:02d}" for index in range(40)] + encryptor, fake = make(tmp_path, concurrency=8, batch_size=1) + + def server(seconds: float) -> Callable[[httpx.Request], httpx.Response]: + def answer_after(request: httpx.Request) -> httpx.Response: + fake.now += seconds + return httpx.Response(200, json=answer(*json.loads(request.content)["identifiers"])) + + return answer_after + + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page(*identifiers)) + for index in range(len(identifiers)): + httpx_mock.add_callback(server(0.3 if index < 20 else 1.2), method="POST", url=BATCH_URL) + + await run(encryptor) + + assert encryptor.totals.counts == {"encrypted": 40} + assert encryptor.limit.decreases == 0 + assert encryptor.limit.limit == 8 # Adaptive limit def test_the_limit_starts_at_half_the_maximum_and_never_below_the_minimum() -> None: - fake = FakeTime() - - assert AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock).limit == 4 - assert AdaptiveLimit(maximum=1, minimum=1, slow_factor=2.0, clock=fake.clock).limit == 1 - assert AdaptiveLimit(maximum=8, minimum=6, slow_factor=2.0, clock=fake.clock).limit == 6 + assert AdaptiveLimit(maximum=8, minimum=1).limit == 4 + assert AdaptiveLimit(maximum=1, minimum=1).limit == 1 + assert AdaptiveLimit(maximum=8, minimum=6).limit == 6 -def test_the_limit_rises_by_one_after_as_many_quiet_requests_as_the_limit() -> None: - fake = FakeTime() - limit = AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) +def test_the_limit_rises_by_one_after_as_many_successes_as_the_limit() -> None: + limit = AdaptiveLimit(maximum=8, minimum=1) for _ in range(3): - limit.observe(0.01) + limit.succeeded() assert limit.limit == 4 - limit.observe(0.01) + limit.succeeded() assert limit.limit == 5 assert limit.increases == 1 for _ in range(100): - limit.observe(0.01) + limit.succeeded() assert limit.limit == 8 -def test_a_slow_signal_halves_the_limit_and_the_limit_rises_again_when_it_is_quiet() -> None: - fake = FakeTime() - limit = AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) +def test_an_overload_halves_the_limit_and_successes_raise_it_again() -> None: + limit = AdaptiveLimit(maximum=8, minimum=1) for _ in range(4): - limit.observe(0.01) + limit.succeeded() assert limit.limit == 5 - for _ in range(10): - limit.observe(0.5) + limit.overloaded(sent_in_round=limit.round) assert limit.limit == 2 - assert limit.decreases >= 1 + assert limit.decreases == 1 - fake.now += 10_000 - for _ in range(40): - limit.observe(0.5) - assert limit.limit > 2 + for _ in range(2): + limit.succeeded() + assert limit.limit == 3 + + +def test_an_overload_resets_the_count_of_successes() -> None: + limit = AdaptiveLimit(maximum=8, minimum=1) + for _ in range(3): + limit.succeeded() + + limit.overloaded(sent_in_round=limit.round - 1) + limit.succeeded() + + assert limit.limit == 4 + assert limit.increases == 0 def test_the_limit_does_not_fall_below_the_minimum() -> None: - fake = FakeTime() - limit = AdaptiveLimit(maximum=8, minimum=3, slow_factor=2.0, clock=fake.clock) + limit = AdaptiveLimit(maximum=8, minimum=3) for _ in range(5): - limit.shed() - fake.now += 10 + limit.overloaded(sent_in_round=limit.round) assert limit.limit == 3 -def test_a_second_decrease_inside_the_cooldown_is_ignored() -> None: - fake = FakeTime() - limit = AdaptiveLimit(maximum=16, minimum=1, slow_factor=2.0, clock=fake.clock) +def test_an_overload_of_a_request_sent_before_the_last_decrease_is_ignored() -> None: + limit = AdaptiveLimit(maximum=16, minimum=1) + sent_together = limit.round - limit.shed() - limit.shed() + limit.overloaded(sent_in_round=sent_together) + limit.overloaded(sent_in_round=sent_together) assert limit.limit == 4 - fake.now += 2.5 - limit.shed() + assert limit.decreases == 1 + + limit.overloaded(sent_in_round=limit.round) assert limit.limit == 2 + assert limit.decreases == 2 async def test_no_more_requests_are_in_flight_than_the_limit_allows() -> None: - fake = FakeTime() - limit = AdaptiveLimit(maximum=4, minimum=1, slow_factor=2.0, clock=fake.clock) + limit = AdaptiveLimit(maximum=4, minimum=1) assert limit.limit == 2 await limit.acquire() await limit.acquire() @@ -703,6 +732,47 @@ async def test_a_503_answer_is_retried_after_a_backoff(httpx_mock: HTTPXMock, tm assert 1.0 <= fake.sleeps[1] <= 1.0 * 1.25 +@dataclass +class TransientCase: + name: str + failure: httpx.Response | Exception + lowers_the_limit: bool + + +TRANSIENT_CASES = [ + TransientCase(name="http-500", failure=httpx.Response(500, text="database error"), lowers_the_limit=False), + TransientCase(name="http-502", failure=httpx.Response(502), lowers_the_limit=False), + TransientCase(name="http-503", failure=httpx.Response(503), lowers_the_limit=True), + TransientCase(name="http-504", failure=httpx.Response(504), lowers_the_limit=True), + TransientCase(name="read-timeout", failure=httpx.ReadTimeout("no answer"), lowers_the_limit=True), + TransientCase(name="connect-timeout", failure=httpx.ConnectTimeout("no answer"), lowers_the_limit=True), + TransientCase(name="connection-reset", failure=httpx.ReadError("connection reset"), lowers_the_limit=False), + TransientCase(name="connection-refused", failure=httpx.ConnectError("refused"), lowers_the_limit=False), +] + + +@pytest.mark.parametrize("case", [pytest.param(case, id=case.name) for case in TRANSIENT_CASES]) +async def test_a_transient_failure_is_retried_and_only_an_overload_lowers_the_limit( + httpx_mock: HTTPXMock, tmp_path: Path, case: TransientCase +) -> None: + httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) + if isinstance(case.failure, Exception): + httpx_mock.add_exception(case.failure, method="POST", url=BATCH_URL) + else: + httpx_mock.add_response( + method="POST", url=BATCH_URL, status_code=case.failure.status_code, content=case.failure.content + ) + httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) + encryptor, _ = make(tmp_path, concurrency=8) + + await run(encryptor) + + assert encryptor.totals.retries == 1 + assert encryptor.totals.counts == {"encrypted": 1} + assert encryptor.limit.decreases == (1 if case.lowers_the_limit else 0) + assert encryptor.limit.limit == (2 if case.lowers_the_limit else 4) + + async def test_a_connection_error_during_the_run_is_retried(httpx_mock: HTTPXMock, tmp_path: Path) -> None: httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) httpx_mock.add_exception(httpx.ReadError("connection reset"), method="POST", url=BATCH_URL) @@ -728,14 +798,16 @@ async def test_retries_stop_after_max_retries(httpx_mock: HTTPXMock, tmp_path: P assert encryptor.totals.retries == 3 -async def test_a_500_answer_is_not_retried(httpx_mock: HTTPXMock, tmp_path: Path) -> None: +async def test_a_500_answer_stops_the_run_after_max_retries(httpx_mock: HTTPXMock, tmp_path: Path) -> None: httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) - httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=500, text="boom") + for _ in range(3): + httpx_mock.add_response(method="POST", url=BATCH_URL, status_code=500, text="boom") + encryptor, _ = make(tmp_path, max_retries=2) - with pytest.raises(MigrationError, match=r"HTTP 500"): - await run(make(tmp_path)[0]) + with pytest.raises(MigrationError, match=r"still fails after 2 retries: HTTP 500"): + await run(encryptor) - assert len(httpx_mock.get_requests(method="POST")) == 1 + assert len(httpx_mock.get_requests(method="POST")) == 3 async def test_a_server_that_never_answers_fails_after_a_few_retries(httpx_mock: HTTPXMock, tmp_path: Path) -> None: @@ -1571,17 +1643,6 @@ async def test_a_retry_after_given_as_a_date_is_honoured(httpx_mock: HTTPXMock, assert 50.0 < fake.sleeps[0] <= 60.0 -def test_a_first_latency_sample_of_zero_does_not_set_the_floor_to_zero() -> None: - fake = FakeTime() - limit = AdaptiveLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) - - limit.observe(0.0) - limit.observe(0.01) - limit.observe(0.01) - - assert limit.decreases == 0 - - # Expired login @@ -1978,41 +2039,6 @@ async def test_the_count_and_the_run_agree_on_pages_that_are_empty_or_end_beyond assert encryptor.done_bytes == encryptor.total_bytes == 300 -class RecordingLimit(AdaptiveLimit): - """An adaptive limit that keeps the latency samples it is given.""" - - def __init__(self, maximum: int, minimum: int, slow_factor: float, clock: Callable[[], float]) -> None: - super().__init__(maximum=maximum, minimum=minimum, slow_factor=slow_factor, clock=clock) - self.observed: list[float] = [] - - def observe(self, seconds: float) -> None: - self.observed.append(seconds) - super().observe(seconds) - - -async def test_the_pace_of_the_command_is_not_counted_as_the_latency_of_the_server( - httpx_mock: HTTPXMock, tmp_path: Path -) -> None: - identifiers = ["a", "b", "c", "d", "e", "f"] - encryptor, fake = make(tmp_path, concurrency=8, batch_size=1, rate=1.0) - encryptor.limit = RecordingLimit(maximum=8, minimum=1, slow_factor=2.0, clock=fake.clock) - - def server_that_takes_a_tenth_of_a_second(request: httpx.Request) -> httpx.Response: - fake.now += 0.1 - return httpx.Response(200, json=answer(*json.loads(request.content)["identifiers"])) - - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page(*identifiers)) - for _ in identifiers: - httpx_mock.add_callback(server_that_takes_a_tenth_of_a_second, method="POST", url=BATCH_URL) - - await run(encryptor) - - assert encryptor.totals.counts == {"encrypted": 6} - assert sum(fake.sleeps) > 4.0 - assert len(encryptor.limit.observed) == 6 - assert max(encryptor.limit.observed) < 0.11 - - @dataclass class ServerTextCase: name: str From 25649531502311224393682358dee4cae2311154 Mon Sep 17 00:00:00 2001 From: Simon AURA--SCUSSEL Date: Wed, 2 Dec 2026 08:49:28 +0100 Subject: [PATCH 9/9] refactor: inject the clock of the progress display, drop dead state and repeated count tests The progress display takes its clock and sleep as arguments. Its test advances a fake clock and compares the printed lines exactly, instead of patching the time module and racing real sleeps against the refresh. A state file no longer goes through a conversion for the format of development versions of the command; no released version wrote it. A state file with a field this version does not know is refused as unreadable. The count-pass tests that repeated the 429, refusal, connection and malformed-answer cases of the run are removed. One test keeps what only the count pass does on a failure: no batch, no state file, the count flag reset and its requests counted apart from the run. Signed-off-by: Simon AURA--SCUSSEL --- infrahub_sdk/ctl/storage/encrypt.py | 25 ++-- infrahub_sdk/ctl/storage/migration.py | 9 +- tests/unit/ctl/test_storage_app.py | 95 ++++++---------- tests/unit/ctl/test_storage_migration.py | 138 ++--------------------- 4 files changed, 68 insertions(+), 199 deletions(-) diff --git a/infrahub_sdk/ctl/storage/encrypt.py b/infrahub_sdk/ctl/storage/encrypt.py index 1ff8e8b19..aecbdce81 100644 --- a/infrahub_sdk/ctl/storage/encrypt.py +++ b/infrahub_sdk/ctl/storage/encrypt.py @@ -6,6 +6,7 @@ import time from datetime import datetime, timezone from pathlib import Path +from typing import TYPE_CHECKING import httpx import typer @@ -36,6 +37,9 @@ progress_line, ) +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + console = Console() DEFAULT_STATE_FILE = Path("infrahub-storage-encrypt.state.json") @@ -89,8 +93,9 @@ def _done_text(encryptor: StorageEncryptor) -> str: class _Progress: """Builds the progress line from counters, with the recent rate for the remaining time.""" - def __init__(self, encryptor: StorageEncryptor) -> None: + def __init__(self, encryptor: StorageEncryptor, clock: Callable[[], float] = time.monotonic) -> None: self._encryptor = encryptor + self._clock = clock self._tracker = RateTracker() def line(self) -> str: @@ -98,25 +103,29 @@ def line(self) -> str: if encryptor.counting: self._tracker = RateTracker() return f"Counting the objects to process: {format_number(encryptor.counted_objects)} so far" - self._tracker.record(now=time.monotonic(), done=_done_objects(encryptor)) + self._tracker.record(now=self._clock(), done=_done_objects(encryptor)) return progress_line(_view(encryptor, rate=self._tracker.rate())) -async def _show_progress(encryptor: StorageEncryptor) -> None: - progress = _Progress(encryptor) +async def _show_progress( + encryptor: StorageEncryptor, + clock: Callable[[], float] = time.monotonic, + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, +) -> None: + progress = _Progress(encryptor, clock=clock) if console.is_terminal: with Live(console=console, transient=True, refresh_per_second=2) as live: while True: live.update(progress.line()) - await asyncio.sleep(PROGRESS_LIVE_SECONDS) + await sleep(PROGRESS_LIVE_SECONDS) # Sample the counters twice per second so the rate has data, and print a line every PROGRESS_LINE_SECONDS. - next_print = time.monotonic() + PROGRESS_LINE_SECONDS + next_print = clock() + PROGRESS_LINE_SECONDS while True: line = progress.line() - if time.monotonic() >= next_print: + if clock() >= next_print: console.print(line, highlight=False, soft_wrap=True) next_print += PROGRESS_LINE_SECONDS - await asyncio.sleep(PROGRESS_LIVE_SECONDS) + await sleep(PROGRESS_LIVE_SECONDS) async def _run_until_stopped(encryptor: StorageEncryptor, http: httpx.AsyncClient) -> str | None: diff --git a/infrahub_sdk/ctl/storage/migration.py b/infrahub_sdk/ctl/storage/migration.py index 515bc5a15..f11e7b49e 100644 --- a/infrahub_sdk/ctl/storage/migration.py +++ b/infrahub_sdk/ctl/storage/migration.py @@ -8,7 +8,7 @@ import random import time from collections import Counter -from dataclasses import asdict, dataclass, field, fields +from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, TextIO @@ -296,12 +296,7 @@ def load_state(self) -> None: ) start_after = state["start_after"] completed = bool(state["completed"]) - saved = dict(state["totals"]) - known = {item.name for item in fields(Totals)} - totals = Totals(**{name: value for name, value in saved.items() if name in known}) - if "bytes_handled" not in saved: - # A state file of an earlier version did not record the bytes of every outcome. - totals.bytes_handled = totals.bytes_encrypted + totals = Totals(**state["totals"]) except (OSError, ValueError, KeyError, TypeError) as exc: raise MigrationError( f"The state file {path} cannot be read ({type(exc).__name__}: {exc}). " diff --git a/tests/unit/ctl/test_storage_app.py b/tests/unit/ctl/test_storage_app.py index 6d571fc00..babc520f7 100644 --- a/tests/unit/ctl/test_storage_app.py +++ b/tests/unit/ctl/test_storage_app.py @@ -525,17 +525,6 @@ def test_a_refusal_during_the_count_stops_the_run_with_a_clear_message_and_sends assert not (tmp_path / "state.json").exists() -def test_a_server_that_cannot_be_reached_during_the_count_exits_2(httpx_mock: HTTPXMock, files: list[str]) -> None: - httpx_mock.add_exception(httpx.ConnectError("connection refused"), is_reusable=True) - - result = invoke_counting(files) - - assert result.exit_code == 2, result.stdout - assert "ConnectError: connection refused" in text_of(result) - assert httpx_mock.get_requests(method="POST") == [] - assert len(httpx_mock.get_requests()) == migration_module.UNANSWERED_MAX_RETRIES + 1 - - @dataclass class StopCase: name: str @@ -714,49 +703,46 @@ def make_encryptor(tmp_path: Path, *, dry_run: bool = False) -> StorageEncryptor return StorageEncryptor(options=options, address=BASE) -async def test_the_progress_line_printed_when_the_output_is_not_a_terminal_shows_total_percent_and_remaining_time( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - monkeypatch.setattr(encrypt_module, "PROGRESS_LINE_SECONDS", 0.3) - monkeypatch.setattr(encrypt_module, "PROGRESS_LIVE_SECONDS", 0.02) - clock = {"now": 0.0} +class ProgressStoppedError(Exception): + """Ends the endless loop of the progress display in a test.""" - class FakeClockModule: - @staticmethod - def monotonic() -> float: - return clock["now"] - monkeypatch.setattr(encrypt_module, "time", FakeClockModule) +async def test_the_progress_line_printed_when_the_output_is_not_a_terminal_shows_total_percent_and_remaining_time( + tmp_path: Path, +) -> None: encryptor = make_encryptor(tmp_path) encryptor.remaining_objects = 1000 encryptor.remaining_bytes = 100_000 - - async def advance() -> None: - # 100 objects/s: 0.1 s of the fake clock for each 10 objects. - for _ in range(60): - clock["now"] += 0.1 - encryptor.objects_confirmed += 10 - encryptor.bytes_confirmed += 1000 - await asyncio.sleep(0.01) - - with encrypt_module.console.capture() as capture: - task = asyncio.create_task(encrypt_module._show_progress(encryptor)) - await advance() - task.cancel() - await asyncio.gather(task, return_exceptions=True) - - lines = [line for line in capture.get().splitlines() if "objects" in line] - assert lines, capture.get() - last = lines[-1] - assert "/ 1,000 objects (" in last - assert "estimating" not in last - assert " objects/s | remaining " in last - assert "%)" in last - assert "remaining" in last - assert " / 100.0 kB" in last - assert "limit " in last - assert "429: 0" in last - assert "retries: 0" in last + now = 0.0 + + def clock() -> float: + return now + + async def sleep(seconds: float) -> None: + # 100 objects/s and 10 kB/s on the fake clock; stop after 10 seconds. + nonlocal now + if now >= 10.0: + raise ProgressStoppedError("10 seconds shown") + now += seconds + encryptor.objects_confirmed += int(100 * seconds) + encryptor.bytes_confirmed += int(10_000 * seconds) + + with ( + encrypt_module.console.capture() as capture, + pytest.raises(ProgressStoppedError, match="10 seconds shown"), + ): + await encrypt_module._show_progress(encryptor, clock=clock, sleep=sleep) + + assert capture.get().splitlines() == [ + ( + "500 / 1,000 objects (50.0%) | 100 objects/s | remaining 5s | 50.0 kB / 100.0 kB" + " | limit 4/8 | 429: 0 | retries: 0" + ), + ( + "1,000 / 1,000 objects (100.0%) | 100 objects/s | remaining finishing | 100.0 kB / 100.0 kB" + " | limit 4/8 | 429: 0 | retries: 0" + ), + ] @dataclass @@ -773,20 +759,13 @@ class FreezeCase: @pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in FREEZE_CASES]) async def test_the_remaining_time_after_the_process_was_frozen_is_estimating_and_then_right( - case: FreezeCase, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + case: FreezeCase, tmp_path: Path ) -> None: clock = {"now": 1000.0} - - class FakeClockModule: - @staticmethod - def monotonic() -> float: - return clock["now"] - - monkeypatch.setattr(encrypt_module, "time", FakeClockModule) encryptor = make_encryptor(tmp_path) encryptor.remaining_objects = 100_000 encryptor.remaining_bytes = 10_000_000 - progress = encrypt_module._Progress(encryptor) + progress = encrypt_module._Progress(encryptor, clock=lambda: clock["now"]) def run(seconds: float) -> str: """Run at 100 objects/s, with a progress line every 0.5 s; return the last line.""" diff --git a/tests/unit/ctl/test_storage_migration.py b/tests/unit/ctl/test_storage_migration.py index 8d65a4fce..e6085adea 100644 --- a/tests/unit/ctl/test_storage_migration.py +++ b/tests/unit/ctl/test_storage_migration.py @@ -1158,8 +1158,8 @@ async def test_a_rerun_after_a_batch_answer_without_every_object_sends_those_obj # Count pass -def old_state(**overrides: Any) -> dict[str, Any]: # noqa: ANN401 - """A state file as the version without the count pass wrote it.""" +def saved_state(**overrides: Any) -> dict[str, Any]: # noqa: ANN401 + """A state file of a run that stopped after encrypting the objects `a` and `b`.""" state: dict[str, Any] = { "version": 1, "address": BASE, @@ -1180,6 +1180,9 @@ def old_state(**overrides: Any) -> dict[str, Any]: # noqa: ANN401 "limit_decreases": 0, "limit_increases": 0, "limit_final": 4, + "bytes_handled": 200, + "count_seconds": 0.0, + "count_requests": 0, }, } state.update(overrides) @@ -1306,7 +1309,7 @@ async def test_the_count_pass_cuts_the_last_page_at_the_limit(httpx_mock: HTTPXM async def test_a_resumed_count_starts_at_the_saved_position_and_adds_the_objects_of_earlier_runs( httpx_mock: HTTPXMock, tmp_path: Path ) -> None: - (tmp_path / "state.json").write_text(json.dumps(old_state())) + (tmp_path / "state.json").write_text(json.dumps(saved_state())) httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) httpx_mock.add_response(url=f"{LIST_URL}?limit=2&start_after=b", json=page("c")) httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) @@ -1326,7 +1329,7 @@ async def test_a_resumed_count_starts_at_the_saved_position_and_adds_the_objects async def test_a_resumed_run_counts_again_and_does_not_trust_the_total_of_the_state_file( httpx_mock: HTTPXMock, tmp_path: Path ) -> None: - state = old_state(plan={"objects_total": 10, "bytes_total": 1000}) + state = saved_state(plan={"objects_total": 10, "bytes_total": 1000}) (tmp_path / "state.json").write_text(json.dumps(state)) httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c", "d")) httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c", "d")) @@ -1340,24 +1343,6 @@ async def test_a_resumed_run_counts_again_and_does_not_trust_the_total_of_the_st assert plan == {"objects_total": 4, "bytes_total": 400} -async def test_a_state_file_of_the_version_without_the_count_pass_is_read_and_resumed( - httpx_mock: HTTPXMock, tmp_path: Path -) -> None: - (tmp_path / "state.json").write_text(json.dumps(old_state())) - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) - httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) - encryptor, _ = make(tmp_path) - - await run(encryptor) - - assert encryptor.resumed is True - assert encryptor.totals.counts == {"encrypted": 3} - assert encryptor.handled_before == 2 - # The old file has no bytes of every outcome; the bytes of the encrypted objects are the nearest figure. - assert encryptor.totals.bytes_handled == 300 - assert encryptor.total_objects is None - - async def test_the_state_file_keeps_the_total_and_the_count_figures(httpx_mock: HTTPXMock, tmp_path: Path) -> None: mock_count_and_run_of_three(httpx_mock) encryptor, _ = make(tmp_path, page_size=2, count=True) @@ -1372,21 +1357,6 @@ async def test_the_state_file_keeps_the_total_and_the_count_figures(httpx_mock: assert state["version"] == 1 -async def test_a_state_file_with_a_field_this_version_does_not_know_is_still_read( - httpx_mock: HTTPXMock, tmp_path: Path -) -> None: - state = old_state() - state["totals"]["field_of_a_later_version"] = 7 - (tmp_path / "state.json").write_text(json.dumps(state)) - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=b", json=page("c")) - httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("c")) - encryptor, _ = make(tmp_path) - - await run(encryptor) - - assert encryptor.totals.counts == {"encrypted": 3} - - async def test_without_the_count_pass_there_is_no_total_and_no_count_request( httpx_mock: HTTPXMock, tmp_path: Path ) -> None: @@ -1465,105 +1435,21 @@ async def test_the_callback_runs_once_after_the_count(httpx_mock: HTTPXMock, tmp assert seen == [3] -async def test_a_429_answer_during_the_count_is_waited_out_and_counted(httpx_mock: HTTPXMock, tmp_path: Path) -> None: - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", status_code=429, headers={"Retry-After": "3"}) - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a")) - httpx_mock.add_response(method="POST", url=BATCH_URL, json=answer("a")) - encryptor, fake = make(tmp_path, page_size=5000, count=True) - - await run(encryptor) - - assert encryptor.totals.shed_429 >= 1 - assert max(fake.sleeps) >= 3.0 - assert encryptor.remaining_objects == 1 - - -@dataclass -class CountRefusalCase: - name: str - status: int - body: dict[str, Any] - expected: str - - -COUNT_REFUSAL_CASES = [ - CountRefusalCase( - name="token-rejected", status=401, body={"detail": "bad"}, expected="HTTP 401: the server does not accept" - ), - CountRefusalCase( - name="no-super-admin", status=403, body={"detail": "no"}, expected="does not have the super admin permission" - ), - CountRefusalCase( - name="no-routes", - status=404, - body={"detail": "Not Found"}, - expected="does not have the storage encryption routes", - ), - CountRefusalCase( - name="not-enabled", - status=409, - body={"detail": "Storage encryption is not enabled"}, - expected="storage encryption is not enabled on the server", - ), -] - - -@pytest.mark.parametrize("case", [pytest.param(tc, id=tc.name) for tc in COUNT_REFUSAL_CASES]) -async def test_a_refusal_during_the_count_stops_the_run_with_the_same_message_as_during_the_run( - case: CountRefusalCase, httpx_mock: HTTPXMock, tmp_path: Path +async def test_a_refusal_during_the_count_stops_the_run_before_any_batch_and_keeps_its_requests_apart( + httpx_mock: HTTPXMock, tmp_path: Path ) -> None: - httpx_mock.add_response(method="GET", status_code=case.status, json=case.body) + httpx_mock.add_response(method="GET", status_code=403, json={"detail": "no"}) encryptor, _ = make(tmp_path, count=True) - with pytest.raises(MigrationError, match=re.escape(case.expected)) as raised: + with pytest.raises(MigrationError, match=r"The listing of the stored objects was refused.*super admin"): await run(encryptor) - assert "The listing of the stored objects was refused" in str(raised.value) assert httpx_mock.get_requests(method="POST") == [] - assert len(httpx_mock.get_requests()) == 1 assert not (tmp_path / "state.json").exists() assert encryptor.counting is False assert encryptor.total_objects is None - - -async def test_a_refusal_on_a_later_page_of_the_count_stops_the_run_before_any_batch( - httpx_mock: HTTPXMock, tmp_path: Path -) -> None: - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000", json=page("a", next_start_after="a")) - httpx_mock.add_response(url=f"{LIST_URL}?limit=5000&start_after=a", status_code=403, json={"detail": "no"}) - encryptor, _ = make(tmp_path, count=True) - - with pytest.raises(MigrationError, match="super admin"): - await run(encryptor) - - assert httpx_mock.get_requests(method="POST") == [] - - -async def test_a_server_that_cannot_be_reached_during_the_count_stops_the_run_with_the_cause( - httpx_mock: HTTPXMock, tmp_path: Path -) -> None: - httpx_mock.add_exception(httpx.ConnectError("connection refused"), is_reusable=True) - encryptor, _ = make(tmp_path, count=True) - - with pytest.raises(MigrationError, match=r"cannot be reached \(ConnectError: connection refused\)"): - await run(encryptor) - - assert len(httpx_mock.get_requests()) == UNANSWERED_MAX_RETRIES + 1 assert encryptor.totals.requests == 0 - assert not (tmp_path / "state.json").exists() - - -@pytest.mark.parametrize("body", ["not json", '{"unexpected": 1}'], ids=["not-json", "unexpected-shape"]) -async def test_an_unreadable_count_listing_stops_the_run_with_a_message( - body: str, httpx_mock: HTTPXMock, tmp_path: Path -) -> None: - httpx_mock.add_response(method="GET", text=body) - encryptor, _ = make(tmp_path, count=True) - - with pytest.raises(MigrationError, match="listing of the stored objects"): - await run(encryptor) - - assert httpx_mock.get_requests(method="POST") == [] + assert encryptor.totals.count_requests == 1 async def test_cancelling_the_run_during_the_count_saves_nothing_and_ends_the_count(