arf-console 0.6.0

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
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
//! Owned SQLite history storage for arf.
//!
//! [`HistoryStore`] owns the concrete reedline database and is the only layer
//! that performs typed metadata writes.  Each method locks the database for a
//! single short call and releases the lock before returning.  Callers must not
//! hold a store lock across meta-command dispatch, R evaluation, a pager, a
//! confirmation prompt, or any other user interaction.

use super::artifact::{self, HistoryKind};
use super::metadata::HistoryExtraInfo;
use reedline::{
    History, HistoryItem, HistoryItemExtraInfo, HistoryItemId, HistorySessionId, Reedline, Result,
    SearchQuery, SqliteBackedHistory,
};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

/// An arf-owned handle to one SQLite history database.
#[derive(Clone)]
pub struct HistoryStore {
    inner: Arc<Mutex<SqliteBackedHistory>>,
    path: Option<PathBuf>,
    session: Option<HistorySessionId>,
}

/// The result of the most recent adapter save.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HistorySaveOutcome {
    Saved(HistoryItemId),
    Failed,
}

/// Shared receipt through which arf can observe an adapter save result.
#[derive(Clone)]
pub struct HistorySaveReceipt {
    inner: Arc<Mutex<Option<HistorySaveOutcome>>>,
}

impl HistorySaveReceipt {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(None)),
        }
    }

    pub fn take(&self) -> Option<HistorySaveOutcome> {
        self.inner
            .lock()
            .ok()
            .and_then(|mut outcome| outcome.take())
    }

    pub(crate) fn record(&self, outcome: HistorySaveOutcome) {
        if let Ok(mut latest) = self.inner.lock() {
            *latest = Some(outcome);
        }
    }
}

/// 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)]
pub(crate) enum HistoryFailureStage {
    PersistentPathResolution,
    PersistentOpen,
    MemoryInitialization,
}

impl HistoryRuntime {
    /// Construct the complete history lifecycle decision for one runtime.
    ///
    /// Persistent open failures (including an unavailable default path) are
    /// deliberately represented as volatile fallbacks.  Only failure to
    /// create that fallback reaches `Unavailable`.
    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,
        )
    }

    /// 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.
    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>>,
        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 requested_path.clone() {
            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),
            },
            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 =
            super::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 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::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()
    }
}

impl HistoryStore {
    /// Open or create a history database.
    pub(crate) fn open(
        path: PathBuf,
        history_kind: HistoryKind,
        session_id: Option<HistorySessionId>,
        session_timestamp: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Self> {
        artifact::prepare_history_path(&path, history_kind).map_err(|error| {
            reedline::ReedlineError(reedline::ReedlineErrorVariants::HistoryDatabaseError(
                format!("invalid history database artifact: {error:#}"),
            ))
        })?;
        let history = SqliteBackedHistory::with_file(path.clone(), session_id, session_timestamp)?;
        Ok(Self {
            inner: Arc::new(Mutex::new(history)),
            path: Some(path),
            session: session_id,
        })
    }

    /// Create an arf-owned in-memory SQLite history store.
    pub fn in_memory(
        session_id: Option<HistorySessionId>,
        _session_timestamp: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Self> {
        Ok(Self {
            inner: Arc::new(Mutex::new(SqliteBackedHistory::in_memory()?)),
            path: None,
            session: session_id,
        })
    }

    /// Compare ownership identity without opening another backend.
    pub(crate) fn same_owner(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }

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

    /// Save an item with SQL `NULL` in `more_info`.
    pub fn save_unknown(&self, item: HistoryItem) -> Result<HistoryItem> {
        let mut item = item;
        if item.session_id.is_none() {
            item.session_id = self.session;
        }
        let typed = convert_history_item(item, None::<HistoryExtraInfo>);
        let saved = self
            .inner
            .lock()
            .map_err(|_| lock_error())?
            .save_with_extra(typed)?;
        Ok(convert_history_item(saved, None))
    }

    /// Save an item with metadata already determined by arf.
    pub fn save_known(&self, item: HistoryItem, metadata: HistoryExtraInfo) -> Result<HistoryItem> {
        let mut item = item;
        if item.session_id.is_none() {
            item.session_id = self.session;
        }
        let typed = convert_history_item(item, Some(metadata));
        let saved = self
            .inner
            .lock()
            .map_err(|_| lock_error())?
            .save_with_extra(typed)?;
        Ok(convert_history_item(saved, None))
    }

    /// Save a fully typed item imported from an external history source.
    pub(crate) fn save_imported(
        &self,
        item: HistoryItem<HistoryExtraInfo>,
    ) -> Result<HistoryItem<HistoryExtraInfo>> {
        let mut item = item;
        if item.session_id.is_none() {
            item.session_id = self.session;
        }
        self.inner
            .lock()
            .map_err(|_| lock_error())?
            .save_with_extra(item)
    }

    /// Fill missing imported fields only if each row field is still SQL NULL.
    pub(crate) fn set_missing_fields_if_empty(
        &self,
        id: HistoryItemId,
        source: HistoryItem<HistoryExtraInfo>,
    ) -> Result<bool> {
        // This is the one import-only escape hatch from reedline's typed API.
        // Holding the store mutex prevents the raw transaction from racing an
        // adapter write; the helper itself never escapes this ownership boundary.
        let _store_lock = self.inner.lock().map_err(|_| lock_error())?;
        self.set_missing_fields_with_raw_transaction(id, source)
    }

    /// Backfill legacy rows whose `more_info` may contain malformed JSON.
    ///
    /// Reedline's typed loader intentionally rejects malformed metadata, so
    /// import repair must use SQL COALESCE while the owning store is locked.
    fn set_missing_fields_with_raw_transaction(
        &self,
        id: HistoryItemId,
        source: HistoryItem<HistoryExtraInfo>,
    ) -> Result<bool> {
        let serialized_metadata = source
            .more_info
            .as_ref()
            .map(serde_json::to_string)
            .transpose()
            .map_err(|error| {
                reedline::ReedlineError(reedline::ReedlineErrorVariants::HistoryDatabaseError(
                    format!("could not serialize more_info: {error}"),
                ))
            })?;
        let Some(path) = self.path.as_ref() else {
            return Ok(false);
        };
        let mut connection = rusqlite::Connection::open(path).map_err(sqlite_error)?;
        connection
            .busy_timeout(std::time::Duration::from_secs(5))
            .map_err(sqlite_error)?;
        let transaction = connection
            .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
            .map_err(sqlite_error)?;
        let changed = transaction
            .execute(
                "UPDATE history SET
                    session_id = COALESCE(session_id, :session_id),
                    hostname = COALESCE(hostname, :hostname),
                    cwd = COALESCE(cwd, :cwd),
                    duration_ms = COALESCE(duration_ms, :duration_ms),
                    exit_status = COALESCE(exit_status, :exit_status),
                    more_info = COALESCE(more_info, :more_info)
                 WHERE id = :id
                   AND command_line = :command_line
                   AND (
                       :start_timestamp IS NULL
                    OR start_timestamp = :start_timestamp
                   )
                   AND (
                       (:session_id IS NOT NULL AND session_id IS NULL)
                    OR (:hostname IS NOT NULL AND hostname IS NULL)
                    OR (:cwd IS NOT NULL AND cwd IS NULL)
                    OR (:duration_ms IS NOT NULL AND duration_ms IS NULL)
                    OR (:exit_status IS NOT NULL AND exit_status IS NULL)
                    OR (:more_info IS NOT NULL AND more_info IS NULL)
                   )",
                rusqlite::named_params! {
                    ":id": id.0,
                    ":command_line": source.command_line,
                    ":start_timestamp": source.start_timestamp.map(|value| value.timestamp_millis()),
                    ":session_id": source.session_id.map(i64::from),
                    ":hostname": source.hostname,
                    ":cwd": source.cwd,
                    ":duration_ms": source.duration.map(|value| value.as_millis() as i64),
                    ":exit_status": source.exit_status,
                    ":more_info": serialized_metadata,
                },
            )
            .map_err(sqlite_error)?;
        transaction.commit().map_err(sqlite_error)?;
        Ok(changed != 0)
    }

    /// Set the final meta-command disposition while preserving all other fields.
    pub fn finalize_meta_command(&self, id: HistoryItemId, is_meta_command: bool) -> Result<()> {
        self.inner
            .lock()
            .map_err(|_| lock_error())?
            .update_with_extra::<HistoryExtraInfo>(id, &|mut item| {
                let mut metadata: HistoryExtraInfo = item.more_info.unwrap_or_default();
                metadata.set_meta_command(is_meta_command);
                item.more_info = Some(metadata);
                item
            })
    }

    /// Replace the metadata object of an existing row.
    #[allow(dead_code)]
    pub fn set_metadata(&self, id: HistoryItemId, metadata: HistoryExtraInfo) -> Result<()> {
        self.inner
            .lock()
            .map_err(|_| lock_error())?
            .update_with_extra::<HistoryExtraInfo>(id, &|mut item| {
                item.more_info = Some(metadata.clone());
                item
            })
    }

    /// Set the exit status of an existing row.
    pub fn set_exit_status(&self, id: HistoryItemId, exit_status: i64) -> Result<()> {
        self.inner
            .lock()
            .map_err(|_| lock_error())?
            .update_with_extra::<HistoryExtraInfo>(id, &|mut item| {
                item.exit_status = Some(exit_status);
                item
            })
    }

    /// Count all rows without exposing the concrete reedline backend.
    pub fn count_all(&self) -> Result<i64> {
        self.count(SearchQuery::everything(
            reedline::SearchDirection::Backward,
            None,
        ))
    }

    pub fn load(&self, id: HistoryItemId) -> Result<HistoryItem> {
        self.inner.lock().map_err(|_| lock_error())?.load(id)
    }

    #[allow(dead_code)]
    pub fn load_with_metadata(&self, id: HistoryItemId) -> Result<HistoryItem<HistoryExtraInfo>> {
        self.inner
            .lock()
            .map_err(|_| lock_error())?
            .load_with_extra(id)
    }

    pub fn count(&self, query: SearchQuery) -> Result<i64> {
        self.inner.lock().map_err(|_| lock_error())?.count(query)
    }

    pub fn search(&self, query: SearchQuery) -> Result<Vec<HistoryItem>> {
        self.inner.lock().map_err(|_| lock_error())?.search(query)
    }

    /// Search with an exact session scope and a result limit.
    ///
    /// Reedline's session filter intentionally includes rows from before the
    /// current session, which is useful for interactive recall but not for the
    /// IPC contract. This owned API applies exact filtering after each bounded
    /// backend page and keeps scanning by ID until the requested number of rows
    /// is collected. Callers never need to materialize the whole database.
    pub(crate) fn search_strict_session<F>(
        &self,
        mut make_query: F,
        session_id: Option<HistorySessionId>,
        all_sessions: bool,
        limit: i64,
        start_time: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<HistoryItem>>
    where
        F: FnMut(Option<HistoryItemId>) -> SearchQuery,
    {
        const PAGE_SIZE: i64 = 128;
        if limit <= 0 {
            return Ok(Vec::new());
        }

        if all_sessions && start_time.is_none() {
            let mut query = make_query(None);
            query.limit = Some(limit);
            return self.search(query);
        }

        let mut matched = Vec::new();
        let mut start_id = None;
        loop {
            let mut query = make_query(start_id);
            // Never let reedline apply its two-stage session semantics here.
            query.filter.session = None;
            query.limit = Some(PAGE_SIZE);
            let page = self.search(query)?;
            let page_len = page.len();
            let next_start_id = page.last().and_then(|item| item.id);
            matched.extend(page.into_iter().filter(|item| {
                (all_sessions || item.session_id == session_id)
                    && start_time.is_none_or(|start| {
                        item.start_timestamp
                            .is_some_and(|timestamp| timestamp >= start)
                    })
            }));
            if matched.len() >= limit as usize || page_len < PAGE_SIZE as usize {
                matched.truncate(limit as usize);
                return Ok(matched);
            }
            let Some(next_start_id) = next_start_id else {
                matched.truncate(limit as usize);
                return Ok(matched);
            };
            start_id = Some(next_start_id);
        }
    }

    pub fn update(
        &self,
        id: HistoryItemId,
        updater: &dyn Fn(HistoryItem) -> HistoryItem,
    ) -> Result<()> {
        self.inner
            .lock()
            .map_err(|_| lock_error())?
            .update(id, updater)
    }

    pub fn clear(&self) -> Result<()> {
        self.inner.lock().map_err(|_| lock_error())?.clear()
    }

    pub fn delete(&self, id: HistoryItemId) -> Result<()> {
        self.inner.lock().map_err(|_| lock_error())?.delete(id)
    }

    /// Delete several rows while holding the owning backend lock once.
    pub(crate) fn delete_many(&self, ids: &[HistoryItemId]) -> Result<usize> {
        let mut history = self.inner.lock().map_err(|_| lock_error())?;
        let mut deleted = 0;
        for id in ids {
            history.delete(*id)?;
            deleted += 1;
        }
        Ok(deleted)
    }

    pub fn sync(&self) -> std::io::Result<()> {
        self.inner
            .lock()
            .map_err(|_| std::io::Error::other("history store lock poisoned"))?
            .sync()
    }

    pub fn session(&self) -> Option<HistorySessionId> {
        self.session
    }

    #[cfg(test)]
    pub(crate) fn drop_table_for_test(&self, path: &std::path::Path) {
        rusqlite::Connection::open(path)
            .unwrap()
            .execute_batch("DROP TABLE history")
            .unwrap();
    }
}

/// Convert a history item between reedline's type-erased and typed boundaries.
pub(crate) fn convert_history_item<A: HistoryItemExtraInfo, B: HistoryItemExtraInfo>(
    item: HistoryItem<A>,
    more_info: Option<B>,
) -> HistoryItem<B> {
    HistoryItem {
        id: item.id,
        start_timestamp: item.start_timestamp,
        command_line: item.command_line,
        session_id: item.session_id,
        hostname: item.hostname,
        cwd: item.cwd,
        duration: item.duration,
        exit_status: item.exit_status,
        more_info,
    }
}

fn lock_error() -> reedline::ReedlineError {
    reedline::ReedlineError(reedline::ReedlineErrorVariants::HistoryDatabaseError(
        "history store lock poisoned".to_string(),
    ))
}

fn sqlite_error(error: rusqlite::Error) -> reedline::ReedlineError {
    reedline::ReedlineError(reedline::ReedlineErrorVariants::HistoryDatabaseError(
        format!("{error:?}"),
    ))
}

#[cfg(test)]
#[path = "store/tests.rs"]
mod tests;