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 } else {
451 // Mirror to cache
452 if let Some(ref merkle_cache) = self.merkle_cache {
453 let deleted_ids: Vec<String> = ids.iter().map(|s| s.to_string()).collect();
454 if let Err(e) = merkle_cache.sync_affected_from_sql(sql_merkle, &deleted_ids).await {
455 warn!(error = %e, "Failed to sync merkle cache after batch deletion");
456 }
457 }
458 }
459 }
460
461 info!(total, succeeded, "Batch delete completed");
462
463 Ok(BatchResult {
464 total,
465 succeeded,
466 failed: total - succeeded,
467 })
468 }
469
470 /// Get an item, or compute and insert it if missing.
471 ///
472 /// This is the classic "get or insert" pattern, useful for cache-aside:
473 /// 1. Check cache (L1 → L2 → L3)
474 /// 2. If missing, call the async factory function
475 /// 3. Insert the result and return it
476 ///
477 /// The factory is only called if the item is not found.
478 ///
479 /// # Example
480 ///
481 /// ```rust,no_run
482 /// # use sync_engine::{SyncEngine, SyncItem};
483 /// # use serde_json::json;
484 /// # async fn example(engine: &SyncEngine) {
485 /// let item = engine.get_or_insert_with("user.123", || async {
486 /// // Expensive operation - only runs if not cached
487 /// SyncItem::from_json("user.123".into(), json!({"name": "Fetched from DB"}))
488 /// }).await.unwrap();
489 /// # }
490 /// ```
491 pub async fn get_or_insert_with<F, Fut>(
492 &self,
493 id: &str,
494 factory: F,
495 ) -> Result<SyncItem, StorageError>
496 where
497 F: FnOnce() -> Fut,
498 Fut: std::future::Future<Output = SyncItem>,
499 {
500 // Try to get existing
501 if let Some(item) = self.get(id).await? {
502 return Ok(item);
503 }
504
505 // Not found - compute new value
506 let item = factory().await;
507
508 // Insert and return
509 self.submit(item.clone()).await?;
510
511 Ok(item)
512 }
513
514 // ═══════════════════════════════════════════════════════════════════════════
515 // State-based queries: Fast indexed access by caller-defined state tag
516 // ═══════════════════════════════════════════════════════════════════════════
517
518 /// Get items by state from SQL (L3 ground truth).
519 ///
520 /// Uses indexed query for fast retrieval.
521 ///
522 /// # Example
523 ///
524 /// ```rust,no_run
525 /// # use sync_engine::{SyncEngine, StorageError};
526 /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
527 /// // Get all delta items for CRDT merging
528 /// let deltas = engine.get_by_state("delta", 1000).await?;
529 /// for item in deltas {
530 /// println!("Delta: {}", item.object_id);
531 /// }
532 /// # Ok(())
533 /// # }
534 /// ```
535 pub async fn get_by_state(&self, state: &str, limit: usize) -> Result<Vec<SyncItem>, StorageError> {
536 if let Some(ref sql) = self.sql_store {
537 sql.get_by_state(state, limit).await
538 } else {
539 Ok(Vec::new())
540 }
541 }
542
543 /// Count items in a given state (SQL ground truth).
544 ///
545 /// # Example
546 ///
547 /// ```rust,no_run
548 /// # use sync_engine::{SyncEngine, StorageError};
549 /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
550 /// let pending_count = engine.count_by_state("pending").await?;
551 /// println!("{} items pending", pending_count);
552 /// # Ok(())
553 /// # }
554 /// ```
555 pub async fn count_by_state(&self, state: &str) -> Result<u64, StorageError> {
556 if let Some(ref sql) = self.sql_store {
557 sql.count_by_state(state).await
558 } else {
559 Ok(0)
560 }
561 }
562
563 /// Get just the IDs of items in a given state (lightweight query).
564 ///
565 /// Returns IDs from SQL. For Redis state SET, use `list_state_ids_redis()`.
566 pub async fn list_state_ids(&self, state: &str, limit: usize) -> Result<Vec<String>, StorageError> {
567 if let Some(ref sql) = self.sql_store {
568 sql.list_state_ids(state, limit).await
569 } else {
570 Ok(Vec::new())
571 }
572 }
573
574 /// Update the state of an item by ID.
575 ///
576 /// Updates both SQL (ground truth) and Redis state SETs.
577 /// L1 cache is NOT updated - caller should re-fetch if needed.
578 ///
579 /// Returns true if the item was found and updated.
580 pub async fn set_state(&self, id: &str, new_state: &str) -> Result<bool, StorageError> {
581 let mut updated = false;
582
583 // Update SQL (ground truth)
584 if let Some(ref sql) = self.sql_store {
585 updated = sql.set_state(id, new_state).await?;
586 }
587
588 // Note: Redis state SETs are not updated here because we'd need to know
589 // the old state to do SREM. For full Redis state management, the item
590 // should be re-submitted with the new state via submit_with().
591
592 Ok(updated)
593 }
594
595 /// Delete all items in a given state from SQL.
596 ///
597 /// Also removes from L1 cache and Redis state SET.
598 /// Returns the number of deleted items.
599 ///
600 /// # Example
601 ///
602 /// ```rust,no_run
603 /// # use sync_engine::{SyncEngine, StorageError};
604 /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
605 /// // Clean up all processed deltas
606 /// let deleted = engine.delete_by_state("delta").await?;
607 /// println!("Deleted {} delta items", deleted);
608 /// # Ok(())
609 /// # }
610 /// ```
611 pub async fn delete_by_state(&self, state: &str) -> Result<u64, StorageError> {
612 let mut deleted = 0u64;
613
614 // Get IDs first (for L1 cleanup)
615 let ids = if let Some(ref sql) = self.sql_store {
616 sql.list_state_ids(state, 100_000).await?
617 } else {
618 Vec::new()
619 };
620
621 // Remove from L1 cache
622 for id in &ids {
623 self.l1_cache.remove(id);
624 }
625
626 // Delete from SQL
627 if let Some(ref sql) = self.sql_store {
628 deleted = sql.delete_by_state(state).await?;
629 }
630
631 // Note: Redis items with TTL will expire naturally.
632 // For immediate Redis cleanup, call delete_by_state on RedisStore directly.
633
634 info!(state = %state, deleted = deleted, "Deleted items by state");
635
636 Ok(deleted)
637 }
638
639 // =========================================================================
640 // Prefix Scan Operations
641 // =========================================================================
642
643 /// Scan items by ID prefix.
644 ///
645 /// Retrieves all items whose ID starts with the given prefix.
646 /// Queries SQL (ground truth) directly - does NOT check L1 cache.
647 ///
648 /// Useful for CRDT delta-first architecture where deltas are stored as:
649 /// `delta:{object_id}:{op_id}` and you need to fetch all deltas for an object.
650 ///
651 /// # Example
652 ///
653 /// ```rust,no_run
654 /// # use sync_engine::{SyncEngine, StorageError};
655 /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
656 /// // Get base state
657 /// let base = engine.get("base:user.123").await?;
658 ///
659 /// // Get all pending deltas for this object
660 /// let deltas = engine.scan_prefix("delta:user.123:", 1000).await?;
661 ///
662 /// // Merge on-the-fly for read-repair
663 /// for delta in deltas {
664 /// println!("Delta: {} -> {:?}", delta.object_id, delta.content_as_json());
665 /// }
666 /// # Ok(())
667 /// # }
668 /// ```
669 pub async fn scan_prefix(&self, prefix: &str, limit: usize) -> Result<Vec<SyncItem>, StorageError> {
670 if let Some(ref sql) = self.sql_store {
671 sql.scan_prefix(prefix, limit).await
672 } else {
673 Ok(Vec::new())
674 }
675 }
676
677 /// Count items matching an ID prefix (SQL ground truth).
678 pub async fn count_prefix(&self, prefix: &str) -> Result<u64, StorageError> {
679 if let Some(ref sql) = self.sql_store {
680 sql.count_prefix(prefix).await
681 } else {
682 Ok(0)
683 }
684 }
685
686 /// Delete all items matching an ID prefix.
687 ///
688 /// Removes from L1 cache, SQL, and Redis.
689 /// Returns the number of deleted items.
690 ///
691 /// # Example
692 ///
693 /// ```rust,no_run
694 /// # use sync_engine::{SyncEngine, StorageError};
695 /// # async fn example(engine: &SyncEngine) -> Result<(), StorageError> {
696 /// // After merging deltas into base, clean them up
697 /// let deleted = engine.delete_prefix("delta:user.123:").await?;
698 /// println!("Cleaned up {} deltas", deleted);
699 /// # Ok(())
700 /// # }
701 /// ```
702 pub async fn delete_prefix(&self, prefix: &str) -> Result<u64, StorageError> {
703 let mut deleted = 0u64;
704
705 // Get IDs first (for L1/L2 cleanup)
706 let items = if let Some(ref sql) = self.sql_store {
707 sql.scan_prefix(prefix, 100_000).await?
708 } else {
709 Vec::new()
710 };
711
712 // Remove from L1 cache
713 for item in &items {
714 self.l1_cache.remove(&item.object_id);
715 }
716
717 // Remove from L2 (Redis) one-by-one via CacheStore trait
718 if let Some(ref l2) = self.l2_store {
719 for item in &items {
720 let _ = l2.delete(&item.object_id).await;
721 }
722 }
723
724 // Delete from SQL
725 if let Some(ref sql) = self.sql_store {
726 deleted = sql.delete_prefix(prefix).await?;
727 }
728
729 info!(prefix = %prefix, deleted = deleted, "Deleted items by prefix");
730
731 Ok(deleted)
732 }
733}
734
735#[cfg(test)]
736mod tests {
737 use super::*;
738 use crate::config::SyncEngineConfig;
739 use serde_json::json;
740 use tokio::sync::watch;
741
742 fn test_config() -> SyncEngineConfig {
743 SyncEngineConfig {
744 redis_url: None,
745 sql_url: None,
746 wal_path: None,
747 l1_max_bytes: 1024 * 1024,
748 ..Default::default()
749 }
750 }
751
752 fn test_item(id: &str) -> SyncItem {
753 SyncItem::from_json(id.to_string(), json!({"test": "data", "id": id}))
754 }
755
756 #[tokio::test]
757 async fn test_contains_l1_hit() {
758 let config = test_config();
759 let (_tx, rx) = watch::channel(config.clone());
760 let engine = SyncEngine::new(config, rx);
761
762 engine.l1_cache.insert("test.exists".into(), test_item("test.exists"));
763
764 assert!(engine.contains("test.exists").await);
765 }
766
767 #[tokio::test]
768 async fn test_contains_with_trusted_filter() {
769 let config = test_config();
770 let (_tx, rx) = watch::channel(config.clone());
771 let engine = SyncEngine::new(config, rx);
772
773 engine.l3_filter.mark_trusted();
774
775 engine.l1_cache.insert("test.exists".into(), test_item("test.exists"));
776 engine.l3_filter.insert("test.exists");
777
778 assert!(engine.contains("test.exists").await);
779 assert!(!engine.contains("test.missing").await);
780 }
781
782 #[test]
783 fn test_len_and_is_empty() {
784 let config = test_config();
785 let (_tx, rx) = watch::channel(config.clone());
786 let engine = SyncEngine::new(config, rx);
787
788 assert!(engine.is_empty());
789 assert_eq!(engine.len(), 0);
790
791 engine.l1_cache.insert("a".into(), test_item("a"));
792 assert!(!engine.is_empty());
793 assert_eq!(engine.len(), 1);
794
795 engine.l1_cache.insert("b".into(), test_item("b"));
796 assert_eq!(engine.len(), 2);
797 }
798
799 #[tokio::test]
800 async fn test_status_synced_in_l1() {
801 use super::super::EngineState;
802
803 let config = test_config();
804 let (_tx, rx) = watch::channel(config.clone());
805 let engine = SyncEngine::new(config, rx);
806 let _ = engine.state.send(EngineState::Ready);
807
808 engine.submit(test_item("test.item")).await.expect("Submit failed");
809 let _ = engine.l2_batcher.lock().await.force_flush();
810
811 let status = engine.status("test.item").await;
812 assert!(matches!(status, ItemStatus::Synced { in_l1: true, .. }));
813 }
814
815 #[tokio::test]
816 async fn test_status_pending() {
817 use super::super::EngineState;
818
819 let config = test_config();
820 let (_tx, rx) = watch::channel(config.clone());
821 let engine = SyncEngine::new(config, rx);
822 let _ = engine.state.send(EngineState::Ready);
823
824 engine.submit(test_item("test.pending")).await.expect("Submit failed");
825
826 let status = engine.status("test.pending").await;
827 assert_eq!(status, ItemStatus::Pending);
828 }
829
830 #[tokio::test]
831 async fn test_status_missing() {
832 let config = test_config();
833 let (_tx, rx) = watch::channel(config.clone());
834 let engine = SyncEngine::new(config, rx);
835
836 let status = engine.status("test.nonexistent").await;
837 assert_eq!(status, ItemStatus::Missing);
838 }
839
840 #[tokio::test]
841 async fn test_get_many_from_l1() {
842 use super::super::EngineState;
843
844 let config = test_config();
845 let (_tx, rx) = watch::channel(config.clone());
846 let engine = SyncEngine::new(config, rx);
847 let _ = engine.state.send(EngineState::Ready);
848
849 engine.l1_cache.insert("a".into(), test_item("a"));
850 engine.l1_cache.insert("b".into(), test_item("b"));
851 engine.l1_cache.insert("c".into(), test_item("c"));
852
853 let results = engine.get_many(&["a", "b", "missing", "c"]).await;
854
855 assert_eq!(results.len(), 4);
856 assert!(results[0].is_some());
857 assert!(results[1].is_some());
858 assert!(results[2].is_none());
859 assert!(results[3].is_some());
860
861 assert_eq!(results[0].as_ref().unwrap().object_id, "a");
862 assert_eq!(results[1].as_ref().unwrap().object_id, "b");
863 assert_eq!(results[3].as_ref().unwrap().object_id, "c");
864 }
865
866 #[tokio::test]
867 async fn test_submit_many() {
868 use super::super::EngineState;
869
870 let config = test_config();
871 let (_tx, rx) = watch::channel(config.clone());
872 let engine = SyncEngine::new(config, rx);
873 let _ = engine.state.send(EngineState::Ready);
874
875 let items = vec![
876 test_item("batch.1"),
877 test_item("batch.2"),
878 test_item("batch.3"),
879 ];
880
881 let result = engine.submit_many(items).await.expect("Batch submit failed");
882
883 assert_eq!(result.total, 3);
884 assert_eq!(result.succeeded, 3);
885 assert_eq!(result.failed, 0);
886 assert!(result.is_success());
887
888 assert_eq!(engine.len(), 3);
889 assert!(engine.contains("batch.1").await);
890 assert!(engine.contains("batch.2").await);
891 assert!(engine.contains("batch.3").await);
892 }
893
894 #[tokio::test]
895 async fn test_delete_many() {
896 use super::super::EngineState;
897
898 let config = test_config();
899 let (_tx, rx) = watch::channel(config.clone());
900 let engine = SyncEngine::new(config, rx);
901 let _ = engine.state.send(EngineState::Ready);
902
903 engine.l1_cache.insert("del.1".into(), test_item("del.1"));
904 engine.l1_cache.insert("del.2".into(), test_item("del.2"));
905 engine.l1_cache.insert("keep".into(), test_item("keep"));
906
907 let result = engine.delete_many(&["del.1", "del.2"]).await.expect("Batch delete failed");
908
909 assert_eq!(result.total, 2);
910 assert_eq!(result.succeeded, 2);
911 assert!(result.is_success());
912
913 assert!(!engine.l1_cache.contains_key("del.1"));
914 assert!(!engine.l1_cache.contains_key("del.2"));
915 assert!(engine.l1_cache.contains_key("keep"));
916 }
917
918 #[tokio::test]
919 async fn test_get_or_insert_with_existing() {
920 use super::super::EngineState;
921
922 let config = test_config();
923 let (_tx, rx) = watch::channel(config.clone());
924 let engine = SyncEngine::new(config, rx);
925 let _ = engine.state.send(EngineState::Ready);
926
927 let existing = test_item("existing");
928 engine.l1_cache.insert("existing".into(), existing.clone());
929
930 let factory_called = std::sync::atomic::AtomicBool::new(false);
931 let result = engine.get_or_insert_with("existing", || {
932 factory_called.store(true, std::sync::atomic::Ordering::SeqCst);
933 async { test_item("should_not_be_used") }
934 }).await.expect("get_or_insert_with failed");
935
936 assert!(!factory_called.load(std::sync::atomic::Ordering::SeqCst));
937 assert_eq!(result.object_id, "existing");
938 }
939
940 #[tokio::test]
941 async fn test_get_or_insert_with_missing() {
942 use super::super::EngineState;
943
944 let config = test_config();
945 let (_tx, rx) = watch::channel(config.clone());
946 let engine = SyncEngine::new(config, rx);
947 let _ = engine.state.send(EngineState::Ready);
948
949 let result = engine.get_or_insert_with("new_item", || async {
950 SyncItem::from_json("new_item".into(), json!({"created": "by factory"}))
951 }).await.expect("get_or_insert_with failed");
952
953 assert_eq!(result.object_id, "new_item");
954 assert!(engine.contains("new_item").await);
955 }
956}