Spaces:
Sleeping
Sleeping
Tadeas Kosek
commited on
Commit
·
3216021
1
Parent(s):
57c92c0
n8n use passed token
Browse files- application/use_cases/process_job.py +43 -33
- domain/services/notification_service.py +2 -1
- infrastructure/clients/n8n/models.py +2 -2
- infrastructure/clients/n8n/n8n_client.py +15 -9
- infrastructure/clients/n8n/settings.py +0 -1
- infrastructure/config/settings.py +1 -1
- infrastructure/services/container.py +12 -6
- infrastructure/services/n8n_notification_service.py +6 -8
application/use_cases/process_job.py
CHANGED
|
@@ -88,18 +88,25 @@ class ProcessJobUseCase:
|
|
| 88 |
processing_time=processing_time
|
| 89 |
)
|
| 90 |
|
| 91 |
-
#
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
# Clear bearer token for security
|
| 103 |
await self.job_repository.clear_bearer_token(job_id)
|
| 104 |
|
| 105 |
logger.info(f"Job {job_id} completed in {processing_time:.2f} seconds")
|
|
@@ -115,29 +122,32 @@ class ProcessJobUseCase:
|
|
| 115 |
processing_time=processing_time
|
| 116 |
)
|
| 117 |
|
| 118 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
try:
|
| 120 |
-
job_record = await self.job_repository.get(job_id)
|
| 121 |
-
bearer_token = job_record.bearer_token if job_record else None
|
| 122 |
-
|
| 123 |
-
await self.notification_service.send_job_completion_notification(
|
| 124 |
-
job_id=job_id,
|
| 125 |
-
status="failed",
|
| 126 |
-
processing_time=processing_time,
|
| 127 |
-
bearer_token=bearer_token
|
| 128 |
-
)
|
| 129 |
-
|
| 130 |
-
# Clear bearer token for security after notification is sent
|
| 131 |
await self.job_repository.clear_bearer_token(job_id)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
# Don't let notification failures mask the original job failure
|
| 135 |
-
logger.warning(f"Failed to send failure notification for job {job_id}: {notify_error}")
|
| 136 |
-
|
| 137 |
-
# Still clear the token even if notification failed
|
| 138 |
-
try:
|
| 139 |
-
await self.job_repository.clear_bearer_token(job_id)
|
| 140 |
-
except Exception:
|
| 141 |
-
logger.warning(f"Failed to clear bearer token for failed job {job_id}")
|
| 142 |
|
| 143 |
raise
|
|
|
|
| 88 |
processing_time=processing_time
|
| 89 |
)
|
| 90 |
|
| 91 |
+
# Send notification if service is available and we have a bearer token
|
| 92 |
+
if self.notification_service:
|
| 93 |
+
# Get job record to retrieve bearer token and external job ID
|
| 94 |
+
job_record = await self.job_repository.get(job_id)
|
| 95 |
+
bearer_token = job_record.bearer_token if job_record else None
|
| 96 |
+
external_job_id = job_record.external_job_id if job_record else None
|
| 97 |
+
|
| 98 |
+
if bearer_token:
|
| 99 |
+
await self.notification_service.send_job_completion_notification(
|
| 100 |
+
job_id=job_id,
|
| 101 |
+
status="completed",
|
| 102 |
+
processing_time=processing_time,
|
| 103 |
+
bearer_token=bearer_token,
|
| 104 |
+
external_job_id=external_job_id
|
| 105 |
+
)
|
| 106 |
+
else:
|
| 107 |
+
logger.debug(f"Skipping N8N notification for job {job_id} - no bearer token available")
|
| 108 |
|
| 109 |
+
# Clear bearer token for security (regardless of notification status)
|
| 110 |
await self.job_repository.clear_bearer_token(job_id)
|
| 111 |
|
| 112 |
logger.info(f"Job {job_id} completed in {processing_time:.2f} seconds")
|
|
|
|
| 122 |
processing_time=processing_time
|
| 123 |
)
|
| 124 |
|
| 125 |
+
# Send failure notification if service is available and we have a bearer token
|
| 126 |
+
if self.notification_service:
|
| 127 |
+
try:
|
| 128 |
+
job_record = await self.job_repository.get(job_id)
|
| 129 |
+
bearer_token = job_record.bearer_token if job_record else None
|
| 130 |
+
external_job_id = job_record.external_job_id if job_record else None
|
| 131 |
+
|
| 132 |
+
if bearer_token:
|
| 133 |
+
await self.notification_service.send_job_completion_notification(
|
| 134 |
+
job_id=job_id,
|
| 135 |
+
status="failed",
|
| 136 |
+
processing_time=processing_time,
|
| 137 |
+
bearer_token=bearer_token,
|
| 138 |
+
external_job_id=external_job_id
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
logger.debug(f"Skipping N8N failure notification for job {job_id} - no bearer token available")
|
| 142 |
+
|
| 143 |
+
except Exception as notify_error:
|
| 144 |
+
# Don't let notification failures mask the original job failure
|
| 145 |
+
logger.warning(f"Failed to send failure notification for job {job_id}: {notify_error}")
|
| 146 |
+
|
| 147 |
+
# Clear bearer token for security (regardless of notification status)
|
| 148 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
await self.job_repository.clear_bearer_token(job_id)
|
| 150 |
+
except Exception:
|
| 151 |
+
logger.warning(f"Failed to clear bearer token for failed job {job_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
raise
|
domain/services/notification_service.py
CHANGED
|
@@ -17,5 +17,6 @@ class NotificationService(Protocol):
|
|
| 17 |
job_id: str,
|
| 18 |
status: str,
|
| 19 |
processing_time: float,
|
| 20 |
-
bearer_token:
|
|
|
|
| 21 |
...
|
|
|
|
| 17 |
job_id: str,
|
| 18 |
status: str,
|
| 19 |
processing_time: float,
|
| 20 |
+
bearer_token: str,
|
| 21 |
+
external_job_id: Optional[str] = None) -> NotificationResponse:
|
| 22 |
...
|
infrastructure/clients/n8n/models.py
CHANGED
|
@@ -18,6 +18,6 @@ class WebhooksResponse:
|
|
| 18 |
class N8NClientProtocol(Protocol):
|
| 19 |
"""Protocol defining the API client interface."""
|
| 20 |
|
| 21 |
-
async def post_completion_event(self, data: WebhooksRequest, bearer_token: Optional[str] = None) -> WebhooksResponse:
|
| 22 |
-
"""Post to webhooks endpoint with
|
| 23 |
...
|
|
|
|
| 18 |
class N8NClientProtocol(Protocol):
|
| 19 |
"""Protocol defining the API client interface."""
|
| 20 |
|
| 21 |
+
async def post_completion_event(self, data: WebhooksRequest, bearer_token: str, external_job_id: Optional[str] = None) -> WebhooksResponse:
|
| 22 |
+
"""Post to webhooks endpoint with client bearer token for authentication."""
|
| 23 |
...
|
infrastructure/clients/n8n/n8n_client.py
CHANGED
|
@@ -21,9 +21,8 @@ class N8NClient(N8NClientProtocol):
|
|
| 21 |
)
|
| 22 |
|
| 23 |
def _get_default_headers(self) -> Dict[str, str]:
|
| 24 |
-
"""Get default headers
|
| 25 |
return {
|
| 26 |
-
"Authorization": f"Bearer {self.settings.token}",
|
| 27 |
"Content-Type": "application/json",
|
| 28 |
"Accept": "application/json"
|
| 29 |
}
|
|
@@ -88,19 +87,26 @@ class N8NClient(N8NClientProtocol):
|
|
| 88 |
self.logger.error(f"Failed to parse JSON response from {url}: {str(e)}")
|
| 89 |
raise APIResponseError(f"Invalid JSON response: {str(e)}", response.status_code)
|
| 90 |
|
| 91 |
-
async def post_completion_event(self, data: WebhooksRequest, bearer_token: Optional[str] = None) -> WebhooksResponse:
|
| 92 |
-
"""Post to webhooks endpoint with
|
| 93 |
from dataclasses import asdict
|
| 94 |
payload = asdict(data)
|
| 95 |
|
| 96 |
# Extract job_id for header and remove from payload
|
| 97 |
job_id = payload.pop("job_id")
|
| 98 |
-
custom_headers = {"rowID": job_id}
|
| 99 |
|
| 100 |
-
#
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
response_data = await self._make_request("POST", "/lovable-analysis", payload, custom_headers)
|
| 106 |
|
|
|
|
| 21 |
)
|
| 22 |
|
| 23 |
def _get_default_headers(self) -> Dict[str, str]:
|
| 24 |
+
"""Get default headers (no authentication - client token will be provided per request)."""
|
| 25 |
return {
|
|
|
|
| 26 |
"Content-Type": "application/json",
|
| 27 |
"Accept": "application/json"
|
| 28 |
}
|
|
|
|
| 87 |
self.logger.error(f"Failed to parse JSON response from {url}: {str(e)}")
|
| 88 |
raise APIResponseError(f"Invalid JSON response: {str(e)}", response.status_code)
|
| 89 |
|
| 90 |
+
async def post_completion_event(self, data: WebhooksRequest, bearer_token: str, external_job_id: Optional[str] = None) -> WebhooksResponse:
|
| 91 |
+
"""Post to webhooks endpoint with client bearer token for authentication."""
|
| 92 |
from dataclasses import asdict
|
| 93 |
payload = asdict(data)
|
| 94 |
|
| 95 |
# Extract job_id for header and remove from payload
|
| 96 |
job_id = payload.pop("job_id")
|
|
|
|
| 97 |
|
| 98 |
+
# Client bearer token is required for authentication to N8N
|
| 99 |
+
custom_headers = {
|
| 100 |
+
"rowID": job_id,
|
| 101 |
+
"Authorization": f"Bearer {bearer_token}"
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
# Add external job ID as custom header if provided
|
| 105 |
+
if external_job_id:
|
| 106 |
+
custom_headers["externalJobID"] = external_job_id
|
| 107 |
+
self.logger.debug(f"Sending N8N notification for job {job_id} with external job ID {external_job_id}")
|
| 108 |
+
else:
|
| 109 |
+
self.logger.debug(f"Sending N8N notification for job {job_id} using client bearer token")
|
| 110 |
|
| 111 |
response_data = await self._make_request("POST", "/lovable-analysis", payload, custom_headers)
|
| 112 |
|
infrastructure/clients/n8n/settings.py
CHANGED
|
@@ -6,5 +6,4 @@ from typing import Optional
|
|
| 6 |
class ClientSettings:
|
| 7 |
"""Settings for the HTTP client."""
|
| 8 |
base_url: str
|
| 9 |
-
token: str
|
| 10 |
timeout: Optional[int] = 30
|
|
|
|
| 6 |
class ClientSettings:
|
| 7 |
"""Settings for the HTTP client."""
|
| 8 |
base_url: str
|
|
|
|
| 9 |
timeout: Optional[int] = 30
|
infrastructure/config/settings.py
CHANGED
|
@@ -88,8 +88,8 @@ class Settings(BaseSettings):
|
|
| 88 |
|
| 89 |
# N8N Configuration
|
| 90 |
n8n_base_url: str = Field(default="http://localhost:5678", env="N8N_BASE_URL")
|
| 91 |
-
n8n_token: str = Field(env="N8N_TOKEN")
|
| 92 |
n8n_timeout: int = Field(default=30, env="N8N_TIMEOUT")
|
|
|
|
| 93 |
|
| 94 |
# Authentication Configuration
|
| 95 |
enforce_authentication: bool = Field(default=True, env="ENFORCE_AUTHENTICATION")
|
|
|
|
| 88 |
|
| 89 |
# N8N Configuration
|
| 90 |
n8n_base_url: str = Field(default="http://localhost:5678", env="N8N_BASE_URL")
|
|
|
|
| 91 |
n8n_timeout: int = Field(default=30, env="N8N_TIMEOUT")
|
| 92 |
+
n8n_enabled: bool = Field(default=True, env="N8N_ENABLED")
|
| 93 |
|
| 94 |
# Authentication Configuration
|
| 95 |
enforce_authentication: bool = Field(default=True, env="ENFORCE_AUTHENTICATION")
|
infrastructure/services/container.py
CHANGED
|
@@ -61,12 +61,16 @@ class ServiceContainer:
|
|
| 61 |
else:
|
| 62 |
raise ValueError(f"Unsupported storage type: {settings.storage_type}")
|
| 63 |
|
| 64 |
-
def _create_notification_service(self) -> N8NNotificationService:
|
| 65 |
-
"""Create N8N notification service."""
|
| 66 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
n8n_settings = ClientSettings(
|
| 68 |
base_url=settings.n8n_base_url,
|
| 69 |
-
token=settings.n8n_token,
|
| 70 |
timeout=getattr(settings, 'n8n_timeout', 30)
|
| 71 |
)
|
| 72 |
|
|
@@ -93,8 +97,10 @@ class ServiceContainer:
|
|
| 93 |
async def shutdown(self):
|
| 94 |
"""Cleanup services on shutdown."""
|
| 95 |
await self.cleanup_service.stop()
|
| 96 |
-
# Close N8N client if it has async cleanup
|
| 97 |
-
if
|
|
|
|
|
|
|
| 98 |
await self.notification_service.n8n_client.close()
|
| 99 |
|
| 100 |
# Convenience function for getting services
|
|
|
|
| 61 |
else:
|
| 62 |
raise ValueError(f"Unsupported storage type: {settings.storage_type}")
|
| 63 |
|
| 64 |
+
def _create_notification_service(self) -> Optional[N8NNotificationService]:
|
| 65 |
+
"""Create N8N notification service if enabled."""
|
| 66 |
+
# Check if N8N is enabled
|
| 67 |
+
if not settings.n8n_enabled:
|
| 68 |
+
logging.getLogger(__name__).info("N8N notifications disabled via configuration")
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
# Create N8N client settings (no token needed - client tokens are passed per request)
|
| 72 |
n8n_settings = ClientSettings(
|
| 73 |
base_url=settings.n8n_base_url,
|
|
|
|
| 74 |
timeout=getattr(settings, 'n8n_timeout', 30)
|
| 75 |
)
|
| 76 |
|
|
|
|
| 97 |
async def shutdown(self):
|
| 98 |
"""Cleanup services on shutdown."""
|
| 99 |
await self.cleanup_service.stop()
|
| 100 |
+
# Close N8N client if it exists and has async cleanup
|
| 101 |
+
if (self.notification_service and
|
| 102 |
+
hasattr(self.notification_service, 'n8n_client') and
|
| 103 |
+
hasattr(self.notification_service.n8n_client, 'close')):
|
| 104 |
await self.notification_service.n8n_client.close()
|
| 105 |
|
| 106 |
# Convenience function for getting services
|
infrastructure/services/n8n_notification_service.py
CHANGED
|
@@ -25,19 +25,17 @@ class N8NNotificationService(NotificationService):
|
|
| 25 |
job_id: str,
|
| 26 |
status: str,
|
| 27 |
processing_time: float,
|
| 28 |
-
bearer_token:
|
| 29 |
-
|
|
|
|
| 30 |
try:
|
| 31 |
message = f"Job {job_id} {status} in {processing_time:.2f}s"
|
| 32 |
request = NotificationRequest(message=message, job_id=job_id)
|
| 33 |
|
| 34 |
-
# Pass bearer token to N8N client
|
| 35 |
-
response = await self.n8n_client.post_completion_event(request, bearer_token)
|
| 36 |
|
| 37 |
-
|
| 38 |
-
logger.debug(f"Sent N8N notification for job {job_id} with client bearer token")
|
| 39 |
-
else:
|
| 40 |
-
logger.debug(f"Sent N8N notification for job {job_id} without client bearer token")
|
| 41 |
|
| 42 |
return NotificationResponse(acknowledged=response.acknowledged)
|
| 43 |
|
|
|
|
| 25 |
job_id: str,
|
| 26 |
status: str,
|
| 27 |
processing_time: float,
|
| 28 |
+
bearer_token: str,
|
| 29 |
+
external_job_id: Optional[str] = None) -> NotificationResponse:
|
| 30 |
+
"""Send job completion notification via N8N with client bearer token for authentication."""
|
| 31 |
try:
|
| 32 |
message = f"Job {job_id} {status} in {processing_time:.2f}s"
|
| 33 |
request = NotificationRequest(message=message, job_id=job_id)
|
| 34 |
|
| 35 |
+
# Pass client bearer token and external job ID to N8N client
|
| 36 |
+
response = await self.n8n_client.post_completion_event(request, bearer_token, external_job_id)
|
| 37 |
|
| 38 |
+
logger.debug(f"Sent N8N notification for job {job_id} using client bearer token")
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
return NotificationResponse(acknowledged=response.acknowledged)
|
| 41 |
|