pub mod time {
use chrono::{DateTime, Utc};
pub fn now() -> DateTime<Utc> {
Utc::now()
}
pub fn age_since(timestamp: DateTime<Utc>) -> chrono::Duration {
now().signed_duration_since(timestamp)
}
pub fn is_older_than(timestamp: DateTime<Utc>, duration: chrono::Duration) -> bool {
age_since(timestamp) > duration
}
}
pub mod collections {
use std::collections::HashMap;
pub fn new_hashmap<K, V>() -> HashMap<K, V> {
HashMap::new()
}
pub fn with_capacity<K, V>(capacity: usize) -> HashMap<K, V> {
HashMap::with_capacity(capacity)
}
}
pub mod async_utils {
use anyhow::Result;
use std::future::Future;
use std::sync::Arc;
use tokio::sync::RwLock;
pub async fn with_locks_2<T, U, R, F, Fut>(
lock1: &Arc<RwLock<T>>,
lock2: &Arc<RwLock<U>>,
operation: F,
) -> Result<R>
where
F: FnOnce(&mut T, &mut U) -> Fut,
Fut: Future<Output = Result<R>>,
{
let mut guard1 = lock1.write().await;
let mut guard2 = lock2.write().await;
operation(&mut *guard1, &mut *guard2).await
}
pub async fn with_locks_3<T, U, V, R, F, Fut>(
lock1: &Arc<RwLock<T>>,
lock2: &Arc<RwLock<U>>,
lock3: &Arc<RwLock<V>>,
operation: F,
) -> Result<R>
where
F: FnOnce(&mut T, &mut U, &mut V) -> Fut,
Fut: Future<Output = Result<R>>,
{
let mut guard1 = lock1.write().await;
let mut guard2 = lock2.write().await;
let mut guard3 = lock3.write().await;
operation(&mut *guard1, &mut *guard2, &mut *guard3).await
}
pub trait Timestamped {
fn update_timestamp(&mut self);
}
pub fn update_with_timestamp<T: Timestamped>(mut entity: T) -> T {
entity.update_timestamp();
entity
}
}
pub mod errors {
use anyhow::anyhow;
pub fn not_found_error(entity_type: &str, id: &str) -> anyhow::Error {
anyhow!("{} not found: {}", entity_type, id)
}
pub fn validation_error(field: &str, reason: &str) -> anyhow::Error {
anyhow!("Validation failed for {}: {}", field, reason)
}
pub fn invalid_state_error(current_state: &str, expected_state: &str) -> anyhow::Error {
anyhow!(
"Invalid state transition: expected {}, but was {}",
expected_state,
current_state
)
}
}
pub mod logging {
pub fn log_metrics_failure(id: &str, error: &dyn std::fmt::Display) {
log::warn!("Failed to collect metrics for {}: {}", id, error);
}
pub fn log_monitoring_failure(error: &dyn std::fmt::Display) {
log::error!("Monitoring update failed: {}", error);
}
pub fn log_subagent_created(name: &str, instance_id: &str) {
log::info!(
"Created subagent '{}' with instance ID: {}",
name,
instance_id
);
}
pub fn log_task_delegated(agent_id: &str, task: &str) {
log::info!("Delegated task to {}: {}", agent_id, task);
}
pub fn log_init_failure(component: &str, id: &str, error: &dyn std::fmt::Display) {
log::error!("Failed to initialize {} {}: {}", component, id, error);
}
pub fn log_parse_warning(file_path: &str, error: &dyn std::fmt::Display) {
log::warn!("Failed to parse file {}: {}", file_path, error);
}
}