ryo-storage 0.1.0

Persistent storage and transaction log for RYO
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
//! TxLogger: Async transaction logger with background thread
//!
//! Provides non-blocking logging via a channel-based architecture.
//! The background thread collects entries and can be joined to retrieve the final log.

use super::entry::{MutationRecord, TxAction, TxEntry};
use super::log::TxLog;
use crate::storage::StateRef;
use ryo_analysis::SymbolPath;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread::{self, JoinHandle};
use std::time::Instant;

/// Message sent to the background logger thread
enum LoggerMessage {
    /// Log an action
    Log(TxAction),

    /// Log an action with duration
    LogWithDuration(TxAction, u64),

    /// Shutdown and return the log
    Shutdown,
}

/// Async transaction logger
///
/// Uses a background thread to collect log entries without blocking the caller.
pub struct TxLogger {
    sender: Sender<LoggerMessage>,
    handle: Option<JoinHandle<TxLog>>,
    session_start: Instant,
}

impl TxLogger {
    /// Start a new logger with a background thread
    pub fn start(project_path: impl Into<PathBuf>, file_count: usize) -> Self {
        let project_path: PathBuf = project_path.into();
        let project_path_for_thread = project_path.clone();
        let project_path_for_log = project_path.clone();
        let (sender, receiver) = mpsc::channel();
        let session_start = Instant::now();

        let handle = thread::spawn(move || {
            Self::background_worker(receiver, project_path_for_thread, file_count, session_start)
        });

        let logger = Self {
            sender,
            handle: Some(handle),
            session_start,
        };

        // Log session start
        logger.log(TxAction::SessionStart {
            project_path: project_path_for_log,
            file_count,
        });

        logger
    }

    /// Background worker that collects log entries
    fn background_worker(
        receiver: Receiver<LoggerMessage>,
        project_path: PathBuf,
        _file_count: usize,
        session_start: Instant,
    ) -> TxLog {
        let mut log = TxLog::with_project(project_path.to_string_lossy().to_string());
        let mut next_id: u64 = 0;

        loop {
            match receiver.recv() {
                Ok(LoggerMessage::Log(action)) => {
                    let timestamp_ms = session_start.elapsed().as_millis() as u64;
                    log.push(TxEntry::new(next_id, timestamp_ms, action));
                    next_id += 1;
                }
                Ok(LoggerMessage::LogWithDuration(action, duration_us)) => {
                    let timestamp_ms = session_start.elapsed().as_millis() as u64;
                    log.push(
                        TxEntry::new(next_id, timestamp_ms, action).with_duration(duration_us),
                    );
                    next_id += 1;
                }
                Ok(LoggerMessage::Shutdown) => {
                    break;
                }
                Err(_) => {
                    // Channel closed, exit
                    break;
                }
            }
        }

        log.end_session();
        log
    }

    // =========================================================================
    // Core logging methods
    // =========================================================================

    /// Log an action (non-blocking)
    pub fn log(&self, action: TxAction) {
        let _ = self.sender.send(LoggerMessage::Log(action));
    }

    /// Log an action with measured duration
    pub fn log_with_duration(&self, action: TxAction, duration_us: u64) {
        let _ = self
            .sender
            .send(LoggerMessage::LogWithDuration(action, duration_us));
    }

    /// Log a timed action (measures duration automatically)
    pub fn log_timed<F, R>(&self, action_fn: F, make_action: impl FnOnce(R) -> TxAction) -> R
    where
        F: FnOnce() -> R,
    {
        let start = Instant::now();
        let result = action_fn();
        let duration_us = start.elapsed().as_micros() as u64;
        let action = make_action(result);
        self.log_with_duration(action, duration_us);
        // Note: This consumes result in make_action, so we need a different approach
        // for returning the result. Let's use a simpler pattern instead.
        unreachable!() // This method needs redesign
    }

    // =========================================================================
    // Convenience methods
    // =========================================================================

    /// Log a goal being set
    pub fn log_goal(&self, query: &str, intent_type: &str, confidence: f64) {
        self.log(TxAction::GoalSet {
            query: query.to_string(),
            intent_type: intent_type.to_string(),
            confidence,
        });
    }

    /// Log a mutation being applied (legacy API - NOT replayable)
    ///
    /// **Note**: This method does not record mutation_data, so the logged
    /// mutation cannot be replayed. For replayable logging, use `record_mutation()`.
    pub fn log_mutation(&self, mutation_type: &str, target: &str, changes: usize) {
        self.log(TxAction::MutationApplied {
            mutation_type: mutation_type.to_string(),
            target: target.to_string(),
            changes,
            mutation_data: None,
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
    }

    /// Record a mutation with automatic serialization (REPLAYABLE)
    ///
    /// This is the preferred method for logging mutations. It automatically
    /// serializes the mutation for replay capability.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use ryo_core::mutation::{RenameMutation, ToSerializable};
    ///
    /// let mutation = RenameMutation { from: "foo".into(), to: "bar".into() };
    /// let result = mutation.apply(&mut file);
    /// logger.record_mutation(&mutation, result.changes);
    /// ```
    pub fn record_mutation<M>(&self, mutation: &M, changes: usize)
    where
        M: ryo_mutations::Mutation + ryo_mutations::ToSerializable,
    {
        let serializable = mutation.to_serializable();
        self.log(TxAction::MutationApplied {
            mutation_type: mutation.mutation_type().to_string(),
            target: mutation.describe(),
            changes,
            mutation_data: Some(serializable.to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
    }

    /// Record a mutation with file path (REPLAYABLE)
    ///
    /// Like `record_mutation()` but also records the file path for multi-file replay.
    pub fn record_mutation_for_file<M>(
        &self,
        mutation: &M,
        changes: usize,
        file_path: impl AsRef<Path>,
    ) where
        M: ryo_mutations::Mutation + ryo_mutations::ToSerializable,
    {
        let serializable = mutation.to_serializable();
        self.log(TxAction::MutationApplied {
            mutation_type: mutation.mutation_type().to_string(),
            target: mutation.describe(),
            changes,
            mutation_data: Some(serializable.to_json()),
            file_path: Some(file_path.as_ref().to_path_buf()),
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
    }

    /// Record a mutation with full state tracking (REPLAYABLE + VERIFIABLE)
    ///
    /// This is the most complete logging method. It records:
    /// - Mutation specification (for reconstruction)
    /// - File path (for multi-file support)
    /// - Pre/post state references (for deterministic verification)
    pub fn record_mutation_tracked<M>(
        &self,
        mutation: &M,
        changes: usize,
        file_path: impl AsRef<Path>,
        pre_state: StateRef,
        post_state: StateRef,
    ) where
        M: ryo_mutations::Mutation + ryo_mutations::ToSerializable,
    {
        let serializable = mutation.to_serializable();
        self.log(TxAction::MutationApplied {
            mutation_type: mutation.mutation_type().to_string(),
            target: mutation.describe(),
            changes,
            mutation_data: Some(serializable.to_json()),
            file_path: Some(file_path.as_ref().to_path_buf()),
            pre_state: Some(pre_state),
            post_state: Some(post_state),
            affected_symbols: vec![],
        });
    }

    /// Record a mutation with affected symbols (for history tracking)
    ///
    /// This method records the symbols affected by the mutation,
    /// enabling symbol-based history queries via `TxLog::mutations_affecting()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mutation = RenameMutation { from: "foo".into(), to: "bar".into() };
    /// let affected = vec![SymbolPath::from_str("test_crate::module::foo")];
    /// logger.record_mutation_with_symbols(&mutation, 5, affected);
    /// ```
    pub fn record_mutation_with_symbols<M>(
        &self,
        mutation: &M,
        changes: usize,
        affected_symbols: Vec<SymbolPath>,
    ) where
        M: ryo_mutations::Mutation + ryo_mutations::ToSerializable,
    {
        let serializable = mutation.to_serializable();
        self.log(TxAction::MutationApplied {
            mutation_type: mutation.mutation_type().to_string(),
            target: mutation.describe(),
            changes,
            mutation_data: Some(serializable.to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols,
        });
    }

    /// Record a mutation with full tracking (file, state, symbols)
    ///
    /// The most complete logging method, combining:
    /// - Mutation specification (for replay)
    /// - File path (for multi-file support)
    /// - Pre/post state (for verification)
    /// - Affected symbols (for history tracking)
    pub fn record_mutation_full<M>(
        &self,
        mutation: &M,
        changes: usize,
        file_path: impl AsRef<Path>,
        pre_state: StateRef,
        post_state: StateRef,
        affected_symbols: Vec<SymbolPath>,
    ) where
        M: ryo_mutations::Mutation + ryo_mutations::ToSerializable,
    {
        let serializable = mutation.to_serializable();
        self.log(TxAction::MutationApplied {
            mutation_type: mutation.mutation_type().to_string(),
            target: mutation.describe(),
            changes,
            mutation_data: Some(serializable.to_json()),
            file_path: Some(file_path.as_ref().to_path_buf()),
            pre_state: Some(pre_state),
            post_state: Some(post_state),
            affected_symbols,
        });
    }

    /// Log a mutation with serialized data (for replay)
    pub fn log_mutation_with_data(
        &self,
        mutation_type: &str,
        target: &str,
        changes: usize,
        data: serde_json::Value,
    ) {
        self.log(TxAction::MutationApplied {
            mutation_type: mutation_type.to_string(),
            target: target.to_string(),
            changes,
            mutation_data: Some(data),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
    }

    /// Log a batch of mutations
    pub fn log_mutation_batch(&self, mutations: Vec<MutationRecord>, total_changes: usize) {
        self.log(TxAction::MutationBatch {
            mutations,
            total_changes,
        });
    }

    /// Log file loaded
    pub fn log_file_loaded(&self, path: &Path, size_bytes: usize) {
        self.log(TxAction::FileLoaded {
            path: path.to_path_buf(),
            size_bytes,
        });
    }

    /// Log file modified
    pub fn log_file_modified(&self, path: &Path, changes: usize) {
        self.log(TxAction::FileModified {
            path: path.to_path_buf(),
            changes,
        });
    }

    /// Log file written to disk
    pub fn log_file_written(&self, path: &Path) {
        self.log(TxAction::FileWritten {
            path: path.to_path_buf(),
        });
    }

    /// Log compile check result
    pub fn log_compile_check(&self, success: bool, errors: Vec<String>) {
        self.log(TxAction::CompileCheck {
            success,
            error_count: errors.len(),
            errors,
        });
    }

    /// Create a checkpoint
    pub fn checkpoint(&self, name: &str) {
        self.log(TxAction::Checkpoint {
            name: name.to_string(),
        });
    }

    /// Log an undo operation
    pub fn log_undo(&self, target_id: u64) {
        self.log(TxAction::Undo { target_id });
    }

    /// Log a redo operation
    pub fn log_redo(&self, target_id: u64) {
        self.log(TxAction::Redo { target_id });
    }

    /// Log a custom action
    pub fn log_custom(&self, name: &str, data: serde_json::Value) {
        self.log(TxAction::Custom {
            name: name.to_string(),
            data,
        });
    }

    // =========================================================================
    // Session management
    // =========================================================================

    /// Get elapsed time since session start
    pub fn elapsed_ms(&self) -> u64 {
        self.session_start.elapsed().as_millis() as u64
    }

    /// Finish logging and retrieve the complete log
    ///
    /// This shuts down the background thread and returns the collected log.
    pub fn finish(mut self) -> TxLog {
        // Send shutdown signal
        let _ = self.sender.send(LoggerMessage::Shutdown);

        // Take ownership of the handle (Option::take returns owned value)
        match self.handle.take() {
            Some(handle) => handle.join().unwrap_or_else(|_| TxLog::new()),
            None => TxLog::new(),
        }
    }

    /// Finish and dump to JSON file
    pub fn finish_and_dump(self, path: &Path) -> std::io::Result<TxLog> {
        let log = self.finish();
        log.dump_json(path)?;
        Ok(log)
    }
}

impl Drop for TxLogger {
    fn drop(&mut self) {
        // If not already finished, send shutdown signal
        let _ = self.sender.send(LoggerMessage::Shutdown);
        // Note: We can't join here because we'd need to take ownership of handle
    }
}

// ============================================================================
// Sync Logger (for simpler use cases)
// ============================================================================

#[cfg(test)]
/// Synchronous logger for testing only.
struct TxLoggerSync {
    log: TxLog,
}

#[cfg(test)]
impl TxLoggerSync {
    fn new(project_path: impl Into<std::path::PathBuf>, file_count: usize) -> Self {
        let project_path = project_path.into();
        let mut log = TxLog::with_project(project_path.to_string_lossy().to_string());
        log.log(TxAction::SessionStart {
            project_path,
            file_count,
        });
        Self { log }
    }

    fn log_goal(&mut self, query: &str, intent_type: &str, confidence: f64) {
        self.log.log(TxAction::GoalSet {
            query: query.to_string(),
            intent_type: intent_type.to_string(),
            confidence,
        });
    }

    fn log_mutation(&mut self, mutation_type: &str, target: &str, changes: usize) {
        self.log.log(TxAction::MutationApplied {
            mutation_type: mutation_type.to_string(),
            target: target.to_string(),
            changes,
            mutation_data: None,
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
    }

    fn checkpoint(&mut self, name: &str) {
        self.log.log(TxAction::Checkpoint {
            name: name.to_string(),
        });
    }

    fn finish(mut self) -> TxLog {
        self.log.end_session();
        self.log
    }
}

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

    #[test]
    fn test_async_logger() {
        let logger = TxLogger::start("/test/project", 10);

        logger.log_goal("rename foo", "RenameIdent", 0.9);
        logger.log_mutation("Rename", "foo -> bar", 5);
        logger.checkpoint("after_rename");
        logger.log_file_modified(Path::new("/test.rs"), 3);

        // Small delay to ensure messages are processed
        thread::sleep(Duration::from_millis(10));

        let log = logger.finish();

        assert!(log.len() >= 4); // SessionStart + Goal + Mutation + Checkpoint + FileModified

        let summary = log.summary();
        assert!(summary.total_mutations >= 1);
        assert!(summary.checkpoints.contains(&"after_rename".to_string()));
    }

    #[test]
    fn test_sync_logger() {
        let mut logger = TxLoggerSync::new("/test/project", 10);

        logger.log_goal("test query", "TestIntent", 1.0);
        logger.log_mutation("AddField", "MyStruct.field", 1);
        logger.checkpoint("done");

        let log = logger.finish();

        assert_eq!(log.len(), 4); // SessionStart + Goal + Mutation + Checkpoint

        let summary = log.summary();
        assert_eq!(summary.total_mutations, 1);
    }
}