Skip to main content

libgrite_cli/
event_helper.rs

1//! Helper for inserting events into both sled store and Git WAL
2
3use libgrite_core::{types::event::Event, types::ids::ActorId, GriteError, GriteStore};
4use libgrite_git::{GitError, WalManager};
5
6/// Result of inserting an event
7pub struct InsertResult {
8    /// The WAL commit OID (hex string), if WAL append succeeded
9    pub wal_head: Option<String>,
10}
11
12/// Insert an event into both the sled store and the Git WAL
13///
14/// This is the canonical way to persist an event. It:
15/// 1. Inserts the event into the sled store (for fast querying)
16/// 2. Appends the event to the Git WAL (for durability and sync)
17///
18/// If WAL append fails, the event is still persisted in sled and
19/// an error is logged but not returned.
20pub fn insert_and_append(
21    store: &GriteStore,
22    wal: &WalManager,
23    actor: &ActorId,
24    event: &Event,
25) -> Result<InsertResult, GriteError> {
26    // Insert into sled first (fast, local)
27    store.insert_event(event)?;
28    store.flush()?;
29
30    // Append to WAL (may fail if git issues)
31    let wal_head = match wal.append(actor, std::slice::from_ref(event)) {
32        Ok(oid) => Some(oid.to_string()),
33        Err(e) => {
34            // Log error but don't fail - event is in sled
35            eprintln!("Warning: Failed to append to WAL: {}", e);
36            None
37        }
38    };
39
40    Ok(InsertResult { wal_head })
41}
42
43/// Try to append to WAL without inserting to store
44/// Useful for batch operations or when store is already updated
45#[allow(dead_code)]
46pub fn append_to_wal(
47    wal: &WalManager,
48    actor: &ActorId,
49    events: &[Event],
50) -> Result<Option<String>, GitError> {
51    if events.is_empty() {
52        return Ok(None);
53    }
54    let oid = wal.append(actor, events)?;
55    Ok(Some(oid.to_string()))
56}