Skip to content

expected_status

expected_status

Mark HTTP statuses a route converts into a typed exception as expected.

Some routes treat a non-2xx status as a normal outcome: query_dataset_private turns a 404 into DatasetNotFoundError that its callers catch (Domo 404s the query endpoint until a dataset finishes indexing). The lower layers cannot know that, so each one logged the same 404 at ERROR (about five 2 KB blobs per poll).

expected_statuses declares the statuses once, on the route. Every layer beneath it (get_data, looper, the log_call decorators) then logs a matching status at DEBUG. Any other status, and any other exception, still logs at ERROR. The exception itself is untouched: it still raises.

expected_statuses

expected_statuses(
    *statuses: int | Iterable[int],
) -> Callable

Declare HTTP statuses a route expects, so they log at DEBUG instead of ERROR.

Use it when a route turns a non-2xx status into a typed exception that its callers catch and act on. The standard case is polling: Domo answers 404 on the query endpoint until a new dataset finishes indexing, so a caller waiting on indexing sees several 404s that are not failures.

What changes while the decorated route runs:

  • get_data and looper log a matching status at DEBUG.
  • log_call records for the route and everything under it that carry a matching status (from http_details or the raised exception's status) drop from ERROR to DEBUG.

What does not change:

  • The exception still raises, so callers still see the typed error.
  • Any other status, and any exception without a declared status, still logs at ERROR.

Declarations nest and accumulate: a route called from a decorated route inherits that route's statuses and adds its own. The declaration lasts only for the call (it lives in a ContextVar), so concurrent tasks do not leak it to each other.

Apply it as the OUTERMOST decorator, outside log_call, so the route's own log record is covered too::

@expected_statuses(404)
@gd.route_function
@log_call(level_name="route")
async def query_dataset_private(...): ...

Declare only a status the route converts into an exception its callers handle. A status the caller cannot recover from should stay at ERROR.

Parameters:

Name Type Description Default
*statuses int | Iterable[int]

HTTP status codes, given as ints or as iterables of ints.

()

Returns:

Type Description
Callable

A decorator for an async route function.

Source code in src/crew_dcs/utils/logging/expected_status.py
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def expected_statuses(*statuses: int | Iterable[int]) -> Callable:
    """Declare HTTP statuses a route expects, so they log at DEBUG instead of ERROR.

    Use it when a route turns a non-2xx status into a typed exception that its
    callers catch and act on. The standard case is polling: Domo answers 404 on
    the query endpoint until a new dataset finishes indexing, so a caller waiting
    on indexing sees several 404s that are not failures.

    What changes while the decorated route runs:

    - ``get_data`` and ``looper`` log a matching status at DEBUG.
    - ``log_call`` records for the route and everything under it that carry a
      matching status (from ``http_details`` or the raised exception's
      ``status``) drop from ERROR to DEBUG.

    What does not change:

    - The exception still raises, so callers still see the typed error.
    - Any other status, and any exception without a declared status, still logs
      at ERROR.

    Declarations nest and accumulate: a route called from a decorated route
    inherits that route's statuses and adds its own. The declaration lasts only
    for the call (it lives in a ``ContextVar``), so concurrent tasks do not leak
    it to each other.

    Apply it as the OUTERMOST decorator, outside ``log_call``, so the route's own
    log record is covered too::

        @expected_statuses(404)
        @gd.route_function
        @log_call(level_name="route")
        async def query_dataset_private(...): ...

    Declare only a status the route converts into an exception its callers
    handle. A status the caller cannot recover from should stay at ERROR.

    Args:
        *statuses: HTTP status codes, given as ints or as iterables of ints.

    Returns:
        A decorator for an async route function.
    """
    flat: set[int] = set()
    for item in statuses:
        if isinstance(item, int):
            flat.add(item)
        else:
            flat.update(int(i) for i in item)
    declared = frozenset(flat)

    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        async def wrapper(*args: Any, **kwargs: Any) -> Any:
            token = _expected.set(_expected.get() | declared)
            try:
                return await func(*args, **kwargs)
            finally:
                _expected.reset(token)

        return wrapper

    return decorator

is_expected_status

is_expected_status(status: Any) -> bool

True when status was declared expected by an enclosing route call.

Source code in src/crew_dcs/utils/logging/expected_status.py
28
29
30
31
32
33
def is_expected_status(status: Any) -> bool:
    """True when ``status`` was declared expected by an enclosing route call."""
    try:
        return int(status) in _expected.get()
    except (TypeError, ValueError):
        return False

status_of_log_context

status_of_log_context(
    context: dict[str, Any],
) -> int | None

HTTP status carried by a log_call record: http_details or the raised exception.

Source code in src/crew_dcs/utils/logging/expected_status.py
36
37
38
39
40
41
42
43
44
45
def status_of_log_context(context: dict[str, Any]) -> int | None:
    """HTTP status carried by a ``log_call`` record: ``http_details`` or the raised exception."""
    http_details = context.get("http_details")
    status = getattr(http_details, "status_code", None)
    if status is None:
        status = getattr(context.get("exc_info"), "status", None)
    try:
        return int(status) if status is not None else None
    except (TypeError, ValueError):
        return None