Source code for smarter.apps.api.v1.cli.views.base

"""Smarter API command-line interface Base class API view."""

import re
import traceback
from functools import cached_property
from http import HTTPStatus
from typing import Optional, Type, Union

import yaml
from django.conf import settings
from django.contrib.auth import SESSION_KEY
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.handlers.asgi import ASGIRequest
from django.http import HttpRequest
from pydantic import ValidationError as PydanticValidationError
from rest_framework.authentication import BaseAuthentication, SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed, NotAuthenticated
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.views import APIView

from smarter.apps.account.models import Account, User, UserProfile
from smarter.apps.api.signals import (
    api_request_completed,
    api_request_failed,
    api_request_initiated,
)
from smarter.apps.api.v1.cli.brokers import Brokers
from smarter.apps.api.v1.manifests.enum import SAMKinds
from smarter.apps.api.v1.manifests.version import SMARTER_API_VERSION
from smarter.common.conf import smarter_settings
from smarter.common.exceptions import (
    SmarterBusinessRuleViolation,
    SmarterConfigurationError,
    SmarterException,
    SmarterIlligalInvocationError,
    SmarterInvalidApiKeyError,
    SmarterValueError,
)
from smarter.common.utils import is_authenticated_request, mask_string
from smarter.lib import json, logging
from smarter.lib.django.request import SmarterRequestMixin
from smarter.lib.django.token_generators import SmarterTokenError
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.drf.token_authentication import SmarterTokenAuthentication
from smarter.lib.drf.views.helpers import SmarterAuthenticatedPermissionClass
from smarter.lib.journal.enum import SmarterJournalCliCommands
from smarter.lib.journal.http import SmarterJournaledJsonErrorResponse
from smarter.lib.manifest.broker import (
    AbstractBroker,
    SAMBrokerError,
    SAMBrokerErrorNotFound,
    SAMBrokerErrorNotImplemented,
    SAMBrokerErrorNotReady,
    SAMBrokerInternalError,
    SAMBrokerReadOnlyError,
)
from smarter.lib.manifest.exceptions import SAMBadRequestError, SAMValidationError
from smarter.lib.manifest.sam_apps import raise_if_kind_disabled
from smarter.lib.typing import SmarterDictType

logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.API_LOGGING])

BUG_REPORT = (
    "Encountered an unexpected error. "
    f"This is a bug. Please contact {smarter_settings.platform_branding_support_email} "
    f"and/or report to {smarter_settings.repository_url}/issues."
)
"""The note that an error response's description ends with, when the error is a bug in the platform."""


[docs] class APIV1CLIViewError(SmarterException): """Base class for all APIV1CLIView errors.""" @property def get_formatted_err_message(self): """The heading of this error's message.""" return "Smarter api v1 command-line interface error"
[docs] class SmarterAPIV1CLIViewErrorNotAuthenticated(APIV1CLIViewError): """Error class for not authenticated errors.""" @property def get_formatted_err_message(self): """The heading of this error's message.""" return "Smarter api v1 command-line interface error: not authenticated"
[docs] class APIV1CLIViewBadRequestError(APIV1CLIViewError): """Error class for requests that are the client's error, such as an invalid manifest.""" @property def get_formatted_err_message(self): """The heading of this error's message.""" return "Smarter api v1 command-line interface error: bad request"
[docs] class APIV1CLIViewNotFoundError(APIV1CLIViewError): """Error class for requests for something that does not exist, e.g. the user profile of an api key's user.""" @property def get_formatted_err_message(self): """The heading of this error's message.""" return "Smarter api v1 command-line interface error: not found"
# errors that are the client's fault, e.g. an invalid manifest, and that are therefore a 400. CLIENT_ERRORS: tuple[Type[BaseException], ...] = ( PydanticValidationError, DjangoValidationError, yaml.YAMLError, SAMValidationError, SAMBadRequestError, SmarterValueError, SmarterIlligalInvocationError, SmarterBusinessRuleViolation, APIV1CLIViewBadRequestError, ) MAX_INPUT_LENGTH = 80 CLI_COMMAND_PATTERN = re.compile(r"/cli/([^/]+)/") """Finds the command in a cli api url, e.g. ``apply`` in ``/api/v1/cli/apply/``."""
[docs] def exception_chain(e: BaseException) -> list[BaseException]: """The exception, followed by its causes, i.e. ``raise ... from ...``, outermost first.""" retval: list[BaseException] = [] while e is not None and e not in retval: retval.append(e) e = e.__cause__ # type: ignore[assignment] return retval
[docs] def client_error_in(e: BaseException) -> Optional[BaseException]: """The first client error in the chain of the exception and its causes, or None.""" return next((err for err in exception_chain(e) if isinstance(err, CLIENT_ERRORS)), None)
[docs] def format_validation_error(e: BaseException) -> str: """A readable, one line description of a Pydantic or Django validation error.""" if isinstance(e, PydanticValidationError): problems = [] for error in e.errors(): location = ".".join(str(part) for part in error.get("loc", ())) or e.title problem = f"{location}: {error.get('msg')}" if "input" in error and not isinstance(error["input"], dict): value = repr(error["input"]) if len(value) > MAX_INPUT_LENGTH: value = value[:MAX_INPUT_LENGTH] + "..." problem += f" (got {value})" problems.append(problem) return f"{e.title} is not valid. " + "; ".join(problems) if isinstance(e, DjangoValidationError): if hasattr(e, "error_dict"): return "; ".join(f"{field}: {' '.join(messages)}" for field, messages in e.message_dict.items()) return " ".join(e.messages) return str(e)
[docs] def http_status_for_exception(e: BaseException) -> int: """ The HTTP status of the response to a request that raised the exception. Exceptions are matched by class, including their subclasses, so that e.g. a broker's own ``SAM<Kind>BrokerError`` is treated as a ``SAMBrokerError``. A broker error that was raised from an exception that is not the client's error, e.g. a database error, is a 500. """ if isinstance(e, SAMBrokerInternalError): return HTTPStatus.INTERNAL_SERVER_ERROR.value if isinstance(e, SAMBrokerErrorNotImplemented): return HTTPStatus.NOT_IMPLEMENTED.value if isinstance(e, SAMBrokerErrorNotReady): return HTTPStatus.SERVICE_UNAVAILABLE.value if isinstance(e, (SAMBrokerErrorNotFound, APIV1CLIViewNotFoundError)): return HTTPStatus.NOT_FOUND.value if isinstance(e, SAMBrokerReadOnlyError): return HTTPStatus.METHOD_NOT_ALLOWED.value if ( isinstance( e, ( SmarterAPIV1CLIViewErrorNotAuthenticated, SmarterInvalidApiKeyError, SmarterTokenError, NotAuthenticated, AuthenticationFailed, ), ) or type(e) is AttributeError ): # can be raised by a django admin decorator if request or request.user is None return HTTPStatus.FORBIDDEN.value if client_error_in(e) is not None: return HTTPStatus.BAD_REQUEST.value if isinstance(e, SAMBrokerError) and e.__cause__ is None: return HTTPStatus.BAD_REQUEST.value return HTTPStatus.INTERNAL_SERVER_ERROR.value
[docs] def session_csrf_failure(request: Request) -> Optional[str]: """ Explain why a signed-in browser session failed authentication, if it was the CSRF check. DRF's ``SessionAuthentication`` rejects a session request without a valid CSRF token, and then treats it as anonymous, so the view sees only ``NotAuthenticated``. DRF also replaces the Django request's user with ``AnonymousUser``, so the session itself is the evidence: if it holds a signed-in user's id, the user was signed in, and the CSRF check is what failed. :param request: The DRF request that failed authentication. :returns: ``CSRF cookie not set.`` when the browser sent no ``csrftoken`` cookie, e.g. because it expired (issue #885); ``CSRF token missing or incorrect.`` when it sent one; or None if the session isn't signed in, so that the failure is not about CSRF. """ session = getattr(request._request, "session", None) # pylint: disable=protected-access if session is None or not session.get(SESSION_KEY): return None if settings.CSRF_COOKIE_NAME not in request.COOKIES: return "CSRF cookie not set." return "CSRF token missing or incorrect."
[docs] def describe_exception(e: BaseException, status: int) -> Optional[str]: """ The error description that is returned to the client, or None for the exception's own message. A 500 is a bug, so its description asks for a bug report. A client error describes what the client did wrong, including the validation error that caused it, if any. """ client_error = client_error_in(e) if isinstance(e, (PydanticValidationError, DjangoValidationError)): description = format_validation_error(e) elif client_error is not None and client_error is not e: description = f"{e}: {format_validation_error(client_error)}" elif client_error is not None or status == HTTPStatus.INTERNAL_SERVER_ERROR.value: description = str(e) else: return None if status == HTTPStatus.INTERNAL_SERVER_ERROR.value: description = f"{type(e)}: {BUG_REPORT} {description}" return description
[docs] class CliBaseApiView(APIView, SmarterRequestMixin): """ Base class for all Smarter API v1 command-line interface (CLI) views. This class provides common functionality for all `/api/v1/cli` endpoints, including: - Authentication using either Knox TokenAuthentication or Django SessionAuthentication. - Initialization of the :class:`AbstractBroker` instance from the request's manifest. - Resolution of the manifest kind and broker for the YAML manifest document. - Setting the user profile for the request. The base class is responsible for as much request "housekeeping" as possible, so that child views can focus on business logic. The following attributes are set up and managed: Notes ----- - The base class is designed to minimize boilerplate in child views. - Manifest parsing and broker instantiation are implemented lazily. - Authentication is enforced by default, but can be bypassed for internal API requests. Examples -------- Example URL with a manifest name: ``/api/v1/cli/describe/llm-client/<str:name>/`` Example command extraction: If the URL path is ``/api/v1/cli/apply/``, then the command will be :attr:`SmarterJournalCliCommands.APPLY`. """ permission_classes: tuple[type[BasePermission], ...] = (SmarterAuthenticatedPermissionClass,) authentication_classes: tuple[type[BaseAuthentication], ...] = (SmarterTokenAuthentication, SessionAuthentication)
[docs] def get_permissions(self): """ Do not require authentication for OPTIONS requests. OPTIONS requests are used both for DRF's own metadata introspection and, more importantly, as CORS preflight probes issued by browsers. Preflight requests never carry credentials (no cookies, no Authorization header), so if CORS middleware doesn't intercept them first (e.g. a misconfigured/disallowed origin, or the middleware being disabled), enforcing authentication here causes the preflight itself to fail with a 401. That, in turn, makes the browser abort the real (authenticated) request before it's ever sent, which looks like "I'm logged in but I still get an authentication error". """ if getattr(self, "request", None) is not None and self.request.method == "OPTIONS": return [] return super().get_permissions()
_BrokerClass: Optional[Type[AbstractBroker]] = None _broker: Optional[AbstractBroker] = None _manifest_data: Optional[Union[SmarterDictType, str]] = None """The manifest's data, or the raw JSON body until :attr:`manifest_data` parses it.""" _manifest_kind: Optional[str] = None _manifest_kind_url_parsed: bool = False _manifest_name: Optional[str] = None _prompt: Optional[str] = None
[docs] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # extract user, account, user_profile, and request from kwargs # in practice it is highly unlikely that these will be passed in # via kwargs, since DRF begins the request lifecycle by calling # setup() and dispatch(), but we include them here for completeness # as well as to document the expected parameters. user = kwargs.pop("user", None) or next((arg for arg in args if isinstance(arg, User)), None) account = kwargs.pop("account", None) or next((arg for arg in args if isinstance(arg, Account)), None) user_profile = kwargs.pop("user_profile", None) or next( (arg for arg in args if isinstance(arg, UserProfile)), None ) request = kwargs.pop("request", None) or next( (arg for arg in args if isinstance(arg, (Request, HttpRequest, ASGIRequest))), None ) SmarterRequestMixin.__init__( self, request=request, user=user, account=account, user_profile=user_profile, *args, **kwargs )
@property def formatted_class_name(self) -> str: """ Returns the class name in a formatted string along with the name of this mixin. :return: Formatted class name string :rtype: str """ parent_class = super().formatted_class_name this_class = f".{CliBaseApiView.__name__}[][{id(self)}]" return f"{parent_class}{self.formatted_text(this_class)}" @property def BrokerClass(self) -> Type[AbstractBroker]: """ Get the broker class for the manifest kind. This is used to instantiate a broker for the manifest kind. :return: Broker class for the manifest kind :rtype: Type[AbstractBroker] """ if not self._BrokerClass: if self.manifest_kind: self._BrokerClass = Brokers.get_broker(self.manifest_kind) logger.debug( "set to: %s", self._BrokerClass.__name__ if self._BrokerClass else "<None>", ) if not self._BrokerClass: raise APIV1CLIViewBadRequestError( f"Could not find broker for {self.manifest_kind or '<-- Missing -->'} manifest." ) # a kind whose SAM app is disabled, e.g. with SMARTER_APP_GUARDRAIL_ENABLE=false, has no broker. if self.manifest_kind: raise_if_kind_disabled(self.manifest_kind) return self._BrokerClass @property def broker(self) -> Optional[AbstractBroker]: """ Use a loader to try to instantiate a broker. A broker is a class that implements the broker service pattern. It provides a service interface that 'brokers' the http request for the underlying object that provides the object-specific service (create, update, get, delete, etc). :return: Broker instance for the manifest kind :rtype: Optional[AbstractBroker] """ if not self._broker: BrokerClass = self.BrokerClass try: self._broker = BrokerClass( request=self.smarter_request, user=self.user, account=self.user_profile.cached_account if self.user_profile else None, user_profile=self.user_profile, api_version=SMARTER_API_VERSION, name=self.manifest_name, kind=self.manifest_kind, manifest=self.manifest_data, ) if self._broker: logger.debug( "broker %s %s is instantiated and ready.", self._broker.kind, self._broker.name, ) else: logger.debug( "broker %s %s is instantiated but is not in a ready state.", self._broker.kind, self._broker.name, ) return self._broker except APIV1CLIViewError as e: logger.error( "failed to instantiate broker: %s", e, exc_info=True, ) except CLIENT_ERRORS as e: # the manifest is not valid, e.g. a Pydantic validation error. This is the # client's error, which must be returned to the client rather than swallowed. logger.warning( "the %s manifest is not valid: %s", self.manifest_kind, e, ) raise # pylint: disable=broad-except except Exception as e: logger.error( "unexpected error instantiating broker: %s: %s", type(e), e, exc_info=True, ) return self._broker @property def manifest_data(self) -> Optional[SmarterDictType]: """ The raw manifest data from the request body. The manifest data is a json object which needs to be rendered into a Pydantic model. The Pydantic model is then used to instantiate a broker for the manifest kind. :return: Raw manifest data as a json object :rtype: Optional[dict] """ data = self._manifest_data # belt & suspenders: ensure that the manifest data is a json object. if isinstance(data, str) and data: parsed: SmarterDictType = json.loads(data) self._manifest_data = parsed return parsed if isinstance(data, str): return None return data @property def manifest_name(self) -> Optional[str]: """ The name of the manifest. The manifest name is used to identify the resource within a Kind. For example, the manifest name for a LLMClient resource is the name of the llmclient. The manifest name is used to identify the resource within a Kind. The name can be passed from inside the raw manifest data, or it can be passed as part of a url path. Example url path with a name: /api/v1/cli/describe/llm-client/<str:name>/ :return: The name of the manifest :rtype: Optional[str] """ if not self._manifest_name and self.manifest_data: metadata = self.manifest_data.get("metadata") if isinstance(metadata, dict): self._manifest_name = metadata.get("name") return self._manifest_name @property def manifest_kind(self) -> Optional[str]: """ The kind of the manifest. The manifest kind is used to identify the type of resource that the manifest is describing. The kind is used to identify the broker that will be used to broker the http request for the resource. :return: The kind of the manifest :rtype: Optional[str] """ if not self._manifest_kind and self.manifest_data: self._manifest_kind = str(self.manifest_data.get("kind", None)) # if we still don't have a manifest kind, then we should # analyze the url path to determine the manifest kind. # urls: # - http://testserver/api/v1/cli/logs/LLMClient/?name=TestLLMClient # - http://testserver/api/v1/cli/prompt/config/TestLLMClient/ if not self._manifest_kind and not self._manifest_kind_url_parsed: url = self.url # from_url() raises TypeError on None, so a request without a url has no kind. # It logs a warning whenever the url has no kind, so it is called once per request. if url is not None: self._manifest_kind = SAMKinds.from_url(url) self._manifest_kind_url_parsed = True if self._manifest_kind: logger.warning( "setting manifest kind to %s from analysis of url %s", self._manifest_kind, self.smarter_request, ) # may or may not have a manifest kind at this point. # anti examples: # - http://testserver/api/v1/cli/whoami/ # - http://testserver/api/v1/cli/apply/ return self._manifest_kind
[docs] @cached_property def command(self) -> SmarterJournalCliCommands: """ Translate the request route into a SmarterJournalCliCommands enum instance. It is cached until the request changes: setting ``smarter_request`` clears it. For example, if the route is '/api/v1/cli/apply/', then the corresponding command will be SmarterJournalCliCommands.APPLY. url: - http://testserver/api/v1/cli/logs/LLMClient/?name=TestLLMClient - http://testserver/api/v1/cli/apply :return: SmarterJournalCliCommands enum instance :rtype: SmarterJournalCliCommands """ match = CLI_COMMAND_PATTERN.search(self.url or "") if match: _command = match.group(1) _command = self.to_snake_case(_command) return SmarterJournalCliCommands(_command) raise APIV1CLIViewError(f"Could not determine command from url: {self.url}")
@property def cba_ready(self) -> bool: """ Check if the CliBaseApiView is ready. :return: True if the view is ready, False otherwise :rtype: bool """ return True @property def is_cli_base_api_view_ready_state(self) -> str: """ Get a string representation of the readiness state of the CliBaseApiView. :return: Readiness state as a string :rtype: str """ if self.cba_ready: return self.formatted_state_ready return self.formatted_state_not_ready @property def ready(self) -> bool: """ Check if the CliBaseApiView and SmarterRequestMixin are ready. :return: True if both the view and mixin are ready, False otherwise :rtype: bool """ if not self.srm_ready: logger.debug("returning False because SmarterRequestMixin is not ready") return False return self.cba_ready
[docs] def setup(self, request: HttpRequest, *args, **kwargs): """ Setup the view. This is called by Django before dispatch() and is used to set up the view for the request. the request is not yet authenticated. :param request: The HTTP request object :type request: HttpRequest """ super().setup(request, *args, **kwargs) SmarterRequestMixin.smarter_request_setup(self, request=request, *args, **kwargs) # note: setup() is the earliest point in the request lifecycle where we can # send signals. api_request_initiated.send(sender=self.__class__, instance=self, request=request)
[docs] def initial(self, request: Request, *args, **kwargs): """ Perform view initialization after setup and before dispatch. This method is called by Django REST Framework (DRF) after the `setup()` method but before the `dispatch()` method. It is the earliest point in the DRF view lifecycle where the request object is fully available and can be used to complete any additional initialization required by the view. In DRF, the `initial()` method is responsible for performing tasks such as: - Completing any remaining setup that depends on the request object. - Enforcing authentication and permission checks. - Raising appropriate exceptions if the request is not valid or not authenticated. In this implementation, `initial()` ensures that the `SmarterRequestMixin` and any related mixins are fully initialized with the request object. It also performs authentication checks, sets up user and account context, and prepares manifest data or prompt text for downstream processing. If authentication fails, it raises a custom error with detailed logging. Parameters ---------- request : Request The HTTP request object provided by DRF. This object contains all request data, headers, user information, and other context needed for processing the API call. *args Additional positional arguments passed to the view. **kwargs Additional keyword arguments passed to the view, often including URL parameters extracted by the router. Raises ------ SmarterAPIV1CLIViewErrorNotAuthenticated If the request is not authenticated and is not an internal API request, this exception is raised to indicate authentication failure. SmarterConfigurationError If the request object is not properly set up in the view, this error is raised to indicate a misconfiguration. Notes ----- - This method is a critical part of the DRF request lifecycle, ensuring that all necessary context and validation is in place before the main handler methods (`get`, `post`, etc.) are called. - Manifest parsing and broker instantiation are deferred (lazy) and only performed when needed by child views. - The method also logs key events and warnings for observability. See Also -------- https://www.django-rest-framework.org/api-guide/views/#view-initialization DRF documentation on the view initialization process. """ # there are cases where the requests lifecycle begins with a ASGIRequest that is # eventually wrapped into a DRF Request object. So we need to ensure that # the smarter_request is always set to the DRF Request object. try: self.smarter_request = request except Exception as e: logger.error( "error setting smarter_request: %s: %s", type(e), e, exc_info=True, ) raise SmarterConfigurationError( f"{self.formatted_class_name} error during initialization: could not set request object." ) from e # Check if the request is authenticated. If not, raise an # authentication error. see SmarterTokenAuthentication for details # on how the token is validated. # The token is passed in the Authorization header as a Bearer token # of the form: 'Authorization: Token YOUR-64-CHARACTER-SMARTER-API-KEY' try: super().initial(request, *args, **kwargs) # super().initial() just ran DRF's real authentication pipeline # (SmarterTokenAuthentication and/or SessionAuthentication), which # is the only path that resolves session-based auth. The earlier # `self.smarter_request = request` assignment above ran before # that, when `request.user` was still anonymous, so it could only # pick up token-based auth via self.authenticate() (see its # docstring: it only ever tries self.api_token). Re-assign now so # SmarterRequestMixin/AccountMixin (self.user, self.user_profile, # self.account) reflect the now-authenticated request.user, # rather than staying stuck on the pre-auth Anonymous state for # session-authenticated requests. When the mixin already has the # request's user, e.g. from token auth, nothing would change, and # re-assigning would only rebuild every cached property. if self.user is None or self.user != request.user: self.smarter_request = request except NotAuthenticated as e: logger.warning( "authenticated failed for url: %s, user: %s, self.user: %s is_authenticated: %s", request, request.user.username if request.user else "Anonymous", # type: ignore[assignment] self.user_profile, is_authenticated_request(request), ) if self.is_internal_api_request(request): logger.debug( "internal api request. Skipping authentication: %s", request, ) else: # regardless of the authentication error, we still need to # initialize the SmarterRequestMixin so that we can # access the request object, headers, url, etc. auth_header = request.headers.get("Authorization") csrf_failure = session_csrf_failure(request) if not auth_header and csrf_failure: # a signed-in browser session, e.g. a web console React app, that failed only # the CSRF check: say so, rather than blame a missing api key. logger.warning( "the session is signed in, but the request failed the CSRF check: %s", csrf_failure, ) raise SmarterAPIV1CLIViewErrorNotAuthenticated( f"Smarter api v1 command-line interface error: {csrf_failure} Reload the page and try again." ) from e # a rejected request is the client's error, answered with 403: a WARNING, # and the guidance for the client goes in the response, not the log. if auth_header: logger.warning( "Authorization header '%s' seems to be invalid. The following exception was raised: %s", mask_string(auth_header), e, ) raise SmarterAPIV1CLIViewErrorNotAuthenticated( "Smarter api v1 command-line interface error: authentication failed" ) from e logger.warning( "the request has no Authorization header: %s", e, ) raise SmarterAPIV1CLIViewErrorNotAuthenticated( "Smarter api v1 command-line interface error: authentication failed. The request has no " "Authorization header. Add one of the form 'Authorization: Token <your Smarter API key>'." ) from e except Exception as e: logger.error( "unexpected error during authentication: %s: %s", type(e), e, exc_info=True, ) raise SmarterAPIV1CLIViewErrorNotAuthenticated( "Smarter api v1 command-line interface error: authentication failed due to an unexpected error" ) from e if self.smarter_request is None: raise SmarterConfigurationError( f"{self.formatted_class_name}.smarter_request request object is not set. This should not happen." ) # Manifest parsing and broker instantiation are lazy implementations. # So for now, we'll only set the private class variable _manifest_data # from the request body, and then we'll leave it to the child views to # decide if/when to actually parse the manifest and instantiate the broker. # if the command is 'prompt', then the raw prompt text # or the encoded file attachment data will be in the request body. # otherwise, the request body should contain manifest text. if self.command == SmarterJournalCliCommands.PROMPT: self._prompt = self.data if isinstance(self.data, str) else None self._manifest_kind = SAMKinds.PROMPT.value else: self._manifest_data = self.data if isinstance(self.data, dict) else None # Parse the query string parameters from the request into a dictionary. # This is used to pass additional parameters to the child view's post method. self._manifest_name = self.params.get("name", None) if self.params else kwargs.get("name", None) # DRF ignores what initial() returns, so an unsupported kind is raised, and dispatch() # answers it with a 400. The url's kind is unsupported, so there is none to find in it. kind = kwargs.get("kind", None) if kind: self._manifest_kind = Brokers.get_broker_kind(kind) if not self._manifest_kind: self._manifest_kind_url_parsed = True raise SAMBadRequestError(f"Unsupported manifest kind: {kind}. should be one of {SAMKinds.all()}") raise_if_kind_disabled(self._manifest_kind)
# pylint: disable=too-many-return-statements,too-many-branches
[docs] def dispatch(self, request: HttpRequest, *args, **kwargs): """ Dispatch the request to the appropriate handler method. This method is a core part of the Django REST Framework (DRF) view lifecycle. It is called automatically by DRF when an HTTP request is received and is responsible for routing the request to the correct handler method (such as ``get()``, ``post()``, ``put()``, etc.) based on the HTTP method of the request. In DRF, the ``dispatch()`` method performs several critical functions: - It determines which handler method should process the request. - It manages the execution of middleware and mixins. - It handles exceptions that may be raised during request processing. - It returns a DRF ``Response`` object to the client. In this base class implementation, the primary objective is to provide robust exception handling for all CLI API views. The method attempts to map known exceptions to appropriate HTTP status codes and, where possible, adds additional context to error messages. This ensures that clients receive meaningful and actionable error responses, even if an unexpected error occurs. Ideally, child views should handle their own exceptions and return a ``SmarterJournaledJsonErrorResponse`` or similar structured response. However, this base implementation acts as a safety net, catching any unhandled exceptions and returning a generic error message along with a bug report URL for further trouble shooting. Signals are emitted to indicate the completion or failure of API requests, which can be used for logging, auditing, or triggering other side effects. Parameters ---------- request : HttpRequest The Django request, which DRF wraps in a ``Request`` inside ``dispatch()``. *args Additional positional arguments passed to the view. **kwargs Additional keyword arguments passed to the view, often including URL parameters. Returns ------- Response A DRF ``Response`` object representing the result of the request, or an error response if an exception was raised. Notes ----- - This method is a critical integration point with DRF's request/response lifecycle. - Exception mapping is comprehensive, covering both application-specific and DRF exceptions. - Unhandled exceptions are logged and reported with a generic message and bug report instructions. - Signals are used for observability and integration with other parts of the application. See Also -------- https://www.django-rest-framework.org/api-guide/views/#view-methods DRF documentation on view methods and the dispatch process. """ if self.is_internal_api_request(request): setattr(request, "_dont_enforce_csrf_checks", True) # setup() has usually set this same request already. Setting it again would only # rebuild every cached property. if self.smarter_request is not request: self.smarter_request = request response = None try: response = super().dispatch(request, *args, **kwargs) api_request_completed.send(sender=self.__class__, instance=self, request=request, response=response) return response # pylint: disable=broad-except except Exception as e: status = http_status_for_exception(e) description = describe_exception(e, status) # its receiver logs the failure, with the traceback of a 500: it runs inside this except block. api_request_failed.send( sender=self.__class__, instance=self, request=request, response=response, exception=e, status=status, description=description, ) return SmarterJournaledJsonErrorResponse( request=request, thing=self.manifest_kind, command=self.command, e=e, status=status, stack_trace=traceback.format_exc(), description=description, )