sync_engine/coordinator/
api.rs

1// Copyright (c) 2025-2026 Adrian Robinson. Licensed under the AGPL-3.0.
2// See LICENSE file in the project root for full license text.
3
4//! V1.1 API: Query and batch operations.
5//!
6//! This module contains the higher-level API methods added in V1.1:
7//! - `contains()` - Fast probabilistic existence check
8//! - `len()` / `is_empty()` - L1 cache size queries
9//! - `status()` - Detailed sync status
10//! - `get_many()` - Parallel batch fetch
11//! - `submit_many()` - Batch upsert
12//! - `delete_many()` - Batch delete
13//! - `get_or_insert_with()` - Cache-aside pattern
14
15use std::sync::atomic::Ordering;
16use tokio::task::JoinSet;
17use tracing::{debug, info, warn, error};
18
19use crate::storage::traits::StorageError;
20use crate::sync_item::SyncItem;
21use crate::merkle::MerkleBatch;
22
23use super::{SyncEngine, ItemStatus, BatchResult};
24
25impl SyncEngine {
26    // ═══════════════════════════════════════════════════════════════════════════
27    // API: Query & Batch Operations
28    // ═══════════════════════════════════════════════════════════════════════════
29
30    /// Check if an item exists across all tiers.
31    ///
32    /// Checks in order: L1 cache → Redis EXISTS → L3 Cuckoo filter → SQL query.
33    /// If found in SQL and Cuckoo filter was untrusted, updates the filter.
34    ///
35    /// # Returns
36    /// - `true` → item definitely exists in at least one tier
37    /// - `false` → item does not exist (authoritative)
38    ///
39    /// # Example
40    ///
41    /// ```rust,no_run
42    /// # use sync_engine::SyncEngine;
43    /// # async fn example(engine: &SyncEngine) {
44    /// if engine.contains("user.123").await {
45    ///     let item = engine.get("user.123").await;
46    /// } else {
47    ///     println!("Not found");
48    /// }
49    /// # }
50    /// ```
51    pub async fn contains(&self, id: &str) -> bool {
52        // L1: In-memory cache (definitive, sync)
53        if self.l1_cache.contains_key(id) {
54            return true;
55        }
56        
57        // L2: Redis EXISTS (async, authoritative for Redis tier)
58        if let Some(ref l2) = self.l2_store {
59            if l2.exists(id).await.unwrap_or(false) {
60                return true;
61            }
62        }
63        
64        // L3: Cuckoo filter check (sync, probabilistic)
65        if self.l3_filter.is_trusted() {
66            // Filter is trusted - use it for fast negative
67            if !self.l3_filter.should_check_l3(id) {
68                return false; // Definitely not in L3
69            }
70        }
71        
72        // L3: SQL query (async, ground truth)
73        if let Some(ref l3) = self.l3_store {
74            if l3.exists(id).await.unwrap_or(false) {
75                // Found in SQL - update Cuckoo if it was untrusted
76                if !self.l3_filter.is_trusted() {
77                    self.l3_filter.insert(id);
78                }
79                return true;
80            }
81        }
82        
83        false
84    }
85    
86    /// Fast check: is this item definitely NOT in L3?
87    ///
88    /// Uses the Cuckoo filter for a fast authoritative negative.
89    /// - Returns `true` → item is **definitely not** in L3 (safe to skip)
90    /// - Returns `false` → item **might** exist (need to check L3)
91    ///
92    /// Only meaningful when the L3 filter is trusted. If untrusted, returns `false`
93    /// (meaning "we don't know, you should check").
94    ///
95    /// # Use Case
96    ///
97    /// Fast early-exit in replication: if definitely missing, apply without checking.
98    ///
99    /// ```rust,no_run
100    /// # use sync_engine::SyncEngine;
101    /// # async fn example(engine: &SyncEngine) {
102    /// if engine.definitely_missing("patient.123") {
103    ///     // Fast path: definitely new, just insert
104    ///     println!("New item, inserting directly");
105    /// } else {
106    ///     // Slow path: might exist, check hash
107    ///     if !engine.is_current("patient.123", "abc123...").await {
108    ///         println!("Outdated, updating");
109    ///     }
110    /// }
111    /// # }
112    /// ```
113    #[must_use]
114    #[inline]
115    pub fn definitely_missing(&self, id: &str) -> bool {
116        // Only authoritative if filter is trusted
117        if !self.l3_filter.is_trusted() {
118            return false; // Unknown, caller should check
119        }
120        // Cuckoo false = definitely not there
121        !self.l3_filter.should_check_l3(id)
122    }
123
124    /// Fast check: might this item exist somewhere?
125    ///
126    /// Checks L1 cache (partial, evicts) and Cuckoo filter (probabilistic).
127    /// - Returns `true` → item is in L1 OR might be in L3 (worth checking)
128    /// - Returns `false` → item is definitely not in L1 or L3
129    ///
130    /// Note: L1 is partial (items evict), so this can return `false` even if
131    /// the item exists in L2/L3. For authoritative check, use `contains()`.
132    ///
133    /// # Use Case
134    ///
135    /// Quick probabilistic check before expensive async lookup.
136    #[must_use]
137    #[inline]
138    pub fn might_exist(&self, id: &str) -> bool {
139        self.l1_cache.contains_key(id) || self.l3_filter.should_check_l3(id)
140    }
141
142    /// Check if the item at `key` has the given content hash.
143    ///
144    /// This is the semantic API for CDC deduplication in replication.
145    /// Returns `true` if the item exists AND its content hash matches.
146    /// Returns `false` if item doesn't exist OR hash differs.
147    ///
148    /// # Arguments
149    /// * `id` - Object ID
150    /// * `content_hash` - SHA256 hash of content (hex-encoded string)
151    ///
152    /// # Example
153    ///
154    /// ```rust,no_run
155    /// # use sync_engine::SyncEngine;
156    /// # async fn example(engine: &SyncEngine) {
157    /// // Skip replication if we already have this version
158    /// let incoming_hash = "abc123...";
159    /// if engine.is_current("patient.123", incoming_hash).await {
160    ///     println!("Already up to date, skipping");
161    ///     return;
162    /// }
163    /// # }
164    /// ```
165    pub async fn is_current(&self, id: &str, content_hash: &str) -> bool {
166        // Check L1 first (fastest)
167        if let Some(item) = self.l1_cache.get(id) {
168            return item.content_hash == content_hash;
169        }
170
171        // Check L2 (if available)
172        if let Some(ref l2) = self.l2_store {
173            if let Ok(Some(item)) = l2.get(id).await {
174                return item.content_hash == content_hash;
175            }
176        }
177
178        // Check L3 (ground truth)
179        if let Some(ref l3) = self.l3_store {
180            if self.l3_filter.should_check_l3(id) {
181                if let Ok(Some(item)) = l3.get(id).await {
182                    return item.content_hash == content_hash;
183                }
184            }
185        }
186
187        false
188    }
189
190    /// Get the current count of items in L1 cache.
191    #[must_use]
192    #[inline]
193    pub fn len(&self) -> usize {
194        self.l1_cache.len()
195    }
196
197    /// Check if L1 cache is empty.
198    #[must_use]
199    #[inline]
200    pub fn is_empty(&self) -> bool {
201        self.l1_cache.is_empty()
202    }
203
204    /// Get the sync status of an item.
205    ///
206    /// Returns detailed state information about where an item exists
207    /// and its sync status across tiers.
208    ///
209    /// # Example
210    ///
211    /// ```rust,no_run
212    /// # use sync_engine::{SyncEngine, ItemStatus};
213    /// # async fn example(engine: &SyncEngine) {
214    /// match engine.status("order.456").await {
215    ///     ItemStatus::Synced { in_l1, in_l2, in_l3 } => {
216    ///         println!("Synced: L1={}, L2={}, L3={}", in_l1, in_l2, in_l3);
217    ///     }
218    ///     ItemStatus::Pending => println!("Queued for sync"),
219    ///     ItemStatus::Missing => println!("Not found"),
220    /// }
221    /// # }
222    /// ```
223    pub async fn status(&self, id: &str) -> ItemStatus {
224        let in_l1 = self.l1_cache.contains_key(id);
225        
226        // Check if pending in batch queue
227        let pending = self.l2_batcher.lock().await.contains(id);
228        if pending {
229            return ItemStatus::Pending;
230        }
231        
232        // Check L2 (if available) - use EXISTS, no filter
233        let in_l2 = if let Some(ref l2) = self.l2_store {
234            l2.exists(id).await.unwrap_or(false)
235        } else {
236            false
237        };
238        
239        // Check L3 (if available)  
240        let in_l3 = if let Some(ref l3) = self.l3_store {
241            self.l3_filter.should_check_l3(id) && l3.get(id).await.ok().flatten().is_some()
242        } else {
243            false
244        };
245        
246        if in_l1 || in_l2 || in_l3 {
247            ItemStatus::Synced { in_l1, in_l2, in_l3 }
248        } else {
249            ItemStatus::Missing
250        }
251    }
252
253    /// Fetch multiple items in parallel.
254    ///
255    /// Returns a vector of `Option<SyncItem>` in the same order as input IDs.
256    /// Missing items are represented as `None`.
257    ///
258    /// # Performance
259    ///
260    /// This method fetches from L1 synchronously, then batches L2/L3 lookups
261    /// for items not in L1. Much faster than sequential `get()` calls.
262    ///
263    /// # Example
264    ///
265    /// ```rust,no_run
266    /// # use sync_engine::SyncEngine;
267    /// # async fn example(engine: &SyncEngine) {
268    /// let ids = vec!["user.1", "user.2", "user.3"];
269    /// let items = engine.get_many(&ids).await;
270    /// for (id, item) in ids.iter().zip(items.iter()) {
271    ///     match item {
272    ///         Some(item) => println!("{}: found", id),
273    ///         None => println!("{}: missing", id),
274    ///     }
275    /// }
276    /// # }
277    /// ```
278    pub async fn get_many(&self, ids: &[&str]) -> Vec<Option<SyncItem>> {
279        let mut results: Vec<Option<SyncItem>> = vec![None; ids.len()];
280        let mut missing_indices: Vec<usize> = Vec::new();
281        
282        // Phase 1: Check L1 (synchronous, fast)
283        for (i, id) in ids.iter().enumerate() {
284            if let Some(item) = self.l1_cache.get(*id) {
285                results[i] = Some(item.clone());
286            } else {
287                missing_indices.push(i);
288            }
289        }
290        
291        // Phase 2: Fetch missing items from L2/L3 in parallel
292        if !missing_indices.is_empty() {
293            let mut join_set: JoinSet<(usize, Option<SyncItem>)> = JoinSet::new();
294            
295            for &i in &missing_indices {
296                let id = ids[i].to_string();
297                let l2_store = self.l2_store.clone();
298                let l3_store = self.l3_store.clone();
299                let l3_filter = self.l3_filter.clone();
300                
301                join_set.spawn(async move {
302                    // Try L2 first (no filter, just try Redis)
303                    if let Some(ref l2) = l2_store {
304                        if let Ok(Some(item)) = l2.get(&id).await {
305                            return (i, Some(item));
306                        }
307                    }
308                    
309                    // Fall back to L3 (use Cuckoo filter if trusted)
310                    if let Some(ref l3) = l3_store {
311                        if !l3_filter.is_trusted() || l3_filter.should_check_l3(&id) {
312                            if let Ok(Some(item)) = l3.get(&id).await {
313                                return (i, Some(item));
314                            }
315                        }
316                    }
317                    
318                    (i, None)
319                });
320            }
321            
322            // Collect results
323            while let Some(result) = join_set.join_next().await {
324                if let Ok((i, item)) = result {
325                    results[i] = item;
326                }
327            }
328        }
329        
330        results
331    }
332
333    /// Submit multiple items for sync atomically.
334    ///
335    /// All items are added to L1 and queued for batch persistence.
336    /// Returns a `BatchResult` with success/failure counts.
337    ///
338    /// # Example
339    ///
340    /// ```rust,no_run
341    /// # use sync_engine::{SyncEngine, SyncItem};
342    /// # use serde_json::json;
343    /// # async fn example(engine: &SyncEngine) {
344    /// let items = vec![
345    ///     SyncItem::from_json("user.1".into(), json!({"name": "Alice"})),
346    ///     SyncItem::from_json("user.2".into(), json!({"name": "Bob"})),
347    /// ];
348    /// let result = engine.submit_many(items).await.unwrap();
349    /// println!("Submitted: {}, Failed: {}", result.succeeded, result.failed);
350    /// # }
351    /// ```
352    pub async fn submit_many(&self, items: Vec<SyncItem>) -> Result<BatchResult, StorageError> {
353        if !self.should_accept_writes() {
354            return Err(StorageError::Backend(format!(
355                "Rejecting batch write: engine state={}, pressure={}",
356                self.state(),
357                self.pressure()
358            )));
359        }
360        
361        let total = items.len();
362        let mut succeeded = 0;
363        
364        // Lock batcher once for the whole batch
365        let mut batcher = self.l2_batcher.lock().await;
366        
367        for item in items {
368            self.insert_l1(item.clone());
369            batcher.add(item);
370            succeeded += 1;
371        }
372        
373        debug!(total, succeeded, "Batch submitted to L1 and queue");
374        
375        Ok(BatchResult {
376            total,
377            succeeded,
378            failed: total - succeeded,
379        })
380    }
381
382    /// Delete multiple items atomically.
383    ///
384    /// Removes items from all tiers (L1, L2, L3) and updates filters.
385    /// Returns a `BatchResult` with counts.
386    ///
387    /// # Example
388    ///
389    /// ```rust,no_run
390    /// # use sync_engine::SyncEngine;
391    /// # async fn example(engine: &SyncEngine) {
392    /// let ids = vec!["user.1", "user.2", "user.3"];
393    /// let result = engine.delete_many(&ids).await.unwrap();
394    /// println!("Deleted: {}", result.succeeded);
395    /// # }
396    /// ```
397    pub async fn delete_many(&self, ids: &[&str]) -> Result<BatchResult, StorageError> {
398        if !self.should_accept_writes() {
399            return Err(StorageError::Backend(format!(
400                "Rejecting batch delete: engine state={}, pressure={}",
401                self.state(),
402                self.pressure()
403            )));
404        }
405        
406        let total = ids.len();
407        let mut succeeded = 0;
408        
409        // Build merkle batch for all deletions
410        let mut merkle_batch = MerkleBatch::new();
411        
412        for id in ids {
413            // Remove from L1
414            if let Some((_, item)) = self.l1_cache.remove(*id) {
415                let size = Self::item_size(&item);
416                self.l1_size_bytes.fetch_sub(size, Ordering::Release);
417            }
418            
419            // Remove from L3 filter (no L2 filter with TTL support)
420            self.l3_filter.remove(id);
421            
422            // Queue merkle deletion
423            merkle_batch.delete(id.to_string());
424            
425            succeeded += 1;
426        }
427        
428        // Batch delete from L2
429        if let Some(ref l2) = self.l2_store {
430            for id in ids {
431                if let Err(e) = l2.delete(id).await {
432                    warn!(id, error = %e, "Failed to delete from L2");
433                }
434            }
435        }
436        
437        // Batch delete from L3
438        if let Some(ref l3) = self.l3_store {
439            for id in ids {
440                if let Err(e) = l3.delete(id).await {
441                    warn!(id, error = %e, "Failed to delete from L3");
442                }
443            }
444        }
445        
446        // Update merkle trees
447        if let Some(ref sql_merkle) = self.sql_merkle {
448            if let Err(e) = sql_merkle.apply_batch(&merkle_batch).await {
449                error!(error = %e, "Failed to update SQL Merkle tree for batch deletion");
450            }
451        }
452        
453        if let Some(ref redis_merkle) = self.redis_merkle {
454            if let Err(e) = redis_merkle.apply_batch(&merkle_batch).await {
455                warn!(error = %e, "Failed to update Redis Merkle tree for batch deletion");
456            }
457        }
458        
459        info!(total, succeeded, "Batch delete completed");
460        
461        Ok(BatchResult {
462            total,
463            succeeded,
464            failed: total - succeeded,
465        })
466    }
467
468    /// Get an item, or compute and insert it if missing.
469    ///
470    /// This is the classic "get or insert" pattern, useful for cache-aside:
471    /// 1. Check cache (L1 → L2 → L3)
472    /// 2. If missing, call the async factory function
473    /// 3. Insert the result and return it
474    ///
475    /// The factory is only called if the item is not found.
476    ///
477    /// # Example
478    ///
479    /// ```rust,no_run
480    /// # use sync_engine::{SyncEngine, SyncItem};
481    /// # use serde_json::json;
482    /// # async fn example(engine: &SyncEngine) {
483    /// let item = engine.get_or_insert_with("user.123", || async {
484    ///     // Expensive operation - only runs if not cached
485    ///     SyncItem::from_json("user.123".into(), json!({"name": "Fetched from DB"}))
486    /// }).await.unwrap();
487    /// # }
488    /// ```
489    pub async fn get_or_insert_with<F, Fut>(
490        &self,
491        id: &str,
492        factory: F,
493    ) -> Result<SyncItem, StorageError>
494    where
495        F: FnOnce() -> Fut,
496        Fut: std::future::Future<Output = SyncItem>,
497    {
498        // Try to get existing
499        if let Some(item) = self.get(id).await? {
500            return Ok(item);
501        }
502        
503        // Not found - compute new value
504        let item = factory().await;
505        
506        // Insert and return
507        self.submit(item.clone()).await?;
508        
509        Ok(item)
510    }
511    
512    // ═══════════════════════════════════════════════════════════════════════════
513    // State-based queries: Fast indexed access by caller-defined state tag
514    // ═══════════════════════════════════════════════════════════════════════════
515    
516    /// Get items by state from SQL (L3 ground truth).
517    ///
518    /// Uses indexed query for fast retrieval.
519    ///
520    /// # Example
521    ///
522    /// ```rust,no_run
523    /// # use sync_engine::{SyncEngine, StorageError};
524    /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
525    /// // Get all delta items for CRDT merging
526    /// let deltas = engine.get_by_state("delta", 1000).await?;
527    /// for item in deltas {
528    ///     println!("Delta: {}", item.object_id);
529    /// }
530    /// # Ok(())
531    /// # }
532    /// ```
533    pub async fn get_by_state(&self, state: &str, limit: usize) -> Result<Vec<SyncItem>, StorageError> {
534        if let Some(ref sql) = self.sql_store {
535            sql.get_by_state(state, limit).await
536        } else {
537            Ok(Vec::new())
538        }
539    }
540    
541    /// Count items in a given state (SQL ground truth).
542    ///
543    /// # Example
544    ///
545    /// ```rust,no_run
546    /// # use sync_engine::{SyncEngine, StorageError};
547    /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
548    /// let pending_count = engine.count_by_state("pending").await?;
549    /// println!("{} items pending", pending_count);
550    /// # Ok(())
551    /// # }
552    /// ```
553    pub async fn count_by_state(&self, state: &str) -> Result<u64, StorageError> {
554        if let Some(ref sql) = self.sql_store {
555            sql.count_by_state(state).await
556        } else {
557            Ok(0)
558        }
559    }
560    
561    /// Get just the IDs of items in a given state (lightweight query).
562    ///
563    /// Returns IDs from SQL. For Redis state SET, use `list_state_ids_redis()`.
564    pub async fn list_state_ids(&self, state: &str, limit: usize) -> Result<Vec<String>, StorageError> {
565        if let Some(ref sql) = self.sql_store {
566            sql.list_state_ids(state, limit).await
567        } else {
568            Ok(Vec::new())
569        }
570    }
571    
572    /// Update the state of an item by ID.
573    ///
574    /// Updates both SQL (ground truth) and Redis state SETs.
575    /// L1 cache is NOT updated - caller should re-fetch if needed.
576    ///
577    /// Returns true if the item was found and updated.
578    pub async fn set_state(&self, id: &str, new_state: &str) -> Result<bool, StorageError> {
579        let mut updated = false;
580        
581        // Update SQL (ground truth)
582        if let Some(ref sql) = self.sql_store {
583            updated = sql.set_state(id, new_state).await?;
584        }
585        
586        // Note: Redis state SETs are not updated here because we'd need to know
587        // the old state to do SREM. For full Redis state management, the item
588        // should be re-submitted with the new state via submit_with().
589        
590        Ok(updated)
591    }
592    
593    /// Delete all items in a given state from SQL.
594    ///
595    /// Also removes from L1 cache and Redis state SET.
596    /// Returns the number of deleted items.
597    ///
598    /// # Example
599    ///
600    /// ```rust,no_run
601    /// # use sync_engine::{SyncEngine, StorageError};
602    /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
603    /// // Clean up all processed deltas
604    /// let deleted = engine.delete_by_state("delta").await?;
605    /// println!("Deleted {} delta items", deleted);
606    /// # Ok(())
607    /// # }
608    /// ```
609    pub async fn delete_by_state(&self, state: &str) -> Result<u64, StorageError> {
610        let mut deleted = 0u64;
611        
612        // Get IDs first (for L1 cleanup)
613        let ids = if let Some(ref sql) = self.sql_store {
614            sql.list_state_ids(state, 100_000).await?
615        } else {
616            Vec::new()
617        };
618        
619        // Remove from L1 cache
620        for id in &ids {
621            self.l1_cache.remove(id);
622        }
623        
624        // Delete from SQL
625        if let Some(ref sql) = self.sql_store {
626            deleted = sql.delete_by_state(state).await?;
627        }
628        
629        // Note: Redis items with TTL will expire naturally.
630        // For immediate Redis cleanup, call delete_by_state on RedisStore directly.
631        
632        info!(state = %state, deleted = deleted, "Deleted items by state");
633        
634        Ok(deleted)
635    }
636    
637    // =========================================================================
638    // Prefix Scan Operations
639    // =========================================================================
640    
641    /// Scan items by ID prefix.
642    ///
643    /// Retrieves all items whose ID starts with the given prefix.
644    /// Queries SQL (ground truth) directly - does NOT check L1 cache.
645    ///
646    /// Useful for CRDT delta-first architecture where deltas are stored as:
647    /// `delta:{object_id}:{op_id}` and you need to fetch all deltas for an object.
648    ///
649    /// # Example
650    ///
651    /// ```rust,no_run
652    /// # use sync_engine::{SyncEngine, StorageError};
653    /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
654    /// // Get base state
655    /// let base = engine.get("base:user.123").await?;
656    ///
657    /// // Get all pending deltas for this object
658    /// let deltas = engine.scan_prefix("delta:user.123:", 1000).await?;
659    ///
660    /// // Merge on-the-fly for read-repair
661    /// for delta in deltas {
662    ///     println!("Delta: {} -> {:?}", delta.object_id, delta.content_as_json());
663    /// }
664    /// # Ok(())
665    /// # }
666    /// ```
667    pub async fn scan_prefix(&self, prefix: &str, limit: usize) -> Result<Vec<SyncItem>, StorageError> {
668        if let Some(ref sql) = self.sql_store {
669            sql.scan_prefix(prefix, limit).await
670        } else {
671            Ok(Vec::new())
672        }
673    }
674    
675    /// Count items matching an ID prefix (SQL ground truth).
676    pub async fn count_prefix(&self, prefix: &str) -> Result<u64, StorageError> {
677        if let Some(ref sql) = self.sql_store {
678            sql.count_prefix(prefix).await
679        } else {
680            Ok(0)
681        }
682    }
683    
684    /// Delete all items matching an ID prefix.
685    ///
686    /// Removes from L1 cache, SQL, and Redis.
687    /// Returns the number of deleted items.
688    ///
689    /// # Example
690    ///
691    /// ```rust,no_run
692    /// # use sync_engine::{SyncEngine, StorageError};
693    /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
694    /// // After merging deltas into base, clean them up
695    /// let deleted = engine.delete_prefix("delta:user.123:").await?;
696    /// println!("Cleaned up {} deltas", deleted);
697    /// # Ok(())
698    /// # }
699    /// ```
700    pub async fn delete_prefix(&self, prefix: &str) -> Result<u64, StorageError> {
701        let mut deleted = 0u64;
702        
703        // Get IDs first (for L1/L2 cleanup)
704        let items = if let Some(ref sql) = self.sql_store {
705            sql.scan_prefix(prefix, 100_000).await?
706        } else {
707            Vec::new()
708        };
709        
710        // Remove from L1 cache
711        for item in &items {
712            self.l1_cache.remove(&item.object_id);
713        }
714        
715        // Remove from L2 (Redis) one-by-one via CacheStore trait
716        if let Some(ref l2) = self.l2_store {
717            for item in &items {
718                let _ = l2.delete(&item.object_id).await;
719            }
720        }
721        
722        // Delete from SQL
723        if let Some(ref sql) = self.sql_store {
724            deleted = sql.delete_prefix(prefix).await?;
725        }
726        
727        info!(prefix = %prefix, deleted = deleted, "Deleted items by prefix");
728        
729        Ok(deleted)
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736    use crate::config::SyncEngineConfig;
737    use serde_json::json;
738    use tokio::sync::watch;
739
740    fn test_config() -> SyncEngineConfig {
741        SyncEngineConfig {
742            redis_url: None,
743            sql_url: None,
744            wal_path: None,
745            l1_max_bytes: 1024 * 1024,
746            ..Default::default()
747        }
748    }
749
750    fn test_item(id: &str) -> SyncItem {
751        SyncItem::from_json(id.to_string(), json!({"test": "data", "id": id}))
752    }
753
754    #[tokio::test]
755    async fn test_contains_l1_hit() {
756        let config = test_config();
757        let (_tx, rx) = watch::channel(config.clone());
758        let engine = SyncEngine::new(config, rx);
759        
760        engine.l1_cache.insert("test.exists".into(), test_item("test.exists"));
761        
762        assert!(engine.contains("test.exists").await);
763    }
764
765    #[tokio::test]
766    async fn test_contains_with_trusted_filter() {
767        let config = test_config();
768        let (_tx, rx) = watch::channel(config.clone());
769        let engine = SyncEngine::new(config, rx);
770        
771        engine.l3_filter.mark_trusted();
772        
773        engine.l1_cache.insert("test.exists".into(), test_item("test.exists"));
774        engine.l3_filter.insert("test.exists");
775        
776        assert!(engine.contains("test.exists").await);
777        assert!(!engine.contains("test.missing").await);
778    }
779
780    #[test]
781    fn test_len_and_is_empty() {
782        let config = test_config();
783        let (_tx, rx) = watch::channel(config.clone());
784        let engine = SyncEngine::new(config, rx);
785        
786        assert!(engine.is_empty());
787        assert_eq!(engine.len(), 0);
788        
789        engine.l1_cache.insert("a".into(), test_item("a"));
790        assert!(!engine.is_empty());
791        assert_eq!(engine.len(), 1);
792        
793        engine.l1_cache.insert("b".into(), test_item("b"));
794        assert_eq!(engine.len(), 2);
795    }
796
797    #[tokio::test]
798    async fn test_status_synced_in_l1() {
799        use super::super::EngineState;
800        
801        let config = test_config();
802        let (_tx, rx) = watch::channel(config.clone());
803        let engine = SyncEngine::new(config, rx);
804        let _ = engine.state.send(EngineState::Ready);
805        
806        engine.submit(test_item("test.item")).await.expect("Submit failed");
807        let _ = engine.l2_batcher.lock().await.force_flush();
808        
809        let status = engine.status("test.item").await;
810        assert!(matches!(status, ItemStatus::Synced { in_l1: true, .. }));
811    }
812
813    #[tokio::test]
814    async fn test_status_pending() {
815        use super::super::EngineState;
816        
817        let config = test_config();
818        let (_tx, rx) = watch::channel(config.clone());
819        let engine = SyncEngine::new(config, rx);
820        let _ = engine.state.send(EngineState::Ready);
821        
822        engine.submit(test_item("test.pending")).await.expect("Submit failed");
823        
824        let status = engine.status("test.pending").await;
825        assert_eq!(status, ItemStatus::Pending);
826    }
827
828    #[tokio::test]
829    async fn test_status_missing() {
830        let config = test_config();
831        let (_tx, rx) = watch::channel(config.clone());
832        let engine = SyncEngine::new(config, rx);
833        
834        let status = engine.status("test.nonexistent").await;
835        assert_eq!(status, ItemStatus::Missing);
836    }
837
838    #[tokio::test]
839    async fn test_get_many_from_l1() {
840        use super::super::EngineState;
841        
842        let config = test_config();
843        let (_tx, rx) = watch::channel(config.clone());
844        let engine = SyncEngine::new(config, rx);
845        let _ = engine.state.send(EngineState::Ready);
846        
847        engine.l1_cache.insert("a".into(), test_item("a"));
848        engine.l1_cache.insert("b".into(), test_item("b"));
849        engine.l1_cache.insert("c".into(), test_item("c"));
850        
851        let results = engine.get_many(&["a", "b", "missing", "c"]).await;
852        
853        assert_eq!(results.len(), 4);
854        assert!(results[0].is_some());
855        assert!(results[1].is_some());
856        assert!(results[2].is_none());
857        assert!(results[3].is_some());
858        
859        assert_eq!(results[0].as_ref().unwrap().object_id, "a");
860        assert_eq!(results[1].as_ref().unwrap().object_id, "b");
861        assert_eq!(results[3].as_ref().unwrap().object_id, "c");
862    }
863
864    #[tokio::test]
865    async fn test_submit_many() {
866        use super::super::EngineState;
867        
868        let config = test_config();
869        let (_tx, rx) = watch::channel(config.clone());
870        let engine = SyncEngine::new(config, rx);
871        let _ = engine.state.send(EngineState::Ready);
872        
873        let items = vec![
874            test_item("batch.1"),
875            test_item("batch.2"),
876            test_item("batch.3"),
877        ];
878        
879        let result = engine.submit_many(items).await.expect("Batch submit failed");
880        
881        assert_eq!(result.total, 3);
882        assert_eq!(result.succeeded, 3);
883        assert_eq!(result.failed, 0);
884        assert!(result.is_success());
885        
886        assert_eq!(engine.len(), 3);
887        assert!(engine.contains("batch.1").await);
888        assert!(engine.contains("batch.2").await);
889        assert!(engine.contains("batch.3").await);
890    }
891
892    #[tokio::test]
893    async fn test_delete_many() {
894        use super::super::EngineState;
895        
896        let config = test_config();
897        let (_tx, rx) = watch::channel(config.clone());
898        let engine = SyncEngine::new(config, rx);
899        let _ = engine.state.send(EngineState::Ready);
900        
901        engine.l1_cache.insert("del.1".into(), test_item("del.1"));
902        engine.l1_cache.insert("del.2".into(), test_item("del.2"));
903        engine.l1_cache.insert("keep".into(), test_item("keep"));
904        
905        let result = engine.delete_many(&["del.1", "del.2"]).await.expect("Batch delete failed");
906        
907        assert_eq!(result.total, 2);
908        assert_eq!(result.succeeded, 2);
909        assert!(result.is_success());
910        
911        assert!(!engine.l1_cache.contains_key("del.1"));
912        assert!(!engine.l1_cache.contains_key("del.2"));
913        assert!(engine.l1_cache.contains_key("keep"));
914    }
915
916    #[tokio::test]
917    async fn test_get_or_insert_with_existing() {
918        use super::super::EngineState;
919        
920        let config = test_config();
921        let (_tx, rx) = watch::channel(config.clone());
922        let engine = SyncEngine::new(config, rx);
923        let _ = engine.state.send(EngineState::Ready);
924        
925        let existing = test_item("existing");
926        engine.l1_cache.insert("existing".into(), existing.clone());
927        
928        let factory_called = std::sync::atomic::AtomicBool::new(false);
929        let result = engine.get_or_insert_with("existing", || {
930            factory_called.store(true, std::sync::atomic::Ordering::SeqCst);
931            async { test_item("should_not_be_used") }
932        }).await.expect("get_or_insert_with failed");
933        
934        assert!(!factory_called.load(std::sync::atomic::Ordering::SeqCst));
935        assert_eq!(result.object_id, "existing");
936    }
937
938    #[tokio::test]
939    async fn test_get_or_insert_with_missing() {
940        use super::super::EngineState;
941        
942        let config = test_config();
943        let (_tx, rx) = watch::channel(config.clone());
944        let engine = SyncEngine::new(config, rx);
945        let _ = engine.state.send(EngineState::Ready);
946        
947        let result = engine.get_or_insert_with("new_item", || async {
948            SyncItem::from_json("new_item".into(), json!({"created": "by factory"}))
949        }).await.expect("get_or_insert_with failed");
950        
951        assert_eq!(result.object_id, "new_item");
952        assert!(engine.contains("new_item").await);
953    }
954}