Module astrapy.exceptions

Expand source code
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import time
from dataclasses import dataclass

import httpx

from astrapy.exceptions.collection_exceptions import (
    CollectionDeleteManyException,
    CollectionInsertManyException,
    CollectionUpdateManyException,
    TooManyDocumentsToCountException,
)
from astrapy.exceptions.data_api_exceptions import (
    CursorException,
    DataAPIErrorDescriptor,
    DataAPIException,
    DataAPIHttpException,
    DataAPIResponseException,
    DataAPITimeoutException,
    UnexpectedDataAPIResponseException,
)
from astrapy.exceptions.devops_api_exceptions import (
    DevOpsAPIErrorDescriptor,
    DevOpsAPIException,
    DevOpsAPIHttpException,
    DevOpsAPIResponseException,
    DevOpsAPITimeoutException,
    UnexpectedDevOpsAPIResponseException,
)
from astrapy.exceptions.table_exceptions import (
    TableInsertManyException,
    TooManyRowsToCountException,
)
from astrapy.utils.api_options import FullTimeoutOptions


def _min_labeled_timeout(
    *timeouts: tuple[int | None, str | None],
) -> tuple[int, str | None]:
    _non_null: list[tuple[int, str | None]] = [
        to  # type: ignore[misc]
        for to in timeouts
        if to[0] is not None
    ]
    if _non_null:
        min_to, min_lb = min(_non_null, key=lambda p: p[0])
        # min_to is never None, this is for added robustness
        return (min_to or 0, min_lb)
    else:
        return (0, None)


def _select_singlereq_timeout_gm(
    *,
    timeout_options: FullTimeoutOptions,
    general_method_timeout_ms: int | None,
    request_timeout_ms: int | None = None,
    timeout_ms: int | None = None,
) -> tuple[int, str | None]:
    """
    Apply the logic for determining and labeling the timeout for
    (non-admin) single-request methods.

    If no int args are passed, pick (and correctly label) the least of the
    involved parameters.
    If any of the int args are passed, pick (and correctly labeled) the least
    of them, disregarding the options altogether.
    """
    if all(
        iarg is None
        for iarg in (general_method_timeout_ms, request_timeout_ms, timeout_ms)
    ):
        ao_r = timeout_options.request_timeout_ms
        ao_gm = timeout_options.general_method_timeout_ms
        if ao_r < ao_gm:
            return (ao_r, "request_timeout_ms")
        else:
            return (ao_gm, "general_method_timeout_ms")
    else:
        return _min_labeled_timeout(
            (general_method_timeout_ms, "general_method_timeout_ms"),
            (request_timeout_ms, "request_timeout_ms"),
            (timeout_ms, "timeout_ms"),
        )


def _select_singlereq_timeout_ca(
    *,
    timeout_options: FullTimeoutOptions,
    collection_admin_timeout_ms: int | None,
    request_timeout_ms: int | None = None,
    timeout_ms: int | None = None,
) -> tuple[int, str | None]:
    """
    Apply the logic for determining and labeling the timeout for
    (collection-admin) single-request methods.

    If no int args are passed, pick (and correctly label) the least of the
    involved parameters.
    If any of the int args are passed, pick (and correctly labeled) the least
    of them, disregarding the options altogether.
    """
    if all(
        iarg is None
        for iarg in (collection_admin_timeout_ms, request_timeout_ms, timeout_ms)
    ):
        ao_r = timeout_options.request_timeout_ms
        ao_gm = timeout_options.collection_admin_timeout_ms
        if ao_r < ao_gm:
            return (ao_r, "request_timeout_ms")
        else:
            return (ao_gm, "collection_admin_timeout_ms")
    else:
        return _min_labeled_timeout(
            (collection_admin_timeout_ms, "collection_admin_timeout_ms"),
            (request_timeout_ms, "request_timeout_ms"),
            (timeout_ms, "timeout_ms"),
        )


def _select_singlereq_timeout_ta(
    *,
    timeout_options: FullTimeoutOptions,
    table_admin_timeout_ms: int | None,
    request_timeout_ms: int | None = None,
    timeout_ms: int | None = None,
) -> tuple[int, str | None]:
    """
    Apply the logic for determining and labeling the timeout for
    (table-admin) single-request methods.

    If no int args are passed, pick (and correctly label) the least of the
    involved parameters.
    If any of the int args are passed, pick (and correctly labeled) the least
    of them, disregarding the options altogether.
    """
    if all(
        iarg is None
        for iarg in (table_admin_timeout_ms, request_timeout_ms, timeout_ms)
    ):
        ao_r = timeout_options.request_timeout_ms
        ao_gm = timeout_options.table_admin_timeout_ms
        if ao_r < ao_gm:
            return (ao_r, "request_timeout_ms")
        else:
            return (ao_gm, "table_admin_timeout_ms")
    else:
        return _min_labeled_timeout(
            (table_admin_timeout_ms, "table_admin_timeout_ms"),
            (request_timeout_ms, "request_timeout_ms"),
            (timeout_ms, "timeout_ms"),
        )


def _select_singlereq_timeout_da(
    *,
    timeout_options: FullTimeoutOptions,
    database_admin_timeout_ms: int | None,
    request_timeout_ms: int | None = None,
    timeout_ms: int | None = None,
) -> tuple[int, str | None]:
    """
    Apply the logic for determining and labeling the timeout for
    (database-admin) single-request methods.

    If no int args are passed, pick (and correctly label) the least of the
    involved parameters.
    If any of the int args are passed, pick (and correctly labeled) the least
    of them, disregarding the options altogether.
    """
    if all(
        iarg is None
        for iarg in (database_admin_timeout_ms, request_timeout_ms, timeout_ms)
    ):
        ao_r = timeout_options.request_timeout_ms
        ao_gm = timeout_options.database_admin_timeout_ms
        if ao_r < ao_gm:
            return (ao_r, "request_timeout_ms")
        else:
            return (ao_gm, "database_admin_timeout_ms")
    else:
        return _min_labeled_timeout(
            (database_admin_timeout_ms, "database_admin_timeout_ms"),
            (request_timeout_ms, "request_timeout_ms"),
            (timeout_ms, "timeout_ms"),
        )


def _select_singlereq_timeout_ka(
    *,
    timeout_options: FullTimeoutOptions,
    keyspace_admin_timeout_ms: int | None,
    request_timeout_ms: int | None = None,
    timeout_ms: int | None = None,
) -> tuple[int, str | None]:
    """
    Apply the logic for determining and labeling the timeout for
    (keyspace-admin) single-request methods.

    If no int args are passed, pick (and correctly label) the least of the
    involved parameters.
    If any of the int args are passed, pick (and correctly labeled) the least
    of them, disregarding the options altogether.
    """
    if all(
        iarg is None
        for iarg in (keyspace_admin_timeout_ms, request_timeout_ms, timeout_ms)
    ):
        ao_r = timeout_options.request_timeout_ms
        ao_gm = timeout_options.keyspace_admin_timeout_ms
        if ao_r < ao_gm:
            return (ao_r, "request_timeout_ms")
        else:
            return (ao_gm, "keyspace_admin_timeout_ms")
    else:
        return _min_labeled_timeout(
            (keyspace_admin_timeout_ms, "keyspace_admin_timeout_ms"),
            (request_timeout_ms, "request_timeout_ms"),
            (timeout_ms, "timeout_ms"),
        )


def _first_valid_timeout(
    *items: tuple[int | None, str | None],
) -> tuple[int, str | None]:
    # items are: (timeout ms, label)
    not_nulls = [itm for itm in items if itm[0] is not None]
    if not_nulls:
        return not_nulls[0]  # type: ignore[return-value]
    else:
        # If no non-nulls provided, return zero
        # (a timeout of zero will stand for 'no timeout' later on to the request).
        return 0, None


class InvalidEnvironmentException(Exception):
    """
    An operation was attempted, that is not available on the specified
    environment. For example, trying to get an AstraDBAdmin from a client
    set to a non-Astra environment.
    """

    pass


def to_dataapi_timeout_exception(
    httpx_timeout: httpx.TimeoutException,
    timeout_context: _TimeoutContext,
) -> DataAPITimeoutException:
    text: str
    text_0 = str(httpx_timeout) or "timed out"
    timeout_ms = timeout_context.nominal_ms or timeout_context.request_ms
    timeout_label = timeout_context.label
    if timeout_ms:
        if timeout_label:
            text = f"{text_0} (timeout honoured: {timeout_label} = {timeout_ms} ms)"
        else:
            text = f"{text_0} (timeout honoured: {timeout_ms} ms)"
    else:
        text = text_0
    if isinstance(httpx_timeout, httpx.ConnectTimeout):
        timeout_type = "connect"
    elif isinstance(httpx_timeout, httpx.ReadTimeout):
        timeout_type = "read"
    elif isinstance(httpx_timeout, httpx.WriteTimeout):
        timeout_type = "write"
    elif isinstance(httpx_timeout, httpx.PoolTimeout):
        timeout_type = "pool"
    else:
        timeout_type = "generic"
    if httpx_timeout.request:
        endpoint = str(httpx_timeout.request.url)
        if isinstance(httpx_timeout.request.content, bytes):
            raw_payload = httpx_timeout.request.content.decode()
        else:
            raw_payload = None
    else:
        endpoint = None
        raw_payload = None
    return DataAPITimeoutException(
        text=text,
        timeout_type=timeout_type,
        endpoint=endpoint,
        raw_payload=raw_payload,
    )


def to_devopsapi_timeout_exception(
    httpx_timeout: httpx.TimeoutException,
    timeout_context: _TimeoutContext,
) -> DevOpsAPITimeoutException:
    text: str
    text_0 = str(httpx_timeout) or "timed out"
    timeout_ms = timeout_context.nominal_ms or timeout_context.request_ms
    timeout_label = timeout_context.label
    if timeout_ms:
        if timeout_label:
            text = f"{text_0} (timeout honoured: {timeout_label} = {timeout_ms} ms)"
        else:
            text = f"{text_0} (timeout honoured: {timeout_ms} ms)"
    if isinstance(httpx_timeout, httpx.ConnectTimeout):
        timeout_type = "connect"
    elif isinstance(httpx_timeout, httpx.ReadTimeout):
        timeout_type = "read"
    elif isinstance(httpx_timeout, httpx.WriteTimeout):
        timeout_type = "write"
    elif isinstance(httpx_timeout, httpx.PoolTimeout):
        timeout_type = "pool"
    else:
        timeout_type = "generic"
    if httpx_timeout.request:
        endpoint = str(httpx_timeout.request.url)
        if isinstance(httpx_timeout.request.content, bytes):
            raw_payload = httpx_timeout.request.content.decode()
        else:
            raw_payload = None
    else:
        endpoint = None
        raw_payload = None
    return DevOpsAPITimeoutException(
        text=text,
        timeout_type=timeout_type,
        endpoint=endpoint,
        raw_payload=raw_payload,
    )


@dataclass
class _TimeoutContext:
    """
    This class encodes standardized "enriched information" attached to a timeout
    value to obey. This makes it possible, in case the timeout is raised, to present
    the user with a better error message detailing the name of the setting responsible
    for the timeout and the "nominal" value (which may not always coincide with the
    actual elapsed number of milliseconds because of cumulative timeouts spanning
    several HTTP requests).

    Args:
        nominal_ms: the original timeout in milliseconds that was ultimately set by
            the user.
        request_ms: the actual number of millisecond a given HTTP request was allowed
            to last. This may be smaller than `nominal_ms` because of timeouts imposed
            on a succession of requests.
        label: a string, providing the name of the timeout setting as known by the user.
    """

    nominal_ms: int | None
    request_ms: int | None
    label: str | None

    def __init__(
        self,
        *,
        request_ms: int | None,
        nominal_ms: int | None = None,
        label: str | None = None,
    ) -> None:
        self.nominal_ms = nominal_ms
        self.request_ms = request_ms
        self.label = label

    def __bool__(self) -> bool:
        return self.nominal_ms is not None or self.request_ms is not None


class MultiCallTimeoutManager:
    """
    A helper class to keep track of timing and timeouts
    in a multi-call method context.

    Args:
        overall_timeout_ms: an optional max duration to track (milliseconds)
        dev_ops_api: whether this manager is used in a DevOps context (a fact
            which affects which timeout exception is raised if needed).

    Attributes:
        overall_timeout_ms: an optional max duration to track (milliseconds)
        started_ms: timestamp of the instance construction (milliseconds)
        deadline_ms: optional deadline in milliseconds (computed by the class).
        timeout_label: a string label identifying the `overall_timeout_ms` in a way
            that is understood by the user who can set timeouts.
    """

    overall_timeout_ms: int | None
    started_ms: int = -1
    deadline_ms: int | None
    timeout_label: str | None

    def __init__(
        self,
        overall_timeout_ms: int | None,
        dev_ops_api: bool = False,
        timeout_label: str | None = None,
    ) -> None:
        self.started_ms = int(time.time() * 1000)
        self.timeout_label = timeout_label
        # zero timeouts provided internally are mapped to None for deadline mgmt:
        self.overall_timeout_ms = overall_timeout_ms or None
        self.dev_ops_api = dev_ops_api
        if self.overall_timeout_ms is not None:
            self.deadline_ms = self.started_ms + self.overall_timeout_ms
        else:
            self.deadline_ms = None

    def remaining_timeout(
        self, cap_time_ms: int | None = None, cap_timeout_label: str | None = None
    ) -> _TimeoutContext:
        """
        Ensure the deadline, if any, is not yet in the past.
        If it is, raise an appropriate timeout error.
        If not, return either None (if no timeout) or the remaining milliseconds.
        For use within the multi-call method.

        Args:
            cap_time_ms: an additional timeout constraint to cap the result of
                this method. If the remaining timeout from this manager exceeds
                the provided cap, the cap is returned.
            cap_timeout_label: the label identifying the "cap timeout" if one is
                set. This is for the purpose of tracing the "lineage" of timeout
                settings in a way that is transparent to the user.

        Returns:
            A _TimeoutContext appropriately detailing the residual time an overall
            operation is allowed to last. Alternatively, the method may not return
            and raise a DataAPITimeoutException/DevOpsAPITimeoutException directly.
        """

        # a zero 'cap' must be treated as None:
        _cap_time_ms = cap_time_ms or None
        now_ms = int(time.time() * 1000)
        if self.deadline_ms is not None:
            if now_ms < self.deadline_ms:
                remaining = self.deadline_ms - now_ms
                if _cap_time_ms is None:
                    return _TimeoutContext(
                        nominal_ms=self.overall_timeout_ms,
                        request_ms=remaining,
                        label=self.timeout_label,
                    )
                else:
                    if remaining > _cap_time_ms:
                        return _TimeoutContext(
                            nominal_ms=_cap_time_ms,
                            request_ms=_cap_time_ms,
                            label=cap_timeout_label,
                        )
                    else:
                        return _TimeoutContext(
                            nominal_ms=self.overall_timeout_ms,
                            request_ms=remaining,
                            label=self.timeout_label,
                        )
            else:
                err_msg: str
                if self.timeout_label:
                    err_msg = (
                        f"Operation timed out (timeout honoured: {self.timeout_label} "
                        f"= {self.overall_timeout_ms} ms)."
                    )
                else:
                    err_msg = f"Operation timed out (timeout honoured: {self.overall_timeout_ms} ms)."
                if not self.dev_ops_api:
                    raise DataAPITimeoutException(
                        text=err_msg,
                        timeout_type="generic",
                        endpoint=None,
                        raw_payload=None,
                    )
                else:
                    raise DevOpsAPITimeoutException(
                        text=err_msg,
                        timeout_type="generic",
                        endpoint=None,
                        raw_payload=None,
                    )
        else:
            if _cap_time_ms is None:
                return _TimeoutContext(
                    nominal_ms=self.overall_timeout_ms,
                    request_ms=None,
                    label=self.timeout_label,
                )
            else:
                return _TimeoutContext(
                    nominal_ms=_cap_time_ms,
                    request_ms=_cap_time_ms,
                    label=cap_timeout_label,
                )


__all__ = [
    "DevOpsAPIException",
    "DevOpsAPIHttpException",
    "DevOpsAPITimeoutException",
    "DevOpsAPIErrorDescriptor",
    "UnexpectedDevOpsAPIResponseException",
    "DevOpsAPIResponseException",
    "DataAPIErrorDescriptor",
    "DataAPIDetailedErrorDescriptor",
    "DataAPIException",
    "DataAPIHttpException",
    "DataAPITimeoutException",
    "CursorException",
    "TooManyDocumentsToCountException",
    "UnexpectedDataAPIResponseException",
    "DataAPIResponseException",
    "CollectionInsertManyException",
    "CollectionDeleteManyException",
    "CollectionUpdateManyException",
    "MultiCallTimeoutManager",
    "TooManyRowsToCountException",
    "TableInsertManyException",
]

__pdoc__ = {
    "to_dataapi_timeout_exception": False,
    "MultiCallTimeoutManager": False,
}

Sub-modules

astrapy.exceptions.collection_exceptions
astrapy.exceptions.data_api_exceptions
astrapy.exceptions.devops_api_exceptions
astrapy.exceptions.table_exceptions

Classes

class CollectionDeleteManyException (partial_result: CollectionDeleteResult, cause: Exception)

An exception occurring during a delete_many (an operation that can span several requests). As such, besides information on the root-cause error, there may be a partial result about the part that succeeded.

Attributes

partial_result
a CollectionDeleteResult object, just like the one that would be the return value of the operation, had it succeeded completely.
cause
a root exception that happened during the delete_many, causing the method call to stop and raise this error.
Expand source code
@dataclass
class CollectionDeleteManyException(DataAPIException):
    """
    An exception occurring during a delete_many (an operation that can span
    several requests). As such, besides information on the root-cause error,
    there may be a partial result about the part that succeeded.

    Attributes:
        partial_result: a CollectionDeleteResult object, just like the one that would
            be the return value of the operation, had it succeeded completely.
        cause: a root exception that happened during the delete_many, causing
            the method call to stop and raise this error.
    """

    partial_result: CollectionDeleteResult
    cause: Exception

    def __str__(self) -> str:
        return f"{self.__class__.__name__}({self.cause.__str__()})"

Ancestors

Class variables

var cause : Exception
var partial_result : CollectionDeleteResult
class CollectionInsertManyException (inserted_ids: list[Any], exceptions: Sequence[Exception])

An exception occurring within an insert_many (an operation that can span several requests). As such, it represents both the root error(s) that happened and information on the portion of the documents that were successfully inserted.

The behaviour of insert_many (concurrency and the ordered setting) make it possible that more than one "root errors" are collected.

Attributes

inserted_ids
a list of the document IDs that have been successfully inserted.
exceptions
a list of the root exceptions leading to this error. The list, under normal circumstances, is not empty.
Expand source code
@dataclass
class CollectionInsertManyException(DataAPIException):
    """
    An exception occurring within an insert_many (an operation that can span
    several requests). As such, it represents both the root error(s) that happened
    and information on the portion of the documents that were successfully inserted.

    The behaviour of insert_many (concurrency and the `ordered` setting) make it
    possible that more than one "root errors" are collected.

    Attributes:
        inserted_ids: a list of the document IDs that have been successfully inserted.
        exceptions: a list of the root exceptions leading to this error. The list,
            under normal circumstances, is not empty.
    """

    inserted_ids: list[Any]
    exceptions: Sequence[Exception]

    def __str__(self) -> str:
        num_ids = len(self.inserted_ids)
        if self.exceptions:
            exc_desc: str
            excs_strs = [exc.__str__() for exc in self.exceptions[:8]]
            if len(self.exceptions) > 8:
                exc_desc = ", ".join(excs_strs) + " ... (more exceptions)"
            else:
                exc_desc = ", ".join(excs_strs)
            return (
                f"{self.__class__.__name__}({exc_desc} "
                f"[with {num_ids} inserted ids])"
            )
        else:
            return f"{self.__class__.__name__}()"

Ancestors

Class variables

var exceptions : Sequence[Exception]
var inserted_ids : list[typing.Any]
class CollectionUpdateManyException (partial_result: CollectionUpdateResult, cause: Exception)

An exception occurring during an update_many (an operation that can span several requests). As such, besides information on the root-cause error, there may be a partial result about the part that succeeded.

Attributes

partial_result
a CollectionUpdateResult object, just like the one that would be the return value of the operation, had it succeeded completely.
cause
a root exception that happened during the update_many, causing the method call to stop and raise this error.
Expand source code
@dataclass
class CollectionUpdateManyException(DataAPIException):
    """
    An exception occurring during an update_many (an operation that can span
    several requests). As such, besides information on the root-cause error,
    there may be a partial result about the part that succeeded.

    Attributes:
        partial_result: a CollectionUpdateResult object, just like the one that would
            be the return value of the operation, had it succeeded completely.
        cause: a root exception that happened during the update_many, causing
            the method call to stop and raise this error.
    """

    partial_result: CollectionUpdateResult
    cause: Exception

    def __str__(self) -> str:
        return f"{self.__class__.__name__}({self.cause.__str__()})"

Ancestors

Class variables

var cause : Exception
var partial_result : CollectionUpdateResult
class CursorException (text: str, *, cursor_state: str)

The cursor operation cannot be invoked if a cursor is not in its pristine state (i.e. is already being consumed or is exhausted altogether).

Attributes

text
a text message about the exception.
cursor_state
a string description of the current state of the cursor. See the documentation for Cursor.
Expand source code
@dataclass
class CursorException(DataAPIException):
    """
    The cursor operation cannot be invoked if a cursor is not in its pristine
    state (i.e. is already being consumed or is exhausted altogether).

    Attributes:
        text: a text message about the exception.
        cursor_state: a string description of the current state
            of the cursor. See the documentation for Cursor.
    """

    text: str
    cursor_state: str

    def __init__(
        self,
        text: str,
        *,
        cursor_state: str,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.cursor_state = cursor_state

Ancestors

Class variables

var cursor_state : str
var text : str
class DataAPIErrorDescriptor (error_dict: dict[str, str] | str)

An object representing a single error, or warning, as returned from the Data API, typically with an error code, a text message and other properties.

This object is used to describe errors/warnings received from the Data API, in the form of HTTP-200 ("success") responses containing errors (and possibly warnings). Depending on the API command semantics, responses may express partial successes with some errors (for instance, an insertMany command inserting most of the documents/rows, but failing on a couple of incompatible inputs).

Attributes

error_code
a string code as found in the API "error" item.
message
the text found in the API "error" item.
title
the text found in the API "title" item.
family
the text found in the API "family" item.
scope
the text found in the API "scope" item.
id
the text found in the API "id" item.
attributes
a dict with any further key-value pairs returned by the API.
Expand source code
@dataclass
class DataAPIErrorDescriptor:
    """
    An object representing a single error, or warning, as returned from the Data API,
    typically with an error code, a text message and other properties.

    This object is used to describe errors/warnings received from the Data API,
    in the form of HTTP-200 ("success") responses containing errors
    (and possibly warnings).
    Depending on the API command semantics, responses may express partial successes
    with some errors (for instance, an insertMany command inserting most of the
    documents/rows, but failing on a couple of incompatible inputs).

    Attributes:
        error_code: a string code as found in the API "error" item.
        message: the text found in the API "error" item.
        title:  the text found in the API "title" item.
        family:  the text found in the API "family" item.
        scope:  the text found in the API "scope" item.
        id:  the text found in the API "id" item.
        attributes: a dict with any further key-value pairs returned by the API.
    """

    title: str | None
    error_code: str | None
    message: str | None
    family: str | None
    scope: str | None
    id: str | None
    attributes: dict[str, Any]

    _known_dict_fields = {
        "title",
        "errorCode",
        "message",
        "family",
        "scope",
        "id",
    }

    def __init__(self, error_dict: dict[str, str] | str) -> None:
        if isinstance(error_dict, str):
            self.message = error_dict
            self.title = None
            self.error_code = None
            self.family = None
            self.scope = None
            self.id = None
            self.attributes = {}
        else:
            self.title = error_dict.get("title")
            self.error_code = error_dict.get("errorCode")
            self.message = error_dict.get("message")
            self.family = error_dict.get("family")
            self.scope = error_dict.get("scope")
            self.id = error_dict.get("id")
            self.attributes = {
                k: v for k, v in error_dict.items() if k not in self._known_dict_fields
            }

    def __repr__(self) -> str:
        pieces = [
            f"{self.title.__repr__()}" if self.title else None,
            f"error_code={self.error_code.__repr__()}" if self.error_code else None,
            f"message={self.message.__repr__()}" if self.message else None,
            f"family={self.family.__repr__()}" if self.family else None,
            f"scope={self.scope.__repr__()}" if self.scope else None,
            f"id={self.id.__repr__()}" if self.id else None,
            f"attributes={self.attributes.__repr__()}" if self.attributes else None,
        ]
        return f"{self.__class__.__name__}({', '.join(pc for pc in pieces if pc)})"

    def __str__(self) -> str:
        return self.summary()

    def summary(self) -> str:
        """
        Determine a string succinct description of this error descriptor.

        The precise format of this summary is determined by which fields are set.
        """
        non_code_part: str | None
        if self.title:
            if self.message:
                non_code_part = f"{self.title}: {self.message}"
            else:
                non_code_part = f"{self.title}"
        else:
            if self.message:
                non_code_part = f"{self.message}"
            else:
                non_code_part = None
        if self.error_code:
            if non_code_part:
                return f"{non_code_part} ({self.error_code})"
            else:
                return f"{self.error_code}"
        else:
            if non_code_part:
                return non_code_part
            else:
                return ""

Class variables

var attributes : dict[str, typing.Any]
var error_code : str | None
var family : str | None
var id : str | None
var message : str | None
var scope : str | None
var title : str | None

Methods

def summary(self) ‑> str

Determine a string succinct description of this error descriptor.

The precise format of this summary is determined by which fields are set.

Expand source code
def summary(self) -> str:
    """
    Determine a string succinct description of this error descriptor.

    The precise format of this summary is determined by which fields are set.
    """
    non_code_part: str | None
    if self.title:
        if self.message:
            non_code_part = f"{self.title}: {self.message}"
        else:
            non_code_part = f"{self.title}"
    else:
        if self.message:
            non_code_part = f"{self.message}"
        else:
            non_code_part = None
    if self.error_code:
        if non_code_part:
            return f"{non_code_part} ({self.error_code})"
        else:
            return f"{self.error_code}"
    else:
        if non_code_part:
            return non_code_part
        else:
            return ""
class DataAPIDetailedErrorDescriptor (error_dict: dict[str, str] | str)

An object representing a single error, or warning, as returned from the Data API, typically with an error code, a text message and other properties.

This object is used to describe errors/warnings received from the Data API, in the form of HTTP-200 ("success") responses containing errors (and possibly warnings). Depending on the API command semantics, responses may express partial successes with some errors (for instance, an insertMany command inserting most of the documents/rows, but failing on a couple of incompatible inputs).

Attributes

error_code
a string code as found in the API "error" item.
message
the text found in the API "error" item.
title
the text found in the API "title" item.
family
the text found in the API "family" item.
scope
the text found in the API "scope" item.
id
the text found in the API "id" item.
attributes
a dict with any further key-value pairs returned by the API.
Expand source code
@dataclass
class DataAPIErrorDescriptor:
    """
    An object representing a single error, or warning, as returned from the Data API,
    typically with an error code, a text message and other properties.

    This object is used to describe errors/warnings received from the Data API,
    in the form of HTTP-200 ("success") responses containing errors
    (and possibly warnings).
    Depending on the API command semantics, responses may express partial successes
    with some errors (for instance, an insertMany command inserting most of the
    documents/rows, but failing on a couple of incompatible inputs).

    Attributes:
        error_code: a string code as found in the API "error" item.
        message: the text found in the API "error" item.
        title:  the text found in the API "title" item.
        family:  the text found in the API "family" item.
        scope:  the text found in the API "scope" item.
        id:  the text found in the API "id" item.
        attributes: a dict with any further key-value pairs returned by the API.
    """

    title: str | None
    error_code: str | None
    message: str | None
    family: str | None
    scope: str | None
    id: str | None
    attributes: dict[str, Any]

    _known_dict_fields = {
        "title",
        "errorCode",
        "message",
        "family",
        "scope",
        "id",
    }

    def __init__(self, error_dict: dict[str, str] | str) -> None:
        if isinstance(error_dict, str):
            self.message = error_dict
            self.title = None
            self.error_code = None
            self.family = None
            self.scope = None
            self.id = None
            self.attributes = {}
        else:
            self.title = error_dict.get("title")
            self.error_code = error_dict.get("errorCode")
            self.message = error_dict.get("message")
            self.family = error_dict.get("family")
            self.scope = error_dict.get("scope")
            self.id = error_dict.get("id")
            self.attributes = {
                k: v for k, v in error_dict.items() if k not in self._known_dict_fields
            }

    def __repr__(self) -> str:
        pieces = [
            f"{self.title.__repr__()}" if self.title else None,
            f"error_code={self.error_code.__repr__()}" if self.error_code else None,
            f"message={self.message.__repr__()}" if self.message else None,
            f"family={self.family.__repr__()}" if self.family else None,
            f"scope={self.scope.__repr__()}" if self.scope else None,
            f"id={self.id.__repr__()}" if self.id else None,
            f"attributes={self.attributes.__repr__()}" if self.attributes else None,
        ]
        return f"{self.__class__.__name__}({', '.join(pc for pc in pieces if pc)})"

    def __str__(self) -> str:
        return self.summary()

    def summary(self) -> str:
        """
        Determine a string succinct description of this error descriptor.

        The precise format of this summary is determined by which fields are set.
        """
        non_code_part: str | None
        if self.title:
            if self.message:
                non_code_part = f"{self.title}: {self.message}"
            else:
                non_code_part = f"{self.title}"
        else:
            if self.message:
                non_code_part = f"{self.message}"
            else:
                non_code_part = None
        if self.error_code:
            if non_code_part:
                return f"{non_code_part} ({self.error_code})"
            else:
                return f"{self.error_code}"
        else:
            if non_code_part:
                return non_code_part
            else:
                return ""

Class variables

var attributes : dict[str, typing.Any]
var error_code : str | None
var family : str | None
var id : str | None
var message : str | None
var scope : str | None
var title : str | None

Methods

def summary(self) ‑> str

Determine a string succinct description of this error descriptor.

The precise format of this summary is determined by which fields are set.

Expand source code
def summary(self) -> str:
    """
    Determine a string succinct description of this error descriptor.

    The precise format of this summary is determined by which fields are set.
    """
    non_code_part: str | None
    if self.title:
        if self.message:
            non_code_part = f"{self.title}: {self.message}"
        else:
            non_code_part = f"{self.title}"
    else:
        if self.message:
            non_code_part = f"{self.message}"
        else:
            non_code_part = None
    if self.error_code:
        if non_code_part:
            return f"{non_code_part} ({self.error_code})"
        else:
            return f"{self.error_code}"
    else:
        if non_code_part:
            return non_code_part
        else:
            return ""
class DataAPIException (*args, **kwargs)

Any exception occurred while issuing requests to the Data API and specific to it, such as: - a collection is found not to exist when gettings its metadata, - the API return a response with an error, but not, for instance, - a network error while sending an HTTP request to the API.

Expand source code
class DataAPIException(Exception):
    """
    Any exception occurred while issuing requests to the Data API
    and specific to it, such as:
      - a collection is found not to exist when gettings its metadata,
      - the API return a response with an error,
    but not, for instance,
      - a network error while sending an HTTP request to the API.
    """

    pass

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

class DataAPIHttpException (text: str | None, *, httpx_error: httpx.HTTPStatusError, error_descriptors: list[DataAPIErrorDescriptor])

A request to the Data API resulted in an HTTP 4xx or 5xx response.

In most cases this comes with additional information: the purpose of this class is to present such information in a structured way, akin to what happens for the DataAPIResponseException, while still raising (a subclass of) httpx.HTTPStatusError.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found in the response.
Expand source code
@dataclass
class DataAPIHttpException(DataAPIException, httpx.HTTPStatusError):
    """
    A request to the Data API resulted in an HTTP 4xx or 5xx response.

    In most cases this comes with additional information: the purpose
    of this class is to present such information in a structured way,
    akin to what happens for the DataAPIResponseException, while
    still raising (a subclass of) `httpx.HTTPStatusError`.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found in the response.
    """

    text: str | None
    error_descriptors: list[DataAPIErrorDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        httpx_error: httpx.HTTPStatusError,
        error_descriptors: list[DataAPIErrorDescriptor],
    ) -> None:
        DataAPIException.__init__(self, text)
        httpx.HTTPStatusError.__init__(
            self,
            message=str(httpx_error),
            request=httpx_error.request,
            response=httpx_error.response,
        )
        self.text = text
        self.httpx_error = httpx_error
        self.error_descriptors = error_descriptors

    def __str__(self) -> str:
        return self.text or str(self.httpx_error)

    @classmethod
    def from_httpx_error(
        cls,
        httpx_error: httpx.HTTPStatusError,
        **kwargs: Any,
    ) -> DataAPIHttpException:
        """Parse a httpx status error into this exception."""

        raw_response: dict[str, Any]
        # the attempt to extract a response structure cannot afford failure.
        try:
            raw_response = httpx_error.response.json()
        except Exception:
            raw_response = {}
        error_descriptors = [
            DataAPIErrorDescriptor(error_dict)
            for error_dict in raw_response.get("errors") or []
        ]
        if error_descriptors:
            text = f"{error_descriptors[0].message}. {str(httpx_error)}"
        else:
            text = str(httpx_error)

        return cls(
            text=text,
            httpx_error=httpx_error,
            error_descriptors=error_descriptors,
            **kwargs,
        )

Ancestors

  • DataAPIException
  • httpx.HTTPStatusError
  • httpx.HTTPError
  • builtins.Exception
  • builtins.BaseException

Class variables

var error_descriptors : list[DataAPIErrorDescriptor]
var text : str | None

Static methods

def from_httpx_error(httpx_error: httpx.HTTPStatusError, **kwargs: Any) ‑> DataAPIHttpException

Parse a httpx status error into this exception.

Expand source code
@classmethod
def from_httpx_error(
    cls,
    httpx_error: httpx.HTTPStatusError,
    **kwargs: Any,
) -> DataAPIHttpException:
    """Parse a httpx status error into this exception."""

    raw_response: dict[str, Any]
    # the attempt to extract a response structure cannot afford failure.
    try:
        raw_response = httpx_error.response.json()
    except Exception:
        raw_response = {}
    error_descriptors = [
        DataAPIErrorDescriptor(error_dict)
        for error_dict in raw_response.get("errors") or []
    ]
    if error_descriptors:
        text = f"{error_descriptors[0].message}. {str(httpx_error)}"
    else:
        text = str(httpx_error)

    return cls(
        text=text,
        httpx_error=httpx_error,
        error_descriptors=error_descriptors,
        **kwargs,
    )
class DataAPIResponseException (text: str | None, *, command: dict[str, Any] | None, raw_response: dict[str, Any], error_descriptors: list[DataAPIErrorDescriptor], warning_descriptors: list[DataAPIWarningDescriptor])

The Data API returned an HTTP 200 ("success") response, which however reports API-specific error(s), possibly alongside partial successes.

Attributes

text
a text message about the exception.
command
the payload to the API that led to the response.
raw_response
the full response from the API.
error_descriptors
a list of DataAPIErrorDescriptor, one for each item in the API response's "errors" field.
warning_descriptors
a list of DataAPIWarningDescriptor, one for each item in the API response's "warnings" field (if there are any).
Expand source code
@dataclass
class DataAPIResponseException(DataAPIException):
    """
    The Data API returned an HTTP 200 ("success") response, which however
    reports API-specific error(s), possibly alongside partial successes.

    Attributes:
        text: a text message about the exception.
        command: the payload to the API that led to the response.
        raw_response: the full response from the API.
        error_descriptors: a list of DataAPIErrorDescriptor, one for each
            item in the API response's "errors" field.
        warning_descriptors: a list of DataAPIWarningDescriptor, one for each
            item in the API response's "warnings" field (if there are any).
    """

    text: str | None
    command: dict[str, Any] | None
    raw_response: dict[str, Any]
    error_descriptors: list[DataAPIErrorDescriptor]
    warning_descriptors: list[DataAPIWarningDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        command: dict[str, Any] | None,
        raw_response: dict[str, Any],
        error_descriptors: list[DataAPIErrorDescriptor],
        warning_descriptors: list[DataAPIWarningDescriptor],
    ) -> None:
        super().__init__(text)
        self.text = text
        self.command = command
        self.raw_response = raw_response
        self.error_descriptors = error_descriptors
        self.warning_descriptors = warning_descriptors

    @staticmethod
    def from_response(
        *,
        command: dict[str, Any] | None,
        raw_response: dict[str, Any],
        **kwargs: Any,
    ) -> DataAPIResponseException:
        """Parse a raw response from the API into this exception."""

        error_descriptors = [
            DataAPIErrorDescriptor(error_dict)
            for error_dict in raw_response.get("errors") or []
        ]
        warning_descriptors = [
            DataAPIWarningDescriptor(error_dict)
            for error_dict in raw_response.get("warnings") or []
        ]

        if error_descriptors:
            summaries = [e_d.summary() for e_d in error_descriptors]
            if len(summaries) == 1:
                text = summaries[0]
            else:
                _j_summaries = "; ".join(
                    f"[{summ_i + 1}] {summ_s}"
                    for summ_i, summ_s in enumerate(summaries)
                )
                text = f"[{len(summaries)} errors collected] {_j_summaries}"
        else:
            text = ""

        return DataAPIResponseException(
            text,
            command=command,
            raw_response=raw_response,
            error_descriptors=error_descriptors,
            warning_descriptors=warning_descriptors,
            **kwargs,
        )

Ancestors

Class variables

var command : dict[str, typing.Any] | None
var error_descriptors : list[DataAPIErrorDescriptor]
var raw_response : dict[str, typing.Any]
var text : str | None
var warning_descriptors : list[DataAPIErrorDescriptor]

Static methods

def from_response(*, command: dict[str, Any] | None, raw_response: dict[str, Any], **kwargs: Any) ‑> DataAPIResponseException

Parse a raw response from the API into this exception.

Expand source code
@staticmethod
def from_response(
    *,
    command: dict[str, Any] | None,
    raw_response: dict[str, Any],
    **kwargs: Any,
) -> DataAPIResponseException:
    """Parse a raw response from the API into this exception."""

    error_descriptors = [
        DataAPIErrorDescriptor(error_dict)
        for error_dict in raw_response.get("errors") or []
    ]
    warning_descriptors = [
        DataAPIWarningDescriptor(error_dict)
        for error_dict in raw_response.get("warnings") or []
    ]

    if error_descriptors:
        summaries = [e_d.summary() for e_d in error_descriptors]
        if len(summaries) == 1:
            text = summaries[0]
        else:
            _j_summaries = "; ".join(
                f"[{summ_i + 1}] {summ_s}"
                for summ_i, summ_s in enumerate(summaries)
            )
            text = f"[{len(summaries)} errors collected] {_j_summaries}"
    else:
        text = ""

    return DataAPIResponseException(
        text,
        command=command,
        raw_response=raw_response,
        error_descriptors=error_descriptors,
        warning_descriptors=warning_descriptors,
        **kwargs,
    )
class DataAPITimeoutException (text: str, *, timeout_type: str, endpoint: str | None, raw_payload: str | None)

A Data API operation timed out. This can be a request timeout occurring during a specific HTTP request, or can happen over the course of a method involving several requests in a row, such as a paginated find.

Attributes

text
a textual description of the error
timeout_type
this denotes the phase of the HTTP request when the event occurred ("connect", "read", "write", "pool") or "generic" if there is not a specific request associated to the exception.
endpoint
if the timeout is tied to a specific request, this is the URL that the request was targeting.
raw_payload
if the timeout is tied to a specific request, this is the associated payload (as a string).
Expand source code
@dataclass
class DataAPITimeoutException(DataAPIException):
    """
    A Data API operation timed out. This can be a request timeout occurring
    during a specific HTTP request, or can happen over the course of a method
    involving several requests in a row, such as a paginated find.

    Attributes:
        text: a textual description of the error
        timeout_type: this denotes the phase of the HTTP request when the event
            occurred ("connect", "read", "write", "pool") or "generic" if there is
            not a specific request associated to the exception.
        endpoint: if the timeout is tied to a specific request, this is the
            URL that the request was targeting.
        raw_payload:  if the timeout is tied to a specific request, this is the
            associated payload (as a string).
    """

    text: str
    timeout_type: str
    endpoint: str | None
    raw_payload: str | None

    def __init__(
        self,
        text: str,
        *,
        timeout_type: str,
        endpoint: str | None,
        raw_payload: str | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.timeout_type = timeout_type
        self.endpoint = endpoint
        self.raw_payload = raw_payload

Ancestors

Class variables

var endpoint : str | None
var raw_payload : str | None
var text : str
var timeout_type : str
class DevOpsAPIErrorDescriptor (error_dict: dict[str, Any])

An object representing a single error returned from the DevOps API, typically with an error code and a text message.

A single response from the Devops API may return zero, one or more of these.

Attributes

id
a numeric code as found in the API "ID" item.
message
the text found in the API "error" item.
attributes
a dict with any further key-value pairs returned by the API.
Expand source code
@dataclass
class DevOpsAPIErrorDescriptor:
    """
    An object representing a single error returned from the DevOps API,
    typically with an error code and a text message.

    A single response from the Devops API may return zero, one or more of these.

    Attributes:
        id: a numeric code as found in the API "ID" item.
        message: the text found in the API "error" item.
        attributes: a dict with any further key-value pairs returned by the API.
    """

    id: int | None
    message: str | None
    attributes: dict[str, Any]

    def __init__(self, error_dict: dict[str, Any]) -> None:
        self.id = error_dict.get("ID")
        self.message = error_dict.get("message")
        self.attributes = {
            k: v for k, v in error_dict.items() if k not in {"ID", "message"}
        }

Class variables

var attributes : dict[str, typing.Any]
var id : int | None
var message : str | None
class DevOpsAPIException (text: str | None = None)

An exception specific to issuing requests to the DevOps API.

Expand source code
class DevOpsAPIException(Exception):
    """
    An exception specific to issuing requests to the DevOps API.
    """

    def __init__(self, text: str | None = None):
        Exception.__init__(self, text or "")

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

class DevOpsAPIHttpException (text: str | None, *, httpx_error: httpx.HTTPStatusError, error_descriptors: list[DevOpsAPIErrorDescriptor])

A request to the DevOps API resulted in an HTTP 4xx or 5xx response.

Though the DevOps API seldom enriches such errors with a response text, this class acts as the DevOps counterpart to DataAPIHttpException to facilitate a symmetryc handling of errors at application lebel.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DevOpsAPIErrorDescriptor objects found in the response.
Expand source code
@dataclass
class DevOpsAPIHttpException(DevOpsAPIException, httpx.HTTPStatusError):
    """
    A request to the DevOps API resulted in an HTTP 4xx or 5xx response.

    Though the DevOps API seldom enriches such errors with a response text,
    this class acts as the DevOps counterpart to DataAPIHttpException
    to facilitate a symmetryc handling of errors at application lebel.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DevOpsAPIErrorDescriptor objects
            found in the response.
    """

    text: str | None
    error_descriptors: list[DevOpsAPIErrorDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        httpx_error: httpx.HTTPStatusError,
        error_descriptors: list[DevOpsAPIErrorDescriptor],
    ) -> None:
        DevOpsAPIException.__init__(self, text)
        httpx.HTTPStatusError.__init__(
            self,
            message=str(httpx_error),
            request=httpx_error.request,
            response=httpx_error.response,
        )
        self.text = text
        self.httpx_error = httpx_error
        self.error_descriptors = error_descriptors

    def __str__(self) -> str:
        return self.text or str(self.httpx_error)

    @classmethod
    def from_httpx_error(
        cls,
        httpx_error: httpx.HTTPStatusError,
        **kwargs: Any,
    ) -> DevOpsAPIHttpException:
        """Parse a httpx status error into this exception."""

        raw_response: dict[str, Any]
        # the attempt to extract a response structure cannot afford failure.
        try:
            raw_response = httpx_error.response.json()
        except Exception:
            raw_response = {}
        error_descriptors = [
            DevOpsAPIErrorDescriptor(error_dict)
            for error_dict in raw_response.get("errors") or []
        ]
        if error_descriptors:
            text = f"{error_descriptors[0].message}. {str(httpx_error)}"
        else:
            text = str(httpx_error)

        return cls(
            text=text,
            httpx_error=httpx_error,
            error_descriptors=error_descriptors,
            **kwargs,
        )

Ancestors

  • DevOpsAPIException
  • httpx.HTTPStatusError
  • httpx.HTTPError
  • builtins.Exception
  • builtins.BaseException

Class variables

var error_descriptors : list[DevOpsAPIErrorDescriptor]
var text : str | None

Static methods

def from_httpx_error(httpx_error: httpx.HTTPStatusError, **kwargs: Any) ‑> DevOpsAPIHttpException

Parse a httpx status error into this exception.

Expand source code
@classmethod
def from_httpx_error(
    cls,
    httpx_error: httpx.HTTPStatusError,
    **kwargs: Any,
) -> DevOpsAPIHttpException:
    """Parse a httpx status error into this exception."""

    raw_response: dict[str, Any]
    # the attempt to extract a response structure cannot afford failure.
    try:
        raw_response = httpx_error.response.json()
    except Exception:
        raw_response = {}
    error_descriptors = [
        DevOpsAPIErrorDescriptor(error_dict)
        for error_dict in raw_response.get("errors") or []
    ]
    if error_descriptors:
        text = f"{error_descriptors[0].message}. {str(httpx_error)}"
    else:
        text = str(httpx_error)

    return cls(
        text=text,
        httpx_error=httpx_error,
        error_descriptors=error_descriptors,
        **kwargs,
    )
class DevOpsAPIResponseException (text: str | None = None, *, command: dict[str, Any] | None = None, error_descriptors: list[DevOpsAPIErrorDescriptor] = [])

A request to the DevOps API returned with a non-success return code and one of more errors in the HTTP response.

Attributes

text
a text message about the exception.
command
the raw payload that was sent to the DevOps API.
error_descriptors
a list of all DevOpsAPIErrorDescriptor objects returned by the API in the response.
Expand source code
class DevOpsAPIResponseException(DevOpsAPIException):
    """
    A request to the DevOps API returned with a non-success return code
    and one of more errors in the HTTP response.

    Attributes:
        text: a text message about the exception.
        command: the raw payload that was sent to the DevOps API.
        error_descriptors: a list of all DevOpsAPIErrorDescriptor objects
            returned by the API in the response.
    """

    text: str | None
    command: dict[str, Any] | None
    error_descriptors: list[DevOpsAPIErrorDescriptor]

    def __init__(
        self,
        text: str | None = None,
        *,
        command: dict[str, Any] | None = None,
        error_descriptors: list[DevOpsAPIErrorDescriptor] = [],
    ) -> None:
        super().__init__(text or self.__class__.__name__)
        self.text = text
        self.command = command
        self.error_descriptors = error_descriptors

    @staticmethod
    def from_response(
        command: dict[str, Any] | None,
        raw_response: dict[str, Any],
    ) -> DevOpsAPIResponseException:
        """Parse a raw response from the API into this exception."""

        error_descriptors = [
            DevOpsAPIErrorDescriptor(error_dict)
            for error_dict in raw_response.get("errors") or []
        ]
        if error_descriptors:
            _text = error_descriptors[0].message
        else:
            _text = None
        return DevOpsAPIResponseException(
            text=_text, command=command, error_descriptors=error_descriptors
        )

Ancestors

Class variables

var command : dict[str, typing.Any] | None
var error_descriptors : list[DevOpsAPIErrorDescriptor]
var text : str | None

Static methods

def from_response(command: dict[str, Any] | None, raw_response: dict[str, Any]) ‑> DevOpsAPIResponseException

Parse a raw response from the API into this exception.

Expand source code
@staticmethod
def from_response(
    command: dict[str, Any] | None,
    raw_response: dict[str, Any],
) -> DevOpsAPIResponseException:
    """Parse a raw response from the API into this exception."""

    error_descriptors = [
        DevOpsAPIErrorDescriptor(error_dict)
        for error_dict in raw_response.get("errors") or []
    ]
    if error_descriptors:
        _text = error_descriptors[0].message
    else:
        _text = None
    return DevOpsAPIResponseException(
        text=_text, command=command, error_descriptors=error_descriptors
    )
class DevOpsAPITimeoutException (text: str, *, timeout_type: str, endpoint: str | None, raw_payload: str | None)

A DevOps API operation timed out.

Attributes

text
a textual description of the error
timeout_type
this denotes the phase of the HTTP request when the event occurred ("connect", "read", "write", "pool") or "generic" if there is not a specific request associated to the exception.
endpoint
if the timeout is tied to a specific request, this is the URL that the request was targeting.
raw_payload
if the timeout is tied to a specific request, this is the associated payload (as a string).
Expand source code
@dataclass
class DevOpsAPITimeoutException(DevOpsAPIException):
    """
    A DevOps API operation timed out.

    Attributes:
        text: a textual description of the error
        timeout_type: this denotes the phase of the HTTP request when the event
            occurred ("connect", "read", "write", "pool") or "generic" if there is
            not a specific request associated to the exception.
        endpoint: if the timeout is tied to a specific request, this is the
            URL that the request was targeting.
        raw_payload:  if the timeout is tied to a specific request, this is the
            associated payload (as a string).
    """

    text: str
    timeout_type: str
    endpoint: str | None
    raw_payload: str | None

    def __init__(
        self,
        text: str,
        *,
        timeout_type: str,
        endpoint: str | None,
        raw_payload: str | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.timeout_type = timeout_type
        self.endpoint = endpoint
        self.raw_payload = raw_payload

Ancestors

Class variables

var endpoint : str | None
var raw_payload : str | None
var text : str
var timeout_type : str
class TableInsertManyException (inserted_ids: list[Any], inserted_id_tuples: list[tuple[Any, ...]], exceptions: Sequence[Exception])

An exception occurring within an insert_many (an operation that can span several requests). As such, it represents both the root error(s) that happened and information on the portion of the row that were successfully inserted.

The behaviour of insert_many (concurrency and the ordered setting) make it possible that more than one "root errors" are collected.

Attributes

inserted_ids
a list of the row IDs that have been successfully inserted, in the form of a dictionary matching the table primary key).
inserted_id_tuples
the same information as for inserted_ids (in the same order), but in form of a tuples for each ID.
exceptions
a list of the root exceptions leading to this error. The list, under normal circumstances, is not empty.
Expand source code
@dataclass
class TableInsertManyException(DataAPIException):
    """
    An exception occurring within an insert_many (an operation that can span
    several requests). As such, it represents both the root error(s) that happened
    and information on the portion of the row that were successfully inserted.

    The behaviour of insert_many (concurrency and the `ordered` setting) make it
    possible that more than one "root errors" are collected.

    Attributes:
        inserted_ids: a list of the row IDs that have been successfully inserted,
            in the form of a dictionary matching the table primary key).
        inserted_id_tuples: the same information as for `inserted_ids` (in the same
            order), but in form of a tuples for each ID.
        exceptions: a list of the root exceptions leading to this error. The list,
            under normal circumstances, is not empty.
    """

    inserted_ids: list[Any]
    inserted_id_tuples: list[tuple[Any, ...]]
    exceptions: Sequence[Exception]

    def __str__(self) -> str:
        num_ids = len(self.inserted_ids)
        if self.exceptions:
            exc_desc: str
            excs_strs = [exc.__str__() for exc in self.exceptions[:8]]
            if len(self.exceptions) > 8:
                exc_desc = ", ".join(excs_strs) + " ... (more exceptions)"
            else:
                exc_desc = ", ".join(excs_strs)
            return (
                f"{self.__class__.__name__}({exc_desc} "
                f"[with {num_ids} inserted ids])"
            )
        else:
            return f"{self.__class__.__name__}()"

Ancestors

Class variables

var exceptions : Sequence[Exception]
var inserted_id_tuples : list[tuple[typing.Any, ...]]
var inserted_ids : list[typing.Any]
class TooManyDocumentsToCountException (text: str, *, server_max_count_exceeded: bool)

A count_documents() operation on a collection failed because the resulting number of documents exceeded either the upper bound set by the caller or the hard limit imposed by the Data API.

Attributes

text
a text message about the exception.
server_max_count_exceeded
True if the count limit imposed by the API is reached. In that case, increasing the upper bound in the method invocation is of no help.
Expand source code
@dataclass
class TooManyDocumentsToCountException(DataAPIException):
    """
    A `count_documents()` operation on a collection failed because the resulting
    number of documents exceeded either the upper bound set by the caller or the
    hard limit imposed by the Data API.

    Attributes:
        text: a text message about the exception.
        server_max_count_exceeded: True if the count limit imposed by the API
            is reached. In that case, increasing the upper bound in the method
            invocation is of no help.
    """

    text: str
    server_max_count_exceeded: bool

    def __init__(
        self,
        text: str,
        *,
        server_max_count_exceeded: bool,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.server_max_count_exceeded = server_max_count_exceeded

Ancestors

Class variables

var server_max_count_exceeded : bool
var text : str
class TooManyRowsToCountException (text: str, *, server_max_count_exceeded: bool)

A count_documents() operation on a table failed because of the excessive amount of rows to count.

Attributes

text
a text message about the exception.
Expand source code
@dataclass
class TooManyRowsToCountException(DataAPIException):
    """
    A `count_documents()` operation on a table failed because of the excessive amount
    of rows to count.

    Attributes:
        text: a text message about the exception.
    """

    text: str
    server_max_count_exceeded: bool

    def __init__(
        self,
        text: str,
        *,
        server_max_count_exceeded: bool,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.server_max_count_exceeded = server_max_count_exceeded

Ancestors

Class variables

var server_max_count_exceeded : bool
var text : str
class UnexpectedDataAPIResponseException (text: str, raw_response: dict[str, Any] | None)

The Data API response is malformed in that it does not have expected field(s), or they are of the wrong type.

Attributes

text
a text message about the exception.
raw_response
the response returned by the API in the form of a dict.
Expand source code
@dataclass
class UnexpectedDataAPIResponseException(DataAPIException):
    """
    The Data API response is malformed in that it does not have
    expected field(s), or they are of the wrong type.

    Attributes:
        text: a text message about the exception.
        raw_response: the response returned by the API in the form of a dict.
    """

    text: str
    raw_response: dict[str, Any] | None

    def __init__(
        self,
        text: str,
        raw_response: dict[str, Any] | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.raw_response = raw_response

Ancestors

Class variables

var raw_response : dict[str, typing.Any] | None
var text : str
class UnexpectedDevOpsAPIResponseException (text: str, raw_response: dict[str, Any] | None)

The DevOps API response is malformed in that it does not have expected field(s), or they are of the wrong type.

Attributes

text
a text message about the exception.
raw_response
the response returned by the API in the form of a dict.
Expand source code
@dataclass
class UnexpectedDevOpsAPIResponseException(DevOpsAPIException):
    """
    The DevOps API response is malformed in that it does not have
    expected field(s), or they are of the wrong type.

    Attributes:
        text: a text message about the exception.
        raw_response: the response returned by the API in the form of a dict.
    """

    text: str
    raw_response: dict[str, Any] | None

    def __init__(
        self,
        text: str,
        raw_response: dict[str, Any] | None,
    ) -> None:
        super().__init__(text)
        self.text = text
        self.raw_response = raw_response

Ancestors

Class variables

var raw_response : dict[str, typing.Any] | None
var text : str