do-memory-storage-turso 0.1.30

Turso/libSQL storage backend for the do-memory-core episodic learning system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Cache Invalidation Strategies
//!
//! Provides multiple invalidation strategies for the query cache:
//! - Time-based expiration (TTL)
//! - Dependency-based invalidation (table changes)
//! - Event-driven invalidation (CRUD operations)
//! - Manual invalidation
//! - Batch invalidation
//! - Pattern-based invalidation

use super::query_cache::{
    AdvancedCacheStats, AdvancedQueryCache, InvalidationMessage, QueryType, TableDependency,
};
#[path = "invalidation_types.rs"]
mod types;
use parking_lot::RwLock;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio::time::interval;
use tracing::{debug, info, trace, warn};
pub use types::{
    CrudOperation, InvalidationConfig, InvalidationEvent, InvalidationMetrics, InvalidationRule,
    InvalidationRuleBuilder, InvalidationStrategy, InvalidationTarget, SchemaChangeType, utils,
};

/// Invalidation manager for query cache
pub struct InvalidationManager {
    /// Configuration
    config: InvalidationConfig,
    /// Reference to query cache
    cache: AdvancedQueryCache,
    /// Invalidation rules
    rules: Arc<RwLock<Vec<InvalidationRule>>>,
    /// Event receiver
    event_rx: mpsc::UnboundedReceiver<InvalidationEvent>,
    /// Event sender (for external use)
    event_tx: mpsc::UnboundedSender<InvalidationEvent>,
    /// Invalidation receiver from cache
    invalidation_rx: mpsc::UnboundedReceiver<InvalidationMessage>,
    /// Metrics
    metrics: Arc<RwLock<InvalidationMetrics>>,
    /// Pending invalidations (for batching)
    pending: Arc<RwLock<VecDeque<InvalidationEvent>>>,
    /// Last batch time
    last_batch_time: Arc<RwLock<Instant>>,
}

impl InvalidationManager {
    /// Create a new invalidation manager
    pub fn new(
        config: InvalidationConfig,
        cache: AdvancedQueryCache,
    ) -> (Self, mpsc::UnboundedSender<InvalidationEvent>) {
        let (event_tx, event_rx) = mpsc::unbounded_channel();
        let invalidation_rx = {
            // We need to create a new channel since we can't extract from cache
            let (_tx, rx) = mpsc::unbounded_channel();
            rx
        };

        let manager = Self {
            config,
            cache,
            rules: Arc::new(RwLock::new(Vec::new())),
            event_rx,
            event_tx: event_tx.clone(),
            invalidation_rx,
            metrics: Arc::new(RwLock::new(InvalidationMetrics::default())),
            pending: Arc::new(RwLock::new(VecDeque::new())),
            last_batch_time: Arc::new(RwLock::new(Instant::now())),
        };

        (manager, event_tx)
    }

    /// Create with default configuration
    pub fn default(cache: AdvancedQueryCache) -> (Self, mpsc::UnboundedSender<InvalidationEvent>) {
        Self::new(InvalidationConfig::default(), cache)
    }

    /// Add an invalidation rule
    pub fn add_rule(&self, rule: InvalidationRule) {
        let mut rules = self.rules.write();

        if rules.len() >= self.config.max_rules {
            warn!("Max rules reached, removing lowest priority rule");
            rules.sort_by(|a, b| a.priority.cmp(&b.priority));
            rules.remove(0);
        }

        rules.push(rule);
        rules.sort_by(|a, b| b.priority.cmp(&a.priority)); // Higher priority first

        debug!("Added invalidation rule, total rules: {}", rules.len());
    }

    /// Remove all rules
    pub fn clear_rules(&self) {
        self.rules.write().clear();
        debug!("Cleared all invalidation rules");
    }

    /// Get rules matching a SQL query
    pub fn get_matching_rules(&self, sql: &str) -> Vec<InvalidationRule> {
        self.rules
            .read()
            .iter()
            .filter(|rule| rule.matches(sql))
            .cloned()
            .collect()
    }

    /// Handle an invalidation event
    pub fn handle_event(&self, event: InvalidationEvent) {
        let start = Instant::now();

        match &event {
            InvalidationEvent::TableModified {
                table,
                operation,
                affected_rows,
            } => {
                debug!(
                    "Handling table modification: {:?} {:?}, {} rows affected",
                    table, operation, affected_rows
                );

                // Invalidate by table dependency
                self.cache.invalidate_by_table(table);

                // Update metrics
                let mut metrics = self.metrics.write();
                metrics.total_invalidations += 1;
                *metrics.by_table.entry(table.clone()).or_default() += 1;
                *metrics.by_operation.entry(*operation).or_default() += 1;
                metrics.entries_invalidated += *affected_rows;
            }

            InvalidationEvent::BatchCompleted {
                tables,
                operation_count,
            } => {
                debug!(
                    "Handling batch completion: {} tables, {} operations",
                    tables.len(),
                    operation_count
                );

                for table in tables {
                    self.cache.invalidate_by_table(table);
                }

                self.metrics.write().batch_count += 1;
                self.metrics.write().entries_invalidated += *operation_count;
            }

            InvalidationEvent::SchemaChanged { table, change_type } => {
                info!("Schema changed on {:?}: {:?}", table, change_type);
                // Invalidate all queries for this table on schema changes
                self.cache.invalidate_by_table(table);
            }

            InvalidationEvent::ManualInvalidation { target, reason } => {
                info!("Manual invalidation: {} - {:?}", reason, target);
                self.handle_manual_invalidation(target);
            }
        }

        // Record timing
        let elapsed = start.elapsed().as_micros() as u64;
        let mut metrics = self.metrics.write();
        let total = metrics.total_invalidations;
        metrics.avg_invalidation_time_us =
            (metrics.avg_invalidation_time_us * (total - 1) + elapsed) / total.max(1);
    }

    /// Handle manual invalidation
    fn handle_manual_invalidation(&self, target: &InvalidationTarget) {
        match target {
            InvalidationTarget::All => {
                self.cache.clear();
            }
            InvalidationTarget::Table(table) => {
                self.cache.invalidate_by_table(table);
            }
            InvalidationTarget::Query(key) => {
                self.cache.invalidate_key(key);
            }
            InvalidationTarget::Pattern(pattern) => {
                // Find and invalidate queries matching pattern
                self.invalidate_by_pattern(pattern);
            }
            InvalidationTarget::Type(query_type) => {
                self.invalidate_by_type(*query_type);
            }
        }
    }

    /// Invalidate queries matching a pattern
    fn invalidate_by_pattern(&self, pattern: &str) {
        // This would require access to the query keys in the cache
        // For now, we clear all as a safe fallback
        warn!(
            "Pattern-based invalidation not fully implemented, clearing all: {}",
            pattern
        );
        self.cache.clear();
    }

    /// Invalidate queries by type
    fn invalidate_by_type(&self, query_type: QueryType) {
        // This would require type-based indexing in the cache
        // For now, we rely on table-based invalidation
        debug!("Type-based invalidation requested for: {:?}", query_type);
    }

    /// Queue an event for batch processing
    pub fn queue_event(&self, event: InvalidationEvent) {
        self.pending.write().push_back(event);

        // Check if we should process the batch
        let should_process = {
            let pending = self.pending.read();
            pending.len() >= self.config.batch_size
                || self.last_batch_time.read().elapsed() > Duration::from_secs(5)
        };

        if should_process {
            self.process_batch();
        }
    }

    /// Process pending invalidation events in batch
    pub fn process_batch(&self) {
        let mut pending = self.pending.write();

        if pending.is_empty() {
            return;
        }

        debug!("Processing {} pending invalidation events", pending.len());

        // Group events by table for efficiency
        let mut by_table: HashMap<TableDependency, Vec<InvalidationEvent>> = HashMap::new();

        for event in pending.drain(..) {
            if let Some(table) = Self::get_event_table(&event) {
                by_table.entry(table).or_default().push(event);
            }
        }

        // Process each table's events
        for (table, events) in by_table {
            let total_rows: u64 = events
                .iter()
                .filter_map(|e| match e {
                    InvalidationEvent::TableModified { affected_rows, .. } => Some(*affected_rows),
                    _ => None,
                })
                .sum();

            // Single invalidation for all events on this table
            self.cache.invalidate_by_table(&table);

            // Update metrics
            let mut metrics = self.metrics.write();
            metrics.total_invalidations += 1;
            *metrics.by_table.entry(table.clone()).or_default() += 1;
            *metrics
                .by_operation
                .entry(CrudOperation::Update)
                .or_default() += 1;
            metrics.entries_invalidated += total_rows;
        }

        *self.last_batch_time.write() = Instant::now();
    }

    /// Get table from event
    fn get_event_table(event: &InvalidationEvent) -> Option<TableDependency> {
        match event {
            InvalidationEvent::TableModified { table, .. } => Some(table.clone()),
            InvalidationEvent::SchemaChanged { table, .. } => Some(table.clone()),
            _ => None,
        }
    }

    /// Get current metrics
    pub fn metrics(&self) -> InvalidationMetrics {
        self.metrics.read().clone()
    }

    /// Clear metrics
    pub fn clear_metrics(&self) {
        *self.metrics.write() = InvalidationMetrics::default();
    }

    /// Get cache stats
    pub fn cache_stats(&self) -> AdvancedCacheStats {
        self.cache.stats()
    }

    /// Clear expired cache entries
    pub fn clear_expired(&self) -> usize {
        self.cache.clear_expired()
    }

    /// Start the invalidation manager
    pub async fn run(mut self) {
        info!(
            "Starting invalidation manager with {:?} strategy",
            self.config.strategy
        );

        let mut cleanup_interval = interval(self.config.cleanup_interval);

        loop {
            tokio::select! {
                // Handle invalidation events
                Some(event) = self.event_rx.recv() => {
                    if self.config.enable_event_listening {
                        self.handle_event(event);
                    }
                }

                // Handle messages from cache
                Some(message) = self.invalidation_rx.recv() => {
                    self.handle_invalidation_message(message);
                }

                // Periodic cleanup
                _ = cleanup_interval.tick() => {
                    if self.config.enable_background_cleanup {
                        self.perform_cleanup();
                    }
                }

                // Shutdown signal
                else => {
                    info!("Invalidation manager shutting down");
                    break;
                }
            }
        }
    }

    /// Handle invalidation message from cache
    fn handle_invalidation_message(&self, message: InvalidationMessage) {
        match message {
            InvalidationMessage::TableChanged(table) => {
                self.cache.invalidate_by_table(&table);
            }
            InvalidationMessage::InvalidateKey(key) => {
                self.cache.invalidate_key(&key);
            }
            InvalidationMessage::InvalidateAll => {
                self.cache.clear();
            }
            InvalidationMessage::Shutdown => {
                info!("Received shutdown signal");
            }
        }
    }

    /// Perform periodic cleanup
    fn perform_cleanup(&self) {
        // Process any pending batch events
        self.process_batch();

        // Clear expired cache entries
        let cleared = self.cache.clear_expired();
        if cleared > 0 {
            debug!("Cleared {} expired cache entries during cleanup", cleared);
        }

        // Log metrics
        let metrics = self.metrics();
        if metrics.total_invalidations > 0 {
            trace!(
                "Invalidation metrics: {} total, {} entries invalidated",
                metrics.total_invalidations, metrics.entries_invalidated
            );
        }
    }
}

impl Clone for InvalidationManager {
    fn clone(&self) -> Self {
        let (event_tx, event_rx) = mpsc::unbounded_channel();
        let invalidation_rx = {
            let (_tx, rx) = mpsc::unbounded_channel();
            rx
        };

        Self {
            config: self.config.clone(),
            cache: self.cache.clone(),
            rules: Arc::clone(&self.rules),
            event_rx,
            event_tx,
            invalidation_rx,
            metrics: Arc::clone(&self.metrics),
            pending: Arc::clone(&self.pending),
            last_batch_time: Arc::clone(&self.last_batch_time),
        }
    }
}

#[cfg(test)]
#[path = "invalidation_tests.rs"]
mod tests;