Skip to content

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

UN-2679 [FEAT] Add support for external usage tracking plugins (#1496)

Athul1897ee621e4e
diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.py
index 434751560..9632a6247 100644
--- a/backend/api_v2/api_deployment_views.py
+++ b/backend/api_v2/api_deployment_views.py
@@ -56,6 +56,7 @@ class DeploymentExecution(views.APIView):
) -> Response:
api: APIDeployment = deployment_execution_dto.api
api_key: str = deployment_execution_dto.api_key
+
serializer = ExecutionRequestSerializer(
data=request.data, context={"api": api, "api_key": api_key}
)
@@ -84,6 +85,7 @@ class DeploymentExecution(views.APIView):
tag_names=tag_names,
llm_profile_id=llm_profile_id,
hitl_queue_name=hitl_queue_name,
+ request_headers=dict(request.headers),
)
if "error" in response and response["error"]:
logger.error("API deployment execution failed")
diff --git a/backend/api_v2/deployment_helper.py b/backend/api_v2/deployment_helper.py
index 82d2e8f6a..a70207ee8 100644
--- a/backend/api_v2/deployment_helper.py
+++ b/backend/api_v2/deployment_helper.py
@@ -7,6 +7,7 @@ import requests
from configuration.models import Configuration
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile, UploadedFile
+from plugins.workflow_manager.workflow_v2.api_hub_usage_utils import APIHubUsageUtil
from rest_framework.request import Request
from rest_framework.serializers import Serializer
from rest_framework.utils.serializer_helpers import ReturnDict
@@ -154,6 +155,7 @@ class DeploymentHelper(BaseAPIKeyValidator):
tag_names: list[str] = [],
llm_profile_id: str | None = None,
hitl_queue_name: str | None = None,
+ request_headers=None,
) -> ReturnDict:
"""Execute workflow by api.
@@ -186,6 +188,33 @@ class DeploymentHelper(BaseAPIKeyValidator):
)
execution_id = workflow_execution.id
+ # Store API hub headers for usage tracking (enterprise feature)
+ if request_headers:
+ try:
+ # Extract and normalize API hub headers
+ normalized_headers = APIHubUsageUtil.extract_api_hub_headers(
+ request_headers
+ )
+
+ if normalized_headers:
+ # Cache headers for later usage tracking by file execution tasks
+ success = APIHubUsageUtil.cache_api_hub_headers(
+ str(execution_id), normalized_headers
+ )
+ if not success:
+ logger.warning(
+ f"Failed to cache API hub headers for execution {execution_id}"
+ )
+ else:
+ logger.debug(
+ "No API hub subscription headers found in request headers"
+ )
+ except Exception as e:
+ # Log but don't fail the API execution for header caching issues
+ logger.debug(
+ f"API hub header caching failed for execution {execution_id}: {e}"
+ )
+
hash_values_of_files = SourceConnector.add_input_file_to_api_storage(
pipeline_id=pipeline_id,
workflow_id=workflow_id,
diff --git a/backend/plugins/workflow_manager/workflow_v2/api_hub_usage_utils.py b/backend/plugins/workflow_manager/workflow_v2/api_hub_usage_utils.py
new file mode 100644
index 000000000..3b895773e
--- /dev/null
+++ b/backend/plugins/workflow_manager/workflow_v2/api_hub_usage_utils.py
@@ -0,0 +1,80 @@
+"""API Hub usage tracking utilities for workflow execution.
+
+This module provides a clean interface for API Hub usage tracking in workflows.
+The OSS version provides default no-op implementations that can be overridden
+by enterprise plugins during the build process.
+"""
+
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+class APIHubUsageUtil:
+ """Utility class for handling API Hub usage tracking in workflows.
+
+ This is the OSS version that provides default no-op implementations.
+ Enterprise builds will replace this file with enhanced functionality.
+ """
+
+ @staticmethod
+ def track_api_hub_usage(
+ workflow_execution_id: str,
+ workflow_file_execution_id: str,
+ organization_id: str | None = None,
+ ) -> bool:
+ """Track API hub usage if enterprise plugin is available.
+
+ OSS version: This is a no-op implementation that always returns False.
+ Enterprise version: Will track actual usage in verticals.subscription_usage table.
+
+ Args:
+ workflow_execution_id: The workflow execution ID
+ workflow_file_execution_id: The file execution ID
+ organization_id: Optional organization ID
+
+ Returns:
+ bool: False in OSS version (usage tracking not available).
+ Enterprise version returns True if tracking succeeded.
+ """
+ # OSS version - no usage tracking available
+ logger.debug("API hub usage tracking not available in OSS version")
+ return False
+
+ @staticmethod
+ def extract_api_hub_headers(request_headers: dict) -> dict | None:
+ """Extract API hub headers from request headers.
+
+ OSS version: Returns None (no API hub support).
+ Enterprise version: Extracts and normalizes API hub headers.
+
+ Args:
+ request_headers: Request headers dictionary
+
+ Returns:
+ None in OSS version. Enterprise version returns normalized headers.
+ """
+ # OSS version - no API hub header extraction
+ return None
+
+ @staticmethod
+ def cache_api_hub_headers(
+ execution_id: str,
+ headers: dict,
+ ttl_seconds: int = 7200,
+ ) -> bool:
+ """Cache API hub headers for later usage tracking.
+
+ OSS version: No-op implementation.
+ Enterprise version: Caches headers in Redis.
+
+ Args:
+ execution_id: The execution ID to use as cache key
+ headers: Headers to cache
+ ttl_seconds: Time-to-live in seconds (default 2 hours)
+
+ Returns:
+ False in OSS version. Enterprise version returns True if caching succeeded.
+ """
+ # OSS version - no caching available
+ return False
diff --git a/backend/workflow_manager/workflow_v2/file_execution_tasks.py b/backend/workflow_manager/workflow_v2/file_execution_tasks.py
index 36ea1cc00..a978abb26 100644
--- a/backend/workflow_manager/workflow_v2/file_execution_tasks.py
+++ b/backend/workflow_manager/workflow_v2/file_execution_tasks.py
@@ -4,6 +4,7 @@ from uuid import UUID
from account_v2.constants import Common
from django.conf import settings
+from plugins.workflow_manager.workflow_v2.api_hub_usage_utils import APIHubUsageUtil
from plugins.workflow_manager.workflow_v2.utils import WorkflowUtil
from tool_instance_v2.constants import ToolInstanceKey
from tool_instance_v2.models import ToolInstance
@@ -1135,6 +1136,27 @@ class FileExecutionTasks:
api_result=final_result,
)
+ # Track usage for API Hub deployments (graceful fallback for OSS)
+ try:
+ organization_id = None
+ if workflow_execution and workflow_execution.workflow:
+ if (
+ hasattr(workflow_execution.workflow, "organization")
+ and workflow_execution.workflow.organization
+ ):
+ organization_id = (
+ workflow_execution.workflow.organization.organization_id
+ )
+
+ APIHubUsageUtil.track_api_hub_usage(
+ workflow_execution_id=str(workflow_execution.id),
+ workflow_file_execution_id=str(workflow_file_execution.id),
+ organization_id=organization_id,
+ )
+ except Exception as e:
+ # Log but don't fail the main execution for usage tracking issues
+ logger.debug(f"Could not track API hub usage: {e}")
+
if destination:
try:
logger.info(