Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions tests/test_project_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@
from pathlib import Path
from unittest.mock import Mock, patch

import httpx
import pytest
from click.testing import CliRunner

from th_cli.api_lib_autogen import models as api_models
from th_cli.api_lib_autogen.exceptions import UnexpectedResponse
from th_cli.commands.project import project
from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse
from th_cli.commands.project import PROJECT_LOGS_TIMEOUT, project


@pytest.mark.unit
Expand Down Expand Up @@ -1070,6 +1071,73 @@ def test_import_project_help_message(self, cli_runner: CliRunner) -> None:
assert "--file" in result.output


@pytest.mark.unit
@pytest.mark.cli
class TestProjectLogsTimeout:
"""`project logs` must not use httpx's 5s default: the backend sends the first byte only after it has built the
whole archive, so the wait grows with the project."""

def invoke_logs(self, cli_runner, mock_sync_apis, mock_api_client, temp_dir, **download):
mock_sync_apis.projects_api.download_project_logs_api_v1_projects__id__logs_get.configure_mock(**download)
with patch("th_cli.commands.project.get_client", return_value=mock_api_client) as get_client:
with patch("th_cli.commands.project.SyncApis", return_value=mock_sync_apis):
with cli_runner.isolated_filesystem(temp_dir=temp_dir):
result = cli_runner.invoke(project, ["logs", "--id", "1"])
written = list(Path(".").iterdir())
return result, get_client, written

def test_logs_asks_for_an_extended_timeout(
self, cli_runner, mock_sync_apis, mock_api_client, sample_project, temp_dir
):
mock_sync_apis.projects_api.read_project_api_v1_projects__id__get.return_value = sample_project
result, get_client, _ = self.invoke_logs(
cli_runner, mock_sync_apis, mock_api_client, temp_dir, return_value=b"zip"
)
assert result.exit_code == 0
assert get_client.call_args.kwargs["timeout"] is PROJECT_LOGS_TIMEOUT
assert PROJECT_LOGS_TIMEOUT.read >= 120.0 # at least what a single execution's log download gets
assert PROJECT_LOGS_TIMEOUT.connect == 10.0

def test_other_project_commands_keep_the_default_timeout(self, cli_runner, mock_sync_apis, mock_api_client):
mock_sync_apis.projects_api.read_projects_api_v1_projects__get.return_value = []
with patch("th_cli.commands.project.get_client", return_value=mock_api_client) as get_client:
with patch("th_cli.commands.project.SyncApis", return_value=mock_sync_apis):
cli_runner.invoke(project, ["list"])
assert get_client.call_args.kwargs["timeout"] is None

def test_a_read_timeout_is_reported_as_slow_not_as_backend_down(
self, cli_runner, mock_sync_apis, mock_api_client, temp_dir
):
error = ResponseHandlingException(httpx.ReadTimeout(""))
result, _, written = self.invoke_logs(cli_runner, mock_sync_apis, mock_api_client, temp_dir, side_effect=error)
assert result.exit_code == 1
assert "no data received for 300s" in result.output
assert "accepted the connection" in result.output
assert "Is the backend running?" not in result.output # the connection worked
assert written == [] # no partial file

def test_a_refused_connection_still_gets_the_backend_hint(
self, cli_runner, mock_sync_apis, mock_api_client, temp_dir
):
error = ResponseHandlingException(httpx.ConnectError(""))
result, _, _ = self.invoke_logs(cli_runner, mock_sync_apis, mock_api_client, temp_dir, side_effect=error)
assert result.exit_code == 1
assert "ConnectError" in result.output
assert "Is the backend running?" in result.output
assert "no data received" not in result.output

def test_only_a_read_timeout_is_reported_as_slow_archive(
self, cli_runner, mock_sync_apis, mock_api_client, temp_dir
):
"""Connect, write and pool timeouts do not say the backend accepted the connection and is busy."""
for exc in (httpx.ConnectTimeout(""), httpx.WriteTimeout(""), httpx.PoolTimeout("")):
error = ResponseHandlingException(exc)
result, _, _ = self.invoke_logs(cli_runner, mock_sync_apis, mock_api_client, temp_dir, side_effect=error)
assert result.exit_code == 1, type(exc).__name__
assert "no data received" not in result.output, type(exc).__name__
assert "accepted the connection" not in result.output, type(exc).__name__


@pytest.mark.unit
@pytest.mark.cli
class TestProjectLogsCommand:
Expand Down
29 changes: 25 additions & 4 deletions th_cli/commands/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@
from typing import Any

import click
from httpx import ReadTimeout, Timeout
from pydantic import ValidationError

from th_cli.api_lib_autogen.api_client import SyncApis
from th_cli.api_lib_autogen.exceptions import UnexpectedResponse
from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse
from th_cli.api_lib_autogen.models import (
PICS,
BodyImportprojectConfigApiV1ProjectsImportPost,
Expand Down Expand Up @@ -58,11 +59,18 @@ def project():
pass


# `project logs` asks the backend for an archive of every log row of every execution in the project. The backend
# builds the whole archive before it sends the first byte, so the wait grows with the project and httpx's default 5s
# read timeout is far too short (a project with 12 executions, 36 MB of logs, failed at 5.8s every time). A single
# execution's log gets 120s (TEST_RUN_EXECUTION_IO_TIMEOUT); a project is the sum of its executions.
PROJECT_LOGS_TIMEOUT = Timeout(300.0, connect=10.0) # 300s read/write, 10s connect


@contextmanager
def get_sync_apis(operation: str):
def get_sync_apis(operation: str, timeout: Timeout | None = None):
client = None
try:
client = get_client()
client = get_client(timeout=timeout)
yield SyncApis(client)
except CLIError:
raise
Expand Down Expand Up @@ -333,7 +341,7 @@ def applicable_tests(id: int, json_output: bool) -> None:
)
def logs(id: int, grouped: bool, output_file: str | None) -> None:
"""Download all logs for a project as a single zip archive"""
with get_sync_apis("logs") as sync_apis:
with get_sync_apis("logs", timeout=PROJECT_LOGS_TIMEOUT) as sync_apis:
_download_project_logs(sync_apis, id, grouped, output_file)


Expand Down Expand Up @@ -737,6 +745,19 @@ def _download_project_logs(sync_apis: SyncApis, id: int, grouped: bool, output_f
log_bytes: bytes = sync_apis.projects_api.download_project_logs_api_v1_projects__id__logs_get(
id=id, grouped=grouped
)
except ResponseHandlingException as e:
if isinstance(e.error, ReadTimeout):
# The connection was made, so "is the backend running?" would send the user the wrong way. httpx's read
# timeout runs between chunks of data, so this does not say whether the first byte ever arrived; building
# the archive of a large project is the likely cause, not an established fact. Connect, write and pool
# timeouts do not mean that, and keep the generic transport error below.
raise CLIError(
f"Timed out waiting for the logs of project {id}: no data received for "
f"{PROJECT_LOGS_TIMEOUT.read:.0f}s. "
"The backend accepted the connection; building the archive of a project with many or large "
"executions can take longer than that."
) from e
raise
except UnexpectedResponse as e:
if e.status_code == 404:
if isinstance(e.content, dict):
Expand Down
Loading