# pylint: disable=W0718
"""PluginMeta views."""
from http import HTTPStatus
from typing import Optional
from urllib.parse import urljoin
import yaml
from django.core.handlers.asgi import ASGIRequest
from django.http import HttpRequest, HttpResponseRedirect, JsonResponse
from django.shortcuts import redirect
from rest_framework.parsers import FileUploadParser
from smarter.apps.account.models import UserProfile, get_resolved_user
from smarter.apps.llmtool.contract.models import PluginApiPluginMeta
from smarter.apps.llmtool.manifest.controller import (
PLUGIN_MAP,
SAM_MAP,
PluginController,
SAMPluginControllerError,
)
from smarter.apps.llmtool.models import PluginMeta
from smarter.apps.llmtool.plugin.base import PluginBase, SmarterPluginError
from smarter.apps.llmtool.serializers import PluginMetaSerializer
from smarter.common.conf import smarter_settings
from smarter.common.exceptions import SmarterValueError
from smarter.lib import json, logging
from smarter.lib.django import waffle
from smarter.lib.django.http.client_errors import (
CLIENT_ERROR_TYPES,
REQUEST_DATA_ERROR_TYPES,
client_error_message,
)
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.drf.views.contract import ContractListMixin
from smarter.lib.drf.views.token_authentication_helpers import (
SmarterAuthenticatedAPIView,
SmarterAuthenticatedListAPIView,
)
from smarter.lib.typing import SmarterDictType
logger = logging.getSmarterLogger(__name__)
[docs]
class PluginView(SmarterAuthenticatedAPIView):
"""Plugin view for smarter api."""
[docs]
def get(self, request: ASGIRequest, plugin_id):
"""
Return a plugin's manifest, if the ``ALLOW_API_GET`` waffle switch is active.
:param request: The request.
:param plugin_id: The plugin's id, from the url.
:returns: The response of :func:`get_plugin`, or 405 if the switch is inactive.
"""
if not waffle.switch_is_active(SmarterWaffleSwitches.ALLOW_API_GET):
logger.error(
"is not allowed because %s switch is inactive.",
SmarterWaffleSwitches.ALLOW_API_GET,
)
return JsonResponse(
{"detail": "GET method is not allowed for this endpoint."}, status=HTTPStatus.METHOD_NOT_ALLOWED
)
return get_plugin(request, plugin_id)
[docs]
def put(self, request: ASGIRequest, plugin_id: Optional[int] = None):
"""
Update the plugin with the given id from the manifest in the request body, or create one if no id is given.
:param request: The request, whose body is the plugin's manifest.
:param plugin_id: The plugin's id, from the url.
:returns: A redirect to the plugin, or an error response.
"""
if plugin_id is not None:
return update_plugin(request, plugin_id)
return create_plugin(request)
[docs]
def post(self, request: ASGIRequest, plugin_id: Optional[int] = None):
"""
Update the plugin with the given id from the manifest in the request body, or create one if no id is given.
:param request: The request, whose body is the plugin's manifest.
:param plugin_id: The plugin's id, from the url.
:returns: A redirect to the plugin, or an error response.
"""
if plugin_id is not None:
return update_plugin(request, plugin_id)
return create_plugin(request)
[docs]
def patch(self, request: ASGIRequest, plugin_id: Optional[int] = None):
"""
Update a plugin from the manifest in the request body.
:param request: The request, whose body is the plugin's manifest.
:param plugin_id: The plugin's id, from the url, or None to find the plugin by the manifest's name.
:returns: The response of :func:`update_plugin`.
"""
return update_plugin(request, plugin_id)
[docs]
def delete(self, request: ASGIRequest, plugin_id):
"""
Delete a plugin.
:param request: The request.
:param plugin_id: The plugin's id, from the url.
:returns: The response of :func:`delete_plugin`.
"""
return delete_plugin(request, plugin_id)
[docs]
class PluginCloneView(SmarterAuthenticatedAPIView):
"""Plugin clone view for smarter api."""
[docs]
def post(self, request: ASGIRequest, plugin_id, new_name):
"""
Clone a plugin under a new name, and redirect to the clone.
:param request: The request.
:param plugin_id: The id of the plugin to clone, from the url.
:param new_name: The clone's name, from the url.
:returns: A redirect to ``/plugins/<new id>/``, or an error response.
"""
user = get_resolved_user(request.user)
if not user:
return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED)
user_profile = UserProfile.get_cached_object(user=user) # type: ignore
plugin_controller = PluginController(
user_profile=user_profile,
plugin_meta=PluginMeta.get_cached_object(pk=plugin_id), # type: ignore[attr-defined]
)
if not plugin_controller or not plugin_controller.plugin:
return JsonResponse(
{
"error": f"PluginController could not be created for plugin_id: {plugin_id}, user_profile: {user_profile}"
},
status=HTTPStatus.BAD_REQUEST,
)
plugin = plugin_controller.plugin
new_id = plugin.clone(new_name)
return redirect("/plugins/" + str(new_id) + "/")
[docs]
class PluginListView(ContractListMixin, SmarterAuthenticatedListAPIView):
"""Plugins list view for smarter api."""
serializer_class = PluginMetaSerializer
contract_model = PluginApiPluginMeta
[docs]
def item(self, row):
"""A plugin of the response, whose ``canDelete`` is the requesting user's."""
return PluginApiPluginMeta.from_model(row, self.request.user).model_dump(mode="json")
[docs]
def get_queryset(self):
"""Return the plugins that the requesting user has ownership permission for, newest first."""
plugins = PluginMeta.objects.with_ownership_permission_for(user=self.user_profile.user).order_by("-created_at") # type: ignore
return plugins
[docs]
class PluginUploadView(SmarterAuthenticatedAPIView):
"""Plugin view for smarter api."""
parser_class = (FileUploadParser,)
[docs]
@staticmethod
def parse_yaml_file(data):
"""
Parse a plugin manifest, as YAML or else JSON.
:param data: The manifest: a YAML or JSON string or bytes, or an already parsed dict or list,
which is returned as is.
:returns: The parsed manifest.
:raises SmarterValueError: If the data is neither YAML nor JSON.
"""
if type(data) in [dict, list]:
return data
if isinstance(data, str):
data = data.encode("utf-8")
try:
return yaml.safe_load(data)
except yaml.YAMLError:
pass
try:
return json.loads(data)
except json.JSONDecodeError:
pass
raise SmarterValueError("Invalid data format: expected JSON or YAML.")
def _create(self, request: ASGIRequest):
data = self.parse_yaml_file(data=request.body.decode("utf-8"))
return create_plugin(request=request, data=data)
[docs]
def put(self, request: ASGIRequest):
"""
Create a plugin from the YAML or JSON manifest in the request body.
:param request: The request.
:returns: The response of :func:`create_plugin`.
"""
return self._create(request)
[docs]
def post(self, request: ASGIRequest):
"""
Create a plugin from the YAML or JSON manifest in the request body.
:param request: The request.
:returns: The response of :func:`create_plugin`.
"""
return self._create(request)
# -----------------------------------------------------------------------
# handlers for plugins
# -----------------------------------------------------------------------
[docs]
def get_plugin(request, plugin_id):
"""
Get a plugin's manifest, by id, if the user may read the plugin.
A plugin that the user may not read is not found, so that the plugins of other accounts are not
disclosed. Errors are Django REST framework's ``{"detail": ...}``.
"""
plugin: Optional[PluginBase] = None
try:
user_profile = UserProfile.get_cached_object(user=request.user)
except UserProfile.DoesNotExist:
return JsonResponse({"detail": "User not found"}, status=HTTPStatus.NOT_FOUND)
readable = PluginMeta.objects.with_read_permission_for(user=request.user) # type: ignore[attr-defined]
if not readable.filter(pk=plugin_id).exists():
return JsonResponse({"detail": "Plugin not found"}, status=HTTPStatus.NOT_FOUND)
try:
plugin_controller = PluginController(
user_profile=user_profile,
plugin_meta=PluginMeta.get_cached_object(pk=plugin_id), # type: ignore[attr-defined]
)
if not plugin_controller or not plugin_controller.plugin:
raise SmarterPluginError(
f"PluginController could not be created for plugin_id: {plugin_id}, user_profile: {user_profile}"
)
plugin = plugin_controller.plugin
except PluginMeta.DoesNotExist:
return JsonResponse({"detail": "Plugin not found"}, status=HTTPStatus.NOT_FOUND)
except CLIENT_ERROR_TYPES as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"detail": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"detail": "An unknown error occurred while loading the plugin."}, status=HTTPStatus.INTERNAL_SERVER_ERROR
)
if plugin.ready:
return JsonResponse(plugin.to_json(), status=HTTPStatus.OK)
return JsonResponse({"detail": "Internal plugin error."}, status=HTTPStatus.INTERNAL_SERVER_ERROR)
[docs]
def create_plugin(request, data: Optional[SmarterDictType] = None):
"""
Create a plugin from a json representation in the body of the request.
:param request: The request. Its user's profile owns the new plugin.
:param data: The plugin's manifest. If not given, the request's parsed body is used.
:returns: A redirect to the new plugin in the plugins api, or an error response.
"""
try:
user_profile = UserProfile.get_cached_object(user=request.user)
except UserProfile.DoesNotExist:
return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED)
# reading the manifest, and building the plugin from it, both handle the client's data.
try:
if not data:
data = getattr(request, "data", None)
if not isinstance(data, dict):
return JsonResponse(
{"error": f"Invalid request data. Expected a JSON dict in request body but received {type(data)}"},
status=HTTPStatus.BAD_REQUEST,
)
if "user_profile" not in data:
data["user_profile"] = user_profile
plugin_controller = PluginController(
user_profile=user_profile,
manifest=data, # type: ignore[arg-type]
)
if not plugin_controller or not plugin_controller.plugin:
# the controller found no plugin for a valid manifest: a server error, which the
# catch-all logs and answers with a 500.
raise SmarterPluginError("A plugin could not be created from the manifest.")
plugin = plugin_controller.plugin
# the manifest is the client's: pydantic's ValidationError is a ValueError, and
# SAMPluginControllerError refuses e.g. a kind that isn't a plugin's.
except REQUEST_DATA_ERROR_TYPES + (SAMPluginControllerError,) as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while creating the plugin."}, status=HTTPStatus.INTERNAL_SERVER_ERROR
)
base_url = f"{smarter_settings.api_schema}://{request.get_host()}/"
plugins_api_url = urljoin(base_url, "/api/v1/plugins/")
return HttpResponseRedirect(plugins_api_url + str(plugin.id) + "/")
[docs]
def update_plugin(request: HttpRequest, plugin_id: Optional[int] = None):
"""
Update a plugin from a json representation in the body of the request.
:param plugin_id: The id of the plugin to update, from the url. If provided, it must
be the plugin that the manifest names.
"""
user = get_resolved_user(request.user)
if not user:
return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED)
try:
user_profile = UserProfile.get_cached_object(user=user) # type: ignore
except UserProfile.DoesNotExist:
return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED)
if not user_profile:
return JsonResponse({"error": "User profile not found"}, status=HTTPStatus.UNAUTHORIZED)
# everything from here on reads the client's manifest, or builds the plugin from it.
try:
# a DRF request has already parsed its body; a plain django request has not.
data = getattr(request, "data", None)
if data is None:
data = PluginUploadView.parse_yaml_file(request.body.decode("utf-8"))
if not isinstance(data, dict) or not data:
return JsonResponse(
{"error": f"Invalid request data. Expected a JSON dict in request body but received {type(data)}"},
status=HTTPStatus.BAD_REQUEST,
)
data = dict(data)
kind = data.get("kind")
if kind not in PLUGIN_MAP:
return JsonResponse(
{"error": f"Invalid manifest kind {kind}. Expected one of: {list(PLUGIN_MAP)}"},
status=HTTPStatus.BAD_REQUEST,
)
metadata = data.get("metadata") or {}
manifest_name = metadata.get("name")
if plugin_id is not None:
try:
plugin_meta = PluginMeta.get_cached_object(pk=plugin_id) # type: ignore[attr-defined]
except PluginMeta.DoesNotExist:
plugin_meta = None
if not plugin_meta:
return JsonResponse({"error": "Plugin not found"}, status=HTTPStatus.NOT_FOUND)
if manifest_name != plugin_meta.name:
return JsonResponse(
{"error": f"Manifest name {manifest_name} does not match plugin {plugin_id}: {plugin_meta.name}"},
status=HTTPStatus.BAD_REQUEST,
)
elif not PluginMeta.objects.filter(name=manifest_name, user_profile=user_profile).exists():
return JsonResponse({"error": "Plugin not found"}, status=HTTPStatus.NOT_FOUND)
manifest = SAM_MAP[kind](**data) # type: ignore[arg-type]
# a PluginController prefers the stored PluginMeta to the manifest, so
# the plugin is instantiated from the manifest, which updates it.
plugin = PLUGIN_MAP[kind](manifest=manifest, user_profile=user_profile) # type: ignore[call-arg]
if not plugin or not plugin.ready:
raise SmarterPluginError(f"Plugin {manifest_name} is not ready after update.")
# the manifest is the client's: pydantic's ValidationError is a ValueError, and
# SAMPluginControllerError refuses e.g. a kind that isn't a plugin's.
except REQUEST_DATA_ERROR_TYPES + (SAMPluginControllerError,) as e:
message = client_error_message(e, "The request data is not valid.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while updating the plugin."}, status=HTTPStatus.INTERNAL_SERVER_ERROR
)
return HttpResponseRedirect(request.path_info)
[docs]
def delete_plugin(request, plugin_id):
"""
Delete a plugin by id.
:param request: The request.
:param plugin_id: The id of the plugin to delete.
:returns: A redirect to the plugins list, or an error response.
"""
try:
user_profile = UserProfile.get_cached_object(user=request.user)
except UserProfile.DoesNotExist:
return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED)
try:
plugin_controller = PluginController(
user_profile=user_profile,
plugin_meta=PluginMeta.get_cached_object(pk=plugin_id), # type: ignore[attr-defined]
)
if not plugin_controller or not plugin_controller.plugin:
raise SmarterPluginError(
f"PluginController could not be created for plugin_id: {plugin_id}, user_profile: {user_profile}"
)
plugin = plugin_controller.plugin
except PluginMeta.DoesNotExist:
return JsonResponse({"error": "Plugin not found"}, status=HTTPStatus.NOT_FOUND)
# pylint: disable=broad-except
except Exception:
logger.error("could not load the plugin", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while loading the plugin."}, status=HTTPStatus.INTERNAL_SERVER_ERROR
)
try:
plugin.delete()
except CLIENT_ERROR_TYPES as e:
logger.warning("refused: %s", e)
message = client_error_message(e, "The resource could not be deleted.")
return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST)
# pylint: disable=broad-except
except Exception:
logger.error("failed", exc_info=True)
return JsonResponse(
{"error": "An unknown error occurred while deleting the plugin."}, status=HTTPStatus.INTERNAL_SERVER_ERROR
)
plugins_path = request.path_info.rsplit("/", 2)[0]
return HttpResponseRedirect(plugins_path)