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 (
    CumulativeOperationException,
    CursorException,
    DataAPIDetailedErrorDescriptor,
    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(ValueError):
    """
    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 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",
    "CumulativeOperationException",
    "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 (text: str, partial_result: CollectionDeleteResult, *pargs: Any, **kwargs: Any)

An exception of type DataAPIResponseException (see) occurred during a delete_many (that in general spans several requests). As such, besides information on the error, it may have accumulated a partial result from past successful Data API requests.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found across all requests involved in this exception, which are possibly more than one.
detailed_error_descriptors
a list of DataAPIDetailedErrorDescriptor objects, one for each of the requests performed during this operation. For single-request methods, such as insert_one, this list always has a single element.
partial_result
a CollectionDeleteResult object, just like the one that would be the return value of the operation, had it succeeded completely.
Expand source code
@dataclass
class CollectionDeleteManyException(CumulativeOperationException):
    """
    An exception of type DataAPIResponseException (see) occurred
    during a delete_many (that in general spans several requests).
    As such, besides information on the error, it may have accumulated
    a partial result from past successful Data API requests.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found across all requests involved in this exception, which are
            possibly more than one.
        detailed_error_descriptors: a list of DataAPIDetailedErrorDescriptor
            objects, one for each of the requests performed during this operation.
            For single-request methods, such as insert_one, this list always
            has a single element.
        partial_result: a CollectionDeleteResult object, just like the one that would
            be the return value of the operation, had it succeeded completely.
    """

    partial_result: CollectionDeleteResult

    def __init__(
        self,
        text: str,
        partial_result: CollectionDeleteResult,
        *pargs: Any,
        **kwargs: Any,
    ) -> None:
        super().__init__(text, *pargs, **kwargs)
        self.partial_result = partial_result

Ancestors

Class variables

var partial_result : CollectionDeleteResult

Inherited members

class CollectionInsertManyException (text: str, partial_result: CollectionInsertManyResult, *pargs: Any, **kwargs: Any)

An exception of type DataAPIResponseException (see) occurred during an insert_many (that in general spans several requests). As such, besides information on the error, it may have accumulated a partial result from past successful Data API requests.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found across all requests involved in this exception, which are possibly more than one.
detailed_error_descriptors
a list of DataAPIDetailedErrorDescriptor objects, one for each of the requests performed during this operation. For single-request methods, such as insert_one, this list always has a single element.
partial_result
a CollectionInsertManyResult object, just like the one that would be the return value of the operation, had it succeeded completely.
Expand source code
@dataclass
class CollectionInsertManyException(CumulativeOperationException):
    """
    An exception of type DataAPIResponseException (see) occurred
    during an insert_many (that in general spans several requests).
    As such, besides information on the error, it may have accumulated
    a partial result from past successful Data API requests.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found across all requests involved in this exception, which are
            possibly more than one.
        detailed_error_descriptors: a list of DataAPIDetailedErrorDescriptor
            objects, one for each of the requests performed during this operation.
            For single-request methods, such as insert_one, this list always
            has a single element.
        partial_result: a CollectionInsertManyResult object, just like the one
            that would be the return value of the operation, had it succeeded
            completely.
    """

    partial_result: CollectionInsertManyResult

    def __init__(
        self,
        text: str,
        partial_result: CollectionInsertManyResult,
        *pargs: Any,
        **kwargs: Any,
    ) -> None:
        super().__init__(text, *pargs, **kwargs)
        self.partial_result = partial_result

Ancestors

Class variables

var partial_result : CollectionInsertManyResult

Inherited members

class CollectionUpdateManyException (text: str, partial_result: CollectionUpdateResult, *pargs: Any, **kwargs: Any)

An exception of type DataAPIResponseException (see) occurred during an update_many (that in general spans several requests). As such, besides information on the error, it may have accumulated a partial result from past successful Data API requests.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found across all requests involved in this exception, which are possibly more than one.
detailed_error_descriptors
a list of DataAPIDetailedErrorDescriptor objects, one for each of the requests performed during this operation. For single-request methods, such as insert_one, this list always has a single element.
partial_result
a CollectionUpdateResult object, just like the one that would be the return value of the operation, had it succeeded completely.
Expand source code
@dataclass
class CollectionUpdateManyException(CumulativeOperationException):
    """
    An exception of type DataAPIResponseException (see) occurred
    during an update_many (that in general spans several requests).
    As such, besides information on the error, it may have accumulated
    a partial result from past successful Data API requests.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found across all requests involved in this exception, which are
            possibly more than one.
        detailed_error_descriptors: a list of DataAPIDetailedErrorDescriptor
            objects, one for each of the requests performed during this operation.
            For single-request methods, such as insert_one, this list always
            has a single element.
        partial_result: a CollectionUpdateResult object, just like the one that would
            be the return value of the operation, had it succeeded completely.
    """

    partial_result: CollectionUpdateResult

    def __init__(
        self,
        text: str,
        partial_result: CollectionUpdateResult,
        *pargs: Any,
        **kwargs: Any,
    ) -> None:
        super().__init__(text, *pargs, **kwargs)
        self.partial_result = partial_result

Ancestors

Class variables

var partial_result : CollectionUpdateResult

Inherited members

class CumulativeOperationException (text: str | None, *, error_descriptors: list[DataAPIErrorDescriptor], detailed_error_descriptors: list[DataAPIDetailedErrorDescriptor])

An exception of type DataAPIResponseException (see) occurred during a collection operation that in general may span several requests. As such, besides information on the error, it may have accumulated a partial result from past successful Data API requests.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found across all requests involved in this exception, which are possibly more than one.
detailed_error_descriptors
a list of DataAPIDetailedErrorDescriptor objects, one for each of the requests performed during this operation. For single-request methods, such as insert_one, this list always has a single element.
Expand source code
class CumulativeOperationException(DataAPIResponseException):
    """
    An exception of type DataAPIResponseException (see) occurred
    during a collection operation that in general may span several requests.
    As such, besides information on the error, it may have accumulated
    a partial result from past successful Data API requests.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found across all requests involved in this exception, which are
            possibly more than one.
        detailed_error_descriptors: a list of DataAPIDetailedErrorDescriptor
            objects, one for each of the requests performed during this operation.
            For single-request methods, such as insert_one, this list always
            has a single element.
    """

    pass

Ancestors

Subclasses

Inherited members

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

  • DataAPIException
  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException

Class variables

var cursor_state : str
var text : str
class DataAPIDetailedErrorDescriptor (error_descriptors: list[DataAPIErrorDescriptor], command: dict[str, Any] | None, raw_response: dict[str, Any])

An object representing an errorful response from the Data API. Errors specific to the Data API (as opposed to e.g. network failures) would result in an HTTP 200 success response code but coming with one or more DataAPIErrorDescriptor objects.

This object corresponds to one response, and as such its attributes are a single request payload, a single response, but a list of DataAPIErrorDescriptor instances.

Attributes

error_descriptors
a list of DataAPIErrorDescriptor objects.
command
the raw payload of the API request.
raw_response
the full API response in the form of a dict.
Expand source code
@dataclass
class DataAPIDetailedErrorDescriptor:
    """
    An object representing an errorful response from the Data API.
    Errors specific to the Data API (as opposed to e.g. network failures)
    would result in an HTTP 200 success response code but coming with
    one or more DataAPIErrorDescriptor objects.

    This object corresponds to one response, and as such its attributes
    are a single request payload, a single response, but a list of
    DataAPIErrorDescriptor instances.

    Attributes:
        error_descriptors: a list of DataAPIErrorDescriptor objects.
        command: the raw payload of the API request.
        raw_response: the full API response in the form of a dict.
    """

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

Class variables

var command : dict[str, typing.Any] | None
var error_descriptors : list[DataAPIErrorDescriptor]
var raw_response : dict[str, typing.Any]
class DataAPIErrorDescriptor (error_dict: dict[str, str])

An object representing a single error returned from the Data API, typically with an error code and a text message. An API request would return with an HTTP 200 success error code, but contain a nonzero amount of these.

A single response from the Data API may return zero, one or more of these. Moreover, some operations, such as an insert_many, may partally succeed yet return these errors about the rest of the operation (such as, some of the input documents could not be inserted).

Attributes

error_code
a string code as found in the API "error" 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 DataAPIErrorDescriptor:
    """
    An object representing a single error returned from the Data API,
    typically with an error code and a text message.
    An API request would return with an HTTP 200 success error code,
    but contain a nonzero amount of these.

    A single response from the Data API may return zero, one or more of these.
    Moreover, some operations, such as an insert_many, may partally succeed
    yet return these errors about the rest of the operation (such as,
    some of the input documents could not be inserted).

    Attributes:
        error_code: a string code as found in the API "error" item.
        message: the text found in the API "error" 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]) -> None:
        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:
        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
Expand source code
def summary(self) -> str:
    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(ValueError):
    """
    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.ValueError
  • 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
  • builtins.ValueError
  • 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, *, error_descriptors: list[DataAPIErrorDescriptor], detailed_error_descriptors: list[DataAPIDetailedErrorDescriptor])

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

This exception is related to an operation that can have spanned several HTTP requests in sequence (e.g. a chunked insert_many). For this reason, it should be not thought as being in a 1:1 relation with actual API requests, rather with operations invoked by the user, such as the methods of the Collection object.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found across all requests involved in this exception, which are possibly more than one.
detailed_error_descriptors
a list of DataAPIDetailedErrorDescriptor objects, one for each of the requests performed during this operation. For single-request methods, such as insert_one, this list always has a single element.
Expand source code
@dataclass
class DataAPIResponseException(DataAPIException):
    """
    The Data API returned an HTTP 200 success response, which however
    reports about API-specific error(s), possibly alongside partial successes.

    This exception is related to an operation that can have spanned several
    HTTP requests in sequence (e.g. a chunked insert_many). For this
    reason, it should be not thought as being in a 1:1 relation with
    actual API requests, rather with operations invoked by the user,
    such as the methods of the Collection object.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found across all requests involved in this exception, which are
            possibly more than one.
        detailed_error_descriptors: a list of DataAPIDetailedErrorDescriptor
            objects, one for each of the requests performed during this operation.
            For single-request methods, such as insert_one, this list always
            has a single element.
    """

    text: str | None
    error_descriptors: list[DataAPIErrorDescriptor]
    detailed_error_descriptors: list[DataAPIDetailedErrorDescriptor]

    def __init__(
        self,
        text: str | None,
        *,
        error_descriptors: list[DataAPIErrorDescriptor],
        detailed_error_descriptors: list[DataAPIDetailedErrorDescriptor],
    ) -> None:
        super().__init__(text)
        self.text = text
        self.error_descriptors = error_descriptors
        self.detailed_error_descriptors = detailed_error_descriptors

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

        return cls.from_responses(
            commands=[command],
            raw_responses=[raw_response],
            **kwargs,
        )

    @classmethod
    def from_responses(
        cls,
        commands: list[dict[str, Any] | None],
        raw_responses: list[dict[str, Any]],
        **kwargs: Any,
    ) -> DataAPIResponseException:
        """Parse a list of raw responses from the API into this exception."""

        detailed_error_descriptors: list[DataAPIDetailedErrorDescriptor] = []
        for command, raw_response in zip(commands, raw_responses):
            if raw_response.get("errors", []):
                error_descriptors = [
                    DataAPIErrorDescriptor(error_dict)
                    for error_dict in raw_response["errors"]
                ]
                detailed_error_descriptor = DataAPIDetailedErrorDescriptor(
                    error_descriptors=error_descriptors,
                    command=command,
                    raw_response=raw_response,
                )
                detailed_error_descriptors.append(detailed_error_descriptor)

        # flatten
        error_descriptors = [
            error_descriptor
            for d_e_d in detailed_error_descriptors
            for error_descriptor in d_e_d.error_descriptors
        ]

        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 cls(
            text,
            error_descriptors=error_descriptors,
            detailed_error_descriptors=detailed_error_descriptors,
            **kwargs,
        )

    def data_api_response_exception(self) -> DataAPIResponseException:
        """Cast the exception, whatever the subclass, into this parent superclass."""

        return DataAPIResponseException(
            text=self.text,
            error_descriptors=self.error_descriptors,
            detailed_error_descriptors=self.detailed_error_descriptors,
        )

Ancestors

  • DataAPIException
  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException

Subclasses

Class variables

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

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

    return cls.from_responses(
        commands=[command],
        raw_responses=[raw_response],
        **kwargs,
    )
def from_responses(commands: list[dict[str, Any] | None], raw_responses: list[dict[str, Any]], **kwargs: Any) ‑> DataAPIResponseException

Parse a list of raw responses from the API into this exception.

Expand source code
@classmethod
def from_responses(
    cls,
    commands: list[dict[str, Any] | None],
    raw_responses: list[dict[str, Any]],
    **kwargs: Any,
) -> DataAPIResponseException:
    """Parse a list of raw responses from the API into this exception."""

    detailed_error_descriptors: list[DataAPIDetailedErrorDescriptor] = []
    for command, raw_response in zip(commands, raw_responses):
        if raw_response.get("errors", []):
            error_descriptors = [
                DataAPIErrorDescriptor(error_dict)
                for error_dict in raw_response["errors"]
            ]
            detailed_error_descriptor = DataAPIDetailedErrorDescriptor(
                error_descriptors=error_descriptors,
                command=command,
                raw_response=raw_response,
            )
            detailed_error_descriptors.append(detailed_error_descriptor)

    # flatten
    error_descriptors = [
        error_descriptor
        for d_e_d in detailed_error_descriptors
        for error_descriptor in d_e_d.error_descriptors
    ]

    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 cls(
        text,
        error_descriptors=error_descriptors,
        detailed_error_descriptors=detailed_error_descriptors,
        **kwargs,
    )

Methods

def data_api_response_exception(self) ‑> DataAPIResponseException

Cast the exception, whatever the subclass, into this parent superclass.

Expand source code
def data_api_response_exception(self) -> DataAPIResponseException:
    """Cast the exception, whatever the subclass, into this parent superclass."""

    return DataAPIResponseException(
        text=self.text,
        error_descriptors=self.error_descriptors,
        detailed_error_descriptors=self.detailed_error_descriptors,
    )
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

  • DataAPIException
  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException

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(ValueError):
    """
    An exception specific to issuing requests to the DevOps API.
    """

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

Ancestors

  • builtins.ValueError
  • 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
  • builtins.ValueError
  • 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 (text: str, partial_result: TableInsertManyResult, *pargs: Any, **kwargs: Any)

An exception of type DataAPIResponseException (see) occurred during an insert_many (that in general spans several requests). As such, besides information on the error, it may have accumulated a partial result from past successful Data API requests.

Attributes

text
a text message about the exception.
error_descriptors
a list of all DataAPIErrorDescriptor objects found across all requests involved in this exception, which are possibly more than one.
detailed_error_descriptors
a list of DataAPIDetailedErrorDescriptor objects, one for each of the requests performed during this operation. For single-request methods, such as insert_one, this list always has a single element.
partial_result
a TableInsertManyResult object, just like the one that would be the return value of the operation, had it succeeded completely.
Expand source code
@dataclass
class TableInsertManyException(CumulativeOperationException):
    """
    An exception of type DataAPIResponseException (see) occurred
    during an insert_many (that in general spans several requests).
    As such, besides information on the error, it may have accumulated
    a partial result from past successful Data API requests.

    Attributes:
        text: a text message about the exception.
        error_descriptors: a list of all DataAPIErrorDescriptor objects
            found across all requests involved in this exception, which are
            possibly more than one.
        detailed_error_descriptors: a list of DataAPIDetailedErrorDescriptor
            objects, one for each of the requests performed during this operation.
            For single-request methods, such as insert_one, this list always
            has a single element.
        partial_result: a TableInsertManyResult object, just like the one
            that would be the return value of the operation, had it succeeded
            completely.
    """

    partial_result: TableInsertManyResult

    def __init__(
        self,
        text: str,
        partial_result: TableInsertManyResult,
        *pargs: Any,
        **kwargs: Any,
    ) -> None:
        super().__init__(text, *pargs, **kwargs)
        self.partial_result = partial_result

Ancestors

Class variables

var partial_result : TableInsertManyResult

Inherited members

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

  • DataAPIException
  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException

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

  • DataAPIException
  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException

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

  • DataAPIException
  • builtins.ValueError
  • builtins.Exception
  • builtins.BaseException

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