Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ members = [
"examples/token",
"examples/escrow",
"examples/vesting",
"examples/lending",
]
resolver = "2"

Expand Down
36 changes: 32 additions & 4 deletions backend/src/api/handlers/profiling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@ use crate::api::contracts::{
use crate::config::reload::ConfigManager;
use crate::error::AppError;
use crate::services::{
error_recovery::ErrorManager, log_aggregator::LogAggregator, sys_metrics::MetricsExporter,
contract_benchmark::{
ContractBenchmarkError, ContractBenchmarkReport, ContractBenchmarkRequest,
ContractBenchmarkService,
},
error_recovery::ErrorManager,
log_aggregator::LogAggregator,
sys_metrics::MetricsExporter,
tracing::TracingService,
};
use crate::AppError;
use axum::{extract::State, response::IntoResponse, Json};
use chrono::{DateTime, Utc};
use redis::Client as RedisClient;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::sync::Arc;
use tracing::{info, info_span, instrument};
use utoipa::ToSchema;
Expand All @@ -22,6 +28,7 @@ pub struct AppState {
pub error_manager: Arc<ErrorManager>,
pub config_manager: Arc<ConfigManager>,
pub log_aggregator: Arc<LogAggregator>,
pub contract_benchmark_service: Arc<ContractBenchmarkService>,
pub redis: RedisClient,
}

Expand Down Expand Up @@ -120,9 +127,9 @@ pub async fn get_health(State(state): State<Arc<AppState>>) -> Result<impl IntoR
let db_span = TracingService::db_query_span("SELECT 1", "postgres", "PING");
let _db_enter = db_span.enter();

let db_healthy = if let Some(ref pool) = state.db {
let db_healthy = if let Some(db) = &state.db {
sqlx::query("SELECT 1")
.fetch_optional(pool)
.fetch_optional(db)
.await
.map(|result| result.is_some())
.unwrap_or_else(|e| {
Expand Down Expand Up @@ -229,3 +236,24 @@ pub async fn trigger_profile_collection(
estimated_completion,
}))
}

/// Handler for contract performance benchmark aggregation.
#[instrument(skip_all, fields(http.method = "POST", http.route = "/api/v1/profiling/contracts/benchmark"))]
pub async fn run_contract_benchmark(
State(state): State<Arc<AppState>>,
Json(payload): Json<ContractBenchmarkRequest>,
) -> Result<ApiResponse<ContractBenchmarkReport>, AppError> {
let report = state
.contract_benchmark_service
.run_benchmark(payload)
.await
.map_err(map_contract_benchmark_error)?;

Ok(ApiResponse::new(report))
}

fn map_contract_benchmark_error(error: ContractBenchmarkError) -> AppError {
match error {
ContractBenchmarkError::Validation(message) => AppError::BadRequest(message),
}
}
11 changes: 6 additions & 5 deletions backend/src/api/middleware/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,14 @@ pub async fn logging_middleware(
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{reload::ConfigManager, AppConfig};
use crate::services::{
error_recovery::ErrorManager, log_aggregator::LogAggregator, sys_metrics::MetricsExporter,
contract_benchmark::ContractBenchmarkService, error_recovery::ErrorManager,
log_aggregator::LogAggregator, sys_metrics::MetricsExporter,
};
use axum::{routing::get, Router};
use hyper::StatusCode;
use redis::Client as RedisClient;
use sqlx::PgPool;
use tower::ServiceExt;

#[tokio::test]
Expand All @@ -92,15 +93,15 @@ mod tests {
let (log_aggregator, _rx) = LogAggregator::new();
let log_aggregator = Arc::new(log_aggregator);

// Use connect_lazy for testing to avoid needing a real DB
let db = PgPool::connect_lazy("postgres://localhost/test").unwrap();
let redis = RedisClient::open("redis://localhost").unwrap();

let state = Arc::new(AppState {
db: None,
metrics_exporter,
error_manager,
config_manager: Arc::new(ConfigManager::new(AppConfig::default())),
log_aggregator,
db,
contract_benchmark_service: Arc::new(ContractBenchmarkService::new()),
redis,
});

Expand Down
15 changes: 12 additions & 3 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use backend::{
},
jobs::{monitor_transaction, TransactionMonitorJob},
services::{
contract_benchmark::ContractBenchmarkService,
error_recovery::ErrorManager,
log_aggregator::LogAggregator,
log_alerts::AlertManager,
Expand Down Expand Up @@ -87,6 +88,7 @@ async fn main() -> Result<(), anyhow::Error> {
let alert_manager = Arc::new(AlertManager::new());
let (log_aggregator, log_receiver) = LogAggregator::new();
let log_aggregator = Arc::new(log_aggregator);
let contract_benchmark_service = Arc::new(ContractBenchmarkService::new());

tokio::spawn(MetricsExporter::run_collector(metrics_exporter.clone()));
tokio::spawn(LogAggregator::run_worker(log_receiver));
Expand Down Expand Up @@ -115,14 +117,17 @@ async fn main() -> Result<(), anyhow::Error> {
metrics_exporter: metrics_exporter.clone(),
error_manager: error_manager.clone(),
config_manager: config_manager.clone(),
log_aggregator: log_aggregator.clone(),
contract_benchmark_service: contract_benchmark_service.clone(),
redis: redis_client.clone(),
});

// Create dashboard state
let dashboard_state = Arc::new(DashboardState {
metrics_exporter,
error_manager,
alert_manager,
db: db_pool,
db: db_pool.clone(),
redis: redis_client.clone(),
});

Expand Down Expand Up @@ -172,6 +177,10 @@ async fn main() -> Result<(), anyhow::Error> {
.route("/prometheus", get(profiling::get_prometheus_metrics))
.route("/status", get(profiling::get_system_status))
.route("/profile", post(profiling::trigger_profile_collection))
.route(
"/contracts/benchmark",
post(profiling::run_contract_benchmark),
)
.with_state(state.clone()),
)
.nest(
Expand Down Expand Up @@ -286,11 +295,11 @@ async fn main() -> Result<(), anyhow::Error> {

// Close database connection pool
tracing::info!("Closing database connection pool");
drop(state.db); // This closes the pool
drop(db_pool); // This closes the pool when all clones are released

// Close Redis connection
tracing::info!("Closing Redis connection");
drop(state.redis); // This closes the connection manager
drop(redis_conn_dashboard); // This closes the dashboard connection manager

tracing::info!("Graceful shutdown completed successfully");

Expand Down
Loading