sqry-core 11.0.1

Core library for sqry - semantic code search engine
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
//! Progress reporting for indexing operations.
//!
//! This module provides types for tracking and reporting progress during
//! graph indexing operations. Progress events can be used to implement
//! progress bars, logging, or other user feedback mechanisms.
//!
//! # Example
//!
//! ```rust
//! use sqry_core::progress::{IndexProgress, ProgressReporter};
//! use std::sync::Arc;
//!
//! struct ConsoleProgress;
//!
//! impl ProgressReporter for ConsoleProgress {
//!     fn report(&self, event: IndexProgress) {
//!         match event {
//!             IndexProgress::Started { total_files } => {
//!                 println!("Starting to index {} files...", total_files);
//!             }
//!             IndexProgress::FileCompleted { path, symbols } => {
//!                 println!("Processed {:?}: {} items", path, symbols);
//!             }
//!             IndexProgress::Completed { total_symbols, duration } => {
//!                 println!("Indexed {} items in {:?}", total_symbols, duration);
//!             }
//!             _ => {}
//!         }
//!     }
//! }
//!
//! // Use ConsoleProgress when building graphs with progress reporting
//! let reporter: Arc<dyn ProgressReporter> = Arc::new(ConsoleProgress);
//! ```

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::graph::NodeKind;

/// Progress events emitted during indexing operations.
///
/// # Stability
///
/// This enum is marked `#[non_exhaustive]` to allow adding new progress events
/// in future versions without breaking downstream code. Always include a
/// wildcard arm (`_ => {}`) when matching on this enum.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum IndexProgress {
    // === File Processing Events ===
    /// Indexing has started.
    Started {
        /// Total number of files to process
        total_files: usize,
    },

    /// A file is currently being processed.
    FileProcessing {
        /// Path to the file being processed
        path: PathBuf,
        /// Current file number (1-based)
        current: usize,
        /// Total number of files
        total: usize,
    },

    /// A file has been processed successfully.
    FileCompleted {
        /// Path to the completed file
        path: PathBuf,
        /// Number of items extracted from this file
        symbols: usize,
    },

    // === Ingest Progress ===
    /// Progress while ingesting nodes and relations into the index.
    IngestProgress {
        /// Files ingested so far
        files_processed: usize,
        /// Total files to ingest
        total_files: usize,
        /// Total items ingested so far
        total_symbols: usize,
        /// Node-kind breakdown
        counts: NodeIngestCounts,
        /// Elapsed time for ingestion
        elapsed: Duration,
        /// Estimated remaining time (best-effort)
        eta: Option<Duration>,
    },

    /// A file is about to be ingested into the index.
    IngestFileStarted {
        /// Path to the file being ingested
        path: PathBuf,
        /// Current file number (1-based)
        current: usize,
        /// Total number of files to ingest
        total: usize,
    },

    /// A file has finished ingesting into the index.
    IngestFileCompleted {
        /// Path to the ingested file
        path: PathBuf,
        /// Number of items ingested from this file
        symbols: usize,
        /// Duration of the ingest work for this file
        duration: Duration,
    },

    // === Stage Events ===
    /// A coarse-grained indexing stage has started.
    StageStarted {
        /// Human-readable stage name (e.g., "Resolve imports")
        /// Uses `&'static str` to avoid allocations.
        stage_name: &'static str,
    },

    /// A coarse-grained indexing stage has completed.
    StageCompleted {
        /// Human-readable stage name
        stage_name: &'static str,
        /// Duration of the stage
        stage_duration: Duration,
    },

    // === Graph Building Events ===
    /// A graph build phase has started.
    GraphPhaseStarted {
        /// Phase number (1-4)
        phase_number: u8,
        /// Human-readable phase name (e.g., "AST extraction")
        /// Uses `&'static str` to avoid allocations in hot paths.
        phase_name: &'static str,
        /// Total items to process in this phase
        total_items: usize,
    },

    /// Progress within a graph build phase.
    GraphPhaseProgress {
        /// Phase number (1-4)
        phase_number: u8,
        /// Number of items processed so far
        items_processed: usize,
        /// Total items in this phase
        total_items: usize,
    },

    /// A graph build phase has completed.
    GraphPhaseCompleted {
        /// Phase number (1-4)
        phase_number: u8,
        /// Human-readable phase name
        phase_name: &'static str,
        /// Duration of this phase
        phase_duration: Duration,
    },

    // === Index Saving Events ===
    /// Index save operation has started for a component.
    SavingStarted {
        /// Component being saved (e.g., "symbols", "trigrams", "unified graph")
        /// Uses `&'static str` to avoid allocations.
        component_name: &'static str,
    },

    /// Index save operation has completed for a component.
    SavingCompleted {
        /// Component that was saved
        component_name: &'static str,
        /// Duration of the save operation
        save_duration: Duration,
    },

    // === Completion Event ===
    /// Indexing has completed.
    Completed {
        /// Total number of items indexed
        total_symbols: usize,
        /// Duration of the indexing operation
        duration: Duration,
    },
}

/// Trait for reporting progress during indexing operations.
///
/// Implementors can display progress bars, log events, or perform
/// other actions in response to indexing progress.
///
/// # Thread Safety
///
/// Implementations must be `Send + Sync` to support parallel indexing.
/// Progress events may be reported from multiple threads concurrently.
pub trait ProgressReporter: Send + Sync {
    /// Report a progress event.
    ///
    /// This method is called during indexing to report progress.
    /// Implementations should be non-blocking to avoid slowing down
    /// the indexing process.
    fn report(&self, event: IndexProgress);
}

/// Helper for emitting coarse-grained stage progress.
pub struct ProgressStage {
    reporter: SharedReporter,
    stage_name: &'static str,
    start: Instant,
}

impl ProgressStage {
    /// Emit a stage start event and return a timer for completion.
    #[must_use]
    pub fn start(reporter: &SharedReporter, stage_name: &'static str) -> Self {
        reporter.report(IndexProgress::StageStarted { stage_name });
        Self {
            reporter: Arc::clone(reporter),
            stage_name,
            start: Instant::now(),
        }
    }

    /// Emit a stage completion event.
    pub fn finish(self) {
        self.reporter.report(IndexProgress::StageCompleted {
            stage_name: self.stage_name,
            stage_duration: self.start.elapsed(),
        });
    }
}

/// Node-kind counters for ingestion progress reporting.
#[derive(Debug, Clone, Default)]
pub struct NodeIngestCounts {
    /// Function nodes.
    pub functions: usize,
    /// Class nodes.
    pub classes: usize,
    /// Method nodes.
    pub methods: usize,
    /// Struct nodes.
    pub structs: usize,
    /// Enum nodes.
    pub enums: usize,
    /// Interface/trait nodes.
    pub interfaces: usize,
    /// Variable-like nodes (variables, properties, parameters).
    pub variables: usize,
    /// Constant nodes.
    pub constants: usize,
    /// Type alias nodes.
    pub types: usize,
    /// Module nodes.
    pub modules: usize,
    /// All other nodes not covered by the explicit buckets.
    pub other: usize,
}

impl NodeIngestCounts {
    /// Add a single node kind to the appropriate counter.
    pub fn add_node_kind(&mut self, kind: &NodeKind) {
        match kind {
            NodeKind::Function { .. } => self.functions += 1,
            NodeKind::Class { .. } => self.classes += 1,
            NodeKind::Module { .. } => self.modules += 1,
            NodeKind::Variable { .. } => self.variables += 1,
        }
    }

    /// Add a slice of node kinds to the counters.
    pub fn add_node_kinds(&mut self, kinds: &[NodeKind]) {
        for kind in kinds {
            self.add_node_kind(kind);
        }
    }

    /// Total number of nodes across all buckets.
    #[must_use]
    pub fn total(&self) -> usize {
        self.functions
            + self.classes
            + self.methods
            + self.structs
            + self.enums
            + self.interfaces
            + self.variables
            + self.constants
            + self.types
            + self.modules
            + self.other
    }
}

/// Time-throttled ingestion progress tracker.
pub struct IngestProgressTracker {
    reporter: SharedReporter,
    total_files: usize,
    processed_files: usize,
    counts: NodeIngestCounts,
    start: Instant,
    last_emit: Instant,
}

impl IngestProgressTracker {
    /// Create a new ingestion progress tracker.
    #[must_use]
    pub fn new(reporter: &SharedReporter, total_files: usize) -> Self {
        let now = Instant::now();
        Self {
            reporter: Arc::clone(reporter),
            total_files,
            processed_files: 0,
            counts: NodeIngestCounts::default(),
            start: now,
            last_emit: now,
        }
    }

    /// Record the node kinds ingested for one file and emit a progress update if needed.
    pub fn record_node_kinds(&mut self, kinds: &[NodeKind]) {
        self.processed_files = self.processed_files.saturating_add(1);
        self.counts.add_node_kinds(kinds);
        self.maybe_emit(false);
    }

    /// Emit a final progress update.
    pub fn finish(&mut self) {
        self.maybe_emit(true);
    }

    fn maybe_emit(&mut self, force: bool) {
        let now = Instant::now();
        let elapsed = now.duration_since(self.start);
        if !force && now.duration_since(self.last_emit) < Duration::from_millis(800) {
            return;
        }
        self.last_emit = now;

        let eta = self.estimate_eta(elapsed);
        self.reporter.report(IndexProgress::IngestProgress {
            files_processed: self.processed_files,
            total_files: self.total_files,
            total_symbols: self.counts.total(),
            counts: self.counts.clone(),
            elapsed,
            eta,
        });
    }

    fn estimate_eta(&self, elapsed: Duration) -> Option<Duration> {
        if self.processed_files == 0 || self.total_files == 0 {
            return None;
        }
        let elapsed_nanos = elapsed.as_nanos();
        if elapsed_nanos == 0 {
            return None;
        }
        let processed_files = u128::from(self.processed_files as u64);
        let remaining_files =
            u128::from(self.total_files.saturating_sub(self.processed_files) as u64);
        if processed_files == 0 || remaining_files == 0 {
            return Some(Duration::from_secs(0));
        }
        let nanos_per_file = elapsed_nanos / processed_files;
        let remaining_nanos = nanos_per_file.saturating_mul(remaining_files);
        let remaining_nanos_u64 = u64::try_from(remaining_nanos).ok()?;
        Some(Duration::from_nanos(remaining_nanos_u64))
    }
}

/// A no-op progress reporter that discards all events.
///
/// This is the default reporter used when no progress reporting is needed.
#[derive(Debug, Clone, Copy)]
pub struct NoOpReporter;

impl ProgressReporter for NoOpReporter {
    fn report(&self, _event: IndexProgress) {
        // Intentionally empty - no progress reporting
    }
}

/// Type alias for a shared progress reporter.
pub type SharedReporter = Arc<dyn ProgressReporter>;

/// Creates a new no-op reporter.
///
/// This is useful as a default when no progress reporting is needed.
#[must_use]
pub fn no_op_reporter() -> SharedReporter {
    Arc::new(NoOpReporter)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    struct TestReporter {
        events: Mutex<Vec<IndexProgress>>,
    }

    impl TestReporter {
        fn new() -> Self {
            Self {
                events: Mutex::new(Vec::new()),
            }
        }

        fn events(&self) -> Vec<IndexProgress> {
            self.events.lock().unwrap().clone()
        }
    }

    impl ProgressReporter for TestReporter {
        fn report(&self, event: IndexProgress) {
            self.events.lock().unwrap().push(event);
        }
    }

    #[test]
    fn test_progress_event_sequence() {
        let reporter = TestReporter::new();

        // Simulate indexing progress
        reporter.report(IndexProgress::Started { total_files: 2 });
        reporter.report(IndexProgress::FileProcessing {
            path: PathBuf::from("file1.rs"),
            current: 1,
            total: 2,
        });
        reporter.report(IndexProgress::FileCompleted {
            path: PathBuf::from("file1.rs"),
            symbols: 10,
        });
        reporter.report(IndexProgress::FileProcessing {
            path: PathBuf::from("file2.rs"),
            current: 2,
            total: 2,
        });
        reporter.report(IndexProgress::FileCompleted {
            path: PathBuf::from("file2.rs"),
            symbols: 15,
        });
        reporter.report(IndexProgress::Completed {
            total_symbols: 25,
            duration: Duration::from_secs(1),
        });

        let events = reporter.events();
        assert_eq!(events.len(), 6);

        // Verify event types in order
        matches!(events[0], IndexProgress::Started { .. });
        matches!(events[1], IndexProgress::FileProcessing { .. });
        matches!(events[2], IndexProgress::FileCompleted { .. });
        matches!(events[3], IndexProgress::FileProcessing { .. });
        matches!(events[4], IndexProgress::FileCompleted { .. });
        matches!(events[5], IndexProgress::Completed { .. });
    }

    #[test]
    fn test_no_op_reporter() {
        let reporter = no_op_reporter();

        // Should not panic or produce side effects
        reporter.report(IndexProgress::Started { total_files: 5 });
        reporter.report(IndexProgress::Completed {
            total_symbols: 100,
            duration: Duration::from_millis(500),
        });
    }

    #[test]
    fn test_reporter_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<NoOpReporter>();
        assert_send_sync::<TestReporter>();
    }
}