code-search-cli 0.3.3

Intelligent code search tool for tracing text (UI text, function names, variables) to implementation code
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! # Concurrency Patterns - Rust Book Chapter 16
//!
//! This module demonstrates thread-safe caching with minimal shared state from
//! [The Rust Book Chapter 16](https://doc.rust-lang.org/book/ch16-00-concurrency.html).
//!
//! ## Key Concepts Demonstrated
//!
//! 1. **Shared State with Mutex** (Chapter 16.3)
//!    - `front_cache: Mutex<HashMap<...>>` for thread-safe in-memory cache
//!    - Lock held for minimal time to reduce contention
//!    - Appropriate use case: infrequent updates, small critical sections
//!
//! 2. **When NOT to Use Arc<Mutex<T>>** (Chapter 15 + 16)
//!    - This module does NOT use `Arc<Mutex<T>>` for the main cache
//!    - Instead uses a persistent database (`sled`) with built-in concurrency
//!    - Demonstrates that not all shared state needs `Arc<Mutex<T>>`
//!
//! 3. **Process-Level Concurrency**
//!    - Background cache server process (optional)
//!    - TCP communication between processes
//!    - Demonstrates concurrency beyond threads
//!
//! ## Design Decisions
//!
//! **Why `Mutex<HashMap>` for front cache?**
//! - Small, frequently accessed data (LRU cache)
//! - Lock contention is acceptable (not in hot loop)
//! - Simpler than lock-free alternatives
//!
//! **Why NOT `Arc<Mutex<Vec>>` for results?**
//! - Results are returned, not shared
//! - Caller owns the data
//! - No need for reference counting
//!
//! **Why persistent database instead of in-memory?**
//! - Cache survives process restarts
//! - Built-in concurrency control
//! - Automatic disk management
//!
//! ## Learning Notes
//!
//! This module shows that effective concurrency doesn't always mean:
//! - Using `Arc` everywhere
//! - Sharing everything with `Mutex`
//! - Complex lock-free algorithms
//!
//! Sometimes the best approach is:
//! - Minimal shared state
//! - Clear ownership boundaries
//! - Letting libraries handle concurrency (like `sled`)

use crate::error::{Result, SearchError};
use crate::parse::TranslationEntry;
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use sled::Db;
use std::fs;
use std::io::{Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::time::{Duration, SystemTime};

const CACHE_DIR_NAME: &str = "cs";
const PORT_FILE: &str = "cache.port";
const SERVER_FLAG: &str = "--cache-server";
const FRONT_CACHE_CAP: usize = 512;
const MAX_CACHE_SIZE: u64 = 1_000_000_000;
const MAX_CACHE_AGE_SECS: u64 = 30 * 24 * 60 * 60;
const CLEANUP_INTERVAL_SECS: u64 = 6 * 60 * 60;

/// Cache value stored for each (file, query) pair
#[derive(Serialize, Deserialize, Clone)]
struct CacheValue {
    mtime_secs: u64,
    file_size: u64,
    last_accessed: u64,
    results: Vec<TranslationEntry>,
}

/// Cross-process cache client: tries a background TCP server; falls back to local cache.
pub struct SearchResultCache {
    backend: CacheBackend,
}

enum CacheBackend {
    Local(LocalCache),
    Remote(RemoteCache),
}

#[derive(Serialize, Deserialize, Debug)]
enum CacheRequest {
    Get {
        file: PathBuf,
        query: String,
        case_sensitive: bool,
        mtime_secs: u64,
        file_size: u64,
    },
    Set {
        file: PathBuf,
        query: String,
        case_sensitive: bool,
        mtime_secs: u64,
        file_size: u64,
        results: Vec<TranslationEntry>,
    },
    Clear,
    Ping,
}

#[derive(Serialize, Deserialize, Debug)]
enum CacheResponse {
    Get(Option<Vec<TranslationEntry>>),
    Ack(bool),
}

impl SearchResultCache {
    /// Create a cache client. Prefers a background TCP server unless disabled.
    pub fn new() -> Result<Self> {
        if std::env::var("CS_DISABLE_CACHE_SERVER").is_ok() {
            return Ok(Self {
                backend: CacheBackend::Local(LocalCache::new()?),
            });
        }

        if let Some(remote) = RemoteCache::connect_or_spawn()? {
            return Ok(Self {
                backend: CacheBackend::Remote(remote),
            });
        }

        Ok(Self {
            backend: CacheBackend::Local(LocalCache::new()?),
        })
    }

    /// Test helper: force cache to use a specific directory (local only).
    pub fn with_cache_dir(cache_dir: PathBuf) -> Result<Self> {
        Ok(Self {
            backend: CacheBackend::Local(LocalCache::with_cache_dir(cache_dir)?),
        })
    }

    pub fn get(
        &self,
        file: &Path,
        query: &str,
        case_sensitive: bool,
        current_mtime: SystemTime,
        current_size: u64,
    ) -> Option<Vec<TranslationEntry>> {
        match &self.backend {
            CacheBackend::Local(inner) => {
                inner.get(file, query, case_sensitive, current_mtime, current_size)
            }
            CacheBackend::Remote(remote) => remote
                .get(file, query, case_sensitive, current_mtime, current_size)
                .ok()
                .flatten(),
        }
    }

    pub fn set(
        &self,
        file: &Path,
        query: &str,
        case_sensitive: bool,
        mtime: SystemTime,
        file_size: u64,
        results: &[TranslationEntry],
    ) -> Result<()> {
        match &self.backend {
            CacheBackend::Local(inner) => {
                inner.set(file, query, case_sensitive, mtime, file_size, results)
            }
            CacheBackend::Remote(remote) => {
                remote.set(file, query, case_sensitive, mtime, file_size, results)
            }
        }
    }

    pub fn clear(&self) -> Result<()> {
        match &self.backend {
            CacheBackend::Local(inner) => inner.clear(),
            CacheBackend::Remote(remote) => remote.clear(),
        }
    }

    /// Hidden entrypoint: block and run cache server.
    pub fn start_server_blocking() -> Result<()> {
        run_cache_server()
    }
}

/// Local cache implementation with two-tier storage.
///
/// # Rust Book Reference
///
/// **Chapter 16.3: Shared-State Concurrency**
/// https://doc.rust-lang.org/book/ch16-03-shared-state.html
///
/// # Educational Notes - Appropriate Use of Mutex
///
/// This struct demonstrates when `Mutex` is the right choice:
///
/// ```rust,ignore
/// struct LocalCache {
///     front_cache: Mutex<HashMap<Vec<u8>, CacheValue>>,  // Thread-safe
///     db: Db,  // Already thread-safe (sled handles it)
/// }
/// ```
///
/// **Why `Mutex<HashMap>` for front_cache?**
/// 1. **Small, hot data** - LRU cache for recent queries
/// 2. **Infrequent writes** - Only on cache misses
/// 3. **Short lock duration** - Just hash lookup/insert
/// 4. **Simpler than alternatives** - No need for lock-free structures
///
/// **Why NOT `Mutex<Db>`?**
/// - `sled::Db` is already thread-safe
/// - Adding `Mutex` would be redundant and slower
/// - Let the library handle concurrency
///
/// **Lock scope is minimal:**
/// ```rust,ignore
/// fn front_get(&self, key: &[u8]) -> Option<CacheValue> {
///     self.front_cache.lock().ok()?.get(key).cloned()
///     // Lock released here automatically (RAII)
/// }
/// ```
///
/// **Contrast with message passing:**
/// - Message passing (channels) is better for producer-consumer
/// - Shared state (Mutex) is better for shared cache
/// - Choose the right tool for the job!
struct LocalCache {
    db: Db,
    last_cleanup: SystemTime,
    front_cache: Mutex<HashMap<Vec<u8>, CacheValue>>,
    cache_dir: PathBuf,
}

impl LocalCache {
    fn cache_dir() -> PathBuf {
        dirs::cache_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(CACHE_DIR_NAME)
    }

    fn with_cache_dir(cache_dir: PathBuf) -> Result<Self> {
        fs::create_dir_all(&cache_dir)?;
        let db = sled::open(cache_dir.join("db"))
            .map_err(|e| SearchError::Generic(format!("Failed to open cache: {}", e)))?;

        let last_cleanup = Self::read_last_cleanup_marker(&cache_dir)?;
        let cache = Self {
            db,
            last_cleanup,
            front_cache: Mutex::new(HashMap::new()),
            cache_dir,
        };
        cache.maybe_cleanup_on_open()?;
        Ok(cache)
    }

    fn new() -> Result<Self> {
        Self::with_cache_dir(Self::cache_dir())
    }

    fn get(
        &self,
        file: &Path,
        query: &str,
        case_sensitive: bool,
        current_mtime: SystemTime,
        current_size: u64,
    ) -> Option<Vec<TranslationEntry>> {
        let key = self.make_key(file, query, case_sensitive);

        if let Some(entries) = self.front_get(&key, current_mtime, current_size) {
            return Some(entries);
        }

        let cached_bytes = self.db.get(&key).ok()??;
        let mut cached: CacheValue = bincode::deserialize(&cached_bytes).ok()?;

        let current_secs = current_mtime
            .duration_since(SystemTime::UNIX_EPOCH)
            .ok()?
            .as_secs();

        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .ok()?
            .as_secs();

        // Check if entry is expired (lazy cleanup)
        if now.saturating_sub(cached.last_accessed) > MAX_CACHE_AGE_SECS {
            // Entry expired - delete it and return None
            let _ = self.db.remove(&key);
            return None;
        }

        if cached.mtime_secs == current_secs && cached.file_size == current_size {
            cached.last_accessed = now;

            if let Ok(updated_bytes) = bincode::serialize(&cached) {
                let _ = self.db.insert(&key, updated_bytes);
            }

            self.front_set(key.clone(), cached.clone());
            Some(cached.results)
        } else {
            // File changed - delete stale entry
            let _ = self.db.remove(&key);
            None
        }
    }

    fn set(
        &self,
        file: &Path,
        query: &str,
        case_sensitive: bool,
        mtime: SystemTime,
        file_size: u64,
        results: &[TranslationEntry],
    ) -> Result<()> {
        let key = self.make_key(file, query, case_sensitive);

        let mtime_secs = mtime
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| SearchError::Generic(format!("Invalid mtime: {}", e)))?
            .as_secs();

        let last_accessed = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| SearchError::Generic(format!("Failed to get current time: {}", e)))?
            .as_secs();

        let value = CacheValue {
            mtime_secs,
            file_size,
            last_accessed,
            results: results.to_vec(),
        };

        let value_bytes = bincode::serialize(&value)
            .map_err(|e| SearchError::Generic(format!("Failed to serialize cache: {}", e)))?;

        self.front_set(key.clone(), value.clone());

        self.db
            .insert(key, value_bytes)
            .map_err(|e| SearchError::Generic(format!("Failed to write cache: {}", e)))?;

        Ok(())
    }

    fn clear(&self) -> Result<()> {
        self.db
            .clear()
            .map_err(|e| SearchError::Generic(format!("Failed to clear cache: {}", e)))?;
        if let Ok(mut map) = self.front_cache.lock() {
            map.clear();
        }
        let _ = fs::remove_file(Self::meta_file_path(&self.cache_dir));
        Ok(())
    }

    fn front_get(
        &self,
        key: &[u8],
        current_mtime: SystemTime,
        current_size: u64,
    ) -> Option<Vec<TranslationEntry>> {
        let guard = self.front_cache.lock().ok()?;
        let entry = guard.get(key)?;
        let current_secs = current_mtime
            .duration_since(SystemTime::UNIX_EPOCH)
            .ok()?
            .as_secs();
        if entry.mtime_secs == current_secs && entry.file_size == current_size {
            Some(entry.results.clone())
        } else {
            None
        }
    }

    fn front_set(&self, key: Vec<u8>, value: CacheValue) {
        if let Ok(mut map) = self.front_cache.lock() {
            if map.len() >= FRONT_CACHE_CAP {
                if let Some(oldest_key) = map
                    .iter()
                    .min_by_key(|(_, v)| v.last_accessed)
                    .map(|(k, _)| k.clone())
                {
                    map.remove(&oldest_key);
                }
            }
            map.insert(key, value);
        }
    }

    fn make_key(&self, file: &Path, query: &str, case_sensitive: bool) -> Vec<u8> {
        let normalized_query = if case_sensitive {
            query.to_string()
        } else {
            query.to_lowercase()
        };
        format!("{}|{}", file.display(), normalized_query).into_bytes()
    }

    fn maybe_cleanup_on_open(&self) -> Result<()> {
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| SearchError::Generic(format!("Failed to get current time: {}", e)))?
            .as_secs();

        let last = self
            .last_cleanup
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        if now.saturating_sub(last) >= CLEANUP_INTERVAL_SECS {
            self.cleanup_if_needed()?;
        }

        Ok(())
    }

    fn cleanup_if_needed(&self) -> Result<()> {
        // Check if cache size exceeded limit
        let size = self
            .db
            .size_on_disk()
            .map_err(|e| SearchError::Generic(format!("Failed to get cache size: {}", e)))?;

        // Only do cleanup if size limit exceeded (expiry handled lazily at read time)
        if size <= MAX_CACHE_SIZE {
            return Ok(());
        }

        // Collect all entries with their last access time
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| SearchError::Generic(format!("Failed to get current time: {}", e)))?
            .as_secs();

        // ITERATOR IMPROVEMENT: Use filter_map instead of manual loop
        // Rust Book Chapter 13.2: Iterator Adapters
        // filter_map combines filtering and mapping in one pass
        let mut entries: Vec<(Vec<u8>, u64)> = self
            .db
            .iter()
            .flatten()
            .filter_map(|(key, value)| {
                // Try to deserialize, convert Result to Option
                bincode::deserialize::<CacheValue>(&value)
                    .ok()
                    // Filter out expired entries
                    .filter(|cache_value| {
                        now.saturating_sub(cache_value.last_accessed) <= MAX_CACHE_AGE_SECS
                    })
                    // Map to the tuple we need
                    .map(|cache_value| (key.to_vec(), cache_value.last_accessed))
            })
            .collect();

        // Sort by last accessed time (oldest first)
        entries.sort_by_key(|(_, last_accessed)| *last_accessed);

        // Remove oldest entries until size is under limit
        for (key, _) in entries.iter() {
            if self
                .db
                .size_on_disk()
                .ok()
                .map(|s| s <= MAX_CACHE_SIZE)
                .unwrap_or(true)
            {
                break;
            }
            let _ = self.db.remove(key);
        }

        let _ = self.db.flush();
        self.write_last_cleanup_marker(&self.cache_dir);
        Ok(())
    }

    fn meta_file_path(cache_dir: &Path) -> PathBuf {
        cache_dir.join("meta.last")
    }

    fn write_last_cleanup_marker(&self, cache_dir: &Path) {
        let _ = fs::write(
            Self::meta_file_path(cache_dir),
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .map(|d| d.as_secs().to_string())
                .unwrap_or_else(|_| "0".to_string()),
        );
    }

    fn read_last_cleanup_marker(cache_dir: &Path) -> Result<SystemTime> {
        let path = Self::meta_file_path(cache_dir);

        let contents = fs::read_to_string(path).ok();
        if let Some(s) = contents {
            if let Ok(secs) = s.trim().parse::<u64>() {
                return Ok(SystemTime::UNIX_EPOCH + Duration::from_secs(secs));
            }
        }

        Ok(SystemTime::UNIX_EPOCH)
    }
}

struct RemoteCache {
    addr: String,
}

impl RemoteCache {
    fn connect_or_spawn() -> Result<Option<Self>> {
        if let Some(addr) = read_port_file() {
            if Self::ping_addr(&addr).is_ok() {
                return Ok(Some(Self { addr }));
            }
        }

        spawn_server()?;

        if let Some(addr) = read_port_file() {
            if Self::ping_addr(&addr).is_ok() {
                return Ok(Some(Self { addr }));
            }
        }

        Ok(None)
    }

    fn ping_addr(addr: &str) -> Result<()> {
        let client = Self {
            addr: addr.to_string(),
        };
        match client.send_request(CacheRequest::Ping)? {
            CacheResponse::Ack(true) => Ok(()),
            _ => Err(SearchError::Generic(
                "Cache server did not acknowledge ping".to_string(),
            )),
        }
    }

    fn get(
        &self,
        file: &Path,
        query: &str,
        case_sensitive: bool,
        current_mtime: SystemTime,
        current_size: u64,
    ) -> Result<Option<Vec<TranslationEntry>>> {
        let mtime_secs = current_mtime
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| SearchError::Generic(format!("Invalid mtime: {}", e)))?
            .as_secs();

        let req = CacheRequest::Get {
            file: file.to_path_buf(),
            query: query.to_string(),
            case_sensitive,
            mtime_secs,
            file_size: current_size,
        };

        match self.send_request(req)? {
            CacheResponse::Get(res) => Ok(res),
            _ => Err(SearchError::Generic("Invalid cache response".to_string())),
        }
    }

    fn set(
        &self,
        file: &Path,
        query: &str,
        case_sensitive: bool,
        mtime: SystemTime,
        file_size: u64,
        results: &[TranslationEntry],
    ) -> Result<()> {
        let mtime_secs = mtime
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|e| SearchError::Generic(format!("Invalid mtime: {}", e)))?
            .as_secs();

        let req = CacheRequest::Set {
            file: file.to_path_buf(),
            query: query.to_string(),
            case_sensitive,
            mtime_secs,
            file_size,
            results: results.to_vec(),
        };

        match self.send_request(req)? {
            CacheResponse::Ack(true) => Ok(()),
            _ => Err(SearchError::Generic("Cache write failed".to_string())),
        }
    }

    fn clear(&self) -> Result<()> {
        match self.send_request(CacheRequest::Clear)? {
            CacheResponse::Ack(true) => Ok(()),
            _ => Err(SearchError::Generic("Failed to clear cache".to_string())),
        }
    }

    fn send_request(&self, req: CacheRequest) -> Result<CacheResponse> {
        let mut stream = TcpStream::connect(&self.addr)
            .map_err(|e| SearchError::Generic(format!("Failed to connect cache server: {}", e)))?;

        let bytes = bincode::serialize(&req)
            .map_err(|e| SearchError::Generic(format!("Failed to encode cache request: {}", e)))?;

        stream
            .write_all(&bytes)
            .map_err(|e| SearchError::Generic(format!("Failed to write cache request: {}", e)))?;
        let _ = stream.shutdown(Shutdown::Write);

        let mut buf = Vec::new();
        stream
            .read_to_end(&mut buf)
            .map_err(|e| SearchError::Generic(format!("Failed to read cache response: {}", e)))?;

        let resp: CacheResponse = bincode::deserialize(&buf)
            .map_err(|e| SearchError::Generic(format!("Failed to decode cache response: {}", e)))?;
        Ok(resp)
    }
}

/// ---------- Server ----------
fn run_cache_server() -> Result<()> {
    let cache_dir = LocalCache::cache_dir();
    fs::create_dir_all(&cache_dir)?;

    let listener = TcpListener::bind("127.0.0.1:0")
        .map_err(|e| SearchError::Generic(format!("Failed to bind cache server: {}", e)))?;
    let addr = listener
        .local_addr()
        .map_err(|e| SearchError::Generic(format!("Failed to get cache server address: {}", e)))?;
    write_port_file(&cache_dir, &addr.to_string())?;

    let local = LocalCache::with_cache_dir(cache_dir)?;
    for stream in listener.incoming() {
        match stream {
            Ok(mut stream) => {
                let _ = handle_connection(&local, &mut stream);
            }
            Err(_) => continue,
        }
    }
    Ok(())
}

fn handle_connection(local: &LocalCache, stream: &mut TcpStream) -> Result<()> {
    let mut buf = Vec::new();
    stream.read_to_end(&mut buf)?;
    let req: CacheRequest = bincode::deserialize(&buf)
        .map_err(|e| SearchError::Generic(format!("Failed to decode cache request: {}", e)))?;

    let resp = match req {
        CacheRequest::Get {
            file,
            query,
            case_sensitive,
            mtime_secs,
            file_size,
        } => {
            let ts = SystemTime::UNIX_EPOCH + Duration::from_secs(mtime_secs);
            let hit = local.get(&file, &query, case_sensitive, ts, file_size);
            CacheResponse::Get(hit)
        }
        CacheRequest::Set {
            file,
            query,
            case_sensitive,
            mtime_secs,
            file_size,
            results,
        } => {
            let ts = SystemTime::UNIX_EPOCH + Duration::from_secs(mtime_secs);
            let res = local.set(&file, &query, case_sensitive, ts, file_size, &results);
            CacheResponse::Ack(res.is_ok())
        }
        CacheRequest::Clear => {
            let res = local.clear();
            CacheResponse::Ack(res.is_ok())
        }
        CacheRequest::Ping => CacheResponse::Ack(true),
    };

    let resp_bytes = bincode::serialize(&resp)
        .map_err(|e| SearchError::Generic(format!("Failed to encode cache response: {}", e)))?;
    stream.write_all(&resp_bytes)?;
    let _ = stream.shutdown(Shutdown::Write);
    Ok(())
}

/// ---------- Helpers ----------
fn cache_port_path(cache_dir: &Path) -> PathBuf {
    cache_dir.join(PORT_FILE)
}

fn write_port_file(cache_dir: &Path, addr: &str) -> Result<()> {
    fs::write(cache_port_path(cache_dir), addr)
        .map_err(|e| SearchError::Generic(format!("Failed to write cache port: {}", e)))
}

fn read_port_file() -> Option<String> {
    let path = cache_port_path(&LocalCache::cache_dir());
    fs::read_to_string(path).ok().map(|s| s.trim().to_string())
}

fn spawn_server() -> Result<()> {
    let exe = resolve_server_binary()?;

    Command::new(exe)
        .arg(SERVER_FLAG)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| SearchError::Generic(format!("Failed to spawn cache server: {}", e)))?;
    std::thread::sleep(Duration::from_millis(150));
    Ok(())
}

fn resolve_server_binary() -> Result<PathBuf> {
    let exe = std::env::current_exe()
        .map_err(|e| SearchError::Generic(format!("Failed to get current exe: {}", e)))?;

    let bin_name = if cfg!(target_os = "windows") {
        "cs.exe"
    } else {
        "cs"
    };

    // Prefer the real CLI binary (in target/debug or target/release) before falling back to the
    // current executable (which is a test harness when running integration tests).
    let mut candidates = Vec::new();
    if let Some(dir) = exe.parent() {
        candidates.push(dir.join(bin_name));
        if let Some(parent) = dir.parent() {
            candidates.push(parent.join(bin_name));
        }
    }
    candidates.push(exe.clone());

    for path in candidates {
        if path.exists() {
            return Ok(path);
        }
    }

    Err(SearchError::Generic(
        "Could not locate cache server binary".to_string(),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::{NamedTempFile, TempDir};

    #[test]
    fn test_cache_hit_local() {
        let cache_dir = TempDir::new().unwrap();
        let cache = SearchResultCache::with_cache_dir(cache_dir.path().to_path_buf()).unwrap();
        let file = NamedTempFile::new().unwrap();
        fs::write(&file, "test content").unwrap();

        let metadata = fs::metadata(file.path()).unwrap();
        let mtime = metadata.modified().unwrap();
        let size = metadata.len();

        let results = vec![TranslationEntry {
            key: "test.key".to_string(),
            value: "test value".to_string(),
            file: file.path().to_path_buf(),
            line: 1,
        }];

        cache
            .set(file.path(), "query", false, mtime, size, &results)
            .unwrap();
        let cached = cache.get(file.path(), "query", false, mtime, size);
        assert!(cached.is_some());
        assert_eq!(cached.unwrap().len(), 1);
    }

    #[test]
    fn test_cache_invalidation_on_file_change_local() {
        let cache_dir = TempDir::new().unwrap();
        let cache = SearchResultCache::with_cache_dir(cache_dir.path().to_path_buf()).unwrap();
        let file = NamedTempFile::new().unwrap();
        fs::write(&file, "original content").unwrap();

        let metadata = fs::metadata(file.path()).unwrap();
        let mtime = metadata.modified().unwrap();
        let size = metadata.len();

        let results = vec![TranslationEntry {
            key: "test.key".to_string(),
            value: "test value".to_string(),
            file: file.path().to_path_buf(),
            line: 1,
        }];

        cache
            .set(file.path(), "query", false, mtime, size, &results)
            .unwrap();

        std::thread::sleep(std::time::Duration::from_secs(1));
        fs::write(&file, "modified content with different size").unwrap();

        let new_metadata = fs::metadata(file.path()).unwrap();
        let new_mtime = new_metadata.modified().unwrap();
        let new_size = new_metadata.len();

        assert!(new_size != size || new_mtime != mtime);

        let cached = cache.get(file.path(), "query", false, new_mtime, new_size);
        assert!(cached.is_none());
    }

    #[test]
    fn test_case_insensitive_normalization_local() {
        let cache_dir = TempDir::new().unwrap();
        let cache = SearchResultCache::with_cache_dir(cache_dir.path().to_path_buf()).unwrap();
        let file = NamedTempFile::new().unwrap();
        fs::write(&file, "test content").unwrap();

        let metadata = fs::metadata(file.path()).unwrap();
        let mtime = metadata.modified().unwrap();
        let size = metadata.len();

        let results = vec![TranslationEntry {
            key: "test.key".to_string(),
            value: "test value".to_string(),
            file: file.path().to_path_buf(),
            line: 1,
        }];

        cache
            .set(file.path(), "query", false, mtime, size, &results)
            .unwrap();

        let cached = cache.get(file.path(), "QUERY", false, mtime, size);
        assert!(cached.is_some());
    }
}