use async_trait::async_trait;
use std::time::{Duration, SystemTime};
use thread_utilities::RapidMap;
use crate::error::ServiceResult;
use crate::types::{AnalysisContext, CrossFileRelationship, ParsedDocument};
use thread_ast_engine::source::Doc;
#[async_trait]
pub trait StorageService: Send + Sync {
async fn store_analysis_result<D: Doc>(
&self,
key: &AnalysisKey,
result: &AnalysisResult<D>,
context: &AnalysisContext,
) -> ServiceResult<()>
where
Self: Sized;
async fn load_analysis_result<D: Doc>(
&self,
key: &AnalysisKey,
context: &AnalysisContext,
) -> ServiceResult<Option<AnalysisResult<D>>>
where
Self: Sized;
async fn store_parsed_document<D: Doc>(
&self,
document: &ParsedDocument<D>,
context: &AnalysisContext,
) -> ServiceResult<StorageKey>
where
Self: Sized;
async fn load_parsed_document<D: Doc>(
&self,
key: &StorageKey,
context: &AnalysisContext,
) -> ServiceResult<Option<ParsedDocument<D>>>
where
Self: Sized;
async fn store_relationships(
&self,
relationships: &[CrossFileRelationship],
context: &AnalysisContext,
) -> ServiceResult<()>;
async fn load_relationships(
&self,
context: &AnalysisContext,
) -> ServiceResult<Vec<CrossFileRelationship>>;
fn capabilities(&self) -> StorageCapabilities;
async fn maintenance(
&self,
operation: MaintenanceOperation,
) -> ServiceResult<MaintenanceResult>;
async fn get_statistics(&self) -> ServiceResult<StorageStatistics>;
}
#[async_trait]
pub trait CacheService: Send + Sync {
async fn store<T: CacheableItem>(
&self,
key: &CacheKey,
item: &T,
ttl: Option<Duration>,
) -> ServiceResult<()>;
async fn load<T: CacheableItem>(&self, key: &CacheKey) -> ServiceResult<Option<T>>;
async fn invalidate(&self, pattern: &CachePattern) -> ServiceResult<usize>;
async fn get_cache_stats(&self) -> ServiceResult<CacheStatistics>;
async fn maintenance(&self) -> ServiceResult<()>;
}
#[async_trait]
pub trait AnalyticsService: Send + Sync {
async fn record_operation(
&self,
operation: &OperationRecord,
context: &AnalysisContext,
) -> ServiceResult<()>;
async fn get_analytics(&self, query: &AnalyticsQuery) -> ServiceResult<AnalyticsResult>;
async fn get_performance_metrics(
&self,
period: &TimePeriod,
) -> ServiceResult<PerformanceMetrics>;
async fn generate_insights(&self, context: &AnalysisContext) -> ServiceResult<Vec<Insight>>;
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct AnalysisKey {
pub operation_type: String,
pub content_fingerprint: recoco_utils::fingerprint::Fingerprint,
pub configuration_hash: u64,
pub version: String,
}
#[derive(Debug)]
pub struct AnalysisResult<D: Doc> {
pub documents: Vec<ParsedDocument<D>>,
pub relationships: Vec<CrossFileRelationship>,
pub metadata: RapidMap<String, String>,
pub timestamp: SystemTime,
pub version: String,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct StorageKey {
pub namespace: String,
pub identifier: String,
pub version: Option<String>,
}
#[derive(Debug, Clone)]
pub struct StorageCapabilities {
pub max_storage_size: Option<u64>,
pub supported_backends: Vec<StorageBackend>,
pub supports_distributed: bool,
pub supports_encryption: bool,
pub supports_backup: bool,
pub supports_multi_tenancy: bool,
pub performance_profile: StoragePerformanceProfile,
}
#[derive(Debug, Clone, PartialEq)]
pub enum StorageBackend {
PostgreSQL,
Redis,
S3,
FileSystem,
InMemory,
Custom(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum StoragePerformanceProfile {
HighThroughput,
LowLatency,
Balanced,
CostOptimized,
}
#[derive(Debug, Clone)]
pub enum MaintenanceOperation {
Cleanup { older_than: Duration },
Optimize,
Backup { destination: String },
Restore { source: String },
HealthCheck,
Vacuum,
}
#[derive(Debug, Clone)]
pub struct MaintenanceResult {
pub operation: MaintenanceOperation,
pub success: bool,
pub message: String,
pub metrics: RapidMap<String, f64>,
pub duration: Duration,
}
#[derive(Debug, Clone)]
pub struct StorageStatistics {
pub total_size: u64,
pub total_items: u64,
pub cache_hit_rate: f64,
pub average_response_time: Duration,
pub error_rate: f64,
pub last_updated: SystemTime,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CacheKey {
pub namespace: String,
pub key: String,
}
#[derive(Debug, Clone)]
pub struct CachePattern {
pub namespace: Option<String>,
pub key_pattern: String,
}
pub trait CacheableItem: Send + Sync {
fn serialize(&self) -> ServiceResult<Vec<u8>>;
fn deserialize(data: &[u8]) -> ServiceResult<Self>
where
Self: Sized;
fn cache_key(&self) -> String;
fn ttl(&self) -> Option<Duration>;
}
#[derive(Debug, Clone)]
pub struct CacheStatistics {
pub total_items: u64,
pub hit_rate: f64,
pub miss_rate: f64,
pub eviction_rate: f64,
pub memory_usage: u64,
pub last_updated: SystemTime,
}
#[derive(Debug, Clone)]
pub struct OperationRecord {
pub operation_type: String,
pub duration: Duration,
pub files_processed: usize,
pub patterns_used: Vec<String>,
pub success: bool,
pub error_type: Option<String>,
pub user_id: Option<String>,
pub timestamp: SystemTime,
}
#[derive(Debug, Clone)]
pub struct AnalyticsQuery {
pub time_period: TimePeriod,
pub operation_types: Option<Vec<String>>,
pub user_ids: Option<Vec<String>>,
pub aggregation_level: AggregationLevel,
}
#[derive(Debug, Clone)]
pub struct TimePeriod {
pub start: SystemTime,
pub end: SystemTime,
}
#[derive(Debug, Clone, PartialEq)]
pub enum AggregationLevel {
Hourly,
Daily,
Weekly,
Monthly,
}
#[derive(Debug, Clone)]
pub struct AnalyticsResult {
pub query: AnalyticsQuery,
pub data_points: Vec<AnalyticsDataPoint>,
pub summary: AnalyticsSummary,
}
#[derive(Debug, Clone)]
pub struct AnalyticsDataPoint {
pub timestamp: SystemTime,
pub operation_count: u64,
pub success_rate: f64,
pub average_duration: Duration,
pub files_processed: u64,
}
#[derive(Debug, Clone)]
pub struct AnalyticsSummary {
pub total_operations: u64,
pub overall_success_rate: f64,
pub average_duration: Duration,
pub peak_usage: SystemTime,
pub most_common_operations: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct PerformanceMetrics {
pub period: TimePeriod,
pub throughput: f64, pub latency_percentiles: RapidMap<String, Duration>, pub error_rates: RapidMap<String, f64>,
pub resource_usage: ResourceUsage,
}
#[derive(Debug, Clone)]
pub struct ResourceUsage {
pub cpu_usage: f64,
pub memory_usage: u64,
pub storage_usage: u64,
pub network_io: u64,
}
#[derive(Debug, Clone)]
pub struct Insight {
pub insight_type: InsightType,
pub title: String,
pub description: String,
pub severity: InsightSeverity,
pub recommendations: Vec<String>,
pub confidence: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub enum InsightType {
Performance,
Usage,
Optimization,
Security,
Maintenance,
}
#[derive(Debug, Clone, PartialEq)]
pub enum InsightSeverity {
Info,
Warning,
Critical,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_analysis_key() {
let key = AnalysisKey {
operation_type: "pattern_match".to_string(),
content_fingerprint: recoco_utils::fingerprint::Fingerprint([0u8; 16]),
configuration_hash: 67890,
version: "1.0".to_string(),
};
assert_eq!(key.operation_type, "pattern_match");
assert_eq!(
key.content_fingerprint,
recoco_utils::fingerprint::Fingerprint([0u8; 16])
);
}
#[test]
fn test_storage_capabilities() {
let caps = StorageCapabilities {
max_storage_size: Some(1024 * 1024 * 1024), supported_backends: vec![StorageBackend::PostgreSQL, StorageBackend::Redis],
supports_distributed: true,
supports_encryption: true,
supports_backup: true,
supports_multi_tenancy: true,
performance_profile: StoragePerformanceProfile::Balanced,
};
assert!(caps.supports_encryption);
assert!(caps.supports_backup);
assert_eq!(
caps.performance_profile,
StoragePerformanceProfile::Balanced
);
}
}