Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

ETL or Task Pipeline can be triggered by APIs (#556)

ali089055b62471
diff --git a/backend/api/api_key_validator.py b/backend/api/api_key_validator.py
new file mode 100644
index 000000000..5883b2e11
--- /dev/null
+++ b/backend/api/api_key_validator.py
@@ -0,0 +1,65 @@
+import logging
+from functools import wraps
+from typing import Any
+
+from api.exceptions import Forbidden
+from django_tenants.utils import get_tenant_model, tenant_context
+from rest_framework.request import Request
+
+logger = logging.getLogger(__name__)
+
+
+class BaseAPIKeyValidator:
+ @classmethod
+ def validate_api_key(cls, func: Any) -> Any:
+ """Decorator that validates the API key.
+
+ Sample header:
+ Authorization: Bearer 123e4567-e89b-12d3-a456-426614174001
+ Args:
+ func (Any): Function to wrap for validation
+ """
+
+ @wraps(func)
+ def wrapper(self: Any, request: Request, *args: Any, **kwargs: Any) -> Any:
+ """Wrapper to validate the inputs and key.
+
+ Args:
+ request (Request): Request context
+
+ Raises:
+ Forbidden: _description_
+ APINotFound: _description_
+
+ Returns:
+ Any: _description_
+ """
+ authorization_header = request.headers.get("Authorization")
+ api_key = None
+ if authorization_header and authorization_header.startswith("Bearer "):
+ api_key = authorization_header.split(" ")[1]
+ if not api_key:
+ raise Forbidden("Missing api key")
+ org_name = kwargs.get("org_name") or request.data.get("org_name")
+ cls.validate_parameters(request, **kwargs)
+ tenant = get_tenant_model().objects.get(schema_name=org_name)
+ with tenant_context(tenant):
+ # Call the method to handle the specific validation and processing
+ return cls.validate_and_process(
+ self, request, func, *args, **kwargs, api_key=api_key
+ )
+
+ return wrapper
+
+ @staticmethod
+ def validate_parameters(request: Request, **kwargs: Any) -> None:
+ """Validate specific parameters required by subclasses."""
+ pass
+
+ @staticmethod
+ def validate_and_process(
+ self: Any, request: Request, func: Any, api_key: str, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Process and validate API key with specific logic required by
+ subclasses."""
+ pass
diff --git a/backend/api/api_key_views.py b/backend/api/api_key_views.py
index 8f26eab65..020685c60 100644
--- a/backend/api/api_key_views.py
+++ b/backend/api/api_key_views.py
@@ -1,8 +1,12 @@
+from typing import Optional
+
from api.deployment_helper import DeploymentHelper
-from api.exceptions import APINotFound
+from api.exceptions import APINotFound, PathVariablesNotFound
from api.key_helper import KeyHelper
from api.models import APIKey
from api.serializers import APIKeyListSerializer, APIKeySerializer
+from pipeline.exceptions import PipelineNotFound
+from pipeline.pipeline_processor import PipelineProcessor
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
@@ -18,11 +22,26 @@ class APIKeyViewSet(viewsets.ModelViewSet):
return APIKeySerializer
@action(detail=True, methods=["get"])
- def api_keys(self, request: Request, api_id: str) -> Response:
+ def api_keys(
+ self,
+ request: Request,
+ api_id: Optional[str] = None,
+ pipeline_id: Optional[str] = None,
+ ) -> Response:
"""Custom action to fetch api keys of an api deployment."""
- api = DeploymentHelper.get_api_by_id(api_id=api_id)
- if not api:
- raise APINotFound()
- keys = KeyHelper.list_api_keys_of_api(api_instance=api)
+ if api_id:
+ api = DeploymentHelper.get_api_by_id(api_id=api_id)
+ if not api:
+ raise APINotFound()
+ keys = KeyHelper.list_api_keys_of_api(api_instance=api)
+ elif pipeline_id:
+ pipeline = PipelineProcessor.get_active_pipeline(pipeline_id=pipeline_id)
+ if not pipeline:
+ raise PipelineNotFound()
+ keys = KeyHelper.list_api_keys_of_pipeline(pipeline_instance=pipeline)
+ else:
+ raise PathVariablesNotFound(
+ "Either `api_id` or `pipeline_id` path variable must be provided."
+ )
serializer = self.get_serializer(keys, many=True)
return Response(serializer.data)
diff --git a/backend/api/deployment_helper.py b/backend/api/deployment_helper.py
index 59f7b3b3a..e9831ad7a 100644
--- a/backend/api/deployment_helper.py
+++ b/backend/api/deployment_helper.py
@@ -1,26 +1,22 @@
import logging
import uuid
-from functools import wraps
from typing import Any, Optional
from urllib.parse import urlencode
+from api.api_key_validator import BaseAPIKeyValidator
from api.constants import ApiExecution
from api.exceptions import (
ApiKeyCreateException,
APINotFound,
- Forbidden,
InactiveAPI,
- UnauthorizedKey,
+ InvalidAPIRequest,
)
from api.key_helper import KeyHelper
from api.models import APIDeployment, APIKey
from api.serializers import APIExecutionResponseSerializer
from django.core.files.uploadedfile import UploadedFile
from django.db import connection
-from django_tenants.utils import get_tenant_model, tenant_context
-from rest_framework import status
from rest_framework.request import Request
-from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework.utils.serializer_helpers import ReturnDict
from workflow_manager.endpoint.destination import DestinationConnector
@@ -32,61 +28,24 @@ from workflow_manager.workflow.workflow_helper import WorkflowHelper
logger = logging.getLogger(__name__)
-class DeploymentHelper:
+class DeploymentHelper(BaseAPIKeyValidator):
@staticmethod
- def validate_api_key(func: Any) -> Any:
- """Decorator that validates the API key.
+ def validate_parameters(request: Request, **kwargs: Any) -> None:
+ """Validate api_name for API deployments."""
+ api_name = kwargs.get("api_name") or request.data.get("api_name")
+ if not api_name:
+ raise InvalidAPIRequest("Missing params api_name")
- Sample header:
- Authorization: Bearer 123e4567-e89b-12d3-a456-426614174001
- Args:
- func (Any): Function to wrap for validation
- """
-
- @wraps(func)
- def wrapper(self: Any, request: Request, *args: Any, **kwargs: Any) -> Any:
- """Wrapper to validate the inputs and key.
-
- Args:
- request (Request): Request context
-
- Raises:
- Forbidden: _description_
- APINotFound: _description_
-
- Returns:
- Any: _description_
- """
- try:
- authorization_header = request.headers.get("Authorization")
- api_key = None
- if authorization_header and authorization_header.startswith("Bearer "):
- api_key = authorization_header.split(" ")[1]
- if not api_key:
- raise Forbidden("Missing api key")
- org_name = kwargs.get("org_name") or request.data.get("org_name")
- api_name = kwargs.get("api_name") or request.data.get("api_name")
- if not api_name:
- raise Forbidden("Missing api_name")
- tenant = get_tenant_model().objects.get(schema_name=org_name)
- with tenant_context(tenant):
- api_deployment = DeploymentHelper.get_deployment_by_api_name(
- api_name=api_name
- )
- DeploymentHelper.validate_api(
- api_deployment=api_deployment, api_key=api_key
- )
- kwargs["api"] = api_deployment
- return func(self, request, *args, **kwargs)
- except (UnauthorizedKey, InactiveAPI, APINotFound):
- raise
- except Exception as exception:
- logger.error(f"Exception: {exception}")
- return Response(
- {"error": str(exception)}, status=status.HTTP_403_FORBIDDEN
- )
-
- return wrapper
+ @staticmethod
+ def validate_and_process(
+ self: Any, request: Request, func: Any, api_key: str, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Fetch API deployment and validate API key."""
+ api_name = kwargs.get("api_name") or request.data.get("api_name")
+ api_deployment = DeploymentHelper.get_deployment_by_api_name(api_name=api_name)
+ DeploymentHelper.validate_api(api_deployment=api_deployment, api_key=api_key)
+ kwargs["api"] = api_deployment
+ return func(self, request, *args, **kwargs)
@staticmethod
def validate_api(api_deployment: Optional[APIDeployment], api_key: str) -> None:
@@ -104,7 +63,7 @@ class DeploymentHelper:
raise APINotFound()
if not api_deployment.is_active:
raise InactiveAPI()
- KeyHelper.validate_api_key(api_key=api_key, api_instance=api_deployment)
+ KeyHelper.validate_api_key(api_key=api_key, instance=api_deployment)
@staticmethod
def validate_and_get_workflow(workflow_id: str) -> Workflow:
diff --git a/backend/api/exceptions.py b/backend/api/exceptions.py
index c3a58ff05..f2e4c415e 100644
--- a/backend/api/exceptions.py
+++ b/backend/api/exceptions.py
@@ -3,6 +3,15 @@ from typing import Optional
from rest_framework.exceptions import APIException
+class NotFoundException(APIException):
+ status_code = 404
+ default_detail = "The requested resource was not found."
+
+
+class PathVariablesNotFound(NotFoundException):
+ default_detail = "Path variable must be provided."
+
+
class MandatoryWorkflowId(APIException):
status_code = 400
default_detail = "Workflow ID is mandatory"
@@ -20,8 +29,7 @@ class Forbidden(APIException):
)
-class APINotFound(APIException):
- status_code = 404
+class APINotFound(NotFoundException):
default_detail = "API not found"
@@ -30,8 +38,7 @@ class InvalidAPIRequest(APIException):
default_detail = "Bad request"
-class InactiveAPI(APIException):
- status_code = 404
+class InactiveAPI(NotFoundException):
default_detail = "API not found or Inactive"
diff --git a/backend/api/key_helper.py b/backend/api/key_helper.py
index d65345c15..3db67d9c8 100644
--- a/backend/api/key_helper.py
+++ b/backend/api/key_helper.py
@@ -1,8 +1,10 @@
import logging
+from typing import Union
-from api.exceptions import Forbidden, UnauthorizedKey
+from api.exceptions import UnauthorizedKey
from api.models import APIDeployment, APIKey
from api.serializers import APIKeySerializer
+from pipeline.models import Pipeline
from workflow_manager.workflow.workflow_helper import WorkflowHelper
logger = logging.getLogger(__name__)
@@ -10,24 +12,24 @@ logger = logging.getLogger(__name__)
class KeyHelper:
@staticmethod
- def validate_api_key(api_key: str, api_instance: APIDeployment) -> None:
+ def validate_api_key(
+ api_key: str, instance: Union[APIDeployment, Pipeline]
+ ) -> None:
"""Validate api key.
Args:
api_key (str): api key from request
- api_instance (APIDeployment): api deployment instance
+ instance (Union[APIDeployment, Pipeline]): api or pipeline instance
Raises:
- Forbidden: _description_
+ UnauthorizedKey: if not valid
"""
try:
api_key_instance: APIKey = APIKey.objects.get(api_key=api_key)
- if not KeyHelper.has_access(api_key_instance, api_instance):
+ if not KeyHelper.has_access(api_key_instance, instance):
raise UnauthorizedKey()
except APIKey.DoesNotExist:
raise UnauthorizedKey()
- except APIDeployment.DoesNotExist:
- raise Forbidden("API not found.")
@staticmethod
def list_api_keys_of_api(api_instance: APIDeployment) -> list[APIKey]:
@@ -35,21 +37,28 @@ class KeyHelper:
return api_keys
@staticmethod
- def has_access(api_key: APIKey, api_instance: APIDeployment) -> bool:
+ def list_api_keys_of_pipeline(pipeline_instance: Pipeline) -> list[APIKey]:
+ api_keys: list[APIKey] = APIKey.objects.filter(pipeline=pipeline_instance).all()
+ return api_keys
+
+ @staticmethod
+ def has_access(api_key: APIKey, instance: Union[APIDeployment, Pipeline]) -> bool:
"""Check if the provided API key has access to the specified API
instance.
Args:
- api_key (APIKey): api key associated with the api
- api_instance (APIDeployment): api model
+ api_key (APIKey): api key associated with the instance
+ instance (Union[APIDeployment, Pipeline]): api or pipeline instance
Returns:
bool: True if allowed to execute, False otherwise
"""
if not api_key.is_active:
return False
- if isinstance(api_key.api, APIDeployment):
- return api_key.api == api_instance
+ if isinstance(instance, APIDeployment):
+ return api_key.api == instance
+ if isinstance(instance, Pipeline):
+ return api_key.pipeline == instance
return False
@staticmethod
@@ -59,12 +68,11 @@ class KeyHelper:
WorkflowHelper.get_workflow_by_id(workflow_id)
@staticmethod
- def create_api_key(deployment: APIDeployment) -> APIKey:
- """Create an APIKey entity with the data from the provided
- APIDeployment instance."""
- # Create an instance of the APIKey model
+ def create_api_key(deployment: Union[APIDeployment, Pipeline]) -> APIKey:
+ """Create an APIKey entity using the data from the provided
+ APIDeployment or Pipeline instance."""
api_key_serializer = APIKeySerializer(
- data={"api": deployment.id, "description": "Initial Access Key"},
+ data=deployment.api_key_data,
context={"deployment": deployment},
)
api_key_serializer.is_valid(raise_exception=True)
diff --git a/backend/api/migrations/0002_apikey_pipeline_alter_apikey_api.py b/backend/api/migrations/0002_apikey_pipeline_alter_apikey_api.py
new file mode 100644
index 000000000..7f5dc61e2
--- /dev/null
+++ b/backend/api/migrations/0002_apikey_pipeline_alter_apikey_api.py
@@ -0,0 +1,37 @@
+# Generated by Django 4.2.1 on 2024-08-05 09:36
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("pipeline", "0002_alter_pipeline_last_run_status"),
+ ("api", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="apikey",
+ name="pipeline",
+ field=models.ForeignKey(
+ blank=True,
+ db_comment="Foreign key reference to the Pipeline model.",
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="pipeline.pipeline",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="apikey",
+ name="api",
+ field=models.ForeignKey(
+ blank=True,
+ db_comment="Foreign key reference to the APIDeployment model.",
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="api.apideployment",
+ ),
+ ),
+ ]
diff --git a/backend/api/models.py b/backend/api/models.py
index a2c81f4fc..2119ff85b 100644
--- a/backend/api/models.py
+++ b/backend/api/models.py
@@ -4,6 +4,7 @@ from typing import Any
from account.models import User
from api.constants import ApiExecution
from django.db import connection, models
+from pipeline.models import Pipeline
from utils.models.base_model import BaseModel
from workflow_manager.workflow.models.workflow import Workflow
@@ -35,6 +36,8 @@ class APIDeployment(BaseModel):
default=True,
db_comment="Flag indicating whether the API is active or not.",
)
+ # TODO: Implement dynamic generation of API endpoints for API deployments
+ # instead of persisting them in the database.
api_endpoint = models.CharField(
max_length=API_ENDPOINT_MAX_LENGTH,
unique=True,
@@ -64,6 +67,10 @@ class APIDeployment(BaseModel):
editable=False,
)
+ @property
+ def api_key_data(self):
+ return {"api": self.id, "description": f"API Key for {self.api_name}"}
+
def __str__(self) -> str:
return f"{self.id} - {self.display_name}"
@@ -107,8 +114,17 @@ class APIKey(BaseModel):
api = models.ForeignKey(
APIDeployment,
on_delete=models.CASCADE,
+ null=True,
+ blank=True,
db_comment="Foreign key reference to the APIDeployment model.",
)
+ pipeline = models.ForeignKey(
+ Pipeline,
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ db_comment="Foreign key reference to the Pipeline model.",
+ )
description = models.CharField(
max_length=DESCRIPTION_MAX_LENGTH,
null=True,
diff --git a/backend/api/postman_collection/constants.py b/backend/api/postman_collection/constants.py
index ffb3ef729..2374c478b 100644
--- a/backend/api/postman_collection/constants.py
+++ b/backend/api/postman_collection/constants.py
@@ -1,6 +1,7 @@
class CollectionKey:
POSTMAN_COLLECTION_V210 = "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" # noqa: E501
EXECUTE_API_KEY = "Process document"
+ EXECUTE_PIPELINE_API_KEY = "Process pipeline"
STATUS_API_KEY = "Execution status"
STATUS_EXEC_ID_DEFAULT = "REPLACE_WITH_EXECUTION_ID"
AUTH_QUERY_PARAM_DEFAULT = "REPLACE_WITH_API_KEY"
diff --git a/backend/api/postman_collection/dto.py b/backend/api/postman_collection/dto.py
index c862baf81..dc0e7be12 100644
--- a/backend/api/postman_collection/dto.py
+++ b/backend/api/postman_collection/dto.py
@@ -1,11 +1,13 @@
+from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field
-from typing import Any, Optional
+from typing import Any, Optional, Union
from urllib.parse import urlencode, urljoin
from api.constants import ApiExecution
from api.models import APIDeployment
from api.postman_collection.constants import CollectionKey
from django.conf import settings
+from pipeline.models import Pipeline
from utils.request import HTTPMethod
@@ -60,6 +62,128 @@ class PostmanInfo:
description: str = "Contains APIs meant for using the deployed Unstract API"
+class APIBase(ABC):
+
+ # @abstractmethod
+ # def get_name(self) -> str:
+ # pass
+
+ # @abstractmethod
+ # def get_description(self) -> str:
+ # pass
+
+ @abstractmethod
+ def get_form_data_items(self) -> list[FormDataItem]:
+ pass
+
+ @abstractmethod
+ def get_api_endpoint(self) -> str:
+ pass
+
+ @abstractmethod
+ def get_postman_items(self) -> list[PostmanItem]:
+ pass
+
+ @abstractmethod
+ def get_api_key(self) -> str:
+ pass
+
+ def get_execute_body(self) -> BodyItem:
+ form_data_items = self.get_form_data_items()
+ return BodyItem(formdata=form_data_items)
+
+ def get_create_api_request(self) -> RequestItem:
+ header_list = [
+ HeaderItem(key="Authorization", value=f"Bearer {self.get_api_key()}")
+ ]
+ abs_api_endpoint = urljoin(settings.WEB_APP_ORIGIN_URL, self.get_api_endpoint())
+ return RequestItem(
+ method=HTTPMethod.POST,
+ header=header_list,
+ body=self.get_execute_body(),
+ url=abs_api_endpoint,
+ )
+
+
+@dataclass
+class APIDeploymentDto(APIBase):
+ display_name: str
+ description: str
+ api_endpoint: str
+ api_key: str
+
+ def get_postman_info(self) -> PostmanInfo:
+ return PostmanInfo(name=self.display_name, description=self.description)
+
+ def get_form_data_items(self) -> list[FormDataItem]:
+ return [
+ FormDataItem(
+ key=ApiExecution.FILES_FORM_DATA, type="file", src="/path_to_file"
+ ),
+ FormDataItem(
+ key=ApiExecution.TIMEOUT_FORM_DATA,
+ type="text",
+ value=ApiExecution.MAXIMUM_TIMEOUT_IN_SEC,
+ ),
+ FormDataItem(key=ApiExecution.INCLUDE_METADATA, type="text", value="False"),
+ ]
+
+ def get_api_key(self) -> str:
+ return self.api_key
+
+ def get_api_endpoint(self) -> str:
+ return self.api_endpoint
+
+ def _get_status_api_request(self) -> RequestItem:
+ header_list = [HeaderItem(key="Authorization", value=f"Bearer {self.api_key}")]
+ status_query_param = {"execution_id": CollectionKey.STATUS_EXEC_ID_DEFAULT}
+ status_query_str = urlencode(status_query_param)
+ abs_api_endpoint = urljoin(settings.WEB_APP_ORIGIN_URL, self.api_endpoint)
+ status_url = urljoin(abs_api_endpoint, "?" + status_query_str)
+ return RequestItem(method=HTTPMethod.GET, header=header_list, url=status_url)
+
+ def get_postman_items(self) -> list[PostmanItem]:
+ postman_item_list = [
+ PostmanItem(
+ name=CollectionKey.EXECUTE_API_KEY,
+ request=self.get_create_api_request(),
+ ),
+ PostmanItem(
+ name=CollectionKey.STATUS_API_KEY,
+ request=self._get_status_api_request(),
+ ),
+ ]
+ return postman_item_list
+
+
+@dataclass
+class PipelineDto(APIBase):
+ pipeline_name: str
+ api_endpoint: str
+ api_key: str
+
+ def get_postman_info(self) -> PostmanInfo:
+ return PostmanInfo(name=self.pipeline_name, description="")
+
+ def get_form_data_items(self) -> list[FormDataItem]:
+ return []
+
+ def get_api_endpoint(self) -> str:
+ return self.api_endpoint
+
+ def get_api_key(self) -> str:
+ return self.api_key
+
+ def get_postman_items(self) -> list[PostmanItem]:
+ postman_item_list = [
+ PostmanItem(
+ name=CollectionKey.EXECUTE_PIPELINE_API_KEY,
+ request=self.get_create_api_request(),
+ )
+ ]
+ return postman_item_list
+
+
@dataclass
class PostmanCollection:
info: PostmanInfo
@@ -68,7 +192,7 @@ class PostmanCollection:
@classmethod
def create(
cls,
- instance: APIDeployment,
+ instance: Union[APIDeployment, Pipeline],
api_key: str = CollectionKey.AUTH_QUERY_PARAM_DEFAULT,
) -> "PostmanCollection":
"""Creates a PostmanCollection instance.
@@ -84,49 +208,22 @@ class PostmanCollection:
Returns:
PostmanCollection: Instance representing PostmanCollection
"""
- postman_info = PostmanInfo(
- name=instance.display_name, description=instance.description
- )
- header_list = [HeaderItem(key="Authorization", value=f"Bearer {api_key}")]
- abs_api_endpoint = urljoin(settings.WEB_APP_ORIGIN_URL, instance.api_endpoint)
-
- # API execution API
- execute_body = BodyItem(
- formdata=[
- FormDataItem(
- key=ApiExecution.FILES_FORM_DATA, type="file", src="/path_to_file"
- ),
- FormDataItem(
- key=ApiExecution.TIMEOUT_FORM_DATA,
- type="text",
- value=ApiExecution.MAXIMUM_TIMEOUT_IN_SEC,
- ),
- FormDataItem(
- key=ApiExecution.INCLUDE_METADATA,
- type="text",
- value=False,
- ),
- ]
- )
- execute_request = RequestItem(
- method=HTTPMethod.POST,
- header=header_list,
- body=execute_body,
- url=abs_api_endpoint,
- )
-
- # Status API
- status_query_param = {"execution_id": CollectionKey.STATUS_EXEC_ID_DEFAULT}
- status_query_str = urlencode(status_query_param)
- status_url = urljoin(abs_api_endpoint, "?" + status_query_str)
- status_request = RequestItem(
- method=HTTPMethod.GET, header=header_list, url=status_url
- )
-
- postman_item_list = [
- PostmanItem(name=CollectionKey.EXECUTE_API_KEY, request=execute_request),
- PostmanItem(name=CollectionKey.STATUS_API_KEY, request=status_request),
- ]
+ data_object: APIBase
+ if isinstance(instance, APIDeployment):
+ data_object = APIDeploymentDto(
+ display_name=instance.display_name,
+ description=instance.description,
+ api_endpoint=instance.api_endpoint,
+ api_key=api_key,
+ )
+ elif isinstance(instance, Pipeline):
+ data_object = PipelineDto(
+ pipeline_name=instance.pipeline_name,
+ api_endpoint=instance.api_endpoint,
+ api_key=api_key,
+ )
+ postman_info: PostmanInfo = data_object.get_postman_info()
+ postman_item_list = data_object.get_postman_items()
return cls(info=postman_info, item=postman_item_list)
def to_dict(self) -> dict[str, Any]:
diff --git a/backend/api/serializers.py b/backend/api/serializers.py
index 6f483f5e9..88af3b740 100644
--- a/backend/api/serializers.py
+++ b/backend/api/serializers.py
@@ -4,6 +4,7 @@ from typing import Any, Union
from api.constants import ApiExecution
from api.models import APIDeployment, APIKey
from django.core.validators import RegexValidator
+from pipeline.models import Pipeline
from rest_framework.serializers import (
CharField,
IntegerField,
@@ -37,15 +38,42 @@ class APIKeySerializer(AuditSerializer):
model = APIKey
fields = "__all__"
+ def validate(self, data):
+ api = data.get("api")
+ pipeline = data.get("pipeline")
+
+ if api and pipeline:
+ raise ValidationError(
+ "Only one of `api` or `pipeline` should be set, not both."
+ )
+ elif not api and not pipeline:
+ raise ValidationError("At least one of `api` or `pipeline` must be set.")
+
+ return data
+
def to_representation(self, instance: APIKey) -> OrderedDict[str, Any]:
"""Override the to_representation method to include additional
context."""
- context = self.context.get("context", {})
- deployment: APIDeployment = context.get("deployment")
+ deployment: Union[APIDeployment, Pipeline] = self.context.get("deployment")
representation: OrderedDict[str, Any] = super().to_representation(instance)
+
if deployment:
- representation["api"] = deployment.id
- representation["description"] = f"API Key for {deployment.name}"
+ # Handle APIDeployment and Pipeline separately
+ if isinstance(deployment, APIDeployment):
+ representation["api"] = deployment.id
+ representation["pipeline"] = None
+ representation["description"] = f"API Key for {deployment.api_name}"
+ elif isinstance(deployment, Pipeline):
+ representation["api"] = None
+ representation["pipeline"] = deployment.id
+ representation["description"] = (
+ f"API Key for {deployment.pipeline_name}"
+ )
+ else:
+ raise ValueError(
+ "Context must be an instance of APIDeployment or Pipeline"
+ )
+
representation["is_active"] = True
return representation
diff --git a/backend/api/urls.py b/backend/api/urls.py
index 43eabf73e..689bdd63b 100644
--- a/backend/api/urls.py
+++ b/backend/api/urls.py
@@ -58,6 +58,9 @@ urlpatterns = format_suffix_patterns(
name="api_deployment_execution",
),
path("keys/<uuid:pk>/", key_details, name="key_details"),
- path("keys/api/<str:api_id>/", api_key, name="api_key"),
+ path("keys/api/<str:api_id>/", api_key, name="api_key_api"),
+ path("keys/api/", api_key, name="api_keys_api"),
+ path("keys/pipeline/<str:pipeline_id>/", api_key, name="api_key_pipeline"),
+ path("keys/pipeline/", api_key, name="api_keys_pipeline"),
]
)
diff --git a/backend/backend/public_urls.py b/backend/backend/public_urls.py
index 971ccfcec..7b40d2655 100644
--- a/backend/backend/public_urls.py
+++ b/backend/backend/public_urls.py
@@ -31,6 +31,7 @@ urlpatterns = [
path(f"{path_prefix}/", include("docs.urls")),
# API deployment
path(f"{api_path_prefix}/", include("api.urls")),
+ path(f"{api_path_prefix}/pipeline/", include("pipeline.public_api_urls")),
# Feature flags
path(f"{path_prefix}/flags/", include("feature_flag.urls")),
]
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.py
index 902a7d012..ee6297442 100644
--- a/backend/backend/settings/base.py
+++ b/backend/backend/settings/base.py
@@ -124,6 +124,7 @@ SESSION_COOKIE_SECURE = os.environ.get("SESSION_COOKIE_SECURE", True)
CSRF_COOKIE_SECURE = os.environ.get("CSRF_COOKIE_SECURE", True)
PATH_PREFIX = os.environ.get("PATH_PREFIX", "api/v1").strip("/")
+# Resetting the path prefix will require reconfiguring all existing deployed APIs
API_DEPLOYMENT_PATH_PREFIX = os.environ.get(
"API_DEPLOYMENT_PATH_PREFIX", "deployment"
).strip("/")
diff --git a/backend/pipeline/deployment_helper.py b/backend/pipeline/deployment_helper.py
new file mode 100644
index 000000000..1044220c1
--- /dev/null
+++ b/backend/pipeline/deployment_helper.py
@@ -0,0 +1,33 @@
+import logging
+from typing import Any
+
+from api.api_key_validator import BaseAPIKeyValidator
+from api.exceptions import InvalidAPIRequest
+from api.key_helper import KeyHelper
+from pipeline.exceptions import PipelineNotFound
+from pipeline.pipeline_processor import PipelineProcessor
+from rest_framework.request import Request
+
+logger = logging.getLogger(__name__)
+
+
+class DeploymentHelper(BaseAPIKeyValidator):
+ @staticmethod
+ def validate_parameters(request: Request, **kwargs: Any) -> None:
+ """Validate pipeline_id for pipeline deployments."""
+ pipeline_id = kwargs.get("pipeline_id") or request.data.get("pipeline_id")
+ if not pipeline_id:
+ raise InvalidAPIRequest("Missing params pipeline_id")
+
+ @staticmethod
+ def validate_and_process(
+ self: Any, request: Request, func: Any, api_key: str, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Fetch pipeline and validate API key."""
+ pipeline_id = kwargs.get("pipeline_id") or request.data.get("pipeline_id")
+ pipeline = PipelineProcessor.get_active_pipeline(pipeline_id=pipeline_id)
+ if not pipeline:
+ raise PipelineNotFound()
+ KeyHelper.validate_api_key(api_key=api_key, instance=pipeline)
+ kwargs["pipeline"] = pipeline
+ return func(self, request, *args, **kwargs)
diff --git a/backend/pipeline/exceptions.py b/backend/pipeline/exceptions.py
index 8da26c481..7d2885a98 100644
--- a/backend/pipeline/exceptions.py
+++ b/backend/pipeline/exceptions.py
@@ -3,6 +3,11 @@ from typing import Optional
from rest_framework.exceptions import APIException
+class NotFoundException(APIException):
+ status_code = 404
+ default_detail = "The requested resource was not found."
+
+
class WorkflowTriggerError(APIException):
status_code = 400
default_detail = "Error triggering workflow. Pipeline created"
@@ -44,3 +49,7 @@ class MandatoryWorkflowId(APIException):
class MandatoryCronSchedule(APIException):
status_code = 400
default_detail = "Cron schedule is mandatory"
+
+
+class PipelineNotFound(NotFoundException):
+ default_detail = "Pipeline not found"
diff --git a/backend/pipeline/models.py b/backend/pipeline/models.py
index f23bf0c37..ba0603c78 100644
--- a/backend/pipeline/models.py
+++ b/backend/pipeline/models.py
@@ -1,7 +1,8 @@
import uuid
from account.models import User
-from django.db import models
+from django.conf import settings
+from django.db import connection, models
from utils.models.base_model import BaseModel
from workflow_manager.workflow.models.workflow import Workflow
@@ -80,8 +81,19 @@ class Pipeline(BaseModel):
blank=True,
)
+ @property
+ def api_key_data(self):
+ return {"pipeline": self.id, "description": f"API Key for {self.pipeline_name}"}
+
+ @property
+ def api_endpoint(self):
+ org_schema = connection.get_tenant().schema_name
+ deployment_endpoint = settings.API_DEPLOYMENT_PATH_PREFIX + "/pipeline/api"
+ api_endpoint = f"{deployment_endpoint}/{org_schema}/{self.id}/"
+ return api_endpoint
+
def __str__(self) -> str:
- return f"Pipeline({self.id})"
+ return f"Pipeline({self.id})(name: {self.pipeline_name})"
class Meta:
constraints = [
diff --git a/backend/pipeline/piepline_api_execution_views.py b/backend/pipeline/piepline_api_execution_views.py
new file mode 100644
index 000000000..763a2963c
--- /dev/null
+++ b/backend/pipeline/piepline_api_execution_views.py
@@ -0,0 +1,43 @@
+import logging
+from typing import Any
+
+from pipeline.deployment_helper import DeploymentHelper
+from pipeline.models import Pipeline
+from rest_framework import status, views
+from rest_framework.request import Request
+from rest_framework.response import Response
+from scheduler.tasks import execute_pipeline_task
+
+logger = logging.getLogger(__name__)
+
+
+class PipelineApiExecution(views.APIView):
+ def initialize_request(
+ self, request: Request, *args: Any, **kwargs: Any
+ ) -> Request:
+ """To remove csrf request for public API.
+
+ Args:
+ request (Request): _description_
+
+ Returns:
+ Request: _description_
+ """
+ setattr(request, "csrf_processing_done", True)
+ return super().initialize_request(request, *args, **kwargs)
+
+ @DeploymentHelper.validate_api_key
+ def post(
+ self, request: Request, org_name: str, pipeline_id: str, pipeline: Pipeline
+ ) -> Response:
+ execute_pipeline_task.delay(
+ workflow_id="",
+ org_schema=org_name,
+ execution_action="",
+ execution_id="",
+ pipepline_id=pipeline_id,
+ with_logs=True,
+ name=pipeline.pipeline_name,
+ )
+ logger.info(f"Triggered {pipeline} by API")
+ return Response({"message": f"Triggered {pipeline}"}, status=status.HTTP_200_OK)
diff --git a/backend/pipeline/pipeline_processor.py b/backend/pipeline/pipeline_processor.py
index 707377577..5a84ef665 100644
--- a/backend/pipeline/pipeline_processor.py
+++ b/backend/pipeline/pipeline_processor.py
@@ -37,6 +37,14 @@ class PipelineProcessor:
raise InactivePipelineError(pipeline_name=pipeline.pipeline_name)
return pipeline
+ @classmethod
+ def get_active_pipeline(cls, pipeline_id: str) -> Optional[Pipeline]:
+ """Retrieves a list of active pipelines."""
+ try:
+ return cls.fetch_pipeline(pipeline_id, check_active=True)
+ except Pipeline.DoesNotExist:
+ return None
+
@staticmethod
def _update_pipeline_status(
pipeline: Pipeline,
diff --git a/backend/pipeline/public_api_urls.py b/backend/pipeline/public_api_urls.py
new file mode 100644
index 000000000..6384ab48e
--- /dev/null
+++ b/backend/pipeline/public_api_urls.py
@@ -0,0 +1,15 @@
+from django.urls import re_path
+from pipeline.piepline_api_execution_views import PipelineApiExecution
+from rest_framework.urlpatterns import format_suffix_patterns
+
+execute = PipelineApiExecution.as_view()
+
+urlpatterns = format_suffix_patterns(
+ [
+ re_path(
+ r"^api/(?P<org_name>[\w-]+)/(?P<pipeline_id>[\w-]+)/?$",
+ execute,
+ name="pipeline_api_deployment_execution",
+ ),
+ ]
+)
diff --git a/backend/pipeline/serializers/crud.py b/backend/pipeline/serializers/crud.py
index 3480ac832..2076f5ba0 100644
--- a/backend/pipeline/serializers/crud.py
+++ b/backend/pipeline/serializers/crud.py
@@ -5,9 +5,11 @@ from typing import Any
from connector.connector_instance_helper import ConnectorInstanceHelper
from connector.models import ConnectorInstance
from connector_processor.connector_processor import ConnectorProcessor
+from django.conf import settings
from pipeline.constants import PipelineConstants as PC
from pipeline.constants import PipelineKey as PK
from pipeline.models import Pipeline
+from rest_framework.serializers import SerializerMethodField
from scheduler.helper import SchedulerHelper
from utils.serializer_utils import SerializerUtils
from workflow_manager.endpoint.models import WorkflowEndpoint
@@ -16,14 +18,32 @@ from backend.serializers import AuditSerializer
from unstract.connectors.connectorkit import Connectorkit
logger = logging.getLogger(__name__)
+DEPLOYMENT_ENDPOINT = settings.API_DEPLOYMENT_PATH_PREFIX + "/pipeline"
class PipelineSerializer(AuditSerializer):
+ api_endpoint = SerializerMethodField()
+
class Meta:
model = Pipeline
fields = "__all__"
+ def get_api_endpoint(self, instance: Pipeline):
+ """Retrieve the API endpoint URL for a given Pipeline instance.
+
+ This method is an internal serializer call that fetches the
+ `api_endpoint` property from the provided Pipeline instance.
+
+ Args:
+ instance (Pipeline): The Pipeline instance for which the API
+ endpoint URL is being retrieved.
+
+ Returns:
+ str: The API endpoint URL associated with the Pipeline instance.
+ """
+ return instance.api_endpoint
+
def create(self, validated_data: dict[str, Any]) -> Any:
# TODO: Deduce pipeline type based on WF?
validated_data[PK.ACTIVE] = True # Add this as default instead?
diff --git a/backend/pipeline/urls.py b/backend/pipeline/urls.py
index d03ed2587..da3752fa1 100644
--- a/backend/pipeline/urls.py
+++ b/backend/pipeline/urls.py
@@ -24,6 +24,12 @@ pipeline_detail = PipelineViewSet.as_view(
}
)
+download_postman_collection = PipelineViewSet.as_view(
+ {
+ "get": PipelineViewSet.download_postman_collection.__name__,
+ }
+)
+
pipeline_execute = PipelineViewSet.as_view({"post": "execute"})
@@ -37,5 +43,10 @@ urlpatterns = format_suffix_patterns(
name=PipelineURL.EXECUTIONS,
),
path("pipeline/execute/", pipeline_execute, name=PipelineURL.EXECUTE),
+ path(
+ "pipeline/api/postman_collection/<uuid:pk>/",
+ download_postman_collection,
+ name="download_pipeline_postman_collection",
+ ),
]
)
diff --git a/backend/pipeline/views.py b/backend/pipeline/views.py
index 371032d50..6844ffd2d 100644
--- a/backend/pipeline/views.py
+++ b/backend/pipeline/views.py
@@ -1,9 +1,14 @@
+import json
import logging
from typing import Any, Optional
from account.custom_exceptions import DuplicateData
+from api.exceptions import NoActiveAPIKeyError
+from api.key_helper import KeyHelper
+from api.postman_collection.dto import PostmanCollection
from django.db import IntegrityError
from django.db.models import QuerySet
+from django.http import HttpResponse
from permissions.permission import IsOwner
from pipeline.constants import PipelineConstants, PipelineErrors, PipelineExecutionKey
from pipeline.constants import PipelineKey as PK
@@ -14,6 +19,7 @@ from pipeline.serializers.crud import PipelineSerializer
from pipeline.serializers.execute import PipelineExecuteSerializer as ExecuteSerializer
from pipeline.serializers.update import PipelineUpdateSerializer
from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
@@ -72,7 +78,9 @@ class PipelineViewSet(viewsets.ModelViewSet):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
- serializer.save()
+ pipeline_instance = serializer.save()
+ # Create API key using the created instance
+ KeyHelper.create_api_key(pipeline_instance)
except IntegrityError:
raise DuplicateData(
f"{PipelineErrors.PIPELINE_EXISTS}, " f"{PipelineErrors.DUPLICATE_API}"
@@ -110,3 +118,26 @@ class PipelineViewSet(viewsets.ModelViewSet):
)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+
+ @action(detail=True, methods=["get"])
+ def download_postman_collection(
+ self, request: Request, pk: Optional[str] = None
+ ) -> Response:
+ """Downloads a Postman Collection of the API deployment instance."""
+ instance: Pipeline = self.get_object()
+ api_key_inst = instance.apikey_set.filter(is_active=True).first()
+ if not api_key_inst:
+ logger.error(f"No active API key set for pipeline {instance}")
+ raise NoActiveAPIKeyError(deployment_name=instance.pipeline_name)
+
+ # Create a PostmanCollection for a Pipeline
+ postman_collection = PostmanCollection.create(
+ instance=instance, api_key=api_key_inst.api_key
+ )
+ response = HttpResponse(
+ json.dumps(postman_collection.to_dict()), content_type="application/json"
+ )
+ response["Content-Disposition"] = (
+ f'attachment; filename="{instance.pipeline_name}.json"'
+ )
+ return response
diff --git a/backend/scheduler/tasks.py b/backend/scheduler/tasks.py
index abbc7cf91..ec509c158 100644
--- a/backend/scheduler/tasks.py
+++ b/backend/scheduler/tasks.py
@@ -14,14 +14,12 @@ if check_feature_flag_status(FeatureFlag.MULTI_TENANCY_V2):
from pipeline_v2.models import Pipeline
from pipeline_v2.pipeline_processor import PipelineProcessor
from utils.user_context import UserContext
- from workflow_manager.workflow_v2.models.workflow import Workflow
from workflow_manager.workflow_v2.workflow_helper import WorkflowHelper
else:
from account.models import Organization
from account.subscription_loader import load_plugins, validate_etl_run
from pipeline.models import Pipeline
from pipeline.pipeline_processor import PipelineProcessor
- from workflow_manager.workflow.models.workflow import Workflow
from workflow_manager.workflow.workflow_helper import WorkflowHelper
@@ -82,11 +80,15 @@ def execute_pipeline_task(
return
logger.info(f"Executing pipeline name: {name}")
try:
- logger.info(f"Executing workflow id: {workflow_id}")
tenant: Organization = (
get_tenant_model().objects.filter(schema_name=org_schema).first()
)
with tenant_context(tenant):
+ pipeline = PipelineProcessor.fetch_pipeline(
+ pipeline_id=pipepline_id, check_active=True
+ )
+ workflow = pipeline.workflow
+ logger.info(f"Executing workflow: {workflow} by pipeline {pipeline}")
if (
subscription_loader
and subscription_loader[0]
@@ -100,7 +102,6 @@ def execute_pipeline_task(
f"Failed to disable task: {pipepline_id}. Error: {e}"
)
return
- workflow = Workflow.objects.get(id=workflow_id)
logger.info(f"Executing workflow: {workflow}")
PipelineProcessor.update_pipeline(
pipepline_id, Pipeline.PipelineStatus.INPROGRESS
diff --git a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
index eefebdde0..b060c62a4 100644
--- a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
+++ b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
@@ -12,7 +12,7 @@ import { Button, Dropdown, Space, Switch, Tooltip, Typography } from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
-import { getBaseUrl } from "../../../helpers/GetStaticData";
+import { deploymentApiTypes, displayURL } from "../../../helpers/GetStaticData";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
import { workflowService } from "../../workflows/workflow/workflow-service.js";
@@ -26,6 +26,7 @@ import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";
import { LogsModal } from "../../pipelines-or-deployments/log-modal/LogsModal.jsx";
import { fetchExecutionLogs } from "../../pipelines-or-deployments/log-modal/fetchExecutionLogs";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate.js";
+import usePipelineHelper from "../../../hooks/usePipelineHelper.js";
function ApiDeployment() {
const { sessionDetails } = useSessionStore();
@@ -48,6 +49,8 @@ function ApiDeployment() {
const [executionLogs, setExecutionLogs] = useState([]);
const [executionLogsTotalCount, setExecutionLogsTotalCount] = useState(0);
const axiosPrivate = useAxiosPrivate();
+ const { getApiKeys, downloadPostmanCollection, copyUrl } =
+ usePipelineHelper();
const handleFetchLogs = (page, pageSize) => {
fetchExecutionLogs(
@@ -221,74 +224,6 @@ function ApiDeployment() {
});
};
- const displayURL = (text) => {
- return getBaseUrl() + "/" + text;
- };
-
- const copyUrl = (text) => {
- const completeUrl = displayURL(text);
- navigator.clipboard
- .writeText(completeUrl)
- .then(() => {
- setAlertDetails({
- type: "success",
- content: "Endpoint copied to clipboard",
- });
- })
- .catch((error) => {
- setAlertDetails({
- type: "error",
- content: "Copy failed",
- });
- });
- };
-
- const getApiKeys = () => {
- apiDeploymentsApiService
- .getApiKeys(selectedRow?.id)
- .then((res) => {
- setApiKeys(res?.data);
- })
- .catch((err) => {
- setAlertDetails(handleException(err));
- })
- .finally(() => {
- setOpenManageKeysModal(true);
- });
- };
-
- const downloadPostmanCollection = () => {
- apiDeploymentsApiService
- .downloadPostmanCollection(selectedRow?.id)
- .then((res) => {
- const { data, headers } = res;
- const href = URL.createObjectURL(data);
- // Get filename from header or use a default
- const filename =
- headers["content-disposition"]
- ?.split("filename=")[1]
- ?.trim()
- .replaceAll('"', "") || "postman_collection.json";
- // create "a" HTML element with href to file & click
- const link = document.createElement("a");
- link.href = href;
- link.setAttribute("download", filename);
- document.body.appendChild(link);
- link.click();
-
- // clean up "a" element & remove ObjectURL
- document.body.removeChild(link);
- URL.revokeObjectURL(href);
- setAlertDetails({
- type: "success",
- content: "Collection downloaded successfully",
- });
- })
- .catch((err) => {
- setAlertDetails(handleException(err));
- });
- };
-
const openAddModal = (edit) => {
setIsEdit(edit);
setOpenAddApiModal(true);
@@ -318,7 +253,14 @@ function ApiDeployment() {
<Space
direction="horizontal"
className="action-items"
- onClick={getApiKeys}
+ onClick={() =>
+ getApiKeys(
+ apiDeploymentsApiService,
+ selectedRow?.id,
+ setApiKeys,
+ setOpenManageKeysModal
+ )
+ }
>
<div>
<KeyOutlined />
@@ -335,7 +277,9 @@ function ApiDeployment() {
<Space
direction="horizontal"
className="action-items"
- onClick={downloadPostmanCollection}
+ onClick={() =>
+ downloadPostmanCollection(apiDeploymentsApiService, selectedRow?.id)
+ }
>
<div>
<CloudDownloadOutlined />
@@ -442,6 +386,8 @@ function ApiDeployment() {
apiKeys={apiKeys}
setApiKeys={setApiKeys}
selectedApiRow={selectedRow}
+ apiService={apiDeploymentsApiService}
+ type={deploymentApiTypes.api}
/>
<DisplayCode
isDialogOpen={openCodeModal}
diff --git a/frontend/src/components/deployments/manage-keys/ManageKeys.jsx b/frontend/src/components/deployments/manage-keys/ManageKeys.jsx
index c9c05cf28..581df7d7c 100644
--- a/frontend/src/components/deployments/manage-keys/ManageKeys.jsx
+++ b/frontend/src/components/deployments/manage-keys/ManageKeys.jsx
@@ -11,7 +11,6 @@ import { useEffect, useState } from "react";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
-import { apiDeploymentsService } from "../../deployments/api-deployment/api-deployments-service.js";
import { CustomButton } from "../../widgets/custom-button/CustomButton.jsx";
import SpaceWrapper from "../../widgets/space-wrapper/SpaceWrapper.jsx";
import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader.jsx";
@@ -25,8 +24,9 @@ const ManageKeys = ({
apiKeys,
setApiKeys,
selectedApiRow,
+ apiService,
+ type,
}) => {
- const apiDeploymentsApiService = apiDeploymentsService();
const { sessionDetails } = useSessionStore();
const axiosPrivate = useAxiosPrivate();
const handleException = useExceptionHandler();
@@ -43,7 +43,7 @@ const ManageKeys = ({
if (isNewKey) {
setFormDetails({
description: "",
- api: selectedApiRow?.id,
+ [type]: selectedApiRow?.id,
is_active: true,
});
} else {
@@ -55,7 +55,7 @@ const ManageKeys = ({
if (isEditKey) {
setFormDetails({
description: selectedKeyRow?.description,
- api: selectedApiRow?.id,
+ [type]: selectedApiRow?.id,
is_active: selectedKeyRow?.is_active,
});
} else {
@@ -95,7 +95,7 @@ const ManageKeys = ({
};
const createKey = () => {
- apiDeploymentsApiService
+ apiService
.createApiKey(selectedApiRow?.id, formDetails)
.then((res) => {
addTableData(res?.data);
@@ -113,7 +113,7 @@ const ManageKeys = ({
};
const updateKey = () => {
- apiDeploymentsApiService
+ apiService
.updateApiKey(selectedKeyRow?.id, formDetails)
.then((res) => {
updateTableData(selectedKeyRow?.id, res?.data);
@@ -147,7 +147,7 @@ const ManageKeys = ({
};
const deleteApiKey = () => {
- apiDeploymentsApiService
+ apiService
.deleteApiKey(selectedKeyRow?.id)
.then((res) => {
deleteTableData(selectedKeyRow?.id);
@@ -360,6 +360,8 @@ ManageKeys.propTypes = {
apiKeys: PropTypes.array.isRequired,
setApiKeys: PropTypes.func.isRequired,
selectedApiRow: PropTypes.object.isRequired,
+ apiService: PropTypes.func.isRequired,
+ type: PropTypes.string.isRequired,
};
export { ManageKeys };
diff --git a/frontend/src/components/pipelines-or-deployments/pipeline-service.js b/frontend/src/components/pipelines-or-deployments/pipeline-service.js
new file mode 100644
index 000000000..30f1bdd3d
--- /dev/null
+++ b/frontend/src/components/pipelines-or-deployments/pipeline-service.js
@@ -0,0 +1,60 @@
+import { useAxiosPrivate } from "../../hooks/useAxiosPrivate";
+import { useSessionStore } from "../../store/session-store";
+
+function pipelineService() {
+ const axiosPrivate = useAxiosPrivate();
+ const { sessionDetails } = useSessionStore();
+ const path = `/api/v1/unstract/${sessionDetails?.orgId.replaceAll('"', "")}`;
+ const csrfToken = sessionDetails.csrfToken;
+
+ const requestHeaders = {
+ "Content-Type": "application/json",
+ "X-CSRFToken": csrfToken,
+ };
+
+ return {
+ getApiKeys: (id) => {
+ const requestOptions = {
+ url: `${path}/api/keys/pipeline/${id}/`,
+ method: "GET",
+ };
+ return axiosPrivate(requestOptions);
+ },
+ createApiKey: (apiId, record) => {
+ const requestOptions = {
+ method: "POST",
+ url: `${path}/api/keys/pipeline/${apiId}/`,
+ headers: requestHeaders,
+ data: record,
+ };
+ return axiosPrivate(requestOptions);
+ },
+ updateApiKey: (keyId, record) => {
+ const requestOptions = {
+ method: "PUT",
+ url: `${path}/api/keys/${keyId}/`,
+ headers: requestHeaders,
+ data: record,
+ };
+ return axiosPrivate(requestOptions);
+ },
+ deleteApiKey: (keyId) => {
+ const requestOptions = {
+ method: "DELETE",
+ url: `${path}/api/keys/${keyId}/`,
+ headers: requestHeaders,
+ };
+ return axiosPrivate(requestOptions);
+ },
+ downloadPostmanCollection: (id) => {
+ const requestOptions = {
+ method: "GET",
+ url: `${path}/pipeline/api/postman_collection/${id}/`,
+ responseType: "blob",
+ };
+ return axiosPrivate(requestOptions);
+ },
+ };
+}
+
+export { pipelineService };
diff --git a/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx b/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
index dd7318fe1..78fab027f 100644
--- a/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
+++ b/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
@@ -6,13 +6,28 @@ import {
HighlightOutlined,
FileSearchOutlined,
ReloadOutlined,
+ KeyOutlined,
+ CloudDownloadOutlined,
+ CopyOutlined,
} from "@ant-design/icons";
-import { Button, Dropdown, Image, Space, Switch, Typography } from "antd";
+import {
+ Button,
+ Dropdown,
+ Image,
+ Space,
+ Switch,
+ Tooltip,
+ Typography,
+} from "antd";
import PropTypes from "prop-types";
import { useEffect, useState } from "react";
import cronstrue from "cronstrue";
-import { deploymentsStaticContent } from "../../../helpers/GetStaticData";
+import {
+ deploymentApiTypes,
+ deploymentsStaticContent,
+ displayURL,
+} from "../../../helpers/GetStaticData";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate.js";
import { useAlertStore } from "../../../store/alert-store.js";
import { useSessionStore } from "../../../store/session-store.js";
@@ -23,6 +38,9 @@ import { LogsModal } from "../log-modal/LogsModal.jsx";
import { EtlTaskDeploy } from "../etl-task-deploy/EtlTaskDeploy.jsx";
import "./Pipelines.css";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";
+import { pipelineService } from "../pipeline-service.js";
+import { ManageKeys } from "../../deployments/manage-keys/ManageKeys.jsx";
+import usePipelineHelper from "../../../hooks/usePipelineHelper.js";
function Pipelines({ type }) {
const [tableData, setTableData] = useState([]);
@@ -39,6 +57,11 @@ function Pipelines({ type }) {
const [executionLogs, setExecutionLogs] = useState([]);
const [executionLogsTotalCount, setExecutionLogsTotalCount] = useState(0);
const { fetchExecutionLogs } = require("../log-modal/fetchExecutionLogs.js");
+ const [openManageKeysModal, setOpenManageKeysModal] = useState(false);
+ const [apiKeys, setApiKeys] = useState([]);
+ const pipelineApiService = pipelineService();
+ const { getApiKeys, downloadPostmanCollection, copyUrl } =
+ usePipelineHelper();
const handleFetchLogs = (page, pageSize) => {
fetchExecutionLogs(
@@ -282,17 +305,48 @@ function Pipelines({ type }) {
className="action-items"
onClick={() => setOpenDeleteModal(true)}
>
- <div>
- <DeleteOutlined />
- </div>
- <div>
- <Typography.Text>Delete</Typography.Text>
- </div>
+ <DeleteOutlined />
+ <Typography.Text>Delete</Typography.Text>
</Space>
),
},
{
key: "2",
+ label: (
+ <Space
+ direction="horizontal"
+ className="action-items"
+ onClick={() =>
+ getApiKeys(
+ pipelineApiService,
+ selectedPorD?.id,
+ setApiKeys,
+ setOpenManageKeysModal
+ )
+ }
+ >
+ <KeyOutlined />
+ <Typography.Text>Manage Keys</Typography.Text>
+ </Space>
+ ),
+ },
+ {
+ key: "3",
+ label: (
+ <Space
+ direction="horizontal"
+ className="action-items"
+ onClick={() =>
+ downloadPostmanCollection(pipelineApiService, selectedPorD?.id)
+ }
+ >
+ <CloudDownloadOutlined />
+ <Typography.Text>Download Postman Collection</Typography.Text>
+ </Space>
+ ),
+ },
+ {
+ key: "4",
label: (
<Space
direction="horizontal"
@@ -310,51 +364,39 @@ function Pipelines({ type }) {
);
}}
>
- <div>
- <FileSearchOutlined />
- </div>
- <div>
- <Typography.Text>View Logs</Typography.Text>
- </div>
+ <FileSearchOutlined />
+ <Typography.Text>View Logs</Typography.Text>
</Space>
),
},
{
- key: "3",
+ key: "5",
label: (
<Space
direction="horizontal"
className="action-items"
onClick={() => clearCache()}
>
- <div>
- <ClearOutlined />
- </div>
- <div>
- <Typography.Text>Clear Cache</Typography.Text>
- </div>
+ <ClearOutlined />
+ <Typography.Text>Clear Cache</Typography.Text>
</Space>
),
},
{
- key: "4",
+ key: "6",
label: (
<Space
direction="horizontal"
className="action-items"
onClick={() => clearFileMarkers()}
>
- <div>
- <HighlightOutlined />
- </div>
- <div>
- <Typography.Text>Clear Processed File History</Typography.Text>
- </div>
+ <HighlightOutlined />
+ <Typography.Text>Clear Processed File History</Typography.Text>
</Space>
),
},
{
- key: "5",
+ key: "7",
label: (
<Space
direction="horizontal"
@@ -365,12 +407,8 @@ function Pipelines({ type }) {
})
}
>
- <div>
- <SyncOutlined />
- </div>
- <div>
- <Typography.Text>Sync Now</Typography.Text>
- </div>
+ <SyncOutlined />
+ <Typography.Text>Sync Now</Typography.Text>
</Space>
),
},
@@ -421,6 +459,30 @@ function Pipelines({ type }) {
key: "destination",
align: "center",
},
+ {
+ title: "API Endpoint",
+ key: "api_endpoint",
+ render: (_, record) => (
+ <Space direction="horizontal" className="display-flex-space-between">
+ <div>
+ <Typography.Text>
+ {displayURL(record?.api_endpoint)}
+ </Typography.Text>
+ </div>
+ <div>
+ <Tooltip title="click to copy">
+ <Button
+ size="small"
+ onClick={() => copyUrl(record?.api_endpoint)}
+ >
+ <CopyOutlined />
+ </Button>
+ </Tooltip>
+ </div>
+ </Space>
+ ),
+ align: "left",
+ },
{
title: "Status of Previous Run",
dataIndex: "last_run_status",
@@ -467,7 +529,7 @@ function Pipelines({ type }) {
render: (_, record) => (
<div>
<Typography.Text className="p-or-d-typography" strong>
- {cronstrue.toString(record?.cron_string)}
+ {record?.cron_string && cronstrue.toString(record?.cron_string)}
</Typography.Text>
</div>
),
@@ -496,7 +558,7 @@ function Pipelines({ type }) {
placement="bottomLeft"
onOpenChange={() => setSelectedPorD(record)}
>
- <EllipsisOutlined rotate={90} className="p-or-d-actions" />
+ <EllipsisOutlined className="p-or-d-actions cur-pointer" />
</Dropdown>
),
},
@@ -535,6 +597,15 @@ function Pipelines({ type }) {
setOpen={setOpenDeleteModal}
deleteRecord={deletePipeline}
/>
+ <ManageKeys
+ isDialogOpen={openManageKeysModal}
+ setDialogOpen={setOpenManageKeysModal}
+ apiKeys={apiKeys}
+ setApiKeys={setApiKeys}
+ selectedApiRow={selectedPorD}
+ apiService={pipelineApiService}
+ type={deploymentApiTypes.pipeline}
+ />
</div>
);
}
diff --git a/frontend/src/helpers/GetStaticData.js b/frontend/src/helpers/GetStaticData.js
index 58d5153d8..6ad179ee8 100644
--- a/frontend/src/helpers/GetStaticData.js
+++ b/frontend/src/helpers/GetStaticData.js
@@ -205,6 +205,11 @@ const deploymentTypes = {
app: "app",
};
+const deploymentApiTypes = {
+ api: "api",
+ pipeline: "pipeline",
+};
+
const deploymentsStaticContent = {
etl: {
title: "Unstructured to Structured ETL Pipelines",
@@ -494,12 +499,17 @@ function getDocIdFromKey(key) {
}
}
+const displayURL = (text) => {
+ return getBaseUrl() + "/" + text;
+};
+
export {
CONNECTOR_TYPE_MAP,
O_AUTH_PROVIDERS,
THEME,
calculateDivHeight,
deploymentTypes,
+ deploymentApiTypes,
deploymentsStaticContent,
endpointType,
formatBytes,
@@ -536,4 +546,5 @@ export {
getFormattedTotalCost,
pollForCompletion,
getDocIdFromKey,
+ displayURL,
};
diff --git a/frontend/src/hooks/usePipelineHelper.js b/frontend/src/hooks/usePipelineHelper.js
new file mode 100644
index 000000000..7039b65d7
--- /dev/null
+++ b/frontend/src/hooks/usePipelineHelper.js
@@ -0,0 +1,80 @@
+import { displayURL } from "../helpers/GetStaticData";
+import { useAlertStore } from "../store/alert-store";
+import { useExceptionHandler } from "./useExceptionHandler";
+
+const usePipelineHelper = () => {
+ const { setAlertDetails } = useAlertStore();
+ const handleException = useExceptionHandler();
+
+ const getApiKeys = (apiService, id, setApiKeys, setOpenManageKeysModal) => {
+ apiService
+ .getApiKeys(id)
+ .then((res) => {
+ setApiKeys(res?.data);
+ })
+ .catch((err) => {
+ setAlertDetails(handleException(err));
+ })
+ .finally(() => {
+ setOpenManageKeysModal(true);
+ });
+ };
+
+ const downloadPostmanCollection = (apiService, id) => {
+ apiService
+ .downloadPostmanCollection(id)
+ .then((res) => {
+ const { data, headers } = res;
+ const href = URL.createObjectURL(data);
+ // Get filename from header or use a default
+ const filename =
+ headers["content-disposition"]
+ ?.split("filename=")[1]
+ ?.trim()
+ .replaceAll('"', "") || "postman_collection.json";
+ // create "a" HTML element with href to file & click
+ const link = document.createElement("a");
+ link.href = href;
+ link.setAttribute("download", filename);
+ document.body.appendChild(link);
+ link.click();
+
+ // clean up "a" element & remove ObjectURL
+ document.body.removeChild(link);
+ URL.revokeObjectURL(href);
+ setAlertDetails({
+ type: "success",
+ content: "Collection downloaded successfully",
+ });
+ })
+ .catch((err) => {
+ setAlertDetails(handleException(err));
+ });
+ };
+
+ const copyUrl = (text) => {
+ const completeUrl = displayURL(text);
+ navigator.clipboard
+ .writeText(completeUrl)
+ .then(() => {
+ setAlertDetails({
+ type: "success",
+ content: "Endpoint copied to clipboard",
+ });
+ })
+ .catch((error) => {
+ setAlertDetails({
+ type: "error",
+ content: "Copy failed",
+ });
+ });
+ };
+
+ return {
+ getApiKeys,
+ downloadPostmanCollection,
+ copyUrl,
+ };
+};
+
+export default usePipelineHelper;