refactor: add rate limiting to agent coordinator routers
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 18s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Successful in 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 4s
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Successful in 2s
Cross-Node Transaction Testing / transaction-test (push) Successful in 2s
Deploy to Testnet / deploy-testnet (push) Successful in 1m21s
Documentation Validation / validate-docs (push) Failing after 9s
Documentation Validation / validate-policies-strict (push) Successful in 4s
Integration Tests / test-service-integration (push) Successful in 2m38s
Multi-Chain Island Architecture Tests / test-multi-chain-island (push) Successful in 2s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 2s
Multi-Node Stress Testing / stress-test (push) Successful in 3s
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Node Failover Simulation / failover-test (push) Failing after 1h44m34s
P2P Network Verification / p2p-verification (push) Successful in 22s
Production Tests / Production Integration Tests (push) Failing after 27s
Staking Tests / test-staking-service (push) Failing after 4s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Cross-Chain Functionality Tests / aggregate-results (push) Successful in 2s
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 18s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Successful in 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 4s
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Successful in 2s
Cross-Node Transaction Testing / transaction-test (push) Successful in 2s
Deploy to Testnet / deploy-testnet (push) Successful in 1m21s
Documentation Validation / validate-docs (push) Failing after 9s
Documentation Validation / validate-policies-strict (push) Successful in 4s
Integration Tests / test-service-integration (push) Successful in 2m38s
Multi-Chain Island Architecture Tests / test-multi-chain-island (push) Successful in 2s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 2s
Multi-Node Stress Testing / stress-test (push) Successful in 3s
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Node Failover Simulation / failover-test (push) Failing after 1h44m34s
P2P Network Verification / p2p-verification (push) Successful in 22s
Production Tests / Production Integration Tests (push) Failing after 27s
Staking Tests / test-staking-service (push) Failing after 4s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Cross-Chain Functionality Tests / aggregate-results (push) Successful in 2s
- Added Request parameter to all endpoint functions in agents.py, ai.py, alerts.py, auth.py, and consensus.py - Added @rate_limit decorator to all endpoints with appropriate limits: - Write operations (POST/PUT/DELETE): 50 requests per 60 seconds - Read operations (GET): 200 requests per 60 seconds - High-frequency operations (heartbeat, token refresh): 100 requests per 60 seconds - Renamed conflicting request parameters (request -> request_http, request_status)
This commit is contained in:
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,10 @@ router = APIRouter()
|
||||
|
||||
# Agent registration
|
||||
@router.post("/agents/register")
|
||||
async def register_agent(request: AgentRegistrationRequest):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def register_agent(
|
||||
request_http: Request, request: AgentRegistrationRequest
|
||||
):
|
||||
"""Register a new agent"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -65,7 +69,10 @@ async def register_agent(request: AgentRegistrationRequest):
|
||||
|
||||
# Agent discovery
|
||||
@router.post("/agents/discover")
|
||||
async def discover_agents(query: Dict[str, Any]):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def discover_agents(
|
||||
request: Request, query: Dict[str, Any]
|
||||
):
|
||||
"""Discover agents based on criteria"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -87,7 +94,10 @@ async def discover_agents(query: Dict[str, Any]):
|
||||
|
||||
# Get agent by ID
|
||||
@router.get("/agents/{agent_id}")
|
||||
async def get_agent(agent_id: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_agent(
|
||||
request: Request, agent_id: str
|
||||
):
|
||||
"""Get agent information by ID"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -112,7 +122,10 @@ async def get_agent(agent_id: str):
|
||||
|
||||
# Update agent status
|
||||
@router.put("/agents/{agent_id}/status")
|
||||
async def update_agent_status(agent_id: str, request: AgentStatusUpdate):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def update_agent_status(
|
||||
request: Request, agent_id: str, request_status: AgentStatusUpdate
|
||||
):
|
||||
"""Update agent status"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -143,7 +156,10 @@ async def update_agent_status(agent_id: str, request: AgentStatusUpdate):
|
||||
|
||||
# Agent heartbeat
|
||||
@router.post("/agents/{agent_id}/heartbeat")
|
||||
async def agent_heartbeat(agent_id: str):
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def agent_heartbeat(
|
||||
request: Request, agent_id: str
|
||||
):
|
||||
"""Receive heartbeat from agent"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,10 @@ router = APIRouter()
|
||||
|
||||
# Advanced AI/ML endpoints
|
||||
@router.post("/ai/learning/experience")
|
||||
async def record_learning_experience(experience_data: Dict[str, Any]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def record_learning_experience(
|
||||
request: Request, experience_data: Dict[str, Any]
|
||||
):
|
||||
"""Record a learning experience for the AI system"""
|
||||
try:
|
||||
result = await learning_system.record_experience(experience_data)
|
||||
@@ -35,7 +39,10 @@ async def record_learning_experience(experience_data: Dict[str, Any]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/ai/learning/statistics")
|
||||
async def get_learning_statistics():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_learning_statistics(
|
||||
request: Request
|
||||
):
|
||||
"""Get learning system statistics"""
|
||||
try:
|
||||
result = await learning_system.get_learning_statistics()
|
||||
@@ -45,7 +52,10 @@ async def get_learning_statistics():
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/learning/predict")
|
||||
async def predict_performance(context: Dict[str, Any], action: str = Query(...)):
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def predict_performance(
|
||||
request: Request, context: Dict[str, Any], action: str = Query(...)
|
||||
):
|
||||
"""Predict performance for a given action"""
|
||||
try:
|
||||
result = await learning_system.predict_performance(context, action)
|
||||
@@ -55,7 +65,10 @@ async def predict_performance(context: Dict[str, Any], action: str = Query(...))
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/learning/recommend")
|
||||
async def recommend_action(context: Dict[str, Any], available_actions: List[str]):
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def recommend_action(
|
||||
request: Request, context: Dict[str, Any], available_actions: List[str]
|
||||
):
|
||||
"""Get AI-recommended action"""
|
||||
try:
|
||||
result = await learning_system.recommend_action(context, available_actions)
|
||||
@@ -65,7 +78,10 @@ async def recommend_action(context: Dict[str, Any], available_actions: List[str]
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/neural-network/create")
|
||||
async def create_neural_network(config: Dict[str, Any]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_neural_network(
|
||||
request: Request, config: Dict[str, Any]
|
||||
):
|
||||
"""Create a new neural network"""
|
||||
try:
|
||||
result = await ai_integration.create_neural_network(config)
|
||||
@@ -75,7 +91,10 @@ async def create_neural_network(config: Dict[str, Any]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/neural-network/{network_id}/train")
|
||||
async def train_neural_network(network_id: str, training_data: List[Dict[str, Any]], epochs: int = 100):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def train_neural_network(
|
||||
request: Request, network_id: str, training_data: List[Dict[str, Any]], epochs: int = 100
|
||||
):
|
||||
"""Train a neural network"""
|
||||
try:
|
||||
result = await ai_integration.train_neural_network(network_id, training_data, epochs)
|
||||
@@ -85,7 +104,10 @@ async def train_neural_network(network_id: str, training_data: List[Dict[str, An
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/neural-network/{network_id}/predict")
|
||||
async def predict_with_neural_network(network_id: str, features: List[float]):
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def predict_with_neural_network(
|
||||
request: Request, network_id: str, features: List[float]
|
||||
):
|
||||
"""Make prediction with neural network"""
|
||||
try:
|
||||
result = await ai_integration.predict_with_neural_network(network_id, features)
|
||||
@@ -95,7 +117,10 @@ async def predict_with_neural_network(network_id: str, features: List[float]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/ml-model/create")
|
||||
async def create_ml_model(config: Dict[str, Any]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_ml_model(
|
||||
request: Request, config: Dict[str, Any]
|
||||
):
|
||||
"""Create a new ML model"""
|
||||
try:
|
||||
result = await ai_integration.create_ml_model(config)
|
||||
@@ -105,7 +130,10 @@ async def create_ml_model(config: Dict[str, Any]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/ml-model/{model_id}/train")
|
||||
async def train_ml_model(model_id: str, training_data: List[Dict[str, Any]]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def train_ml_model(
|
||||
request: Request, model_id: str, training_data: List[Dict[str, Any]]
|
||||
):
|
||||
"""Train an ML model"""
|
||||
try:
|
||||
result = await ai_integration.train_ml_model(model_id, training_data)
|
||||
@@ -115,7 +143,10 @@ async def train_ml_model(model_id: str, training_data: List[Dict[str, Any]]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/ai/ml-model/{model_id}/predict")
|
||||
async def predict_with_ml_model(model_id: str, features: List[float]):
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def predict_with_ml_model(
|
||||
request: Request, model_id: str, features: List[float]
|
||||
):
|
||||
"""Make prediction with ML model"""
|
||||
try:
|
||||
result = await ai_integration.predict_with_ml_model(model_id, features)
|
||||
@@ -125,7 +156,10 @@ async def predict_with_ml_model(model_id: str, features: List[float]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/ai/statistics")
|
||||
async def get_ai_statistics():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_ai_statistics(
|
||||
request: Request
|
||||
):
|
||||
"""Get comprehensive AI/ML statistics"""
|
||||
try:
|
||||
result = await ai_integration.get_ai_statistics()
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,9 @@ router = APIRouter()
|
||||
|
||||
# Alerting endpoints
|
||||
@router.get("/alerts")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_alerts(
|
||||
request: Request,
|
||||
status: Optional[str] = None,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
@@ -52,7 +55,9 @@ async def get_alerts(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/alerts/{alert_id}/resolve")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def resolve_alert(
|
||||
request: Request,
|
||||
alert_id: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
@@ -72,7 +77,10 @@ async def resolve_alert(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/alerts/stats")
|
||||
async def get_alert_stats(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_alert_stats(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""Get alert statistics"""
|
||||
try:
|
||||
if not permission_manager.has_permission(current_user["user_id"], Permission.SECURITY_VIEW):
|
||||
@@ -92,7 +100,10 @@ async def get_alert_stats(current_user: Dict[str, Any] = Depends(get_current_use
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/alerts/rules")
|
||||
async def get_alert_rules(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_alert_rules(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""Get alert rules"""
|
||||
try:
|
||||
if not permission_manager.has_permission(current_user["user_id"], Permission.SECURITY_VIEW):
|
||||
@@ -114,7 +125,9 @@ async def get_alert_rules(current_user: Dict[str, Any] = Depends(get_current_use
|
||||
|
||||
# SLA monitoring endpoints
|
||||
@router.get("/sla")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_sla_status(
|
||||
request: Request,
|
||||
sla_id: Optional[str] = None,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
@@ -140,7 +153,9 @@ async def get_sla_status(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/sla/{sla_id}/record")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def record_sla_metric(
|
||||
request: Request,
|
||||
sla_id: str,
|
||||
value: float,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
@@ -167,7 +182,10 @@ async def record_sla_metric(
|
||||
|
||||
# System status endpoint with monitoring
|
||||
@router.get("/system/status")
|
||||
async def get_system_status(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_system_status(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""Get comprehensive system status"""
|
||||
try:
|
||||
if not permission_manager.has_permission(current_user["user_id"], Permission.SYSTEM_HEALTH):
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,10 @@ router = APIRouter()
|
||||
|
||||
# Authentication endpoints
|
||||
@router.post("/auth/login")
|
||||
async def login(login_data: Dict[str, str]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def login(
|
||||
request: Request, login_data: Dict[str, str]
|
||||
):
|
||||
"""User login with username and password"""
|
||||
try:
|
||||
username = login_data.get("username")
|
||||
@@ -96,7 +100,10 @@ async def login(login_data: Dict[str, str]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/auth/refresh")
|
||||
async def refresh_token(refresh_data: Dict[str, str]):
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def refresh_token(
|
||||
request: Request, refresh_data: Dict[str, str]
|
||||
):
|
||||
"""Refresh access token using refresh token"""
|
||||
try:
|
||||
refresh_token = refresh_data.get("refresh_token")
|
||||
@@ -118,7 +125,10 @@ async def refresh_token(refresh_data: Dict[str, str]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/auth/validate")
|
||||
async def validate_token(validate_data: Dict[str, str]):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def validate_token(
|
||||
request: Request, validate_data: Dict[str, str]
|
||||
):
|
||||
"""Validate JWT token"""
|
||||
try:
|
||||
token = validate_data.get("token")
|
||||
@@ -140,7 +150,9 @@ async def validate_token(validate_data: Dict[str, str]):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/auth/api-key/generate")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def generate_api_key(
|
||||
request: Request,
|
||||
user_id: str,
|
||||
permissions: List[str] = None,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
@@ -162,7 +174,10 @@ async def generate_api_key(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/auth/api-key/validate")
|
||||
async def validate_api_key(api_key: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def validate_api_key(
|
||||
request: Request, api_key: str
|
||||
):
|
||||
"""Validate API key"""
|
||||
try:
|
||||
result = api_key_manager.validate_api_key(api_key)
|
||||
@@ -179,7 +194,9 @@ async def validate_api_key(api_key: str):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.delete("/auth/api-key/{api_key}")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def revoke_api_key(
|
||||
request: Request,
|
||||
api_key: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,10 @@ router = APIRouter()
|
||||
|
||||
# Distributed consensus endpoints
|
||||
@router.post("/consensus/node/register")
|
||||
async def register_consensus_node(node_data: Dict[str, Any]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def register_consensus_node(
|
||||
request: Request, node_data: Dict[str, Any]
|
||||
):
|
||||
"""Register a node in the consensus network"""
|
||||
try:
|
||||
result = await distributed_consensus.register_node(node_data)
|
||||
@@ -35,7 +39,10 @@ async def register_consensus_node(node_data: Dict[str, Any]):
|
||||
raise HTTPException(status_code=500, detail="Failed to register consensus node")
|
||||
|
||||
@router.post("/consensus/proposal/create")
|
||||
async def create_consensus_proposal(proposal_data: Dict[str, Any]):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_consensus_proposal(
|
||||
request: Request, proposal_data: Dict[str, Any]
|
||||
):
|
||||
"""Create a new consensus proposal"""
|
||||
try:
|
||||
result = await distributed_consensus.create_proposal(proposal_data)
|
||||
@@ -45,7 +52,10 @@ async def create_consensus_proposal(proposal_data: Dict[str, Any]):
|
||||
raise HTTPException(status_code=500, detail="Failed to create consensus proposal")
|
||||
|
||||
@router.post("/consensus/proposal/{proposal_id}/vote")
|
||||
async def cast_consensus_vote(proposal_id: str, node_id: str, vote: bool):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def cast_consensus_vote(
|
||||
request: Request, proposal_id: str, node_id: str, vote: bool
|
||||
):
|
||||
"""Cast a vote for a proposal"""
|
||||
try:
|
||||
result = await distributed_consensus.cast_vote(proposal_id, node_id, vote)
|
||||
@@ -55,7 +65,10 @@ async def cast_consensus_vote(proposal_id: str, node_id: str, vote: bool):
|
||||
raise HTTPException(status_code=500, detail="Failed to cast consensus vote")
|
||||
|
||||
@router.get("/consensus/proposal/{proposal_id}")
|
||||
async def get_proposal_status(proposal_id: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_proposal_status(
|
||||
request: Request, proposal_id: str
|
||||
):
|
||||
"""Get proposal status"""
|
||||
try:
|
||||
result = await distributed_consensus.get_proposal_status(proposal_id)
|
||||
@@ -65,7 +78,10 @@ async def get_proposal_status(proposal_id: str):
|
||||
raise HTTPException(status_code=500, detail="Failed to get proposal status")
|
||||
|
||||
@router.put("/consensus/algorithm")
|
||||
async def set_consensus_algorithm(algorithm: str = Query(..., description="Consensus algorithm")):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def set_consensus_algorithm(
|
||||
request: Request, algorithm: str = Query(..., description="Consensus algorithm")
|
||||
):
|
||||
"""Set the consensus algorithm"""
|
||||
try:
|
||||
result = await distributed_consensus.set_consensus_algorithm(algorithm)
|
||||
@@ -75,7 +91,10 @@ async def set_consensus_algorithm(algorithm: str = Query(..., description="Conse
|
||||
raise HTTPException(status_code=500, detail="Failed to set consensus algorithm")
|
||||
|
||||
@router.get("/consensus/statistics")
|
||||
async def get_consensus_statistics():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_consensus_statistics(
|
||||
request: Request
|
||||
):
|
||||
"""Get consensus statistics"""
|
||||
try:
|
||||
result = await distributed_consensus.get_consensus_statistics()
|
||||
@@ -85,7 +104,10 @@ async def get_consensus_statistics():
|
||||
raise HTTPException(status_code=500, detail="Failed to get consensus statistics")
|
||||
|
||||
@router.put("/consensus/node/{node_id}/status")
|
||||
async def update_node_status(node_id: str, is_active: bool):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def update_node_status(
|
||||
request: Request, node_id: str, is_active: bool
|
||||
):
|
||||
"""Update node status"""
|
||||
try:
|
||||
result = await distributed_consensus.update_node_status(node_id, is_active)
|
||||
@@ -96,7 +118,10 @@ async def update_node_status(node_id: str, is_active: bool):
|
||||
|
||||
# Advanced features status endpoint
|
||||
@router.get("/advanced-features/status")
|
||||
async def get_advanced_features_status():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_advanced_features_status(
|
||||
request: Request
|
||||
):
|
||||
"""Get status of all advanced features"""
|
||||
try:
|
||||
learning_stats = await learning_system.get_learning_statistics()
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,8 @@ router = APIRouter()
|
||||
|
||||
# Health check endpoint
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def health_check(request: Request):
|
||||
"""Health check endpoint"""
|
||||
return {
|
||||
"status": "healthy",
|
||||
@@ -36,7 +38,8 @@ async def health_check():
|
||||
|
||||
# Root endpoint
|
||||
@router.get("/")
|
||||
async def root():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def root(request: Request):
|
||||
"""Root endpoint with service information"""
|
||||
return {
|
||||
"service": "AITBC Agent Coordinator",
|
||||
|
||||
@@ -3,7 +3,8 @@ from typing import Any, Dict, List, Optional
|
||||
import json
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -26,7 +27,10 @@ router = APIRouter()
|
||||
|
||||
# Send message
|
||||
@router.post("/messages/send")
|
||||
async def send_message(request: MessageRequest):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def send_message(
|
||||
request_http: Request, request: MessageRequest
|
||||
):
|
||||
"""Send message to agent"""
|
||||
try:
|
||||
if not state.communication_manager:
|
||||
@@ -100,7 +104,10 @@ async def send_message(request: MessageRequest):
|
||||
|
||||
# Broadcast message
|
||||
@router.post("/messages/broadcast")
|
||||
async def broadcast_message(request: BroadcastRequest):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def broadcast_message(
|
||||
request_http: Request, request: BroadcastRequest
|
||||
):
|
||||
"""Broadcast message to multiple agents"""
|
||||
try:
|
||||
if not state.communication_manager:
|
||||
@@ -191,7 +198,9 @@ async def broadcast_message(request: BroadcastRequest):
|
||||
|
||||
# Get message history
|
||||
@router.get("/messages/history")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_message_history(
|
||||
request: Request,
|
||||
sender_id: Optional[str] = Query(None, description="Filter by sender ID"),
|
||||
receiver_id: Optional[str] = Query(None, description="Filter by receiver ID"),
|
||||
limit: int = Query(100, description="Maximum number of messages"),
|
||||
@@ -232,7 +241,10 @@ async def get_message_history(
|
||||
|
||||
# Get specific message
|
||||
@router.get("/messages/{message_id}")
|
||||
async def get_message(message_id: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_message(
|
||||
request: Request, message_id: str
|
||||
):
|
||||
"""Get a specific message by ID"""
|
||||
try:
|
||||
if not state.message_storage:
|
||||
@@ -257,7 +269,10 @@ async def get_message(message_id: str):
|
||||
|
||||
# Load balancer statistics
|
||||
@router.get("/load-balancer/stats")
|
||||
async def get_load_balancer_stats():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_load_balancer_stats(
|
||||
request: Request
|
||||
):
|
||||
"""Get load balancer statistics"""
|
||||
try:
|
||||
if not state.load_balancer:
|
||||
@@ -277,7 +292,10 @@ async def get_load_balancer_stats():
|
||||
|
||||
# Registry statistics
|
||||
@router.get("/registry/stats")
|
||||
async def get_registry_stats():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_registry_stats(
|
||||
request: Request
|
||||
):
|
||||
"""Get agent registry statistics"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -297,7 +315,10 @@ async def get_registry_stats():
|
||||
|
||||
# Get agents by service
|
||||
@router.get("/agents/service/{service}")
|
||||
async def get_agents_by_service(service: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_agents_by_service(
|
||||
request: Request, service: str
|
||||
):
|
||||
"""Get agents that provide a specific service"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -319,7 +340,10 @@ async def get_agents_by_service(service: str):
|
||||
|
||||
# Get agents by capability
|
||||
@router.get("/agents/capability/{capability}")
|
||||
async def get_agents_by_capability(capability: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_agents_by_capability(
|
||||
request: Request, capability: str
|
||||
):
|
||||
"""Get agents that have a specific capability"""
|
||||
try:
|
||||
if not state.agent_registry:
|
||||
@@ -341,7 +365,10 @@ async def get_agents_by_capability(capability: str):
|
||||
|
||||
# Set load balancing strategy
|
||||
@router.put("/load-balancer/strategy")
|
||||
async def set_load_balancing_strategy(strategy: str = Query(..., description="Load balancing strategy")):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def set_load_balancing_strategy(
|
||||
request: Request, strategy: str = Query(..., description="Load balancing strategy")
|
||||
):
|
||||
"""Set load balancing strategy"""
|
||||
try:
|
||||
if not state.load_balancer:
|
||||
@@ -369,7 +396,10 @@ async def set_load_balancing_strategy(strategy: str = Query(..., description="Lo
|
||||
|
||||
# Peer management endpoints
|
||||
@router.post("/peers/add")
|
||||
async def add_peer(agent_id: str = Query(..., description="Agent ID"), peer_id: str = Query(..., description="Peer agent ID")):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def add_peer(
|
||||
request: Request, agent_id: str = Query(..., description="Agent ID"), peer_id: str = Query(..., description="Peer agent ID")
|
||||
):
|
||||
"""Add a peer connection for an agent"""
|
||||
try:
|
||||
from ..storage.message_storage import PeerStorage
|
||||
@@ -397,7 +427,10 @@ async def add_peer(agent_id: str = Query(..., description="Agent ID"), peer_id:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/peers/remove")
|
||||
async def remove_peer(agent_id: str = Query(..., description="Agent ID"), peer_id: str = Query(..., description="Peer agent ID")):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def remove_peer(
|
||||
request: Request, agent_id: str = Query(..., description="Agent ID"), peer_id: str = Query(..., description="Peer agent ID")
|
||||
):
|
||||
"""Remove a peer connection for an agent"""
|
||||
try:
|
||||
from ..storage.message_storage import PeerStorage
|
||||
@@ -425,7 +458,10 @@ async def remove_peer(agent_id: str = Query(..., description="Agent ID"), peer_i
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/peers/{agent_id}")
|
||||
async def get_agent_peers(agent_id: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_agent_peers(
|
||||
request: Request, agent_id: str
|
||||
):
|
||||
"""Get all peers for a specific agent"""
|
||||
try:
|
||||
from ..storage.message_storage import PeerStorage
|
||||
@@ -450,7 +486,10 @@ async def get_agent_peers(agent_id: str):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/peers")
|
||||
async def get_all_peers():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_all_peers(
|
||||
request: Request
|
||||
):
|
||||
"""Get all peer connections in the system"""
|
||||
try:
|
||||
from ..storage.message_storage import PeerStorage
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
"""Monitor router for AITBC Agent Coordinator."""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Request
|
||||
from typing import List, Dict
|
||||
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
router = APIRouter(tags=["Monitor"])
|
||||
|
||||
|
||||
@router.get("/api/v1/dashboard", response_model=dict)
|
||||
async def get_dashboard():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def get_dashboard(request: Request):
|
||||
"""Get monitoring dashboard data."""
|
||||
return {
|
||||
"overall_status": "operational",
|
||||
@@ -26,7 +29,8 @@ async def get_dashboard():
|
||||
|
||||
|
||||
@router.get("/status", response_model=dict)
|
||||
async def get_status():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def get_status(request: Request):
|
||||
"""Get coordinator status."""
|
||||
return {
|
||||
"status": "online",
|
||||
@@ -37,18 +41,21 @@ async def get_status():
|
||||
|
||||
|
||||
@router.get("/miners", response_model=List[Dict])
|
||||
async def get_miners():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_miners(request: Request):
|
||||
"""Get miners list."""
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/dashboard", response_model=List[Dict])
|
||||
async def get_history_dashboard():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_history_dashboard(request: Request):
|
||||
"""Get historical dashboard data."""
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/jobs", response_model=List[Dict])
|
||||
async def get_jobs():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_jobs(request: Request):
|
||||
"""Get jobs list for history and metrics commands."""
|
||||
return []
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,8 @@ router = APIRouter()
|
||||
|
||||
# Monitoring and metrics endpoints
|
||||
@router.get("/metrics")
|
||||
async def get_prometheus_metrics():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def get_prometheus_metrics(request: Request):
|
||||
"""Get metrics in Prometheus format"""
|
||||
try:
|
||||
metrics = metrics_registry.get_all_metrics()
|
||||
@@ -67,7 +69,8 @@ async def get_prometheus_metrics():
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/metrics/summary")
|
||||
async def get_metrics_summary():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_metrics_summary(request: Request):
|
||||
"""Get metrics summary for dashboard"""
|
||||
try:
|
||||
summary = performance_monitor.get_performance_summary()
|
||||
@@ -92,7 +95,8 @@ async def get_metrics_summary():
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/metrics/health")
|
||||
async def get_health_metrics():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_health_metrics(request: Request):
|
||||
"""Get health metrics for monitoring"""
|
||||
try:
|
||||
# Get system health metrics
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""Swarm coordination router for AITBC Agent Coordinator."""
|
||||
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
router = APIRouter(prefix="/swarm", tags=["Swarm"])
|
||||
|
||||
|
||||
@@ -47,7 +49,9 @@ class ConsensusRequest(BaseModel):
|
||||
|
||||
|
||||
@router.get("/list", response_model=List[SwarmInfo])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_swarms(
|
||||
request: Request,
|
||||
swarm_id: Optional[str] = Query(None, description="Filter by swarm ID"),
|
||||
status: Optional[str] = Query(None, description="Filter by status"),
|
||||
limit: int = Query(20, description="Number of swarms to list")
|
||||
@@ -58,7 +62,10 @@ async def list_swarms(
|
||||
|
||||
|
||||
@router.post("/join", response_model=dict, status_code=201)
|
||||
async def join_swarm(request: JoinRequest):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def join_swarm(
|
||||
request_http: Request, request: JoinRequest
|
||||
):
|
||||
"""Join agent swarm for collective optimization."""
|
||||
import uuid
|
||||
return {
|
||||
@@ -72,7 +79,10 @@ async def join_swarm(request: JoinRequest):
|
||||
|
||||
|
||||
@router.post("/coordinate", response_model=dict, status_code=202)
|
||||
async def coordinate_swarm(request: CoordinateRequest):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def coordinate_swarm(
|
||||
request_http: Request, request: CoordinateRequest
|
||||
):
|
||||
"""Coordinate swarm task execution."""
|
||||
import uuid
|
||||
return {
|
||||
@@ -86,7 +96,10 @@ async def coordinate_swarm(request: CoordinateRequest):
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}/status", response_model=TaskStatus)
|
||||
async def get_task_status(task_id: str):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_task_status(
|
||||
request: Request, task_id: str
|
||||
):
|
||||
"""Get swarm task status."""
|
||||
return {
|
||||
"task_id": task_id,
|
||||
@@ -98,7 +111,10 @@ async def get_task_status(task_id: str):
|
||||
|
||||
|
||||
@router.post("/{swarm_id}/leave", response_model=dict)
|
||||
async def leave_swarm(swarm_id: str):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def leave_swarm(
|
||||
request: Request, swarm_id: str
|
||||
):
|
||||
"""Leave swarm."""
|
||||
return {
|
||||
"swarm_id": swarm_id,
|
||||
@@ -108,7 +124,10 @@ async def leave_swarm(swarm_id: str):
|
||||
|
||||
|
||||
@router.post("/tasks/{task_id}/consensus", response_model=dict)
|
||||
async def achieve_consensus(task_id: str, request: ConsensusRequest):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def achieve_consensus(
|
||||
request: Request, task_id: str, request_consensus: ConsensusRequest
|
||||
):
|
||||
"""Achieve swarm consensus on task result."""
|
||||
return {
|
||||
"task_id": task_id,
|
||||
@@ -119,7 +138,10 @@ async def achieve_consensus(task_id: str, request: ConsensusRequest):
|
||||
|
||||
|
||||
@router.get("/api/v1/dashboard", response_model=dict)
|
||||
async def get_dashboard():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def get_dashboard(
|
||||
request: Request
|
||||
):
|
||||
"""Get monitoring dashboard data."""
|
||||
return {
|
||||
"overall_status": "operational",
|
||||
@@ -138,7 +160,10 @@ async def get_dashboard():
|
||||
|
||||
|
||||
@router.get("/status", response_model=dict)
|
||||
async def get_status():
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def get_status(
|
||||
request: Request
|
||||
):
|
||||
"""Get coordinator status."""
|
||||
return {
|
||||
"status": "online",
|
||||
@@ -149,12 +174,18 @@ async def get_status():
|
||||
|
||||
|
||||
@router.get("/miners", response_model=list)
|
||||
async def get_miners():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_miners(
|
||||
request: Request
|
||||
):
|
||||
"""Get miners list."""
|
||||
return []
|
||||
|
||||
|
||||
@router.get("/dashboard", response_model=list)
|
||||
async def get_history_dashboard():
|
||||
@rate_limit(rate=500, per=60)
|
||||
async def get_history_dashboard(
|
||||
request: Request
|
||||
):
|
||||
"""Get historical dashboard data."""
|
||||
return []
|
||||
|
||||
@@ -3,7 +3,8 @@ import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -26,7 +27,10 @@ router = APIRouter()
|
||||
|
||||
# Submit task
|
||||
@router.post("/tasks/submit")
|
||||
async def submit_task(request: TaskSubmission, background_tasks: BackgroundTasks):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def submit_task(
|
||||
request_http: Request, request: TaskSubmission, background_tasks: BackgroundTasks
|
||||
):
|
||||
"""Submit a task for distribution"""
|
||||
try:
|
||||
if not state.task_distributor:
|
||||
@@ -61,7 +65,10 @@ async def submit_task(request: TaskSubmission, background_tasks: BackgroundTasks
|
||||
|
||||
# Get task status
|
||||
@router.get("/tasks/status")
|
||||
async def get_task_status():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_task_status(
|
||||
request: Request
|
||||
):
|
||||
"""Get task distribution statistics"""
|
||||
try:
|
||||
if not state.task_distributor:
|
||||
@@ -81,7 +88,10 @@ async def get_task_status():
|
||||
|
||||
# Task queue management
|
||||
@router.get("/tasks/queues")
|
||||
async def get_queue_sizes():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_queue_sizes(
|
||||
request: Request
|
||||
):
|
||||
"""Get task queue sizes"""
|
||||
try:
|
||||
if not state.task_distributor:
|
||||
@@ -102,7 +112,10 @@ async def get_queue_sizes():
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/tasks/queues/{priority}/clear")
|
||||
async def clear_queue(priority: str):
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def clear_queue(
|
||||
request: Request, priority: str
|
||||
):
|
||||
"""Clear a priority queue"""
|
||||
try:
|
||||
if not state.task_distributor:
|
||||
@@ -132,7 +145,10 @@ async def clear_queue(priority: str):
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/tasks/queues/stats")
|
||||
async def get_queue_stats():
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_queue_stats(
|
||||
request: Request
|
||||
):
|
||||
"""Get detailed queue statistics"""
|
||||
try:
|
||||
if not state.task_distributor:
|
||||
|
||||
@@ -2,7 +2,8 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Response
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .. import state
|
||||
@@ -25,7 +26,9 @@ router = APIRouter()
|
||||
|
||||
# User management endpoints
|
||||
@router.post("/users/{user_id}/role")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def assign_user_role(
|
||||
request: Request,
|
||||
user_id: str,
|
||||
role: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
@@ -52,7 +55,9 @@ async def assign_user_role(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/users/{user_id}/role")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_user_role(
|
||||
request: Request,
|
||||
user_id: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
@@ -73,7 +78,9 @@ async def get_user_role(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/users/{user_id}/permissions")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_user_permissions(
|
||||
request: Request,
|
||||
user_id: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
@@ -94,7 +101,9 @@ async def get_user_permissions(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/users/{user_id}/permissions/grant")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def grant_user_permission(
|
||||
request: Request,
|
||||
user_id: str,
|
||||
permission: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
@@ -121,7 +130,9 @@ async def grant_user_permission(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.delete("/users/{user_id}/permissions/{permission}")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def revoke_user_permission(
|
||||
request: Request,
|
||||
user_id: str,
|
||||
permission: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
@@ -149,7 +160,10 @@ async def revoke_user_permission(
|
||||
|
||||
# Role and permission management endpoints
|
||||
@router.get("/roles")
|
||||
async def list_all_roles(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_all_roles(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""List all available roles and their permissions"""
|
||||
try:
|
||||
# Check if user has permission to view roles
|
||||
@@ -167,7 +181,9 @@ async def list_all_roles(current_user: Dict[str, Any] = Depends(get_current_user
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/roles/{role}")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_role_permissions(
|
||||
request: Request,
|
||||
role: str,
|
||||
current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
@@ -193,7 +209,10 @@ async def get_role_permissions(
|
||||
raise HTTPException(status_code=500, detail="Failed to get role permissions")
|
||||
|
||||
@router.get("/auth/stats")
|
||||
async def get_permission_stats(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_permission_stats(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""Get statistics about permissions and users"""
|
||||
try:
|
||||
# Check if user has permission to view security stats
|
||||
@@ -212,8 +231,11 @@ async def get_permission_stats(current_user: Dict[str, Any] = Depends(get_curren
|
||||
|
||||
# Protected endpoint example
|
||||
@router.get("/protected/admin")
|
||||
@rate_limit(rate=100, per=60)
|
||||
@require_role([Role.ADMIN])
|
||||
async def admin_only_endpoint(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
async def admin_only_endpoint(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""Admin-only endpoint example"""
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -228,8 +250,11 @@ async def admin_only_endpoint(current_user: Dict[str, Any] = Depends(get_current
|
||||
}
|
||||
|
||||
@router.get("/protected/operator")
|
||||
@rate_limit(rate=100, per=60)
|
||||
@require_role([Role.ADMIN, Role.OPERATOR])
|
||||
async def operator_endpoint(current_user: Dict[str, Any] = Depends(get_current_user)):
|
||||
async def operator_endpoint(
|
||||
request: Request, current_user: Dict[str, Any] = Depends(get_current_user)
|
||||
):
|
||||
"""Operator and admin endpoint example"""
|
||||
return {
|
||||
"status": "success",
|
||||
|
||||
@@ -9,10 +9,11 @@ REST API for agent creativity enhancement, ideation, and cross-domain synthesis
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from aitbc import get_logger
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -83,7 +84,10 @@ class SynthesisRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/capabilities", response_model=CreativeCapabilityResponse)
|
||||
async def create_creative_capability(request: CreativeCapabilityCreate, session: Annotated[Session, Depends(get_session)]) -> CreativeCapabilityResponse:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_creative_capability(
|
||||
request_http: Request, request: CreativeCapabilityCreate, session: Annotated[Session, Depends(get_session)]
|
||||
) -> CreativeCapabilityResponse:
|
||||
"""Initialize a new creative capability for an agent"""
|
||||
engine = CreativityEnhancementEngine()
|
||||
|
||||
@@ -104,7 +108,9 @@ async def create_creative_capability(request: CreativeCapabilityCreate, session:
|
||||
|
||||
|
||||
@router.post("/capabilities/{capability_id}/enhance")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def enhance_creativity(
|
||||
request_http: Request,
|
||||
capability_id: str, request: EnhanceCreativityRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> dict[str, Any]:
|
||||
"""Enhance a specific creative capability using specified algorithm"""
|
||||
@@ -123,7 +129,9 @@ async def enhance_creativity(
|
||||
|
||||
|
||||
@router.post("/capabilities/{capability_id}/evaluate")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def evaluate_creation(
|
||||
request_http: Request,
|
||||
capability_id: str, request: EvaluateCreationRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> dict[str, Any]:
|
||||
"""Evaluate a creative output and update agent capability metrics"""
|
||||
@@ -145,7 +153,10 @@ async def evaluate_creation(
|
||||
|
||||
|
||||
@router.post("/ideation/generate")
|
||||
async def generate_ideas(request: IdeationRequest) -> dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def generate_ideas(
|
||||
request_http: Request, request: IdeationRequest
|
||||
) -> dict[str, Any]:
|
||||
"""Generate innovative ideas using specialized ideation algorithms"""
|
||||
ideation_engine = IdeationAlgorithm()
|
||||
|
||||
@@ -164,7 +175,10 @@ async def generate_ideas(request: IdeationRequest) -> dict[str, Any]:
|
||||
|
||||
|
||||
@router.post("/synthesis/cross-domain")
|
||||
async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[Session, Depends(get_session)]) -> dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def synthesize_cross_domain(
|
||||
request_http: Request, request: SynthesisRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> dict[str, Any]:
|
||||
"""Synthesize concepts from multiple domains to create novel outputs"""
|
||||
integrator = CrossDomainCreativeIntegrator()
|
||||
|
||||
@@ -185,7 +199,10 @@ async def synthesize_cross_domain(request: SynthesisRequest, session: Annotated[
|
||||
|
||||
|
||||
@router.get("/capabilities/{agent_id}")
|
||||
async def list_agent_creative_capabilities(agent_id: str, session: Annotated[Session, Depends(get_session)]) -> list[CreativeCapability]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_agent_creative_capabilities(
|
||||
request: Request, agent_id: str, session: Annotated[Session, Depends(get_session)]
|
||||
) -> list[CreativeCapability]:
|
||||
"""List all creative capabilities for a specific agent"""
|
||||
try:
|
||||
capabilities = session.execute(select(CreativeCapability).where(CreativeCapability.agent_id == agent_id)).all()
|
||||
|
||||
@@ -5,9 +5,10 @@ Agent Integration and Deployment API Router for Verifiable AI Agent Orchestratio
|
||||
Provides REST API endpoints for production deployment and integration management
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from aitbc import get_logger
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -31,7 +32,9 @@ router = APIRouter(prefix="/agents/integration", tags=["Agent Integration"])
|
||||
|
||||
|
||||
@router.post("/deployments/config", response_model=AgentDeploymentConfig)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_deployment_config(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
deployment_name: str,
|
||||
deployment_config: dict,
|
||||
@@ -65,7 +68,9 @@ async def create_deployment_config(
|
||||
|
||||
|
||||
@router.get("/deployments/configs", response_model=list[AgentDeploymentConfig])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_deployment_configs(
|
||||
request: Request,
|
||||
workflow_id: str | None = None,
|
||||
status: DeploymentStatus | None = None,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -99,7 +104,9 @@ async def list_deployment_configs(
|
||||
|
||||
|
||||
@router.get("/deployments/configs/{config_id}", response_model=AgentDeploymentConfig)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_deployment_config(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -126,7 +133,9 @@ async def get_deployment_config(
|
||||
|
||||
|
||||
@router.post("/deployments/{config_id}/deploy")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def deploy_workflow(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
target_environment: str = "production",
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -160,7 +169,9 @@ async def deploy_workflow(
|
||||
|
||||
|
||||
@router.get("/deployments/{config_id}/health")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_deployment_health(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -190,7 +201,9 @@ async def get_deployment_health(
|
||||
|
||||
|
||||
@router.post("/deployments/{config_id}/scale")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def scale_deployment(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
target_instances: int,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -224,7 +237,9 @@ async def scale_deployment(
|
||||
|
||||
|
||||
@router.post("/deployments/{config_id}/rollback")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def rollback_deployment(
|
||||
request: Request,
|
||||
config_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -255,7 +270,9 @@ async def rollback_deployment(
|
||||
|
||||
|
||||
@router.get("/deployments/instances", response_model=list[AgentDeploymentInstance])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_deployment_instances(
|
||||
request: Request,
|
||||
deployment_id: str | None = None,
|
||||
environment: str | None = None,
|
||||
status: DeploymentStatus | None = None,
|
||||
@@ -295,7 +312,9 @@ async def list_deployment_instances(
|
||||
|
||||
|
||||
@router.get("/deployments/instances/{instance_id}", response_model=AgentDeploymentInstance)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_deployment_instance(
|
||||
request: Request,
|
||||
instance_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -326,7 +345,9 @@ async def get_deployment_instance(
|
||||
|
||||
|
||||
@router.post("/integrations/zk/{execution_id}")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def integrate_with_zk_system(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
verification_level: VerificationLevel = VerificationLevel.BASIC,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -360,7 +381,9 @@ async def integrate_with_zk_system(
|
||||
|
||||
|
||||
@router.get("/metrics/deployments/{deployment_id}")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_deployment_metrics(
|
||||
request: Request,
|
||||
deployment_id: str,
|
||||
time_range: str = "1h",
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -391,7 +414,9 @@ async def get_deployment_metrics(
|
||||
|
||||
|
||||
@router.post("/production/deploy")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def deploy_to_production(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
deployment_config: dict,
|
||||
integration_config: dict | None = None,
|
||||
@@ -425,7 +450,9 @@ async def deploy_to_production(
|
||||
|
||||
|
||||
@router.get("/production/dashboard")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_production_dashboard(
|
||||
request: Request,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
|
||||
) -> dict[str, Any]:
|
||||
"""Get comprehensive production dashboard data"""
|
||||
@@ -479,7 +506,9 @@ async def get_production_dashboard(
|
||||
|
||||
|
||||
@router.get("/production/health")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_production_health(
|
||||
request: Request,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
|
||||
) -> dict[str, Any]:
|
||||
"""Get overall production health status"""
|
||||
@@ -549,7 +578,9 @@ async def get_production_health(
|
||||
|
||||
|
||||
@router.get("/production/alerts")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_production_alerts(
|
||||
request: Request,
|
||||
severity: str | None = None,
|
||||
limit: int = 50,
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
|
||||
@@ -10,10 +10,11 @@ REST API for meta-learning, resource optimization, and performance enhancement
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from aitbc import get_logger
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -176,7 +177,9 @@ class CapabilityResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/profiles", response_model=PerformanceProfileResponse)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_performance_profile(
|
||||
request: Request,
|
||||
profile_request: PerformanceProfileRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> PerformanceProfileResponse:
|
||||
"""Create agent performance profile"""
|
||||
@@ -214,7 +217,10 @@ async def create_performance_profile(
|
||||
|
||||
|
||||
@router.get("/profiles/{agent_id}", response_model=Dict[str, Any])
|
||||
async def get_performance_profile(agent_id: str, session: Annotated[Session, Depends(get_session)]) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_performance_profile(
|
||||
request: Request, agent_id: str, session: Annotated[Session, Depends(get_session)]
|
||||
) -> Dict[str, Any]:
|
||||
"""Get agent performance profile"""
|
||||
|
||||
performance_service = AgentPerformanceService(session)
|
||||
@@ -235,7 +241,9 @@ async def get_performance_profile(agent_id: str, session: Annotated[Session, Dep
|
||||
|
||||
|
||||
@router.post("/profiles/{agent_id}/metrics")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def update_performance_metrics(
|
||||
request: Request,
|
||||
agent_id: str,
|
||||
metrics: Dict[str, float],
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
@@ -264,7 +272,9 @@ async def update_performance_metrics(
|
||||
|
||||
|
||||
@router.post("/meta-learning/models", response_model=MetaLearningResponse)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_meta_learning_model(
|
||||
request: Request,
|
||||
model_request: MetaLearningRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> MetaLearningResponse:
|
||||
"""Create meta-learning model"""
|
||||
@@ -300,7 +310,9 @@ async def create_meta_learning_model(
|
||||
|
||||
|
||||
@router.post("/meta-learning/models/{model_id}/adapt")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def adapt_model_to_task(
|
||||
request: Request,
|
||||
model_id: str,
|
||||
task_data: Dict[str, Any],
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
@@ -330,7 +342,9 @@ async def adapt_model_to_task(
|
||||
|
||||
|
||||
@router.get("/meta-learning/models")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_meta_learning_models(
|
||||
request: Request,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
status: Optional[str] = Query(default=None, description="Filter by status"),
|
||||
meta_strategy: Optional[str] = Query(default=None, description="Filter by meta strategy"),
|
||||
@@ -373,7 +387,9 @@ async def list_meta_learning_models(
|
||||
|
||||
|
||||
@router.post("/resources/allocate", response_model=ResourceAllocationResponse)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def allocate_resources(
|
||||
request: Request,
|
||||
allocation_request: ResourceAllocationRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> ResourceAllocationResponse:
|
||||
"""Allocate resources for agent task"""
|
||||
@@ -408,7 +424,9 @@ async def allocate_resources(
|
||||
|
||||
|
||||
@router.get("/resources/{agent_id}")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_resource_allocations(
|
||||
request: Request,
|
||||
agent_id: str,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
status: Optional[str] = Query(default=None, description="Filter by status"),
|
||||
@@ -453,7 +471,9 @@ async def get_resource_allocations(
|
||||
|
||||
|
||||
@router.post("/optimization/optimize", response_model=PerformanceOptimizationResponse)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def optimize_performance(
|
||||
request: Request,
|
||||
optimization_request: PerformanceOptimizationRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> PerformanceOptimizationResponse:
|
||||
"""Optimize agent performance"""
|
||||
@@ -488,7 +508,9 @@ async def optimize_performance(
|
||||
|
||||
|
||||
@router.get("/optimization/{agent_id}")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_optimization_history(
|
||||
request: Request,
|
||||
agent_id: str,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
status: Optional[str] = Query(default=None, description="Filter by status"),
|
||||
@@ -537,7 +559,9 @@ async def get_optimization_history(
|
||||
|
||||
|
||||
@router.post("/capabilities", response_model=CapabilityResponse)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_capability(
|
||||
request: Request,
|
||||
capability_request: CapabilityRequest, session: Annotated[Session, Depends(get_session)]
|
||||
) -> CapabilityResponse:
|
||||
"""Create agent capability"""
|
||||
@@ -580,7 +604,9 @@ async def create_capability(
|
||||
|
||||
|
||||
@router.get("/capabilities/{agent_id}")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_agent_capabilities(
|
||||
request: Request,
|
||||
agent_id: str,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
capability_type: Optional[str] = Query(default=None, description="Filter by capability type"),
|
||||
@@ -631,7 +657,9 @@ async def get_agent_capabilities(
|
||||
|
||||
|
||||
@router.get("/analytics/performance-summary")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_performance_summary(
|
||||
request: Request,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
agent_ids: List[str] = Query(default=[], description="List of agent IDs"),
|
||||
metric: Optional[str] = Query(default="overall_score", description="Metric to summarize"),
|
||||
@@ -713,7 +741,10 @@ def calculate_specialization_distribution(summaries: List[Dict[str, Any]]) -> Di
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check() -> Dict[str, Any]:
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def health_check(
|
||||
request: Request
|
||||
) -> Dict[str, Any]:
|
||||
"""Health check for agent performance service"""
|
||||
|
||||
return {
|
||||
|
||||
@@ -10,9 +10,10 @@ Provides REST API endpoints for agent workflow management and execution
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request
|
||||
|
||||
from aitbc import get_logger
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -35,7 +36,9 @@ router = APIRouter(tags=["AI Agents"])
|
||||
|
||||
|
||||
@router.post("/workflows", response_model=AIAgentWorkflow)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_workflow(
|
||||
request: Request,
|
||||
workflow_data: AgentWorkflowCreate,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -58,7 +61,9 @@ async def create_workflow(
|
||||
|
||||
|
||||
@router.get("/workflows", response_model=list[AIAgentWorkflow])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_workflows(
|
||||
request: Request,
|
||||
owner_id: str | None = None,
|
||||
is_public: bool | None = None,
|
||||
tags: list[str] | None = None,
|
||||
@@ -94,7 +99,9 @@ async def list_workflows(
|
||||
|
||||
|
||||
@router.get("/workflows/{workflow_id}", response_model=AIAgentWorkflow)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_workflow(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -120,7 +127,9 @@ async def get_workflow(
|
||||
|
||||
|
||||
@router.put("/workflows/{workflow_id}", response_model=AIAgentWorkflow)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def update_workflow(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
workflow_data: AgentWorkflowUpdate,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -157,7 +166,9 @@ async def update_workflow(
|
||||
|
||||
|
||||
@router.delete("/workflows/{workflow_id}")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def delete_workflow(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -187,7 +198,9 @@ async def delete_workflow(
|
||||
|
||||
|
||||
@router.post("/workflows/{workflow_id}/execute", response_model=AgentExecutionResponse)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def execute_workflow(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
execution_request: AgentExecutionRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
@@ -233,7 +246,9 @@ async def execute_workflow(
|
||||
|
||||
|
||||
@router.get("/executions/{execution_id}/status", response_model=AgentExecutionStatus)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_execution_status(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -264,7 +279,9 @@ async def get_execution_status(
|
||||
|
||||
|
||||
@router.get("/executions", response_model=list[AgentExecutionStatus])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_executions(
|
||||
request: Request,
|
||||
workflow_id: str | None = None,
|
||||
status: AgentStatus | None = None,
|
||||
limit: int = 50,
|
||||
@@ -325,7 +342,9 @@ async def list_executions(
|
||||
|
||||
|
||||
@router.post("/executions/{execution_id}/cancel")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def cancel_execution(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -365,7 +384,9 @@ async def cancel_execution(
|
||||
|
||||
|
||||
@router.get("/executions/{execution_id}/logs")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_execution_logs(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -423,13 +444,18 @@ async def get_execution_logs(
|
||||
|
||||
|
||||
@router.get("/test")
|
||||
async def test_endpoint() -> dict[str, str]:
|
||||
@rate_limit(rate=1000, per=60)
|
||||
async def test_endpoint(
|
||||
request: Request
|
||||
) -> dict[str, str]:
|
||||
"""Test endpoint to verify router is working"""
|
||||
return {"message": "Agent router is working", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/networks", response_model=dict, status_code=201)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_agent_network(
|
||||
request: Request,
|
||||
network_data: dict,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -469,7 +495,9 @@ async def create_agent_network(
|
||||
|
||||
|
||||
@router.get("/executions/{execution_id}/receipt")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_execution_receipt(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
|
||||
@@ -7,9 +7,13 @@ Agent Security API Router for Verifiable AI Agent Orchestration
|
||||
Provides REST API endpoints for security management and auditing
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from aitbc import get_logger
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -34,7 +38,9 @@ router = APIRouter(prefix="/agents/security", tags=["Agent Security"])
|
||||
|
||||
|
||||
@router.post("/policies", response_model=AgentSecurityPolicy)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_security_policy(
|
||||
request: Request,
|
||||
name: str,
|
||||
description: str,
|
||||
security_level: SecurityLevel,
|
||||
@@ -59,7 +65,9 @@ async def create_security_policy(
|
||||
|
||||
|
||||
@router.get("/policies", response_model=list[AgentSecurityPolicy])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_security_policies(
|
||||
request: Request,
|
||||
security_level: SecurityLevel | None = None,
|
||||
is_active: bool | None = None,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -85,7 +93,9 @@ async def list_security_policies(
|
||||
|
||||
|
||||
@router.get("/policies/{policy_id}", response_model=AgentSecurityPolicy)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_security_policy(
|
||||
request: Request,
|
||||
policy_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -107,7 +117,9 @@ async def get_security_policy(
|
||||
|
||||
|
||||
@router.put("/policies/{policy_id}", response_model=AgentSecurityPolicy)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def update_security_policy(
|
||||
request: Request,
|
||||
policy_id: str,
|
||||
policy_updates: dict,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -150,7 +162,9 @@ async def update_security_policy(
|
||||
|
||||
|
||||
@router.delete("/policies/{policy_id}")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def delete_security_policy(
|
||||
request: Request,
|
||||
policy_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -186,7 +200,9 @@ async def delete_security_policy(
|
||||
|
||||
|
||||
@router.post("/validate-workflow/{workflow_id}")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def validate_workflow_security(
|
||||
request: Request,
|
||||
workflow_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -215,7 +231,9 @@ async def validate_workflow_security(
|
||||
|
||||
|
||||
@router.get("/audit-logs", response_model=list[AgentAuditLog])
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_audit_logs(
|
||||
request: Request,
|
||||
event_type: AuditEventType | None = None,
|
||||
workflow_id: str | None = None,
|
||||
execution_id: str | None = None,
|
||||
@@ -267,7 +285,9 @@ async def list_audit_logs(
|
||||
|
||||
|
||||
@router.get("/audit-logs/{audit_id}", response_model=AgentAuditLog)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_audit_log(
|
||||
request: Request,
|
||||
audit_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -290,7 +310,9 @@ async def get_audit_log(
|
||||
|
||||
|
||||
@router.get("/trust-scores")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_trust_scores(
|
||||
request: Request,
|
||||
entity_type: str | None = None,
|
||||
entity_id: str | None = None,
|
||||
min_score: float | None = None,
|
||||
@@ -330,7 +352,9 @@ async def list_trust_scores(
|
||||
|
||||
|
||||
@router.get("/trust-scores/{entity_type}/{entity_id}", response_model=AgentTrustScore)
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_trust_score(
|
||||
request: Request,
|
||||
entity_type: str,
|
||||
entity_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -360,7 +384,9 @@ async def get_trust_score(
|
||||
|
||||
|
||||
@router.post("/trust-scores/{entity_type}/{entity_id}/update")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def update_trust_score(
|
||||
request: Request,
|
||||
entity_type: str,
|
||||
entity_id: str,
|
||||
execution_success: bool,
|
||||
@@ -409,7 +435,9 @@ async def update_trust_score(
|
||||
|
||||
|
||||
@router.post("/sandbox/{execution_id}/create")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_sandbox(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
security_level: SecurityLevel = SecurityLevel.PUBLIC,
|
||||
workflow_requirements: dict | None = None,
|
||||
@@ -447,7 +475,9 @@ async def create_sandbox(
|
||||
|
||||
|
||||
@router.get("/sandbox/{execution_id}/monitor")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def monitor_sandbox(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -466,7 +496,9 @@ async def monitor_sandbox(
|
||||
|
||||
|
||||
@router.post("/sandbox/{execution_id}/cleanup")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def cleanup_sandbox(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
current_user: str = Depends(require_admin_key()),
|
||||
@@ -495,7 +527,9 @@ async def cleanup_sandbox(
|
||||
|
||||
|
||||
@router.post("/executions/{execution_id}/security-monitor")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def monitor_execution_security(
|
||||
request: Request,
|
||||
execution_id: str,
|
||||
workflow_id: str,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]),
|
||||
@@ -515,7 +549,9 @@ async def monitor_execution_security(
|
||||
|
||||
|
||||
@router.get("/security-dashboard")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_security_dashboard(
|
||||
request: Request,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
|
||||
) -> dict[str, Any]:
|
||||
"""Get comprehensive security dashboard data"""
|
||||
@@ -570,7 +606,9 @@ async def get_security_dashboard(
|
||||
|
||||
|
||||
@router.get("/security-stats")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_security_statistics(
|
||||
request: Request,
|
||||
session: Session = Depends(Annotated[Session, Depends(get_session)]), current_user: str = Depends(require_admin_key())
|
||||
) -> dict[str, Any]:
|
||||
"""Get security statistics and metrics"""
|
||||
|
||||
@@ -8,8 +8,9 @@ Services router for specific GPU workloads
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
|
||||
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from ..deps import require_client_key
|
||||
from ..models.services import (
|
||||
BlenderRequest,
|
||||
@@ -37,7 +38,9 @@ router = APIRouter(tags=["services"])
|
||||
summary="Submit a service-specific job",
|
||||
deprecated=True,
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def submit_service_job(
|
||||
request_http: Request,
|
||||
service_type: ServiceType,
|
||||
request_data: dict[str, Any],
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
@@ -105,7 +108,9 @@ async def submit_service_job(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Transcribe audio using Whisper",
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def whisper_transcribe(
|
||||
request_http: Request,
|
||||
request: WhisperRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -136,7 +141,9 @@ async def whisper_transcribe(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Translate audio using Whisper",
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def whisper_translate(
|
||||
request_http: Request,
|
||||
request: WhisperRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -170,7 +177,9 @@ async def whisper_translate(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Generate images using Stable Diffusion",
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def stable_diffusion_generate(
|
||||
request_http: Request,
|
||||
request: StableDiffusionRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -203,7 +212,9 @@ async def stable_diffusion_generate(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Image-to-image generation",
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def stable_diffusion_img2img(
|
||||
request_http: Request,
|
||||
request: StableDiffusionRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -235,7 +246,9 @@ async def stable_diffusion_img2img(
|
||||
@router.post(
|
||||
"/services/llm/inference", response_model=ServiceResponse, status_code=status.HTTP_201_CREATED, summary="Run LLM inference"
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def llm_inference(
|
||||
request_http: Request,
|
||||
request: LLMRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -263,7 +276,9 @@ async def llm_inference(
|
||||
|
||||
|
||||
@router.post("/services/llm/stream", summary="Stream LLM inference")
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def llm_stream(
|
||||
request_http: Request,
|
||||
request: LLMRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -299,7 +314,9 @@ async def llm_stream(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Transcode video using FFmpeg",
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def ffmpeg_transcode(
|
||||
request_http: Request,
|
||||
request: FFmpegRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -334,7 +351,9 @@ async def ffmpeg_transcode(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Render using Blender",
|
||||
)
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def blender_render(
|
||||
request_http: Request,
|
||||
request: BlenderRequest,
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
client_id: str = Depends(require_client_key()),
|
||||
@@ -366,7 +385,10 @@ async def blender_render(
|
||||
|
||||
# Utility endpoints
|
||||
@router.get("/services", summary="List available services")
|
||||
async def list_services() -> dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_services(
|
||||
request: Request
|
||||
) -> dict[str, Any]:
|
||||
"""List all available service types and their capabilities"""
|
||||
return {
|
||||
"services": [
|
||||
@@ -425,7 +447,10 @@ async def list_services() -> dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/services/{service_type}/schema", summary="Get service request schema", deprecated=True)
|
||||
async def get_service_schema(service_type: ServiceType) -> dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_service_schema(
|
||||
request: Request, service_type: ServiceType
|
||||
) -> dict[str, Any]:
|
||||
"""Get the JSON schema for a specific service type
|
||||
|
||||
DEPRECATED: Use /v1/registry/services/{service_id}/schema instead.
|
||||
|
||||
@@ -6,7 +6,7 @@ import time
|
||||
from typing import Any, Dict, Optional, List
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, HTTPException, status, Request
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from sqlmodel import select, delete
|
||||
|
||||
@@ -20,6 +20,8 @@ from ..sync import ChainSync
|
||||
from ..contracts.agent_messaging_contract import messaging_contract
|
||||
from .contract_service import contract_service
|
||||
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
_logger = get_logger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
@@ -254,7 +256,10 @@ class EstimateFeeRequest(BaseModel):
|
||||
|
||||
|
||||
@router.get("/genesis_allocations", summary="Get genesis allocations from blockchain")
|
||||
async def get_genesis_allocations(chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_genesis_allocations(
|
||||
request: Request, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get genesis allocations from genesis block metadata for RPC bootstrap"""
|
||||
chain_id = get_chain_id(chain_id)
|
||||
|
||||
@@ -286,7 +291,10 @@ async def get_genesis_allocations(chain_id: str = None) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/head", summary="Get current chain head")
|
||||
async def get_head(chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_head(
|
||||
request: Request, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get current chain head"""
|
||||
chain_id = get_chain_id(chain_id)
|
||||
|
||||
@@ -308,7 +316,10 @@ async def get_head(chain_id: str = None) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/blocks/{height}", summary="Get block by height")
|
||||
async def get_block(height: int, chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_block(
|
||||
request: Request, height: int, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get block by height"""
|
||||
chain_id = get_chain_id(chain_id)
|
||||
|
||||
@@ -349,7 +360,10 @@ async def get_block(height: int, chain_id: str = None) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.post("/transaction", summary="Submit transaction")
|
||||
async def submit_transaction(tx_data: TransactionRequest) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def submit_transaction(
|
||||
request: Request, tx_data: TransactionRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""Submit a new transaction to the mempool"""
|
||||
from ..mempool import get_mempool
|
||||
|
||||
@@ -386,7 +400,10 @@ async def submit_transaction(tx_data: TransactionRequest) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/mempool", summary="Get pending transactions")
|
||||
async def get_mempool(chain_id: str = None, limit: int = 100) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_mempool(
|
||||
request: Request, chain_id: str = None, limit: int = 100
|
||||
) -> Dict[str, Any]:
|
||||
"""Get pending transactions from mempool"""
|
||||
from ..mempool import get_mempool
|
||||
|
||||
@@ -405,7 +422,10 @@ async def get_mempool(chain_id: str = None, limit: int = 100) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/account/{address}", summary="Get account information")
|
||||
async def get_account(address: str, chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_account(
|
||||
request: Request, address: str, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get account information"""
|
||||
chain_id = get_chain_id(chain_id)
|
||||
|
||||
@@ -423,13 +443,19 @@ async def get_account(address: str, chain_id: str = None) -> Dict[str, Any]:
|
||||
|
||||
|
||||
@router.get("/accounts/{address}", summary="Get account information (alias)")
|
||||
async def get_account_alias(address: str, chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_account_alias(
|
||||
request: Request, address: str, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get account information (alias endpoint)"""
|
||||
return await get_account(address, chain_id)
|
||||
|
||||
|
||||
@router.post("/transactions/marketplace", summary="Submit marketplace transaction")
|
||||
async def submit_marketplace_transaction(tx_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def submit_marketplace_transaction(
|
||||
request: Request, tx_data: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
"""Submit a marketplace purchase transaction to the blockchain"""
|
||||
from ..config import settings as cfg
|
||||
chain_id = get_chain_id(tx_data.get("chain_id"))
|
||||
@@ -520,7 +546,9 @@ async def submit_marketplace_transaction(tx_data: Dict[str, Any]) -> Dict[str, A
|
||||
|
||||
|
||||
@router.get("/transactions", summary="Query transactions")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def query_transactions(
|
||||
request: Request,
|
||||
transaction_type: Optional[str] = None,
|
||||
island_id: Optional[str] = None,
|
||||
pair: Optional[str] = None,
|
||||
@@ -582,7 +610,10 @@ async def query_transactions(
|
||||
|
||||
|
||||
@router.get("/blocks-range", summary="Get blocks in height range")
|
||||
async def get_blocks_range(start: int = 0, end: int = 10, include_tx: bool = True, chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_blocks_range(
|
||||
request: Request, start: int = 0, end: int = 10, include_tx: bool = True, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get blocks in a height range
|
||||
|
||||
Args:
|
||||
@@ -632,18 +663,27 @@ async def get_blocks_range(start: int = 0, end: int = 10, include_tx: bool = Tru
|
||||
}
|
||||
|
||||
@router.post("/contracts/deploy/messaging", summary="Deploy messaging contract")
|
||||
async def deploy_messaging_contract(deploy_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def deploy_messaging_contract(
|
||||
request: Request, deploy_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Deploy the agent messaging contract to the blockchain"""
|
||||
contract_address = "0xagent_messaging_001"
|
||||
return {"success": True, "contract_address": contract_address, "status": "deployed"}
|
||||
|
||||
@router.get("/contracts", summary="List deployed contracts")
|
||||
async def list_contracts() -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def list_contracts(
|
||||
request: Request
|
||||
) -> Dict[str, Any]:
|
||||
"""List all deployed contracts"""
|
||||
return contract_service.list_contracts()
|
||||
|
||||
@router.post("/contracts/deploy", summary="Deploy a smart contract")
|
||||
async def deploy_contract(deploy_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def deploy_contract(
|
||||
request: Request, deploy_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Deploy a new smart contract to the blockchain"""
|
||||
contract_name = deploy_data.get("name")
|
||||
contract_type = deploy_data.get("type", "zk-verifier")
|
||||
@@ -664,7 +704,10 @@ async def deploy_contract(deploy_data: dict) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
@router.post("/contracts/call", summary="Call a contract method")
|
||||
async def call_contract(call_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def call_contract(
|
||||
request: Request, call_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Call a method on a deployed contract"""
|
||||
contract_address = call_data.get("address")
|
||||
method = call_data.get("method")
|
||||
@@ -684,7 +727,10 @@ async def call_contract(call_data: dict) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
@router.post("/contracts/verify", summary="Verify a ZK proof")
|
||||
async def verify_contract(verify_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def verify_contract(
|
||||
request: Request, verify_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Verify a ZK proof against a contract"""
|
||||
contract_address = verify_data.get("address")
|
||||
proof = verify_data.get("proof")
|
||||
@@ -703,7 +749,10 @@ async def verify_contract(verify_data: dict) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
@router.get("/contracts/messaging/state", summary="Get messaging contract state")
|
||||
async def get_messaging_contract_state() -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_messaging_contract_state(
|
||||
request: Request
|
||||
) -> Dict[str, Any]:
|
||||
"""Get the current state of the messaging contract"""
|
||||
state = {
|
||||
"total_topics": len(messaging_contract.topics),
|
||||
@@ -713,12 +762,18 @@ async def get_messaging_contract_state() -> Dict[str, Any]:
|
||||
return {"success": True, "contract_state": state}
|
||||
|
||||
@router.get("/messaging/topics", summary="Get forum topics")
|
||||
async def get_forum_topics(limit: int = 50, offset: int = 0, sort_by: str = "last_activity") -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_forum_topics(
|
||||
request: Request, limit: int = 50, offset: int = 0, sort_by: str = "last_activity"
|
||||
) -> Dict[str, Any]:
|
||||
"""Get list of forum topics"""
|
||||
return messaging_contract.get_topics(limit, offset, sort_by)
|
||||
|
||||
@router.post("/messaging/topics/create", summary="Create forum topic")
|
||||
async def create_forum_topic(topic_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def create_forum_topic(
|
||||
request: Request, topic_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Create a new forum topic"""
|
||||
return messaging_contract.create_topic(
|
||||
topic_data.get("agent_id"),
|
||||
@@ -729,12 +784,18 @@ async def create_forum_topic(topic_data: dict) -> Dict[str, Any]:
|
||||
)
|
||||
|
||||
@router.get("/messaging/topics/{topic_id}/messages", summary="Get topic messages")
|
||||
async def get_topic_messages(topic_id: str, limit: int = 50, offset: int = 0, sort_by: str = "timestamp") -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_topic_messages(
|
||||
request: Request, topic_id: str, limit: int = 50, offset: int = 0, sort_by: str = "timestamp"
|
||||
) -> Dict[str, Any]:
|
||||
"""Get messages from a forum topic"""
|
||||
return messaging_contract.get_messages(topic_id, limit, offset, sort_by)
|
||||
|
||||
@router.post("/messaging/messages/post", summary="Post message")
|
||||
async def post_message(message_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def post_message(
|
||||
request: Request, message_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Post a message to a forum topic"""
|
||||
return messaging_contract.post_message(
|
||||
message_data.get("agent_id"),
|
||||
@@ -746,7 +807,10 @@ async def post_message(message_data: dict) -> Dict[str, Any]:
|
||||
)
|
||||
|
||||
@router.post("/messaging/messages/{message_id}/vote", summary="Vote on message")
|
||||
async def vote_message(message_id: str, vote_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def vote_message(
|
||||
request: Request, message_id: str, vote_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Vote on a message (upvote/downvote)"""
|
||||
return messaging_contract.vote_message(
|
||||
vote_data.get("agent_id"),
|
||||
@@ -756,17 +820,26 @@ async def vote_message(message_id: str, vote_data: dict) -> Dict[str, Any]:
|
||||
)
|
||||
|
||||
@router.get("/messaging/messages/search", summary="Search messages")
|
||||
async def search_messages(query: str, limit: int = 50) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def search_messages(
|
||||
request: Request, query: str, limit: int = 50
|
||||
) -> Dict[str, Any]:
|
||||
"""Search messages by content"""
|
||||
return messaging_contract.search_messages(query, limit)
|
||||
|
||||
@router.get("/messaging/agents/{agent_id}/reputation", summary="Get agent reputation")
|
||||
async def get_agent_reputation(agent_id: str) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_agent_reputation(
|
||||
request: Request, agent_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""Get agent reputation information"""
|
||||
return messaging_contract.get_agent_reputation(agent_id)
|
||||
|
||||
@router.post("/messaging/messages/{message_id}/moderate", summary="Moderate message")
|
||||
async def moderate_message(message_id: str, moderation_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def moderate_message(
|
||||
request: Request, message_id: str, moderation_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Moderate a message (moderator only)"""
|
||||
return messaging_contract.moderate_message(
|
||||
moderation_data.get("moderator_agent_id"),
|
||||
@@ -777,7 +850,10 @@ async def moderate_message(message_id: str, moderation_data: dict) -> Dict[str,
|
||||
)
|
||||
|
||||
@router.post("/importBlock", summary="Import a block")
|
||||
async def import_block(block_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def import_block(
|
||||
request: Request, block_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Import a block into the blockchain"""
|
||||
global _last_import_time
|
||||
|
||||
@@ -931,7 +1007,10 @@ def _dedupe_import_blocks(blocks: List[Dict[str, Any]], chain_id: str) -> List[D
|
||||
return [latest_by_height[height] for height in sorted(latest_by_height)]
|
||||
|
||||
@router.get("/export-chain", summary="Export full chain state")
|
||||
async def export_chain(chain_id: str = None) -> Dict[str, Any]:
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def export_chain(
|
||||
request: Request, chain_id: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Export full chain state as JSON for manual synchronization"""
|
||||
chain_id = get_chain_id(chain_id)
|
||||
try:
|
||||
@@ -1016,7 +1095,10 @@ async def export_chain(chain_id: str = None) -> Dict[str, Any]:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to export chain: {str(e)}")
|
||||
|
||||
@router.post("/import-chain", summary="Import chain state")
|
||||
async def import_chain(import_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def import_chain(
|
||||
request: Request, import_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Import chain state from JSON for manual synchronization"""
|
||||
async with _import_lock:
|
||||
try:
|
||||
@@ -1145,7 +1227,10 @@ async def import_chain(import_data: dict) -> Dict[str, Any]:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to import chain: {str(e)}")
|
||||
|
||||
@router.post("/force-sync", summary="Force reorg to specified peer")
|
||||
async def force_sync(peer_data: dict) -> Dict[str, Any]:
|
||||
@rate_limit(rate=50, per=60)
|
||||
async def force_sync(
|
||||
request: Request, peer_data: dict
|
||||
) -> Dict[str, Any]:
|
||||
"""Force blockchain reorganization to sync with specified peer"""
|
||||
try:
|
||||
peer_url = peer_data.get("peer_url")
|
||||
@@ -1224,8 +1309,10 @@ class GetLogsResponse(BaseModel):
|
||||
|
||||
|
||||
@router.post("/eth_getLogs", summary="Query smart contract event logs")
|
||||
@rate_limit(rate=200, per=60)
|
||||
async def get_logs(
|
||||
request: GetLogsRequest,
|
||||
request: Request,
|
||||
logs_request: GetLogsRequest,
|
||||
chain_id: Optional[str] = None
|
||||
) -> GetLogsResponse:
|
||||
"""
|
||||
|
||||
358
apps/coordinator-api/DOMAIN_REFACTORING_PLAN.md
Normal file
358
apps/coordinator-api/DOMAIN_REFACTORING_PLAN.md
Normal file
@@ -0,0 +1,358 @@
|
||||
# Domain Refactoring Plan for Coordinator-API Decomposition
|
||||
|
||||
## Current State
|
||||
|
||||
**Phase 1 (Modular Monolith Restructuring):** COMPLETED
|
||||
- 4 contexts created: marketplace, payments, blockchain, agent_identity
|
||||
- 8 routers moved, 8 services moved, 5 domain models moved
|
||||
- Database schema separation with table prefixes completed
|
||||
- All imports updated and compilation verified
|
||||
|
||||
**Remaining Work:** 45 routers and 115 services still in monolithic structure
|
||||
|
||||
## Identified Bounded Contexts
|
||||
|
||||
### Existing Contexts (Phase 1)
|
||||
1. **marketplace** - GPU marketplace functionality
|
||||
2. **payments** - Payment processing and escrow
|
||||
3. **blockchain** - Blockchain interactions and contracts
|
||||
4. **agent_identity** - Agent identity management and verification
|
||||
|
||||
### Additional Bounded Contexts to Create
|
||||
|
||||
#### 1. Governance Context
|
||||
**Routers:** governance.py, governance_enhanced.py
|
||||
**Services:** dao_governance_service.py, governance_service.py
|
||||
**Responsibilities:**
|
||||
- DAO governance mechanisms
|
||||
- Voting and proposal management
|
||||
- Governance rules enforcement
|
||||
|
||||
#### 2. Staking Context
|
||||
**Routers:** staking.py
|
||||
**Services:** staking_service.py
|
||||
**Responsibilities:**
|
||||
- Staking operations
|
||||
- Reward distribution
|
||||
- Stake management
|
||||
|
||||
#### 3. Reputation Context
|
||||
**Routers:** reputation.py
|
||||
**Services:** reputation_service.py
|
||||
**Responsibilities:**
|
||||
- Agent reputation scoring
|
||||
- Trust management
|
||||
- Reputation-based access control
|
||||
|
||||
#### 4. Rewards Context
|
||||
**Routers:** rewards.py
|
||||
**Services:** reward_service.py
|
||||
**Responsibilities:**
|
||||
- Reward distribution
|
||||
- Incentive management
|
||||
- Reward tracking
|
||||
|
||||
#### 5. Trading Context
|
||||
**Routers:** trading.py
|
||||
**Services:** trading_marketplace/
|
||||
**Responsibilities:**
|
||||
- Trading operations
|
||||
- Order management
|
||||
- Trade execution
|
||||
|
||||
#### 6. Analytics Context
|
||||
**Routers:** analytics.py
|
||||
**Services:** advanced_analytics.py, performance_monitoring.py
|
||||
**Responsibilities:**
|
||||
- Data analytics
|
||||
- Performance monitoring
|
||||
- Metrics collection
|
||||
|
||||
#### 7. Certification Context
|
||||
**Routers:** certification.py
|
||||
**Services:** certification/
|
||||
**Responsibilities:**
|
||||
- Agent certification
|
||||
- Badge management
|
||||
- Partnership management
|
||||
|
||||
#### 8. Hermes Context
|
||||
**Routers:** hermes_enhanced.py, hermes_enhanced_simple.py, hermes_enhanced_app.py, hermes_enhanced_health.py
|
||||
**Services:** hermes_enhanced.py, hermes_enhanced_simple.py
|
||||
**Responsibilities:**
|
||||
- Hermes agent orchestration
|
||||
- Agent coordination
|
||||
- Edge computing integration
|
||||
|
||||
#### 9. Multi-modal Context
|
||||
**Routers:** multi_modal_rl.py, multimodal_health.py, modality_optimization_health.py
|
||||
**Services:** multimodal_agent.py, modality_optimization.py, multi_modal_fusion/
|
||||
**Responsibilities:**
|
||||
- Multi-modal AI operations
|
||||
- Modality optimization
|
||||
- Fusion engine management
|
||||
|
||||
#### 10. Advanced RL Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** advanced_rl/
|
||||
**Responsibilities:**
|
||||
- Advanced reinforcement learning
|
||||
- RL agent training
|
||||
- RL model management
|
||||
|
||||
#### 11. AI Analytics Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** ai_analytics/
|
||||
**Responsibilities:**
|
||||
- AI-powered analytics
|
||||
- ML model analytics
|
||||
- AI-driven insights
|
||||
|
||||
#### 12. Cross-chain Context
|
||||
**Routers:** cross_chain_integration.py
|
||||
**Services:** cross_chain/, multi_chain_transaction_manager.py
|
||||
**Responsibilities:**
|
||||
- Cross-chain operations
|
||||
- Multi-chain transaction management
|
||||
- Cross-chain bridge management
|
||||
|
||||
#### 13. Developer Platform Context
|
||||
**Routers:** developer_platform.py
|
||||
**Services:** developer_platform_service.py
|
||||
**Responsibilities:**
|
||||
- Developer tools
|
||||
- API platform
|
||||
- Developer resources
|
||||
|
||||
#### 14. Community Context
|
||||
**Routers:** community.py
|
||||
**Services:** community_service.py
|
||||
**Responsibilities:**
|
||||
- Community management
|
||||
- Social features
|
||||
- Community governance
|
||||
|
||||
#### 15. Bounty Context
|
||||
**Routers:** bounty.py
|
||||
**Services:** bounty_service.py
|
||||
**Responsibilities:**
|
||||
- Bounty management
|
||||
- Task bounties
|
||||
- Reward bounties
|
||||
|
||||
#### 16. Confidential Context
|
||||
**Routers:** confidential.py
|
||||
**Services:** confidential_service.py, fhe_service.py
|
||||
**Responsibilities:**
|
||||
- Confidential transactions
|
||||
- FHE operations
|
||||
- Privacy-preserving computations
|
||||
|
||||
#### 17. ZK Applications Context
|
||||
**Routers:** zk_applications.py, ml_zk_proofs.py
|
||||
**Services:** zk_proofs.py, zk_memory_verification.py
|
||||
**Responsibilities:**
|
||||
- Zero-knowledge proof operations
|
||||
- ZK application management
|
||||
- ZK verification
|
||||
|
||||
#### 18. Agent Coordination Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** agent_coordination/
|
||||
**Responsibilities:**
|
||||
- Agent coordination logic
|
||||
- Agent communication
|
||||
- Agent orchestration
|
||||
|
||||
#### 19. Enterprise Integration Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** enterprise_integration/
|
||||
**Responsibilities:**
|
||||
- Enterprise API gateway
|
||||
- Multi-tenant support
|
||||
- Enterprise features
|
||||
|
||||
#### 20. Advanced AI Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** advanced_ai_service.py, distributed_framework.py, task_decomposition.py
|
||||
**Responsibilities:**
|
||||
- Advanced AI operations
|
||||
- Distributed AI
|
||||
- Task decomposition
|
||||
|
||||
#### 21. Ecosystem Context
|
||||
**Routers:** ecosystem_dashboard.py
|
||||
**Services:** ecosystem_service.py
|
||||
**Responsibilities:**
|
||||
- Ecosystem management
|
||||
- Ecosystem monitoring
|
||||
- Ecosystem analytics
|
||||
|
||||
#### 22. GPU Multimodal Context
|
||||
**Routers:** gpu_multimodal_health.py
|
||||
**Services:** gpu_multimodal.py, gpu_multimodal_app.py
|
||||
**Responsibilities:**
|
||||
- GPU multimodal operations
|
||||
- GPU optimization
|
||||
- Multimodal health monitoring
|
||||
|
||||
#### 23. Edge GPU Context
|
||||
**Routers:** edge_gpu.py
|
||||
**Services:** edge_gpu_service.py
|
||||
**Responsibilities:**
|
||||
- Edge GPU management
|
||||
- Edge computing
|
||||
- GPU resource allocation
|
||||
|
||||
#### 24. Infrastructure Context
|
||||
**Routers:** cache_management.py, web_vitals.py, monitor.py, monitoring_dashboard.py
|
||||
**Services:** global_cdn.py, memory_manager.py, performance_monitoring.py, websocket_stream_manager.py
|
||||
**Responsibilities:**
|
||||
- Caching infrastructure
|
||||
- Performance monitoring
|
||||
- CDN management
|
||||
- Memory management
|
||||
- WebSocket management
|
||||
|
||||
#### 25. Security Context
|
||||
**Routers:** agent_security_router.py, adaptive_learning_health.py, gpu_multimodal_health.py, modality_optimization_health.py
|
||||
**Services:** access_control.py, compliance_security/, encryption.py, hsm_key_manager.py, key_management.py, kyc_aml_providers.py, quota_enforcement.py, trading_surveillance.py
|
||||
**Responsibilities:**
|
||||
- Access control
|
||||
- Encryption
|
||||
- Key management
|
||||
- KYC/AML
|
||||
- Compliance
|
||||
- Security monitoring
|
||||
|
||||
#### 26. Storage Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** ipfs_storage_adapter.py, ipfs_storage_service.py
|
||||
**Responsibilities:**
|
||||
- IPFS storage
|
||||
- Decentralized storage
|
||||
- Storage management
|
||||
|
||||
#### 27. Wallet Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** bitcoin_wallet.py, wallet_crypto.py, wallet_service.py, secure_wallet_service.py
|
||||
**Responsibilities:**
|
||||
- Wallet management
|
||||
- Cryptocurrency operations
|
||||
- Secure wallet operations
|
||||
|
||||
#### 28. Language Context
|
||||
**Routers:** (none at router level)
|
||||
**Services:** multi_language/
|
||||
**Responsibilities:**
|
||||
- Multi-language support
|
||||
- Translation services
|
||||
- Language detection
|
||||
|
||||
#### 29. Settlement Context
|
||||
**Routers:** settlement.py
|
||||
**Services:** receipts.py
|
||||
**Responsibilities:**
|
||||
- Settlement operations
|
||||
- Receipt management
|
||||
- Transaction settlement
|
||||
|
||||
## Refactoring Strategy
|
||||
|
||||
### Phase 2: Context Creation (Weeks 5-8)
|
||||
Create the remaining 25 bounded contexts with proper directory structure:
|
||||
- contexts/governance/
|
||||
- contexts/staking/
|
||||
- contexts/reputation/
|
||||
- contexts/rewards/
|
||||
- contexts/trading/
|
||||
- contexts/analytics/
|
||||
- contexts/certification/
|
||||
- contexts/hermes/
|
||||
- contexts/multimodal/
|
||||
- contexts/advanced_rl/
|
||||
- contexts/ai_analytics/
|
||||
- contexts/cross_chain/
|
||||
- contexts/developer_platform/
|
||||
- contexts/community/
|
||||
- contexts/bounty/
|
||||
- contexts/confidential/
|
||||
- contexts/zk_applications/
|
||||
- contexts/agent_coordination/
|
||||
- contexts/enterprise_integration/
|
||||
- contexts/advanced_ai/
|
||||
- contexts/ecosystem/
|
||||
- contexts/gpu_multimodal/
|
||||
- contexts/edge_gpu/
|
||||
- contexts/infrastructure/
|
||||
- contexts/security/
|
||||
- contexts/storage/
|
||||
- contexts/wallet/
|
||||
- contexts/language/
|
||||
- contexts/settlement/
|
||||
|
||||
### Phase 3: Component Migration (Weeks 9-12)
|
||||
Move routers, services, and domain models to appropriate contexts:
|
||||
- Update import paths
|
||||
- Create context-specific schemas
|
||||
- Update database table prefixes
|
||||
- Verify compilation
|
||||
|
||||
### Phase 4: Dependency Resolution (Weeks 13-16)
|
||||
- Identify and document cross-context dependencies
|
||||
- Create shared libraries for common functionality
|
||||
- Define communication patterns between contexts
|
||||
- Implement event-driven communication where appropriate
|
||||
|
||||
### Phase 5: Microservice Extraction (Weeks 17-20)
|
||||
- Extract high-value contexts as independent microservices
|
||||
- Implement service discovery
|
||||
- Add inter-service communication
|
||||
- Update deployment configurations
|
||||
|
||||
## Priority Order
|
||||
|
||||
**High Priority (Core Business Logic):**
|
||||
1. Governance
|
||||
2. Staking
|
||||
3. Reputation
|
||||
4. Rewards
|
||||
5. Trading
|
||||
6. Hermes
|
||||
7. Security
|
||||
|
||||
**Medium Priority (Supporting Services):**
|
||||
8. Analytics
|
||||
9. Certification
|
||||
10. Cross-chain
|
||||
11. Developer Platform
|
||||
12. Community
|
||||
13. Confidential
|
||||
14. ZK Applications
|
||||
15. Enterprise Integration
|
||||
|
||||
**Low Priority (Infrastructure/Utilities):**
|
||||
16. Infrastructure
|
||||
17. Storage
|
||||
18. Wallet
|
||||
19. Language
|
||||
20. Settlement
|
||||
21. Multi-modal
|
||||
22. Advanced RL
|
||||
23. AI Analytics
|
||||
24. Advanced AI
|
||||
25. Ecosystem
|
||||
26. GPU Multimodal
|
||||
27. Edge GPU
|
||||
28. Agent Coordination
|
||||
29. Bounty
|
||||
|
||||
## Success Metrics
|
||||
|
||||
- All routers and services organized into bounded contexts
|
||||
- Clear domain boundaries defined
|
||||
- Cross-context dependencies documented
|
||||
- Shared libraries created for common functionality
|
||||
- Communication patterns established
|
||||
- Compilation verified after each phase
|
||||
- Test coverage maintained throughout refactoring
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced AI context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced AI domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced AI routers."""
|
||||
@@ -16,8 +16,8 @@ from sqlalchemy.orm import Session
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
|
||||
from aitbc import get_logger
|
||||
from ..services.ai_analytics.adaptive_learning import AdaptiveLearningService
|
||||
from ..storage import get_session
|
||||
from ....services.ai_analytics.adaptive_learning import AdaptiveLearningService
|
||||
from ....storage import get_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced AI services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced AI storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced RL context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced RL domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced RL routers."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced RL services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Advanced RL storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Agent coordination context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Agent coordination domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Agent coordination routers."""
|
||||
@@ -16,14 +16,14 @@ from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
from ..domain.agent_performance import CreativeCapability
|
||||
from ....domain.agent_performance import CreativeCapability
|
||||
from sqlmodel import select
|
||||
from ..services.creative_capabilities_service import (
|
||||
from ....services.creative_capabilities_service import (
|
||||
CreativityEnhancementEngine,
|
||||
CrossDomainCreativeIntegrator,
|
||||
IdeationAlgorithm,
|
||||
)
|
||||
from ..storage import get_session
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter(prefix="/v1/agent-creativity", tags=["agent-creativity"])
|
||||
|
||||
@@ -14,9 +14,9 @@ logger = get_logger(__name__)
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..deps import require_admin_key
|
||||
from ..domain.agent import AgentExecution, AIAgentWorkflow, VerificationLevel
|
||||
from ..services.agent_coordination.integration import (
|
||||
from ....deps import require_admin_key
|
||||
from ....domain.agent import AgentExecution, AIAgentWorkflow, VerificationLevel
|
||||
from ....services.agent_coordination.integration import (
|
||||
AgentDeploymentConfig,
|
||||
AgentDeploymentInstance,
|
||||
AgentDeploymentManager,
|
||||
@@ -25,8 +25,8 @@ from ..services.agent_coordination.integration import (
|
||||
AgentProductionManager,
|
||||
DeploymentStatus,
|
||||
)
|
||||
from ..storage import get_session
|
||||
from ..utils.alerting import alert_dispatcher
|
||||
from ....storage import get_session
|
||||
from ....utils.alerting import alert_dispatcher
|
||||
|
||||
router = APIRouter(prefix="/agents/integration", tags=["Agent Integration"])
|
||||
|
||||
@@ -18,7 +18,7 @@ from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
from ..domain.agent_performance import (
|
||||
from ....domain.agent_performance import (
|
||||
AgentCapability,
|
||||
AgentPerformanceProfile,
|
||||
CreativeCapability,
|
||||
@@ -32,13 +32,13 @@ from ..domain.agent_performance import (
|
||||
ResourceAllocation,
|
||||
ResourceType,
|
||||
)
|
||||
from ..services.agent_coordination.performance import (
|
||||
from ....services.agent_coordination.performance import (
|
||||
AgentPerformanceService,
|
||||
MetaLearningEngine,
|
||||
PerformanceOptimizer,
|
||||
ResourceManager,
|
||||
)
|
||||
from ..storage import get_session
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter(prefix="/v1/agent-performance", tags=["agent-performance"])
|
||||
|
||||
@@ -18,8 +18,8 @@ logger = get_logger(__name__)
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ..deps import require_admin_key
|
||||
from ..domain.agent import (
|
||||
from ....deps import require_admin_key
|
||||
from ....domain.agent import (
|
||||
AgentExecutionRequest,
|
||||
AgentExecutionResponse,
|
||||
AgentExecutionStatus,
|
||||
@@ -28,8 +28,8 @@ from ..domain.agent import (
|
||||
AgentWorkflowUpdate,
|
||||
AIAgentWorkflow,
|
||||
)
|
||||
from ..services.agent_coordination.agent_service import AIAgentOrchestrator
|
||||
from ..storage import get_session
|
||||
from ....services.agent_coordination.agent_service import AIAgentOrchestrator
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter(tags=["AI Agents"])
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Agent coordination services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Agent coordination storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""AI Analytics context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""AI Analytics domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""AI Analytics routers."""
|
||||
@@ -0,0 +1 @@
|
||||
"""AI Analytics services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""AI Analytics storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Analytics context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Analytics domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Analytics routers."""
|
||||
@@ -18,7 +18,7 @@ from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
from ..domain.analytics import (
|
||||
from ....domain.analytics import (
|
||||
AnalyticsPeriod,
|
||||
AnalyticsReport,
|
||||
DashboardConfig,
|
||||
@@ -28,8 +28,8 @@ from ..domain.analytics import (
|
||||
MetricType,
|
||||
ReportType,
|
||||
)
|
||||
from ..services.ai_analytics.analytics import MarketplaceAnalytics
|
||||
from ..storage import get_session
|
||||
from ....services.ai_analytics.analytics import MarketplaceAnalytics
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter(prefix="/v1/analytics", tags=["analytics"])
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Analytics services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Analytics storage layer."""
|
||||
1
apps/coordinator-api/src/app/contexts/bounty/__init__.py
Normal file
1
apps/coordinator-api/src/app/contexts/bounty/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Bounty context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Bounty domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Bounty routers."""
|
||||
@@ -14,8 +14,8 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from aitbc import get_logger
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import (
|
||||
from ....auth import get_current_user
|
||||
from ....domain.bounty import (
|
||||
Bounty,
|
||||
BountyIntegration,
|
||||
BountyStats,
|
||||
@@ -24,9 +24,9 @@ from ..domain.bounty import (
|
||||
BountyTier,
|
||||
SubmissionStatus,
|
||||
)
|
||||
from ..services.blockchain_service import BlockchainService
|
||||
from ..services.bounty_service import BountyService
|
||||
from ..storage import get_session
|
||||
from ....services.blockchain_service import BlockchainService
|
||||
from ....services.bounty_service import BountyService
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -271,7 +271,7 @@ async def get_bounty(
|
||||
async def submit_bounty_solution(
|
||||
request: Request,
|
||||
bounty_id: str,
|
||||
request: BountySubmissionRequest,
|
||||
submission_request: BountySubmissionRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
session: Session = Depends(get_session),
|
||||
bounty_service: BountyService = Depends(get_bounty_service),
|
||||
@@ -354,7 +354,7 @@ async def get_bounty_submissions(
|
||||
async def verify_bounty_submission(
|
||||
request: Request,
|
||||
bounty_id: str,
|
||||
request: BountyVerificationRequest,
|
||||
verification_request: BountyVerificationRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
session: Session = Depends(get_session),
|
||||
bounty_service: BountyService = Depends(get_bounty_service),
|
||||
@@ -396,7 +396,7 @@ async def verify_bounty_submission(
|
||||
async def dispute_bounty_submission(
|
||||
request: Request,
|
||||
bounty_id: str,
|
||||
request: BountyDisputeRequest,
|
||||
dispute_request: BountyDisputeRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
session: Session = Depends(get_session),
|
||||
bounty_service: BountyService = Depends(get_bounty_service),
|
||||
@@ -0,0 +1 @@
|
||||
"""Bounty services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Bounty storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Certification context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Certification domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Certification routers."""
|
||||
@@ -18,7 +18,7 @@ from aitbc.rate_limiting import rate_limit
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
from ..domain.certification import (
|
||||
from ....domain.certification import (
|
||||
AchievementBadge,
|
||||
AgentBadge,
|
||||
AgentCertification,
|
||||
@@ -32,13 +32,13 @@ from ..domain.certification import (
|
||||
VerificationRecord,
|
||||
VerificationType,
|
||||
)
|
||||
from ..services.certification import (
|
||||
from ....services.certification import (
|
||||
BadgeSystem,
|
||||
CertificationAndPartnershipService,
|
||||
CertificationSystem,
|
||||
PartnershipManager,
|
||||
)
|
||||
from ..storage import get_session
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter(prefix="/v1/certification", tags=["certification"])
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Certification services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Certification storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Community context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Community domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Community routers."""
|
||||
@@ -18,20 +18,20 @@ from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
from ..domain.community import (
|
||||
from ....domain.community import (
|
||||
AgentSolution,
|
||||
CommunityPost,
|
||||
DeveloperProfile,
|
||||
Hackathon,
|
||||
InnovationLab,
|
||||
)
|
||||
from ..services.community_service import (
|
||||
from ....services.community_service import (
|
||||
CommunityPlatformService,
|
||||
DeveloperEcosystemService,
|
||||
InnovationLabService,
|
||||
ThirdPartySolutionService,
|
||||
)
|
||||
from ..storage import get_session
|
||||
from ....storage import get_session
|
||||
|
||||
router = APIRouter(prefix="/community", tags=["community"])
|
||||
|
||||
@@ -136,9 +136,9 @@ async def publish_solution(request: SolutionPublishRequest, request_http: Reques
|
||||
@router.get("/solutions", response_model=list[AgentSolution])
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def list_solutions(
|
||||
request: Request,
|
||||
category: str | None = None,
|
||||
limit: int = 50,
|
||||
request: Request,
|
||||
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
|
||||
) -> list[AgentSolution]:
|
||||
"""List available third-party agent solutions"""
|
||||
@@ -166,9 +166,9 @@ async def purchase_solution(
|
||||
@router.post("/labs/propose", response_model=InnovationLab)
|
||||
@rate_limit(rate=10, per=60)
|
||||
async def propose_innovation_lab(
|
||||
request_http: Request,
|
||||
researcher_id: str = Query(...),
|
||||
request: LabProposalRequest = Body(...),
|
||||
request_http: Request,
|
||||
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
|
||||
) -> InnovationLab:
|
||||
"""Propose a new agent innovation lab or research program"""
|
||||
@@ -212,9 +212,9 @@ async def fund_innovation_lab(
|
||||
@router.post("/platform/posts", response_model=CommunityPost)
|
||||
@rate_limit(rate=20, per=60)
|
||||
async def create_community_post(
|
||||
request_http: Request,
|
||||
author_id: str = Query(...),
|
||||
request: PostCreateRequest = Body(...),
|
||||
request_http: Request,
|
||||
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
|
||||
) -> CommunityPost:
|
||||
"""Create a new post in the community forum"""
|
||||
@@ -229,9 +229,9 @@ async def create_community_post(
|
||||
@router.get("/platform/feed", response_model=list[CommunityPost])
|
||||
@rate_limit(rate=100, per=60)
|
||||
async def get_community_feed(
|
||||
request: Request,
|
||||
category: str | None = None,
|
||||
limit: int = 20,
|
||||
request: Request,
|
||||
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
|
||||
) -> list[CommunityPost]:
|
||||
"""Get the latest community posts and discussions"""
|
||||
@@ -255,9 +255,9 @@ async def upvote_community_post(post_id: str, request: Request, session: Annotat
|
||||
@router.post("/hackathons/create", response_model=Hackathon)
|
||||
@rate_limit(rate=10, per=60)
|
||||
async def create_hackathon(
|
||||
request_http: Request,
|
||||
organizer_id: str = Query(...),
|
||||
request: HackathonCreateRequest = Body(...),
|
||||
request_http: Request,
|
||||
session: Annotated[Session, Depends(get_session)] = Depends(get_session),
|
||||
) -> Hackathon:
|
||||
"""Create a new agent innovation hackathon (requires high reputation)"""
|
||||
@@ -0,0 +1 @@
|
||||
"""Community services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Community storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Confidential context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Confidential domain models."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Confidential routers."""
|
||||
@@ -13,8 +13,8 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPBearer
|
||||
|
||||
from aitbc.rate_limiting import rate_limit
|
||||
from ..auth import get_api_key
|
||||
from ..schemas import (
|
||||
from ....auth import get_api_key
|
||||
from ....schemas import (
|
||||
AccessLogQuery,
|
||||
AccessLogResponse,
|
||||
ConfidentialAccessRequest,
|
||||
@@ -25,9 +25,9 @@ from ..schemas import (
|
||||
KeyRegistrationRequest,
|
||||
KeyRegistrationResponse,
|
||||
)
|
||||
from ..services.access_control import AccessController
|
||||
from ..services.encryption import EncryptedData, EncryptionService
|
||||
from ..services.key_management import KeyManagementError, KeyManager
|
||||
from ....services.access_control import AccessController
|
||||
from ....services.encryption import EncryptedData, EncryptionService
|
||||
from ....services.key_management import KeyManagementError, KeyManager
|
||||
|
||||
# Initialize router and security
|
||||
router = APIRouter(prefix="/confidential", tags=["confidential"])
|
||||
@@ -0,0 +1 @@
|
||||
"""Confidential services."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Confidential storage layer."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Cross-chain context for coordinator-api."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Cross-chain domain models."""
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user