This commit is contained in:
alorig
2025-11-22 12:50:59 +05:00
parent 3fb86eacf1
commit e99bec5067
3 changed files with 529 additions and 10 deletions

View File

@@ -204,15 +204,16 @@ class IntegrationService:
integration: SiteIntegration
) -> Dict[str, Any]:
"""
Test WordPress connection.
Test WordPress connection with comprehensive bidirectional health check.
Args:
integration: SiteIntegration instance
Returns:
dict: Connection test result
dict: Connection test result with detailed health status
"""
from igny8_core.utils.wordpress import WordPressClient
import requests
config = integration.config_json
credentials = integration.get_credentials()
@@ -237,31 +238,173 @@ class IntegrationService:
'details': {
'integration_id': integration.id,
'site_id': integration.site.id,
'site_name': integration.site.name
'site_name': integration.site.name,
'checks': {
'site_url_configured': False,
'wp_rest_api_reachable': False,
'plugin_installed': False,
'plugin_can_reach_igny8': False,
'bidirectional_communication': False
}
}
}
username = credentials.get('username')
app_password = credentials.get('app_password')
# Initialize health check results
health_checks = {
'site_url_configured': True,
'wp_rest_api_reachable': False,
'wp_rest_api_authenticated': False,
'plugin_installed': False,
'plugin_connected': False,
'plugin_can_reach_igny8': False,
'bidirectional_communication': False
}
issues = []
try:
client = WordPressClient(site_url, username, app_password)
result = client.test_connection()
# Check 1: WordPress REST API reachable (public)
try:
client = WordPressClient(site_url, username, app_password)
basic_test = client.test_connection()
if basic_test.get('success'):
health_checks['wp_rest_api_reachable'] = True
logger.info(f"[IntegrationService] ✓ WordPress REST API reachable: {site_url}")
else:
issues.append(f"WordPress REST API not reachable: {basic_test.get('message')}")
except Exception as e:
issues.append(f"WordPress REST API unreachable: {str(e)}")
# If connection successful and site_url wasn't in config, save it
if result.get('success') and not config.get('site_url'):
# Check 2: WordPress REST API with authentication
if username and app_password:
try:
# Try authenticated endpoint
auth_response = requests.get(
f"{site_url.rstrip('/')}/wp-json/wp/v2/users/me",
auth=(username, app_password),
timeout=10
)
if auth_response.status_code == 200:
health_checks['wp_rest_api_authenticated'] = True
logger.info(f"[IntegrationService] ✓ WordPress authentication valid")
else:
issues.append(f"WordPress authentication failed: HTTP {auth_response.status_code}")
except Exception as e:
issues.append(f"WordPress authentication check failed: {str(e)}")
# Check 3: IGNY8 Plugin installed and reachable
try:
plugin_response = requests.get(
f"{site_url.rstrip('/')}/wp-json/igny8/v1/",
timeout=10
)
if plugin_response.status_code in [200, 404]: # 404 is ok, means REST API exists
health_checks['plugin_installed'] = True
logger.info(f"[IntegrationService] ✓ IGNY8 plugin REST endpoints detected")
else:
issues.append(f"IGNY8 plugin endpoints not found: HTTP {plugin_response.status_code}")
except Exception as e:
issues.append(f"Cannot detect IGNY8 plugin: {str(e)}")
# Check 4: Plugin connection status (check if plugin has API key)
try:
# Try to get plugin status endpoint
status_response = requests.get(
f"{site_url.rstrip('/')}/wp-json/igny8/v1/status",
timeout=10
)
if status_response.status_code == 200:
status_data = status_response.json()
if status_data.get('connected') or status_data.get('has_api_key'):
health_checks['plugin_connected'] = True
logger.info(f"[IntegrationService] ✓ Plugin has API key configured")
else:
issues.append("Plugin installed but not configured with API key")
else:
# Endpoint might not exist, that's okay
logger.debug(f"[IntegrationService] Plugin status endpoint returned: {status_response.status_code}")
except Exception as e:
logger.debug(f"[IntegrationService] Plugin status check: {str(e)}")
# Check 5: Bidirectional communication (can plugin reach us?)
# This is the critical check - can WordPress plugin make API calls to IGNY8 backend?
try:
# Check if plugin can reach our API by looking at last successful sync
last_sync = integration.last_sync_at
last_structure_sync = config.get('content_types', {}).get('last_structure_fetch')
if last_sync or last_structure_sync:
health_checks['plugin_can_reach_igny8'] = True
health_checks['bidirectional_communication'] = True
logger.info(f"[IntegrationService] ✓ Bidirectional communication confirmed (last sync: {last_sync})")
else:
issues.append("No successful syncs detected - plugin may not be able to reach IGNY8 backend")
except Exception as e:
logger.debug(f"[IntegrationService] Bidirectional check: {str(e)}")
# Overall success determination
# Minimum requirements for "success":
# 1. WordPress REST API must be reachable
# 2. Plugin should be installed
# 3. Ideally, bidirectional communication works
is_healthy = (
health_checks['wp_rest_api_reachable'] and
health_checks['plugin_installed']
)
is_fully_functional = (
is_healthy and
health_checks['plugin_connected'] and
health_checks['bidirectional_communication']
)
# Save site_url to config if successful and not already set
if is_healthy and not config.get('site_url'):
config['site_url'] = site_url
integration.config_json = config
integration.save(update_fields=['config_json'])
logger.info(f"[IntegrationService] Saved site_url to integration {integration.id} config: {site_url}")
return result
# Build response message
if is_fully_functional:
message = "✅ WordPress integration is healthy and fully functional"
elif is_healthy and health_checks['plugin_installed']:
message = "⚠️ WordPress is reachable and plugin detected, but bidirectional sync not confirmed. Plugin may need API key configuration."
elif health_checks['wp_rest_api_reachable']:
message = "⚠️ WordPress is reachable but IGNY8 plugin not detected or not configured"
else:
message = "❌ WordPress connection failed"
return {
'success': is_healthy,
'fully_functional': is_fully_functional,
'message': message,
'site_url': site_url,
'health_checks': health_checks,
'issues': issues if issues else None,
'wp_version': basic_test.get('wp_version') if health_checks['wp_rest_api_reachable'] else None,
'details': {
'last_sync': str(integration.last_sync_at) if integration.last_sync_at else None,
'integration_active': integration.is_active,
'sync_enabled': integration.sync_enabled
}
}
except Exception as e:
logger.error(f"WordPress connection test failed: {e}")
return {
'success': False,
'message': f'WordPress connection failed: {str(e)}',
'fully_functional': False,
'message': f'Connection test failed: {str(e)}',
'site_url': site_url,
'health_checks': health_checks,
'issues': issues + [str(e)],
'details': {
'site_url': site_url,
'error': str(e)
}
}