File size: 10,091 Bytes
bee039d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c46444f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bee039d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad3b06
bee039d
fad3b06
 
bee039d
 
 
 
fad3b06
bee039d
fad3b06
 
bee039d
 
 
 
fad3b06
bee039d
fad3b06
 
bee039d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad3b06
 
 
 
 
 
bee039d
 
fad3b06
bee039d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python3
"""
Service Health Monitor API
Real-time monitoring of all API services and data providers
Shows status, response times, success rates, and health metrics
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Dict, Any, List, Optional
from datetime import datetime
import logging
import asyncio
import httpx
import time

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/health", tags=["Health Monitor"])


class ServiceStatus(BaseModel):
    """Service status model"""
    name: str
    status: str  # "online", "offline", "rate_limited", "degraded"
    response_time_ms: Optional[float] = None
    last_check: str
    last_error: Optional[str] = None
    success_rate: Optional[float] = None
    details: Optional[Dict[str, Any]] = None


class HealthMonitorResponse(BaseModel):
    """Health monitor response"""
    timestamp: str
    total_services: int
    online: int
    offline: int
    rate_limited: int
    degraded: int
    services: List[ServiceStatus]
    overall_health: str  # "healthy", "degraded", "critical"


# Service configuration for health checks
SERVICES_CONFIG = {
    "crypto_api_clean": {
        "name": "Crypto API Clean",
        "category": "Resource Database",
        "endpoint": "https://really-amin-crypto-api-clean-fixed.hf.space/api/resources/stats",
        "timeout": 10,
        "sub_services": ["rpc_nodes (24)", "block_explorers (33)", "market_data_apis (33)", "news_apis (17)", "sentiment_apis (14)"],
        "description": "281+ cryptocurrency resources across 12 categories",
        "priority": 2
    },
    "crypto_dt_source": {
        "name": "Crypto DT Source",
        "category": "Unified Data API",
        "endpoint": "https://crypto-dt-source.onrender.com/api/v1/status",
        "timeout": 15,
        "sub_services": ["prices", "klines", "sentiment", "models", "datasets"],
        "description": "Unified API v2.0.0 with 4 AI models and 5 datasets",
        "priority": 2
    },
    "coingecko": {
        "name": "CoinGecko",
        "category": "Data Provider",
        "endpoint": "https://api.coingecko.com/api/v3/ping",
        "timeout": 5,
        "sub_services": ["prices", "market_data", "ohlcv"]
    },
    "binance": {
        "name": "Binance",
        "category": "Exchange",
        "endpoint": "https://api.binance.com/api/v3/ping",
        "timeout": 5,
        "sub_services": ["spot", "futures", "websocket"]
    },
    "coincap": {
        "name": "CoinCap",
        "category": "Data Provider",
        "endpoint": "https://api.coincap.io/v2/assets/bitcoin",
        "timeout": 5,
        "sub_services": ["assets", "markets", "rates"]
    },
    "cryptocompare": {
        "name": "CryptoCompare",
        "category": "Data Provider",
        "endpoint": "https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD",
        "timeout": 5,
        "sub_services": ["price", "historical", "social"]
    },
    "huggingface": {
        "name": "HuggingFace Space",
        "category": "Internal",
        "endpoint": "/api/health/self",
        "timeout": 3,
        "sub_services": ["api", "websocket", "database"],
        "internal": True
    },
    "backend_indicators": {
        "name": "Technical Indicators",
        "category": "Internal",
        "endpoint": "/api/indicators/services",
        "timeout": 3,
        "sub_services": ["rsi", "macd", "bollinger_bands", "comprehensive"],
        "internal": True
    },
    "backend_market": {
        "name": "Market Data API",
        "category": "Internal",
        "endpoint": "/api/market/crypto/list",
        "timeout": 3,
        "sub_services": ["prices", "ohlcv", "tickers"],
        "internal": True
    }
}


def get_base_url() -> str:
    """Get the base URL for internal services"""
    import os
    # For HF Spaces
    if os.getenv("SPACE_ID"):
        return f"https://{os.getenv('SPACE_ID')}.hf.space"
    # For local development
    return "http://localhost:7860"


async def check_service_health(service_id: str, config: Dict[str, Any]) -> ServiceStatus:
    """
    Check the health of a single service
    """
    start_time = time.time()
    
    try:
        # Build URL for internal services
        endpoint = config["endpoint"]
        if config.get("internal", False):
            base_url = get_base_url()
            endpoint = f"{base_url}{endpoint}" if not endpoint.startswith("http") else endpoint
        
        async with httpx.AsyncClient() as client:
            response = await client.get(
                endpoint,
                timeout=config.get("timeout", 5),
                follow_redirects=True
            )
            
            response_time = (time.time() - start_time) * 1000  # Convert to ms
            
            # Determine status
            if response.status_code == 200:
                status = "online"
            elif response.status_code == 429:
                status = "rate_limited"
            elif 500 <= response.status_code < 600:
                status = "degraded"
            else:
                status = "offline"
            
            # Calculate success rate (simplified - in production, use historical data)
            success_rate = 100.0 if status == "online" else 50.0 if status == "degraded" else 0.0
            
            return ServiceStatus(
                name=config["name"],
                status=status,
                response_time_ms=round(response_time, 2),
                last_check=datetime.utcnow().isoformat() + "Z",
                last_error=None if status == "online" else f"HTTP {response.status_code}",
                success_rate=success_rate,
                details={
                    "category": config.get("category", "Unknown"),
                    "sub_services": config.get("sub_services", []),
                    "http_status": response.status_code
                }
            )
            
    except asyncio.TimeoutError:
        return ServiceStatus(
            name=config["name"],
            status="offline",
            response_time_ms=config.get("timeout", 5) * 1000,
            last_check=datetime.utcnow().isoformat() + "Z",
            last_error="Request timeout",
            success_rate=0.0,
            details={
                "category": config.get("category", "Unknown"),
                "sub_services": config.get("sub_services", []),
                "error_type": "timeout"
            }
        )
    except httpx.ConnectError as e:
        return ServiceStatus(
            name=config["name"],
            status="offline",
            response_time_ms=None,
            last_check=datetime.utcnow().isoformat() + "Z",
            last_error=f"Connection failed: {str(e)[:100]}",
            success_rate=0.0,
            details={
                "category": config.get("category", "Unknown"),
                "sub_services": config.get("sub_services", []),
                "error_type": "connection_error"
            }
        )
    except Exception as e:
        logger.error(f"Error checking {service_id}: {e}")
        return ServiceStatus(
            name=config["name"],
            status="offline",
            response_time_ms=None,
            last_check=datetime.utcnow().isoformat() + "Z",
            last_error=str(e)[:100],
            success_rate=0.0,
            details={
                "category": config.get("category", "Unknown"),
                "sub_services": config.get("sub_services", []),
                "error_type": "unknown_error"
            }
        )


@router.get("/monitor", response_model=HealthMonitorResponse)
async def get_service_health():
    """
    Get health status of all services
    Returns real-time status of all API providers and internal services
    """
    try:
        # Check all services concurrently
        tasks = [
            check_service_health(service_id, config)
            for service_id, config in SERVICES_CONFIG.items()
        ]
        
        services = await asyncio.gather(*tasks)
        
        # Calculate statistics
        online = sum(1 for s in services if s.status == "online")
        offline = sum(1 for s in services if s.status == "offline")
        rate_limited = sum(1 for s in services if s.status == "rate_limited")
        degraded = sum(1 for s in services if s.status == "degraded")
        
        # Determine overall health
        total = len(services)
        if online == total:
            overall_health = "healthy"
        elif online >= total * 0.7:
            overall_health = "degraded"
        else:
            overall_health = "critical"
        
        return HealthMonitorResponse(
            timestamp=datetime.utcnow().isoformat() + "Z",
            total_services=total,
            online=online,
            offline=offline,
            rate_limited=rate_limited,
            degraded=degraded,
            services=services,
            overall_health=overall_health
        )
        
    except Exception as e:
        logger.error(f"Health monitor error: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to check service health: {str(e)}")


@router.get("/self")
async def health_check():
    """
    Simple health check endpoint for this service
    """
    return {
        "status": "healthy",
        "service": "crypto-intelligence-hub",
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "version": "1.0.0"
    }


@router.get("/services")
async def list_monitored_services():
    """
    List all monitored services with their configuration
    """
    return {
        "success": True,
        "total_services": len(SERVICES_CONFIG),
        "services": [
            {
                "id": service_id,
                "name": config["name"],
                "category": config.get("category", "Unknown"),
                "sub_services": config.get("sub_services", [])
            }
            for service_id, config in SERVICES_CONFIG.items()
        ],
        "timestamp": datetime.utcnow().isoformat() + "Z"
    }