ceres-core 0.4.0

Core types, harvesting logic, and services for Ceres
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
//! Progress reporting for harvest operations.
//!
//! This module provides a trait-based abstraction for reporting progress during
//! harvest operations, enabling decoupled logging and UI updates.

use std::time::Duration;

use crate::{BatchHarvestSummary, SyncStats};

/// Events emitted during harvesting operations.
///
/// These events provide fine-grained progress information that consumers
/// can use for logging, UI updates, or metrics collection.
#[derive(Debug, Clone)]
pub enum HarvestEvent<'a> {
    /// Batch harvest starting.
    BatchStarted {
        /// Total number of portals to harvest.
        total_portals: usize,
    },

    /// Single portal harvest starting.
    PortalStarted {
        /// Zero-based index of the current portal.
        portal_index: usize,
        /// Total number of portals in batch.
        total_portals: usize,
        /// Portal name identifier.
        portal_name: &'a str,
        /// Portal URL.
        portal_url: &'a str,
    },

    /// Found existing datasets in database for portal.
    ExistingDatasetsFound {
        /// Number of existing datasets.
        count: usize,
    },

    /// Found datasets on the portal.
    PortalDatasetsFound {
        /// Number of datasets found.
        count: usize,
    },

    /// Progress update during dataset processing.
    DatasetProcessed {
        /// Number of datasets processed so far.
        current: usize,
        /// Total number of datasets to process.
        total: usize,
        /// Counts by outcome type.
        created: usize,
        /// Number of updated datasets.
        updated: usize,
        /// Number of unchanged datasets.
        unchanged: usize,
        /// Number of failed datasets.
        failed: usize,
        /// Number of datasets skipped due to circuit breaker.
        skipped: usize,
    },

    /// Single portal harvest completed successfully.
    PortalCompleted {
        /// Zero-based index of the current portal.
        portal_index: usize,
        /// Total number of portals in batch.
        total_portals: usize,
        /// Portal name identifier.
        portal_name: &'a str,
        /// Final statistics.
        stats: &'a SyncStats,
    },

    /// Single portal harvest failed.
    PortalFailed {
        /// Zero-based index of the current portal.
        portal_index: usize,
        /// Total number of portals in batch.
        total_portals: usize,
        /// Portal name identifier.
        portal_name: &'a str,
        /// Error description.
        error: &'a str,
    },

    /// Batch harvest completed.
    BatchCompleted {
        /// Aggregated summary of all portal results.
        summary: &'a BatchHarvestSummary,
    },

    /// Single portal harvest was cancelled.
    PortalCancelled {
        /// Zero-based index of the current portal.
        portal_index: usize,
        /// Total number of portals in batch.
        total_portals: usize,
        /// Portal name identifier.
        portal_name: &'a str,
        /// Partial statistics at cancellation time.
        stats: &'a SyncStats,
    },

    /// Batch harvest was cancelled.
    BatchCancelled {
        /// Number of portals completed before cancellation.
        completed_portals: usize,
        /// Total number of portals in batch.
        total_portals: usize,
    },

    /// Datasets marked as stale after a successful full sync.
    StaleDetected {
        /// Number of datasets newly marked as stale.
        count: usize,
    },

    /// Circuit breaker is open, harvest pausing/failing.
    CircuitBreakerOpen {
        /// Service name.
        service: &'a str,
        /// Time until recovery attempt.
        retry_after: Duration,
    },

    /// Pre-processing phase (delta detection / hash check) starting.
    PreprocessingStarted {
        /// Total number of datasets to pre-process.
        total: usize,
    },

    /// Pre-processing phase completed — summary before finalization steps
    /// (stale detection).
    ///
    /// Note: in the streaming pipeline, preprocessing and persistence are
    /// interleaved, so this fires after both have completed.
    PreprocessingCompleted {
        /// Number of datasets that need persistence (created + updated).
        changed: usize,
        /// Number of datasets with identical content hash.
        unchanged: usize,
        /// Number of datasets that failed pre-processing.
        failed: usize,
    },
}

/// Trait for reporting harvest progress.
///
/// Implementors can provide CLI output, server event streams, metrics,
/// or any other form of progress reporting.
///
/// The default implementation does nothing (silent mode), which is
/// appropriate for library usage where the caller doesn't need progress updates.
///
/// # Example
///
/// ```
/// use ceres_core::progress::{ProgressReporter, HarvestEvent};
///
/// struct MyReporter;
///
/// impl ProgressReporter for MyReporter {
///     fn report(&self, event: HarvestEvent<'_>) {
///         match event {
///             HarvestEvent::PortalStarted { portal_name, .. } => {
///                 println!("Starting: {}", portal_name);
///             }
///             _ => {}
///         }
///     }
/// }
/// ```
pub trait ProgressReporter: Send + Sync {
    /// Called when a harvest event occurs.
    ///
    /// The default implementation does nothing (silent mode).
    fn report(&self, event: HarvestEvent<'_>) {
        // Default: do nothing (silent mode for library usage)
        let _ = event;
    }
}

/// A no-op reporter that ignores all events.
///
/// Use this when you don't need progress reporting (library mode).
#[derive(Debug, Default, Clone, Copy)]
pub struct SilentReporter;

impl ProgressReporter for SilentReporter {}

/// A reporter that logs events using the `tracing` crate.
///
/// This is suitable for CLI applications that want structured logging.
#[derive(Debug, Default, Clone, Copy)]
pub struct TracingReporter;

impl ProgressReporter for TracingReporter {
    fn report(&self, event: HarvestEvent<'_>) {
        use tracing::{error, info};

        match event {
            HarvestEvent::BatchStarted { total_portals } => {
                info!("Starting batch harvest of {} portal(s)", total_portals);
            }
            HarvestEvent::PortalStarted {
                portal_index,
                total_portals,
                portal_name,
                portal_url,
            } => {
                info!(
                    "[Portal {}/{}] {} ({})",
                    portal_index + 1,
                    total_portals,
                    portal_name,
                    portal_url
                );
            }
            HarvestEvent::ExistingDatasetsFound { count } => {
                info!("Found {} existing dataset(s) in database", count);
            }
            HarvestEvent::PortalDatasetsFound { count } => {
                info!("Found {} dataset(s) on portal", count);
            }
            HarvestEvent::DatasetProcessed {
                current,
                total,
                created,
                updated,
                unchanged,
                failed,
                skipped,
            } => {
                let pct = (current as f64 / total as f64 * 100.0) as u8;
                if skipped > 0 {
                    info!(
                        "Progress: {}/{} ({}%) - {} new, {} updated, {} unchanged, {} failed, {} skipped",
                        current, total, pct, created, updated, unchanged, failed, skipped
                    );
                } else {
                    info!(
                        "Progress: {}/{} ({}%) - {} new, {} updated, {} unchanged, {} failed",
                        current, total, pct, created, updated, unchanged, failed
                    );
                }
            }
            HarvestEvent::PortalCompleted {
                portal_index,
                total_portals,
                portal_name,
                stats,
            } => {
                info!(
                    "[Portal {}/{}] {} completed: {} dataset(s) ({} created, {} updated, {} unchanged)",
                    portal_index + 1,
                    total_portals,
                    portal_name,
                    stats.total(),
                    stats.created,
                    stats.updated,
                    stats.unchanged
                );
            }
            HarvestEvent::PortalFailed {
                portal_index,
                total_portals,
                portal_name,
                error,
            } => {
                error!(
                    "[Portal {}/{}] {} failed: {}",
                    portal_index + 1,
                    total_portals,
                    portal_name,
                    error
                );
            }
            HarvestEvent::BatchCompleted { summary } => {
                info!(
                    "Batch complete: {} portal(s), {} dataset(s) ({} successful, {} failed)",
                    summary.total_portals(),
                    summary.total_datasets(),
                    summary.successful_count(),
                    summary.failed_count()
                );
            }
            HarvestEvent::PortalCancelled {
                portal_index,
                total_portals,
                portal_name,
                stats,
            } => {
                info!(
                    "[Portal {}/{}] {} cancelled: {} dataset(s) processed ({} created, {} updated, {} unchanged)",
                    portal_index + 1,
                    total_portals,
                    portal_name,
                    stats.total(),
                    stats.created,
                    stats.updated,
                    stats.unchanged
                );
            }
            HarvestEvent::BatchCancelled {
                completed_portals,
                total_portals,
            } => {
                info!(
                    "Batch cancelled: {}/{} portal(s) completed before cancellation",
                    completed_portals, total_portals
                );
            }
            HarvestEvent::StaleDetected { count } => {
                use tracing::warn;
                warn!(
                    "{} dataset(s) marked as stale (no longer found on portal)",
                    count
                );
            }
            HarvestEvent::CircuitBreakerOpen {
                service,
                retry_after,
            } => {
                use tracing::warn;
                warn!(
                    "Circuit breaker '{}' is open. Retry after {} seconds.",
                    service,
                    retry_after.as_secs()
                );
            }
            HarvestEvent::PreprocessingStarted { total } => {
                info!("Pre-processing {} dataset(s) (delta detection)...", total);
            }
            HarvestEvent::PreprocessingCompleted {
                changed,
                unchanged,
                failed,
            } => {
                info!(
                    "Pre-processing complete: {} changed, {} unchanged, {} failed",
                    changed, unchanged, failed
                );
            }
        }
    }
}

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

    #[test]
    fn test_silent_reporter_does_nothing() {
        let reporter = SilentReporter;
        // Should not panic
        reporter.report(HarvestEvent::BatchStarted { total_portals: 5 });
    }

    #[test]
    fn test_tracing_reporter_handles_all_events() {
        let reporter = TracingReporter;

        // Test all event variants don't panic
        reporter.report(HarvestEvent::BatchStarted { total_portals: 2 });
        reporter.report(HarvestEvent::PortalStarted {
            portal_index: 0,
            total_portals: 2,
            portal_name: "test",
            portal_url: "https://example.com",
        });
        reporter.report(HarvestEvent::ExistingDatasetsFound { count: 10 });
        reporter.report(HarvestEvent::PortalDatasetsFound { count: 20 });
        reporter.report(HarvestEvent::DatasetProcessed {
            current: 10,
            total: 20,
            created: 2,
            updated: 3,
            unchanged: 5,
            failed: 0,
            skipped: 0,
        });

        let stats = SyncStats {
            unchanged: 5,
            updated: 3,
            created: 2,
            failed: 0,
            skipped: 0,
        };
        reporter.report(HarvestEvent::PortalCompleted {
            portal_index: 0,
            total_portals: 2,
            portal_name: "test",
            stats: &stats,
        });
        reporter.report(HarvestEvent::PortalFailed {
            portal_index: 1,
            total_portals: 2,
            portal_name: "test2",
            error: "connection failed",
        });

        let summary = BatchHarvestSummary::new();
        reporter.report(HarvestEvent::BatchCompleted { summary: &summary });

        // Test cancellation events
        reporter.report(HarvestEvent::PortalCancelled {
            portal_index: 0,
            total_portals: 2,
            portal_name: "test",
            stats: &stats,
        });
        reporter.report(HarvestEvent::BatchCancelled {
            completed_portals: 1,
            total_portals: 3,
        });

        // Test stale detection events
        reporter.report(HarvestEvent::StaleDetected { count: 5 });

        // Test circuit breaker events
        reporter.report(HarvestEvent::CircuitBreakerOpen {
            service: "gemini",
            retry_after: Duration::from_secs(30),
        });

        // Test preprocessing events
        reporter.report(HarvestEvent::PreprocessingStarted { total: 100 });
        reporter.report(HarvestEvent::PreprocessingCompleted {
            changed: 10,
            unchanged: 85,
            failed: 5,
        });
    }

    #[test]
    fn test_default_implementations() {
        let silent = SilentReporter;
        silent.report(HarvestEvent::BatchStarted { total_portals: 1 });

        let tracing = TracingReporter;
        tracing.report(HarvestEvent::BatchStarted { total_portals: 1 });
    }
}