AI platform insights monitoring and website analysis monitoring services added
This commit is contained in:
298
backend/services/scheduler/executors/bing_insights_executor.py
Normal file
298
backend/services/scheduler/executors/bing_insights_executor.py
Normal file
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
Bing Insights Task Executor
|
||||
Handles execution of Bing insights fetch tasks for connected platforms.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.executor_interface import TaskExecutor, TaskExecutionResult
|
||||
from ..core.exception_handler import TaskExecutionError, DatabaseError, SchedulerExceptionHandler
|
||||
from models.platform_insights_monitoring_models import PlatformInsightsTask, PlatformInsightsExecutionLog
|
||||
from services.bing_analytics_storage_service import BingAnalyticsStorageService
|
||||
from services.integrations.bing_oauth import BingOAuthService
|
||||
from utils.logger_utils import get_service_logger
|
||||
|
||||
logger = get_service_logger("bing_insights_executor")
|
||||
|
||||
|
||||
class BingInsightsExecutor(TaskExecutor):
|
||||
"""
|
||||
Executor for Bing insights fetch tasks.
|
||||
|
||||
Handles:
|
||||
- Fetching Bing insights data weekly
|
||||
- On first run: Loads existing cached data
|
||||
- On subsequent runs: Fetches fresh data from Bing API
|
||||
- Logging results and updating task status
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logger
|
||||
self.exception_handler = SchedulerExceptionHandler()
|
||||
database_url = os.getenv('DATABASE_URL', 'sqlite:///alwrity.db')
|
||||
self.storage_service = BingAnalyticsStorageService(database_url)
|
||||
self.bing_oauth = BingOAuthService()
|
||||
|
||||
async def execute_task(self, task: PlatformInsightsTask, db: Session) -> TaskExecutionResult:
|
||||
"""
|
||||
Execute a Bing insights fetch task.
|
||||
|
||||
Args:
|
||||
task: PlatformInsightsTask instance
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
TaskExecutionResult
|
||||
"""
|
||||
start_time = time.time()
|
||||
user_id = task.user_id
|
||||
site_url = task.site_url
|
||||
|
||||
try:
|
||||
self.logger.info(
|
||||
f"Executing Bing insights fetch: task_id={task.id} | "
|
||||
f"user_id={user_id} | site_url={site_url}"
|
||||
)
|
||||
|
||||
# Create execution log
|
||||
execution_log = PlatformInsightsExecutionLog(
|
||||
task_id=task.id,
|
||||
execution_date=datetime.utcnow(),
|
||||
status='running'
|
||||
)
|
||||
db.add(execution_log)
|
||||
db.flush()
|
||||
|
||||
# Fetch insights
|
||||
result = await self._fetch_insights(task, db)
|
||||
|
||||
# Update execution log
|
||||
execution_time_ms = int((time.time() - start_time) * 1000)
|
||||
execution_log.status = 'success' if result.success else 'failed'
|
||||
execution_log.result_data = result.result_data
|
||||
execution_log.error_message = result.error_message
|
||||
execution_log.execution_time_ms = execution_time_ms
|
||||
execution_log.data_source = result.result_data.get('data_source') if result.success else None
|
||||
|
||||
# Update task based on result
|
||||
task.last_check = datetime.utcnow()
|
||||
|
||||
if result.success:
|
||||
task.last_success = datetime.utcnow()
|
||||
task.status = 'active'
|
||||
task.failure_reason = None
|
||||
# Schedule next check (7 days from now)
|
||||
task.next_check = self.calculate_next_execution(
|
||||
task=task,
|
||||
frequency='Weekly',
|
||||
last_execution=task.last_check
|
||||
)
|
||||
else:
|
||||
task.last_failure = datetime.utcnow()
|
||||
task.failure_reason = result.error_message
|
||||
task.status = 'failed'
|
||||
# Schedule retry in 1 day
|
||||
task.next_check = datetime.utcnow() + timedelta(days=1)
|
||||
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
execution_time_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
# Set database session for exception handler
|
||||
self.exception_handler.db = db
|
||||
|
||||
error_result = self.exception_handler.handle_task_execution_error(
|
||||
task=task,
|
||||
error=e,
|
||||
execution_time_ms=execution_time_ms,
|
||||
context="Bing insights fetch"
|
||||
)
|
||||
|
||||
# Update task
|
||||
task.last_check = datetime.utcnow()
|
||||
task.last_failure = datetime.utcnow()
|
||||
task.failure_reason = str(e)
|
||||
task.status = 'failed'
|
||||
task.next_check = datetime.utcnow() + timedelta(days=1)
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
return error_result
|
||||
|
||||
async def _fetch_insights(self, task: PlatformInsightsTask, db: Session) -> TaskExecutionResult:
|
||||
"""
|
||||
Fetch Bing insights data.
|
||||
|
||||
On first run (no last_success), loads cached data.
|
||||
On subsequent runs, fetches fresh data from API.
|
||||
"""
|
||||
user_id = task.user_id
|
||||
site_url = task.site_url
|
||||
|
||||
try:
|
||||
# Check if this is first run (no previous success)
|
||||
is_first_run = task.last_success is None
|
||||
|
||||
if is_first_run:
|
||||
# First run: Try to load from cache
|
||||
self.logger.info(f"First run for Bing insights task {task.id} - loading cached data")
|
||||
cached_data = self._load_cached_data(user_id, site_url)
|
||||
|
||||
if cached_data:
|
||||
self.logger.info(f"Loaded cached Bing data for user {user_id}")
|
||||
return TaskExecutionResult(
|
||||
success=True,
|
||||
result_data={
|
||||
'data_source': 'cached',
|
||||
'insights': cached_data,
|
||||
'message': 'Loaded from cached data (first run)'
|
||||
}
|
||||
)
|
||||
else:
|
||||
# No cached data - try to fetch from API
|
||||
self.logger.info(f"No cached data found, fetching from Bing API")
|
||||
return await self._fetch_fresh_data(user_id, site_url)
|
||||
else:
|
||||
# Subsequent run: Always fetch fresh data
|
||||
self.logger.info(f"Subsequent run for Bing insights task {task.id} - fetching fresh data")
|
||||
return await self._fetch_fresh_data(user_id, site_url)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error fetching Bing insights for user {user_id}: {e}", exc_info=True)
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=f"Failed to fetch Bing insights: {str(e)}",
|
||||
result_data={'error': str(e)}
|
||||
)
|
||||
|
||||
def _load_cached_data(self, user_id: str, site_url: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
"""Load most recent cached Bing data from database."""
|
||||
try:
|
||||
# Get analytics summary from storage service
|
||||
summary = self.storage_service.get_analytics_summary(
|
||||
user_id=user_id,
|
||||
site_url=site_url or '',
|
||||
days=30
|
||||
)
|
||||
|
||||
if summary and isinstance(summary, dict):
|
||||
self.logger.info(f"Found cached Bing data for user {user_id}")
|
||||
return summary
|
||||
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Error loading cached Bing data: {e}")
|
||||
return None
|
||||
|
||||
async def _fetch_fresh_data(self, user_id: str, site_url: Optional[str]) -> TaskExecutionResult:
|
||||
"""Fetch fresh Bing insights from API."""
|
||||
try:
|
||||
# Check if user has active tokens
|
||||
token_status = self.bing_oauth.get_user_token_status(user_id)
|
||||
|
||||
if not token_status.get('has_active_tokens'):
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message="Bing Webmaster tokens not available or expired",
|
||||
result_data={'error': 'No active tokens'}
|
||||
)
|
||||
|
||||
# Get user's sites
|
||||
sites = self.bing_oauth.get_user_sites(user_id)
|
||||
|
||||
if not sites:
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message="No Bing Webmaster sites found",
|
||||
result_data={'error': 'No sites found'}
|
||||
)
|
||||
|
||||
# Use provided site_url or first site
|
||||
if not site_url:
|
||||
site_url = sites[0].get('Url', '') if isinstance(sites[0], dict) else sites[0]
|
||||
|
||||
# Get active token
|
||||
active_tokens = token_status.get('active_tokens', [])
|
||||
if not active_tokens:
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message="No active Bing Webmaster tokens",
|
||||
result_data={'error': 'No tokens'}
|
||||
)
|
||||
|
||||
# For now, use stored analytics data (Bing API integration can be added later)
|
||||
# This ensures we have data available even if the API class doesn't exist yet
|
||||
summary = self.storage_service.get_analytics_summary(user_id, site_url, days=30)
|
||||
|
||||
if summary and isinstance(summary, dict):
|
||||
# Format insights data from stored analytics
|
||||
insights_data = {
|
||||
'site_url': site_url,
|
||||
'date_range': {
|
||||
'start': (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'),
|
||||
'end': datetime.now().strftime('%Y-%m-%d')
|
||||
},
|
||||
'summary': summary.get('summary', {}),
|
||||
'fetched_at': datetime.utcnow().isoformat()
|
||||
}
|
||||
|
||||
self.logger.info(
|
||||
f"Successfully loaded Bing insights from storage for user {user_id}, site {site_url}"
|
||||
)
|
||||
|
||||
return TaskExecutionResult(
|
||||
success=True,
|
||||
result_data={
|
||||
'data_source': 'storage',
|
||||
'insights': insights_data,
|
||||
'message': 'Loaded from stored analytics data'
|
||||
}
|
||||
)
|
||||
else:
|
||||
# No stored data available
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message="No Bing analytics data available. Data will be collected during next onboarding refresh.",
|
||||
result_data={'error': 'No stored data available'}
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error fetching fresh Bing data: {e}", exc_info=True)
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=f"API fetch failed: {str(e)}",
|
||||
result_data={'error': str(e)}
|
||||
)
|
||||
|
||||
def calculate_next_execution(
|
||||
self,
|
||||
task: PlatformInsightsTask,
|
||||
frequency: str,
|
||||
last_execution: Optional[datetime] = None
|
||||
) -> datetime:
|
||||
"""
|
||||
Calculate next execution time based on frequency.
|
||||
|
||||
For platform insights, frequency is always 'Weekly' (7 days).
|
||||
"""
|
||||
if last_execution is None:
|
||||
last_execution = datetime.utcnow()
|
||||
|
||||
if frequency == 'Weekly':
|
||||
return last_execution + timedelta(days=7)
|
||||
elif frequency == 'Daily':
|
||||
return last_execution + timedelta(days=1)
|
||||
else:
|
||||
# Default to weekly
|
||||
return last_execution + timedelta(days=7)
|
||||
|
||||
307
backend/services/scheduler/executors/gsc_insights_executor.py
Normal file
307
backend/services/scheduler/executors/gsc_insights_executor.py
Normal file
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
GSC Insights Task Executor
|
||||
Handles execution of GSC insights fetch tasks for connected platforms.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
import sqlite3
|
||||
|
||||
from ..core.executor_interface import TaskExecutor, TaskExecutionResult
|
||||
from ..core.exception_handler import TaskExecutionError, DatabaseError, SchedulerExceptionHandler
|
||||
from models.platform_insights_monitoring_models import PlatformInsightsTask, PlatformInsightsExecutionLog
|
||||
from services.gsc_service import GSCService
|
||||
from utils.logger_utils import get_service_logger
|
||||
|
||||
logger = get_service_logger("gsc_insights_executor")
|
||||
|
||||
|
||||
class GSCInsightsExecutor(TaskExecutor):
|
||||
"""
|
||||
Executor for GSC insights fetch tasks.
|
||||
|
||||
Handles:
|
||||
- Fetching GSC insights data weekly
|
||||
- On first run: Loads existing cached data
|
||||
- On subsequent runs: Fetches fresh data from GSC API
|
||||
- Logging results and updating task status
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logger
|
||||
self.exception_handler = SchedulerExceptionHandler()
|
||||
self.gsc_service = GSCService()
|
||||
|
||||
async def execute_task(self, task: PlatformInsightsTask, db: Session) -> TaskExecutionResult:
|
||||
"""
|
||||
Execute a GSC insights fetch task.
|
||||
|
||||
Args:
|
||||
task: PlatformInsightsTask instance
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
TaskExecutionResult
|
||||
"""
|
||||
start_time = time.time()
|
||||
user_id = task.user_id
|
||||
site_url = task.site_url
|
||||
|
||||
try:
|
||||
self.logger.info(
|
||||
f"Executing GSC insights fetch: task_id={task.id} | "
|
||||
f"user_id={user_id} | site_url={site_url}"
|
||||
)
|
||||
|
||||
# Create execution log
|
||||
execution_log = PlatformInsightsExecutionLog(
|
||||
task_id=task.id,
|
||||
execution_date=datetime.utcnow(),
|
||||
status='running'
|
||||
)
|
||||
db.add(execution_log)
|
||||
db.flush()
|
||||
|
||||
# Fetch insights
|
||||
result = await self._fetch_insights(task, db)
|
||||
|
||||
# Update execution log
|
||||
execution_time_ms = int((time.time() - start_time) * 1000)
|
||||
execution_log.status = 'success' if result.success else 'failed'
|
||||
execution_log.result_data = result.result_data
|
||||
execution_log.error_message = result.error_message
|
||||
execution_log.execution_time_ms = execution_time_ms
|
||||
execution_log.data_source = result.result_data.get('data_source') if result.success else None
|
||||
|
||||
# Update task based on result
|
||||
task.last_check = datetime.utcnow()
|
||||
|
||||
if result.success:
|
||||
task.last_success = datetime.utcnow()
|
||||
task.status = 'active'
|
||||
task.failure_reason = None
|
||||
# Schedule next check (7 days from now)
|
||||
task.next_check = self.calculate_next_execution(
|
||||
task=task,
|
||||
frequency='Weekly',
|
||||
last_execution=task.last_check
|
||||
)
|
||||
else:
|
||||
task.last_failure = datetime.utcnow()
|
||||
task.failure_reason = result.error_message
|
||||
task.status = 'failed'
|
||||
# Schedule retry in 1 day
|
||||
task.next_check = datetime.utcnow() + timedelta(days=1)
|
||||
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
execution_time_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
# Set database session for exception handler
|
||||
self.exception_handler.db = db
|
||||
|
||||
error_result = self.exception_handler.handle_task_execution_error(
|
||||
task=task,
|
||||
error=e,
|
||||
execution_time_ms=execution_time_ms,
|
||||
context="GSC insights fetch"
|
||||
)
|
||||
|
||||
# Update task
|
||||
task.last_check = datetime.utcnow()
|
||||
task.last_failure = datetime.utcnow()
|
||||
task.failure_reason = str(e)
|
||||
task.status = 'failed'
|
||||
task.next_check = datetime.utcnow() + timedelta(days=1)
|
||||
task.updated_at = datetime.utcnow()
|
||||
db.commit()
|
||||
|
||||
return error_result
|
||||
|
||||
async def _fetch_insights(self, task: PlatformInsightsTask, db: Session) -> TaskExecutionResult:
|
||||
"""
|
||||
Fetch GSC insights data.
|
||||
|
||||
On first run (no last_success), loads cached data.
|
||||
On subsequent runs, fetches fresh data from API.
|
||||
"""
|
||||
user_id = task.user_id
|
||||
site_url = task.site_url
|
||||
|
||||
try:
|
||||
# Check if this is first run (no previous success)
|
||||
is_first_run = task.last_success is None
|
||||
|
||||
if is_first_run:
|
||||
# First run: Try to load from cache
|
||||
self.logger.info(f"First run for GSC insights task {task.id} - loading cached data")
|
||||
cached_data = self._load_cached_data(user_id, site_url)
|
||||
|
||||
if cached_data:
|
||||
self.logger.info(f"Loaded cached GSC data for user {user_id}")
|
||||
return TaskExecutionResult(
|
||||
success=True,
|
||||
result_data={
|
||||
'data_source': 'cached',
|
||||
'insights': cached_data,
|
||||
'message': 'Loaded from cached data (first run)'
|
||||
}
|
||||
)
|
||||
else:
|
||||
# No cached data - try to fetch from API
|
||||
self.logger.info(f"No cached data found, fetching from GSC API")
|
||||
return await self._fetch_fresh_data(user_id, site_url)
|
||||
else:
|
||||
# Subsequent run: Always fetch fresh data
|
||||
self.logger.info(f"Subsequent run for GSC insights task {task.id} - fetching fresh data")
|
||||
return await self._fetch_fresh_data(user_id, site_url)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error fetching GSC insights for user {user_id}: {e}", exc_info=True)
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=f"Failed to fetch GSC insights: {str(e)}",
|
||||
result_data={'error': str(e)}
|
||||
)
|
||||
|
||||
def _load_cached_data(self, user_id: str, site_url: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
"""Load most recent cached GSC data from database."""
|
||||
try:
|
||||
db_path = self.gsc_service.db_path
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Find most recent cached data
|
||||
if site_url:
|
||||
cursor.execute('''
|
||||
SELECT data_json, created_at
|
||||
FROM gsc_data_cache
|
||||
WHERE user_id = ? AND site_url = ? AND data_type = 'analytics'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
''', (user_id, site_url))
|
||||
else:
|
||||
cursor.execute('''
|
||||
SELECT data_json, created_at
|
||||
FROM gsc_data_cache
|
||||
WHERE user_id = ? AND data_type = 'analytics'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
''', (user_id,))
|
||||
|
||||
result = cursor.fetchone()
|
||||
|
||||
if result:
|
||||
data_json, created_at = result
|
||||
insights_data = json.loads(data_json) if isinstance(data_json, str) else data_json
|
||||
|
||||
self.logger.info(
|
||||
f"Found cached GSC data from {created_at} for user {user_id}"
|
||||
)
|
||||
|
||||
return insights_data
|
||||
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Error loading cached GSC data: {e}")
|
||||
return None
|
||||
|
||||
async def _fetch_fresh_data(self, user_id: str, site_url: Optional[str]) -> TaskExecutionResult:
|
||||
"""Fetch fresh GSC insights from API."""
|
||||
try:
|
||||
# If no site_url, get first site
|
||||
if not site_url:
|
||||
sites = self.gsc_service.get_site_list(user_id)
|
||||
if not sites:
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message="No GSC sites found for user",
|
||||
result_data={'error': 'No sites found'}
|
||||
)
|
||||
site_url = sites[0]['siteUrl']
|
||||
|
||||
# Get analytics for last 30 days
|
||||
end_date = datetime.now().strftime('%Y-%m-%d')
|
||||
start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
|
||||
|
||||
# Fetch search analytics
|
||||
search_analytics = self.gsc_service.get_search_analytics(
|
||||
user_id=user_id,
|
||||
site_url=site_url,
|
||||
start_date=start_date,
|
||||
end_date=end_date
|
||||
)
|
||||
|
||||
if 'error' in search_analytics:
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=search_analytics.get('error', 'Unknown error'),
|
||||
result_data=search_analytics
|
||||
)
|
||||
|
||||
# Format insights data
|
||||
insights_data = {
|
||||
'site_url': site_url,
|
||||
'date_range': {
|
||||
'start': start_date,
|
||||
'end': end_date
|
||||
},
|
||||
'overall_metrics': search_analytics.get('overall_metrics', {}),
|
||||
'query_data': search_analytics.get('query_data', {}),
|
||||
'fetched_at': datetime.utcnow().isoformat()
|
||||
}
|
||||
|
||||
self.logger.info(
|
||||
f"Successfully fetched GSC insights for user {user_id}, site {site_url}"
|
||||
)
|
||||
|
||||
return TaskExecutionResult(
|
||||
success=True,
|
||||
result_data={
|
||||
'data_source': 'api',
|
||||
'insights': insights_data,
|
||||
'message': 'Fetched fresh data from GSC API'
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error fetching fresh GSC data: {e}", exc_info=True)
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=f"API fetch failed: {str(e)}",
|
||||
result_data={'error': str(e)}
|
||||
)
|
||||
|
||||
def calculate_next_execution(
|
||||
self,
|
||||
task: PlatformInsightsTask,
|
||||
frequency: str,
|
||||
last_execution: Optional[datetime] = None
|
||||
) -> datetime:
|
||||
"""
|
||||
Calculate next execution time based on frequency.
|
||||
|
||||
For platform insights, frequency is always 'Weekly' (7 days).
|
||||
"""
|
||||
if last_execution is None:
|
||||
last_execution = datetime.utcnow()
|
||||
|
||||
if frequency == 'Weekly':
|
||||
return last_execution + timedelta(days=7)
|
||||
elif frequency == 'Daily':
|
||||
return last_execution + timedelta(days=1)
|
||||
else:
|
||||
# Default to weekly
|
||||
return last_execution + timedelta(days=7)
|
||||
|
||||
@@ -197,7 +197,7 @@ class OAuthTokenMonitoringExecutor(TaskExecutor):
|
||||
- GSC: gsc_credentials table (via GSCService)
|
||||
- Bing: bing_oauth_tokens table (via BingOAuthService)
|
||||
- WordPress: wordpress_oauth_tokens table (via WordPressOAuthService)
|
||||
- Wix: Currently in frontend sessionStorage (backend storage TODO)
|
||||
- Wix: wix_oauth_tokens table (via WixOAuthService)
|
||||
|
||||
Args:
|
||||
task: OAuthTokenMonitoringTask instance
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
"""
|
||||
Website Analysis Task Executor
|
||||
Handles execution of website analysis tasks for user and competitor websites.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from functools import partial
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from ..core.executor_interface import TaskExecutor, TaskExecutionResult
|
||||
from ..core.exception_handler import TaskExecutionError, DatabaseError, SchedulerExceptionHandler
|
||||
from models.website_analysis_monitoring_models import WebsiteAnalysisTask, WebsiteAnalysisExecutionLog
|
||||
from models.onboarding import CompetitorAnalysis, OnboardingSession
|
||||
from utils.logger_utils import get_service_logger
|
||||
|
||||
# Import website analysis services
|
||||
from services.component_logic.web_crawler_logic import WebCrawlerLogic
|
||||
from services.component_logic.style_detection_logic import StyleDetectionLogic
|
||||
from services.website_analysis_service import WebsiteAnalysisService
|
||||
|
||||
logger = get_service_logger("website_analysis_executor")
|
||||
|
||||
|
||||
class WebsiteAnalysisExecutor(TaskExecutor):
|
||||
"""
|
||||
Executor for website analysis tasks.
|
||||
|
||||
Handles:
|
||||
- Analyzing user's website (updates existing WebsiteAnalysis record)
|
||||
- Analyzing competitor websites (stores in CompetitorAnalysis table)
|
||||
- Logging results and updating task status
|
||||
- Scheduling next execution based on frequency_days
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logger
|
||||
self.exception_handler = SchedulerExceptionHandler()
|
||||
self.crawler_logic = WebCrawlerLogic()
|
||||
self.style_logic = StyleDetectionLogic()
|
||||
|
||||
async def execute_task(
|
||||
self,
|
||||
task: WebsiteAnalysisTask,
|
||||
db: Session
|
||||
) -> TaskExecutionResult:
|
||||
"""
|
||||
Execute a website analysis task.
|
||||
|
||||
This performs complete website analysis using the same logic as
|
||||
/api/onboarding/style-detection/complete endpoint.
|
||||
|
||||
Args:
|
||||
task: WebsiteAnalysisTask instance
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
TaskExecutionResult
|
||||
"""
|
||||
start_time = time.time()
|
||||
user_id = task.user_id
|
||||
website_url = task.website_url
|
||||
task_type = task.task_type
|
||||
|
||||
try:
|
||||
self.logger.info(
|
||||
f"Executing website analysis: task_id={task.id} | "
|
||||
f"user_id={user_id} | url={website_url} | type={task_type}"
|
||||
)
|
||||
|
||||
# Create execution log
|
||||
execution_log = WebsiteAnalysisExecutionLog(
|
||||
task_id=task.id,
|
||||
execution_date=datetime.utcnow(),
|
||||
status='running'
|
||||
)
|
||||
db.add(execution_log)
|
||||
db.flush()
|
||||
|
||||
# Perform website analysis
|
||||
result = await self._perform_website_analysis(
|
||||
website_url=website_url,
|
||||
user_id=user_id,
|
||||
task_type=task_type,
|
||||
task=task,
|
||||
db=db
|
||||
)
|
||||
|
||||
# Update execution log
|
||||
execution_time_ms = int((time.time() - start_time) * 1000)
|
||||
execution_log.status = 'success' if result.success else 'failed'
|
||||
execution_log.result_data = result.result_data
|
||||
execution_log.error_message = result.error_message
|
||||
execution_log.execution_time_ms = execution_time_ms
|
||||
|
||||
# Update task based on result
|
||||
task.last_check = datetime.utcnow()
|
||||
task.updated_at = datetime.utcnow()
|
||||
|
||||
if result.success:
|
||||
task.last_success = datetime.utcnow()
|
||||
task.status = 'active'
|
||||
task.failure_reason = None
|
||||
# Schedule next check based on frequency_days
|
||||
task.next_check = self.calculate_next_execution(
|
||||
task=task,
|
||||
frequency='Custom',
|
||||
last_execution=task.last_check,
|
||||
custom_days=task.frequency_days
|
||||
)
|
||||
|
||||
# Commit all changes to database
|
||||
db.commit()
|
||||
|
||||
self.logger.info(
|
||||
f"Website analysis completed successfully for task {task.id}. "
|
||||
f"Next check scheduled for {task.next_check}"
|
||||
)
|
||||
return result
|
||||
else:
|
||||
task.last_failure = datetime.utcnow()
|
||||
task.failure_reason = result.error_message
|
||||
task.status = 'failed'
|
||||
# Do NOT update next_check - wait for manual retry
|
||||
|
||||
# Commit all changes to database
|
||||
db.commit()
|
||||
|
||||
self.logger.warning(
|
||||
f"Website analysis failed for task {task.id}. "
|
||||
f"Error: {result.error_message}. Waiting for manual retry."
|
||||
)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
execution_time_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
# Set database session for exception handler
|
||||
self.exception_handler.db = db
|
||||
|
||||
# Create structured error
|
||||
error = TaskExecutionError(
|
||||
message=f"Error executing website analysis task {task.id}: {str(e)}",
|
||||
user_id=user_id,
|
||||
task_id=task.id,
|
||||
task_type="website_analysis",
|
||||
execution_time_ms=execution_time_ms,
|
||||
context={
|
||||
"website_url": website_url,
|
||||
"task_type": task_type,
|
||||
"user_id": user_id
|
||||
},
|
||||
original_error=e
|
||||
)
|
||||
|
||||
# Handle exception with structured logging
|
||||
self.exception_handler.handle_exception(error)
|
||||
|
||||
# Update execution log with error
|
||||
try:
|
||||
execution_log = WebsiteAnalysisExecutionLog(
|
||||
task_id=task.id,
|
||||
execution_date=datetime.utcnow(),
|
||||
status='failed',
|
||||
error_message=str(e),
|
||||
execution_time_ms=execution_time_ms,
|
||||
result_data={
|
||||
"error_type": error.error_type.value,
|
||||
"severity": error.severity.value,
|
||||
"context": error.context
|
||||
}
|
||||
)
|
||||
db.add(execution_log)
|
||||
|
||||
task.last_failure = datetime.utcnow()
|
||||
task.failure_reason = str(e)
|
||||
task.status = 'failed'
|
||||
task.last_check = datetime.utcnow()
|
||||
task.updated_at = datetime.utcnow()
|
||||
# Do NOT update next_check - wait for manual retry
|
||||
|
||||
db.commit()
|
||||
except Exception as commit_error:
|
||||
db_error = DatabaseError(
|
||||
message=f"Error saving execution log: {str(commit_error)}",
|
||||
user_id=user_id,
|
||||
task_id=task.id,
|
||||
original_error=commit_error
|
||||
)
|
||||
self.exception_handler.handle_exception(db_error)
|
||||
db.rollback()
|
||||
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=str(e),
|
||||
execution_time_ms=execution_time_ms,
|
||||
retryable=True
|
||||
)
|
||||
|
||||
async def _perform_website_analysis(
|
||||
self,
|
||||
website_url: str,
|
||||
user_id: str,
|
||||
task_type: str,
|
||||
task: WebsiteAnalysisTask,
|
||||
db: Session
|
||||
) -> TaskExecutionResult:
|
||||
"""
|
||||
Perform website analysis using existing service logic.
|
||||
|
||||
Reuses the same logic as /api/onboarding/style-detection/complete.
|
||||
"""
|
||||
try:
|
||||
# Step 1: Crawl website content
|
||||
self.logger.info(f"Crawling website: {website_url}")
|
||||
crawl_result = await self.crawler_logic.crawl_website(website_url)
|
||||
|
||||
if not crawl_result.get('success'):
|
||||
error_msg = crawl_result.get('error', 'Crawling failed')
|
||||
self.logger.error(f"Crawling failed for {website_url}: {error_msg}")
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=f"Crawling failed: {error_msg}",
|
||||
result_data={'crawl_result': crawl_result},
|
||||
retryable=True
|
||||
)
|
||||
|
||||
# Step 2: Run style analysis and patterns analysis in parallel
|
||||
self.logger.info(f"Running style analysis for {website_url}")
|
||||
|
||||
async def run_style_analysis():
|
||||
"""Run style analysis in executor"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
partial(self.style_logic.analyze_content_style, crawl_result['content'])
|
||||
)
|
||||
|
||||
async def run_patterns_analysis():
|
||||
"""Run patterns analysis in executor"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
partial(self.style_logic.analyze_style_patterns, crawl_result['content'])
|
||||
)
|
||||
|
||||
# Execute style and patterns analysis in parallel
|
||||
style_analysis, patterns_result = await asyncio.gather(
|
||||
run_style_analysis(),
|
||||
run_patterns_analysis(),
|
||||
return_exceptions=True
|
||||
)
|
||||
|
||||
# Check for exceptions
|
||||
if isinstance(style_analysis, Exception):
|
||||
self.logger.error(f"Style analysis exception: {style_analysis}")
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=f"Style analysis failed: {str(style_analysis)}",
|
||||
retryable=True
|
||||
)
|
||||
|
||||
if isinstance(patterns_result, Exception):
|
||||
self.logger.warning(f"Patterns analysis exception: {patterns_result}")
|
||||
patterns_result = None
|
||||
|
||||
# Step 3: Generate style guidelines
|
||||
style_guidelines = None
|
||||
if style_analysis and style_analysis.get('success'):
|
||||
loop = asyncio.get_event_loop()
|
||||
guidelines_result = await loop.run_in_executor(
|
||||
None,
|
||||
partial(self.style_logic.generate_style_guidelines, style_analysis.get('analysis', {}))
|
||||
)
|
||||
if guidelines_result and guidelines_result.get('success'):
|
||||
style_guidelines = guidelines_result.get('guidelines')
|
||||
|
||||
# Prepare analysis data
|
||||
analysis_data = {
|
||||
'crawl_result': crawl_result,
|
||||
'style_analysis': style_analysis.get('analysis') if style_analysis and style_analysis.get('success') else None,
|
||||
'style_patterns': patterns_result if patterns_result and not isinstance(patterns_result, Exception) else None,
|
||||
'style_guidelines': style_guidelines,
|
||||
}
|
||||
|
||||
# Step 4: Store results based on task type
|
||||
if task_type == 'user_website':
|
||||
# Update existing WebsiteAnalysis record
|
||||
await self._update_user_website_analysis(
|
||||
user_id=user_id,
|
||||
website_url=website_url,
|
||||
analysis_data=analysis_data,
|
||||
db=db
|
||||
)
|
||||
elif task_type == 'competitor':
|
||||
# Store in CompetitorAnalysis table
|
||||
await self._store_competitor_analysis(
|
||||
user_id=user_id,
|
||||
competitor_url=website_url,
|
||||
competitor_id=task.competitor_id,
|
||||
analysis_data=analysis_data,
|
||||
db=db
|
||||
)
|
||||
|
||||
self.logger.info(f"Website analysis completed successfully for {website_url}")
|
||||
|
||||
return TaskExecutionResult(
|
||||
success=True,
|
||||
result_data=analysis_data,
|
||||
retryable=False
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error performing website analysis: {e}", exc_info=True)
|
||||
return TaskExecutionResult(
|
||||
success=False,
|
||||
error_message=str(e),
|
||||
retryable=True
|
||||
)
|
||||
|
||||
async def _update_user_website_analysis(
|
||||
self,
|
||||
user_id: str,
|
||||
website_url: str,
|
||||
analysis_data: Dict[str, Any],
|
||||
db: Session
|
||||
):
|
||||
"""Update existing WebsiteAnalysis record for user's website."""
|
||||
try:
|
||||
# Convert Clerk user ID to integer (same as component_logic.py)
|
||||
# Use the same conversion logic as the website analysis API
|
||||
import hashlib
|
||||
user_id_int = int(hashlib.sha256(user_id.encode()).hexdigest()[:15], 16)
|
||||
|
||||
# Use WebsiteAnalysisService to update
|
||||
analysis_service = WebsiteAnalysisService(db)
|
||||
|
||||
# Prepare data in format expected by save_analysis
|
||||
response_data = {
|
||||
'crawl_result': analysis_data.get('crawl_result'),
|
||||
'style_analysis': analysis_data.get('style_analysis'),
|
||||
'style_patterns': analysis_data.get('style_patterns'),
|
||||
'style_guidelines': analysis_data.get('style_guidelines'),
|
||||
}
|
||||
|
||||
# Save/update analysis
|
||||
analysis_id = analysis_service.save_analysis(
|
||||
session_id=user_id_int,
|
||||
website_url=website_url,
|
||||
analysis_data=response_data
|
||||
)
|
||||
|
||||
if analysis_id:
|
||||
self.logger.info(f"Updated user website analysis for {website_url} (analysis_id: {analysis_id})")
|
||||
else:
|
||||
self.logger.warning(f"Failed to update user website analysis for {website_url}")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error updating user website analysis: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
async def _store_competitor_analysis(
|
||||
self,
|
||||
user_id: str,
|
||||
competitor_url: str,
|
||||
competitor_id: Optional[str],
|
||||
analysis_data: Dict[str, Any],
|
||||
db: Session
|
||||
):
|
||||
"""Store competitor analysis in CompetitorAnalysis table."""
|
||||
try:
|
||||
# Get onboarding session for user
|
||||
session = db.query(OnboardingSession).filter(
|
||||
OnboardingSession.user_id == user_id
|
||||
).first()
|
||||
|
||||
if not session:
|
||||
raise ValueError(f"No onboarding session found for user {user_id}")
|
||||
|
||||
# Extract domain from URL
|
||||
parsed_url = urlparse(competitor_url)
|
||||
competitor_domain = parsed_url.netloc or competitor_id
|
||||
|
||||
# Check if analysis already exists for this competitor
|
||||
existing = db.query(CompetitorAnalysis).filter(
|
||||
CompetitorAnalysis.session_id == session.id,
|
||||
CompetitorAnalysis.competitor_url == competitor_url
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
# Update existing analysis
|
||||
existing.analysis_data = analysis_data
|
||||
existing.analysis_date = datetime.utcnow()
|
||||
existing.status = 'completed'
|
||||
existing.error_message = None
|
||||
existing.warning_message = None
|
||||
existing.updated_at = datetime.utcnow()
|
||||
self.logger.info(f"Updated competitor analysis for {competitor_url}")
|
||||
else:
|
||||
# Create new analysis
|
||||
competitor_analysis = CompetitorAnalysis(
|
||||
session_id=session.id,
|
||||
competitor_url=competitor_url,
|
||||
competitor_domain=competitor_domain,
|
||||
analysis_data=analysis_data,
|
||||
status='completed',
|
||||
analysis_date=datetime.utcnow()
|
||||
)
|
||||
db.add(competitor_analysis)
|
||||
self.logger.info(f"Created new competitor analysis for {competitor_url}")
|
||||
|
||||
db.commit()
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
self.logger.error(f"Error storing competitor analysis: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
def calculate_next_execution(
|
||||
self,
|
||||
task: WebsiteAnalysisTask,
|
||||
frequency: str,
|
||||
last_execution: Optional[datetime] = None,
|
||||
custom_days: Optional[int] = None
|
||||
) -> datetime:
|
||||
"""
|
||||
Calculate next execution time based on frequency or custom days.
|
||||
|
||||
Args:
|
||||
task: WebsiteAnalysisTask instance
|
||||
frequency: Frequency string ('Custom' for website analysis)
|
||||
last_execution: Last execution datetime (defaults to task.last_check or now)
|
||||
custom_days: Custom number of days (from task.frequency_days)
|
||||
|
||||
Returns:
|
||||
Next execution datetime
|
||||
"""
|
||||
if last_execution is None:
|
||||
last_execution = task.last_check if task.last_check else datetime.utcnow()
|
||||
|
||||
# Use custom_days if provided, otherwise use task.frequency_days
|
||||
days = custom_days if custom_days is not None else task.frequency_days
|
||||
|
||||
if frequency == 'Custom' and days:
|
||||
return last_execution + timedelta(days=days)
|
||||
else:
|
||||
# Default to task's frequency_days
|
||||
self.logger.warning(
|
||||
f"Unknown frequency '{frequency}' for website analysis task {task.id}. "
|
||||
f"Using frequency_days={task.frequency_days}."
|
||||
)
|
||||
return last_execution + timedelta(days=task.frequency_days)
|
||||
|
||||
Reference in New Issue
Block a user