arf-console 0.7.0-beta.1

A cross-platform R console written in Rust
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
//! Runtime history lifecycle: persistent, volatile fallback, or unavailable.

use super::HistoryStore;
use super::receipt::{HistorySaveOutcome, HistorySaveReceipt};
use crate::history::artifact::HistoryKind;
use reedline::{HistorySessionId, Reedline, Result};
use std::path::PathBuf;

/// The store and save receipt associated with one reedline editor.
#[derive(Clone)]
pub struct HistoryHandle {
    pub store: HistoryStore,
    pub receipt: HistorySaveReceipt,
}

/// Runtime history lifecycle. Keeping this state explicit prevents a failed
/// persistent open from being confused with an intentional volatile session.
#[derive(Clone)]
pub enum HistoryRuntime {
    Persistent(HistoryHandle),
    Volatile {
        handle: HistoryHandle,
        reason: VolatileHistoryReason,
    },
    Unavailable {
        failure: HistoryFailureDetail,
        previous_failure: Option<HistoryFailureDetail>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VolatileHistoryReason {
    Configured,
    Fallback {
        persistent_failure: HistoryFailureDetail,
    },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HistoryFailureDetail {
    stage: HistoryFailureStage,
    path: Option<PathBuf>,
    message: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum HistoryFailureStage {
    PersistentPathResolution,
    PersistentLocationProbe,
    PersistentOpen,
    MemoryInitialization,
}

impl HistoryRuntime {
    /// Construct the complete history lifecycle decision for one runtime from
    /// an already-chosen database path. Production code goes through
    /// [`Self::initialize_for_location`].
    ///
    /// Persistent open failures (including an unavailable default path) are
    /// deliberately represented as volatile fallbacks.  Only failure to
    /// create that fallback reaches `Unavailable`.
    #[cfg(test)]
    pub(crate) fn initialize(
        mode: &crate::config::HistoryMode,
        requested_path: Option<PathBuf>,
        history_kind: HistoryKind,
        session_id: Option<HistorySessionId>,
        session_timestamp: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Self {
        Self::initialize_with_factories(
            mode,
            requested_path,
            history_kind,
            session_id,
            session_timestamp,
            HistoryStore::open,
            HistoryStore::in_memory,
        )
    }

    /// Construct the lifecycle for one database file of a resolved location.
    ///
    /// Persistent open failures (including an unavailable default path) are
    /// deliberately represented as volatile fallbacks.  Only failure to
    /// create that fallback reaches `Unavailable`.
    ///
    /// A location whose default directories could not be inspected becomes a
    /// persistent failure naming the directory, so it surfaces through the same
    /// volatile-fallback diagnostics as any other persistent open failure.
    pub(crate) fn initialize_for_location(
        mode: &crate::config::HistoryMode,
        location: &crate::config::ResolvedHistoryLocation,
        filename: &str,
        history_kind: HistoryKind,
        session_id: Option<HistorySessionId>,
        session_timestamp: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Self {
        let target = match location.probe_failure() {
            Some(failure) => Err(HistoryFailureDetail::location_probe(failure)),
            None => Ok(location.database_path(filename)),
        };
        Self::initialize_with_target(
            mode,
            target,
            history_kind,
            session_id,
            session_timestamp,
            HistoryStore::open,
            HistoryStore::in_memory,
        )
    }

    /// Apply the lifecycle decision with injectable backend factories.
    ///
    /// The factories are kept private so production callers cannot bypass the
    /// single runtime construction path. Unit tests use this helper to cover
    /// initialization failures that the operating system cannot reliably
    /// reproduce on every platform.
    #[cfg(test)]
    fn initialize_with_factories<Open, Memory>(
        mode: &crate::config::HistoryMode,
        requested_path: Option<PathBuf>,
        history_kind: HistoryKind,
        session_id: Option<HistorySessionId>,
        session_timestamp: Option<chrono::DateTime<chrono::Utc>>,
        open: Open,
        in_memory: Memory,
    ) -> Self
    where
        Open: FnMut(
            PathBuf,
            HistoryKind,
            Option<HistorySessionId>,
            Option<chrono::DateTime<chrono::Utc>>,
        ) -> Result<HistoryStore>,
        Memory: FnMut(
            Option<HistorySessionId>,
            Option<chrono::DateTime<chrono::Utc>>,
        ) -> Result<HistoryStore>,
    {
        Self::initialize_with_target(
            mode,
            Ok(requested_path),
            history_kind,
            session_id,
            session_timestamp,
            open,
            in_memory,
        )
    }

    /// Core of runtime construction. `target` is either the requested database
    /// path (if any) or a failure that already prevents choosing one.
    fn initialize_with_target<Open, Memory>(
        mode: &crate::config::HistoryMode,
        target: std::result::Result<Option<PathBuf>, HistoryFailureDetail>,
        history_kind: HistoryKind,
        session_id: Option<HistorySessionId>,
        session_timestamp: Option<chrono::DateTime<chrono::Utc>>,
        mut open: Open,
        mut in_memory: Memory,
    ) -> Self
    where
        Open: FnMut(
            PathBuf,
            HistoryKind,
            Option<HistorySessionId>,
            Option<chrono::DateTime<chrono::Utc>>,
        ) -> Result<HistoryStore>,
        Memory: FnMut(
            Option<HistorySessionId>,
            Option<chrono::DateTime<chrono::Utc>>,
        ) -> Result<HistoryStore>,
    {
        let make_handle = |store: HistoryStore| HistoryHandle {
            store,
            receipt: HistorySaveReceipt::new(),
        };

        if matches!(mode, crate::config::HistoryMode::Volatile) {
            return match in_memory(session_id, session_timestamp) {
                Ok(store) => Self::Volatile {
                    handle: make_handle(store),
                    reason: VolatileHistoryReason::Configured,
                },
                Err(error) => Self::Unavailable {
                    failure: HistoryFailureDetail::memory(error),
                    previous_failure: None,
                },
            };
        }

        let persistent_failure = match target {
            Err(failure) => failure,
            Ok(Some(path)) => {
                match open(path.clone(), history_kind, session_id, session_timestamp) {
                    Ok(store) => return Self::Persistent(make_handle(store)),
                    Err(error) => HistoryFailureDetail::persistent_open(path, error),
                }
            }
            Ok(None) => HistoryFailureDetail::persistent_path(),
        };

        match in_memory(session_id, session_timestamp) {
            Ok(store) => Self::Volatile {
                handle: make_handle(store),
                reason: VolatileHistoryReason::Fallback { persistent_failure },
            },
            Err(error) => Self::Unavailable {
                failure: HistoryFailureDetail::memory(error),
                previous_failure: Some(persistent_failure),
            },
        }
    }

    /// Install this runtime's owned adapter on an editor, if available.
    pub fn attach_to_editor(&self, line_editor: Reedline) -> Reedline {
        let Some(handle) = self.handle() else {
            return line_editor;
        };
        let adapter = crate::history::ReedlineHistoryAdapter::new(
            handle.store.clone(),
            handle.receipt.clone(),
        );
        line_editor
            .with_history_session_id(handle.store.session())
            .with_history(Box::new(adapter))
    }

    pub fn handle(&self) -> Option<&HistoryHandle> {
        match self {
            Self::Persistent(handle) | Self::Volatile { handle, .. } => Some(handle),
            Self::Unavailable { .. } => None,
        }
    }

    pub fn store(&self) -> Option<HistoryStore> {
        self.handle().map(|handle| handle.store.clone())
    }

    pub fn receipt_outcome(&self) -> Option<HistorySaveOutcome> {
        self.handle().and_then(|handle| handle.receipt.take())
    }

    pub fn is_available(&self) -> bool {
        self.handle().is_some()
    }

    /// Stable state label for diagnostics and machine-readable startup info.
    pub fn state_name(&self) -> &'static str {
        match self {
            Self::Persistent(_) => "persistent",
            Self::Volatile { .. } => "volatile",
            Self::Unavailable { .. } => "unavailable",
        }
    }

    /// Stable machine-readable reason for a non-persistent runtime.
    pub fn reason_name(&self) -> Option<&'static str> {
        match self {
            Self::Persistent(_) => None,
            Self::Volatile { reason, .. } => Some(match reason {
                VolatileHistoryReason::Configured => "configured",
                VolatileHistoryReason::Fallback { .. } => "fallback",
            }),
            Self::Unavailable { .. } => Some("initialization_failed"),
        }
    }

    /// Human-readable startup warning for degraded runtimes.
    ///
    /// Persistent and intentionally configured volatile runtimes are healthy
    /// states and therefore do not produce a warning.
    pub fn startup_warning(&self) -> Option<String> {
        let detail = self.diagnostic_detail()?;
        Some(match self.requested_path() {
            Some(path) => format!("{detail} (requested path: {})", path.display()),
            None => detail,
        })
    }

    /// Human-readable detail shared by startup warnings, `:info`, and JSON.
    pub fn diagnostic_detail(&self) -> Option<String> {
        match self {
            Self::Persistent(_) => None,
            Self::Volatile { reason, .. } => match reason {
                VolatileHistoryReason::Configured => None,
                VolatileHistoryReason::Fallback { persistent_failure } => Some(format!(
                    "{}; using volatile fallback",
                    persistent_failure.describe(),
                )),
            },
            Self::Unavailable {
                failure,
                previous_failure,
            } => {
                let mut details = previous_failure
                    .as_ref()
                    .map(|failure| failure.describe())
                    .unwrap_or_default();
                if !details.is_empty() {
                    details.push_str("; ");
                }
                details.push_str(&failure.describe());
                Some(details)
            }
        }
    }

    pub fn requested_path(&self) -> Option<&std::path::Path> {
        match self {
            Self::Persistent(handle) => handle.store.path(),
            Self::Volatile { reason, .. } => match reason {
                VolatileHistoryReason::Configured => None,
                VolatileHistoryReason::Fallback { persistent_failure } => persistent_failure.path(),
            },
            Self::Unavailable {
                previous_failure, ..
            } => previous_failure
                .as_ref()
                .and_then(HistoryFailureDetail::path),
        }
    }
}

impl HistoryFailureDetail {
    #[cfg(test)]
    pub(crate) fn test_memory() -> Self {
        Self {
            stage: HistoryFailureStage::MemoryInitialization,
            path: None,
            message: "test memory initialization failure".to_string(),
        }
    }

    #[cfg(test)]
    pub(crate) fn test_persistent_open(path: PathBuf) -> Self {
        Self {
            stage: HistoryFailureStage::PersistentOpen,
            path: Some(path),
            message: "test persistent open failure".to_string(),
        }
    }

    #[cfg(test)]
    pub(crate) fn test_path_resolution() -> Self {
        Self::persistent_path()
    }

    fn persistent_path() -> Self {
        Self {
            stage: HistoryFailureStage::PersistentPathResolution,
            path: None,
            message: "no persistent history path is available".to_string(),
        }
    }

    fn location_probe(failure: &crate::config::HistoryProbeFailure) -> Self {
        Self {
            stage: HistoryFailureStage::PersistentLocationProbe,
            path: Some(failure.directory().to_path_buf()),
            message: failure.message().to_string(),
        }
    }

    fn persistent_open(path: PathBuf, error: reedline::ReedlineError) -> Self {
        Self {
            stage: HistoryFailureStage::PersistentOpen,
            path: Some(path),
            message: error.to_string(),
        }
    }

    fn memory(error: reedline::ReedlineError) -> Self {
        Self {
            stage: HistoryFailureStage::MemoryInitialization,
            path: None,
            message: error.to_string(),
        }
    }

    fn describe(&self) -> String {
        match self.stage {
            HistoryFailureStage::PersistentPathResolution => {
                format!(
                    "persistent history path resolution failed: {}",
                    self.message
                )
            }
            HistoryFailureStage::PersistentLocationProbe => {
                format!("persistent history location probe failed: {}", self.message)
            }
            HistoryFailureStage::PersistentOpen => {
                format!("persistent history open failed: {}", self.message)
            }
            HistoryFailureStage::MemoryInitialization => {
                format!("volatile history initialization failed: {}", self.message)
            }
        }
    }

    fn path(&self) -> Option<&std::path::Path> {
        self.path.as_deref()
    }
}

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

    fn injected_failure(message: &str) -> Result<HistoryStore> {
        Err(reedline::ReedlineError(
            reedline::ReedlineErrorVariants::HistoryDatabaseError(message.to_string()),
        ))
    }

    #[test]
    fn configured_volatile_memory_failure_is_unavailable_without_previous_failure() {
        let runtime = HistoryRuntime::initialize_with_factories(
            &crate::config::HistoryMode::Volatile,
            None,
            HistoryKind::R,
            None,
            None,
            |_path, _kind, _session, _timestamp| injected_failure("persistent must not be opened"),
            |_session, _timestamp| injected_failure("configured memory failure"),
        );

        assert!(runtime.requested_path().is_none());
        let HistoryRuntime::Unavailable {
            failure,
            previous_failure,
        } = runtime
        else {
            panic!("configured volatile initialization should be unavailable");
        };
        assert_eq!(failure.stage, HistoryFailureStage::MemoryInitialization);
        assert!(failure.message.contains("configured memory failure"));
        assert!(previous_failure.is_none());
    }

    #[test]
    fn persistent_failure_and_memory_failure_are_both_retained() {
        let requested_path = PathBuf::from("/requested/history.db");
        let runtime = HistoryRuntime::initialize_with_factories(
            &crate::config::HistoryMode::Persistent { dir: None },
            Some(requested_path.clone()),
            HistoryKind::R,
            None,
            None,
            |_path, _kind, _session, _timestamp| injected_failure("persistent open failure"),
            |_session, _timestamp| injected_failure("fallback memory failure"),
        );

        let detail = runtime.diagnostic_detail().expect("unavailable detail");
        assert_eq!(runtime.requested_path(), Some(requested_path.as_path()));
        let HistoryRuntime::Unavailable {
            failure,
            previous_failure,
        } = runtime
        else {
            panic!("persistent and fallback initialization should be unavailable");
        };
        assert_eq!(failure.stage, HistoryFailureStage::MemoryInitialization);
        assert!(failure.message.contains("fallback memory failure"));
        let previous_failure = previous_failure.expect("persistent failure should be retained");
        assert_eq!(previous_failure.stage, HistoryFailureStage::PersistentOpen);
        assert!(previous_failure.message.contains("persistent open failure"));
        assert!(detail.contains("fallback memory failure"));
        let requested_path_text = requested_path.to_string_lossy();
        assert_eq!(detail.matches(requested_path_text.as_ref()).count(), 0);
        let warning = HistoryRuntime::Unavailable {
            failure: HistoryFailureDetail::test_memory(),
            previous_failure: Some(HistoryFailureDetail::test_persistent_open(
                requested_path.clone(),
            )),
        }
        .startup_warning()
        .expect("unavailable warning");
        assert_eq!(warning.matches(requested_path_text.as_ref()).count(), 1);
    }
}