feat: migrate coordinator-api routers and exchange_island CLI to use centralized aitbc package HTTP client
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 9s
CLI Tests / test-cli (push) Failing after 3s
Integration Tests / test-service-integration (push) Successful in 42s
Python Tests / test-python (push) Failing after 39s
Security Scanning / security-scan (push) Successful in 2m36s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 3s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s

- Replace httpx.Client with aitbc.AITBCHTTPClient in client.py get_blocks endpoint
- Migrate monitoring_dashboard.py from httpx.AsyncClient to AITBCHTTPClient
- Replace httpx with AITBCHTTPClient in blockchain.py get_balance function
- Add NetworkError exception handling across all migrated endpoints
- Remove async context managers in favor of direct AITBCHTTPClient usage
- Remove httpx imports
This commit is contained in:
aitbc
2026-04-25 06:34:59 +02:00
parent e60aa70da9
commit 08d6921444
5 changed files with 135 additions and 113 deletions

View File

@@ -226,22 +226,27 @@ async def get_blocks(
) -> dict: # type: ignore[arg-type]
"""Get recent blockchain blocks"""
try:
import httpx
# Query the local blockchain node for blocks
with httpx.Client() as client:
response = client.get(
"http://10.1.223.93:8082/rpc/blocks-range", params={"start": offset, "end": offset + limit}, timeout=5
client = AITBCHTTPClient(timeout=5.0)
try:
blocks_data = client.get(
"http://10.1.223.93:8082/rpc/blocks-range", params={"start": offset, "end": offset + limit}
)
if response.status_code == 200:
blocks_data = response.json()
return {
"blocks": blocks_data.get("blocks", []),
"total": blocks_data.get("total", 0),
"limit": limit,
"offset": offset,
}
return {
"blocks": blocks_data.get("blocks", []),
"total": blocks_data.get("total", 0),
"limit": limit,
"offset": offset,
}
except NetworkError as e:
logger.error(f"Failed to fetch blocks: {e}")
return {
"blocks": [],
"total": 0,
"limit": limit,
"offset": offset,
"error": "Failed to fetch blocks",
}
else:
# Fallback to empty response if blockchain node is unavailable
return {

View File

@@ -191,24 +191,25 @@ async def collect_all_health_data() -> dict[str, Any]:
"""Collect health data from all enhanced services"""
health_data = {}
async with httpx.AsyncClient(timeout=5.0) as client:
tasks = []
client = AITBCHTTPClient(timeout=5.0)
tasks = []
for service_id, service_info in SERVICES.items():
task = check_service_health(client, service_id, service_info)
tasks.append(task)
for service_id, service_info in SERVICES.items():
task = check_service_health(client, service_id, service_info)
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
results = await asyncio.gather(*tasks, return_exceptions=True)
for i, (service_id, service_info) in enumerate(SERVICES.items()):
result = results[i]
if isinstance(result, Exception):
health_data[service_id] = {
"status": "unhealthy",
"error": str(result),
"timestamp": datetime.utcnow().isoformat(),
}
else:
for i, (service_id, service_info) in enumerate(SERVICES.items()):
result = results[i]
if isinstance(result, Exception):
health_data[service_id] = {
"status": "unhealthy",
"error": str(result),
"timestamp": datetime.utcnow().isoformat(),
}
else:
health_data[service_id] = result
return health_data

View File

@@ -53,17 +53,16 @@ def get_balance(address: str) -> float | None:
return None
try:
with httpx.Client() as client:
client = AITBCHTTPClient(timeout=10.0)
try:
response = client.get(
f"{BLOCKCHAIN_RPC}/getBalance/{address}",
headers={"X-Api-Key": settings.admin_api_keys[0] if settings.admin_api_keys else ""},
)
if response.status_code == 200:
data = response.json()
return float(data.get("balance", 0))
return float(response.get("balance", 0))
except NetworkError as e:
logger.error("Error getting balance: %s", e)
return None
except Exception as e:
logger.error("Error getting balance: %s", e)
return None
return None

View File

@@ -8,6 +8,8 @@ import os
import pickle
from typing import Any
from aitbc import REPO_DIR
# Safe classes whitelist: builtins and common types
SAFE_MODULES = {
"builtins": {
@@ -40,8 +42,8 @@ def _initialize_allowed_origins():
# 1. All site-packages directories that are under the application venv
for entry in os.sys.path:
if "site-packages" in entry and os.path.isdir(entry):
# Only include if it's inside /opt/aitbc/apps/coordinator-api/.venv or similar
if "/opt/aitbc" in entry: # restrict to our app directory
# Only include if it's inside the AITBC repository
if str(REPO_DIR) in entry: # restrict to our app directory
_ALLOWED_ORIGINS.add(os.path.realpath(entry))
# 2. Standard library paths (typically without site-packages)
# We'll allow any origin that resolves to a .py file outside site-packages and not in user dirs
@@ -95,14 +97,14 @@ def _lock_sys_path():
if isinstance(sys.path, list):
trusted = []
for p in sys.path:
# Keep site-packages under /opt/aitbc (our venv)
if "site-packages" in p and "/opt/aitbc" in p:
# Keep site-packages under REPO_DIR (our venv)
if "site-packages" in p and str(REPO_DIR) in p:
trusted.append(p)
# Keep stdlib paths (no site-packages, under /usr/lib/python)
elif "site-packages" not in p and ("/usr/lib/python" in p or "/usr/local/lib/python" in p):
trusted.append(p)
# Keep our application directory
elif p.startswith("/opt/aitbc/apps/coordinator-api"):
elif p.startswith(str(REPO_DIR / "apps" / "coordinator-api")):
trusted.append(p)
sys.path = trusted