use anyhow::Result;
use hashbrown::HashMap;
use parking_lot::RwLock;
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::Semaphore;
use crate::core::memory_pool::global_pool;
use crate::tools::registry::ToolExecutionRecord;
#[derive(Clone)]
pub struct ToolMetadata {
pub name: String,
pub description: String,
pub parameters: Value,
pub is_cached: bool,
pub avg_execution_time_ms: u64,
}
pub struct OptimizedToolRegistry {
tool_metadata: Arc<RwLock<HashMap<String, Arc<ToolMetadata>>>>,
execution_semaphore: Arc<Semaphore>,
hot_cache: Arc<RwLock<HashMap<String, Arc<ToolMetadata>>>>,
execution_stats: Arc<RwLock<Vec<ToolExecutionRecord>>>,
}
impl OptimizedToolRegistry {
pub fn new(max_concurrent_tools: usize) -> Self {
Self {
tool_metadata: Arc::new(RwLock::new(HashMap::with_capacity(64))),
execution_semaphore: Arc::new(Semaphore::new(max_concurrent_tools)),
hot_cache: Arc::new(RwLock::new(HashMap::with_capacity(16))),
execution_stats: Arc::new(RwLock::new(Vec::with_capacity(1024))),
}
}
pub fn get_tool_metadata(&self, tool_name: &str) -> Option<Arc<ToolMetadata>> {
if let Some(metadata) = self.hot_cache.read().get(tool_name) {
return Some(Arc::clone(metadata));
}
let metadata = self.tool_metadata.read().get(tool_name).cloned()?;
self.promote_to_hot_cache(tool_name, &metadata);
Some(metadata)
}
pub fn register_tool(&self, metadata: ToolMetadata) {
let tool_name = metadata.name.clone();
let metadata_arc = Arc::new(metadata);
self.tool_metadata.write().insert(tool_name, metadata_arc);
}
pub async fn execute_tool_optimized(&self, tool_name: &str, _args: Value) -> Result<Value> {
let _permit = self.execution_semaphore.acquire().await?;
let start_time = std::time::Instant::now();
let pool = global_pool();
let result_string = pool.get_string();
let result = self.execute_tool_impl(tool_name, _args).await;
let execution_time = start_time.elapsed();
self.record_execution_stats(tool_name, execution_time, result.is_ok());
pool.return_string(result_string);
result
}
fn promote_to_hot_cache(&self, tool_name: &str, metadata: &Arc<ToolMetadata>) {
let mut hot_cache = self.hot_cache.write();
if hot_cache.len() < 16 {
hot_cache.insert(tool_name.to_string(), Arc::clone(metadata));
}
}
fn record_execution_stats(
&self,
tool_name: &str,
execution_time: std::time::Duration,
success: bool,
) {
let record = ToolExecutionRecord {
tool_name: tool_name.to_string(),
requested_name: String::new(), is_mcp: false,
mcp_provider: None,
args: Value::Null,
result: if success {
Ok(Value::Null)
} else {
Err("Error".to_string())
},
timestamp: std::time::SystemTime::now(),
success,
context: crate::tools::registry::HarnessContextSnapshot::new(
"optimized".to_string(),
None,
),
timeout_category: None,
base_timeout_ms: None,
adaptive_timeout_ms: None,
effective_timeout_ms: Some(execution_time.as_millis() as u64),
circuit_breaker: false,
attempt: 1,
retry_after_ms: None,
circuit_breaker_state: None,
};
let mut stats = self.execution_stats.write();
if stats.len() >= 1024 {
stats.drain(..128); }
stats.push(record);
}
async fn execute_tool_impl(&self, _tool_name: &str, _args: Value) -> Result<Value> {
Ok(Value::String("success".to_string()))
}
pub fn get_stats_snapshot(&self) -> Vec<ToolExecutionRecord> {
self.execution_stats.read().clone()
}
pub fn clear_hot_cache(&self) {
self.hot_cache.write().clear();
}
}