offline_first_core 0.5.0

High-performance LMDB-based local storage library optimized for FFI integration with Flutter and cross-platform applications
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
//! Database state management and operations.
//!
//! This module provides the core database functionality using LMDB (Lightning Memory-Mapped Database)
//! as the storage engine. It handles all database operations including initialization, CRUD operations,
//! and connection management.

use crate::local_db_model::LocalDbModel;
use log::{info, warn};
use lmdb::{Environment, Database, Transaction, WriteFlags, Cursor, DatabaseFlags, Error as LmdbError};
use std::fs;
use std::path::Path;
use crate::app_response::AppResponse;

/// The default database name within the LMDB environment.
const MAIN_DB_NAME: &str = "main";

/// Database state container that manages the LMDB environment and database connections.
///
/// This struct encapsulates the LMDB environment and database handle, providing
/// a safe interface for database operations. It maintains the database path for
/// operations like reset that require filesystem manipulation.
///
/// # Examples
///
/// ```no_run
/// use offline_first_core::local_db_state::AppDbState;
///
/// // Initialize a new database
/// let db_state = AppDbState::init("my_database".to_string())?;
///
/// // The database is ready for operations
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct AppDbState {
    /// LMDB environment handle
    env: Environment,
    /// Main database handle within the environment
    db: Database,
    /// Filesystem path to the database directory
    path: String,
}

impl AppDbState {
    /// Initializes a new database instance or opens an existing one.
    ///
    /// This function creates an LMDB environment with the specified name, setting up
    /// a directory-based storage system. The database is configured with a 1GB memory
    /// map size and support for up to 10 named databases.
    ///
    /// # Parameters
    ///
    /// * `name` - The base name for the database. A `.lmdb` extension will be added
    ///   to create the directory name.
    ///
    /// # Returns
    ///
    /// Returns `Ok(AppDbState)` on success, or `Err(LmdbError)` if initialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// // Create or open a database named "user_data"
    /// let db = AppDbState::init("user_data".to_string())?;
    ///
    /// // The database directory will be "./user_data.lmdb"
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The database directory cannot be created
    /// - LMDB environment initialization fails
    /// - The main database cannot be created within the environment
    pub fn init(name: String) -> Result<Self, LmdbError> {
        let db_dir = format!("{name}.lmdb");
        let path = Path::new(&db_dir);
        
        if !path.exists() {
            fs::create_dir_all(path).map_err(|_| LmdbError::Other(2))?;
        }
        
        let env = Environment::new()
            .set_max_dbs(10)
            .set_map_size(1024 * 1024 * 1024) // 1GB
            .open(path)?;
        
        info!("LMDB environment opened at {name}");
        
        let db = env.create_db(Some(MAIN_DB_NAME), DatabaseFlags::empty())?;
        
        info!("Database initialized successfully");
        
        Ok(Self {
            env,
            db,
            path: db_dir
        })
    }

    /// Inserts a new record into the database.
    ///
    /// This method serializes the provided model to JSON and stores it using the model's
    /// ID as the key. The operation is performed within a write transaction to ensure
    /// data consistency.
    ///
    /// # Parameters
    ///
    /// * `model` - The data model to insert into the database
    ///
    /// # Returns
    ///
    /// Returns the inserted model on success, or an error response if the operation fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::{local_db_state::AppDbState, local_db_model::LocalDbModel};
    /// use serde_json::json;
    ///
    /// let db = AppDbState::init("test_db".to_string())?;
    ///
    /// let model = LocalDbModel {
    ///     id: "user_123".to_string(),
    ///     hash: "abc123".to_string(),
    ///     data: json!({"name": "John", "age": 30}),
    /// };
    ///
    /// let result = db.push(model)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - JSON serialization fails
    /// - Transaction creation fails
    /// - Database write operation fails
    /// - Transaction commit fails
    pub fn push(&self, model: LocalDbModel) -> Result<LocalDbModel, AppResponse> {
        let json = serde_json::to_string(&model)?;
        
        let mut txn = self.env.begin_rw_txn().map_err(AppResponse::from)?;
        txn.put(self.db, &model.id, &json, WriteFlags::empty()).map_err(AppResponse::from)?;
        txn.commit().map_err(AppResponse::from)?;
        
        Ok(model)
    }

    /// Retrieves a record from the database by its ID.
    ///
    /// This method performs a read-only lookup using the provided ID as the key.
    /// If found, the JSON data is deserialized back into a `LocalDbModel`.
    ///
    /// # Parameters
    ///
    /// * `id` - The unique identifier of the record to retrieve
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(LocalDbModel))` if the record is found, `Ok(None)` if not found,
    /// or `Err(LmdbError)` if the operation fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// let db = AppDbState::init("test_db".to_string())?;
    ///
    /// match db.get_by_id("user_123")? {
    ///     Some(model) => println!("Found user: {:?}", model),
    ///     None => println!("User not found"),
    /// }
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - Transaction creation fails
    /// - The stored data is not valid UTF-8
    /// - JSON deserialization fails
    pub fn get_by_id(&self, id: &str) -> Result<Option<LocalDbModel>, LmdbError> {
        let txn = self.env.begin_ro_txn()?;
        
        match txn.get(self.db, &id) {
            Ok(bytes) => {
                let json_str = std::str::from_utf8(bytes)
                    .map_err(|_| LmdbError::Other(1))?;
                let model = serde_json::from_str(json_str)
                    .map_err(|_| LmdbError::Other(1))?;
                Ok(Some(model))
            }
            Err(LmdbError::NotFound) => {
                info!("No value found for id {id}");
                Ok(None)
            }
            Err(e) => Err(e)
        }
    }

    /// Retrieves all records from the database.
    ///
    /// This method iterates through all key-value pairs in the database,
    /// deserializing each JSON value back into a `LocalDbModel`. Records that
    /// fail to deserialize are logged and skipped.
    ///
    /// # Returns
    ///
    /// Returns a vector containing all successfully deserialized records,
    /// or an error if the database operation fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// let db = AppDbState::init("test_db".to_string())?;
    ///
    /// let all_records = db.get()?;
    /// println!("Found {} records", all_records.len());
    ///
    /// for record in all_records {
    ///     println!("Record ID: {}", record.id);
    /// }
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - Transaction creation fails
    /// - Cursor creation fails
    pub fn get(&self) -> Result<Vec<LocalDbModel>, LmdbError> {
        let mut models = Vec::new();
        
        let txn = self.env.begin_ro_txn()?;
        let mut cursor = txn.open_ro_cursor(self.db)?;
        
        for (_, value) in cursor.iter() {
            match std::str::from_utf8(value) {
                Ok(json_str) => {
                    match serde_json::from_str::<LocalDbModel>(json_str) {
                        Ok(model) => models.push(model),
                        Err(e) => info!("Error deserializing model: {e:?}"),
                    }
                }
                Err(e) => info!("Error converting to UTF-8: {e:?}"),
            }
        }
        
        Ok(models)
    }

    /// Deletes a record from the database by its ID.
    ///
    /// This method first checks if the record exists, then removes it if found.
    /// The operation is performed within a write transaction for consistency.
    ///
    /// # Parameters
    ///
    /// * `id` - The unique identifier of the record to delete
    ///
    /// # Returns
    ///
    /// Returns `true` if a record was deleted, `false` if no record with the given ID exists,
    /// or an error if the operation fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// let db = AppDbState::init("test_db".to_string())?;
    ///
    /// match db.delete_by_id("user_123")? {
    ///     true => println!("Record deleted successfully"),
    ///     false => println!("Record not found"),
    /// }
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - Transaction creation fails
    /// - Database operations fail
    /// - Transaction commit fails
    pub fn delete_by_id(&self, id: &str) -> Result<bool, LmdbError> {
        let mut txn = self.env.begin_rw_txn()?;
        
        let existed = match txn.get(self.db, &id) {
            Ok(_) => true,
            Err(LmdbError::NotFound) => false,
            Err(e) => return Err(e),
        };
        
        if existed {
            txn.del(self.db, &id, None)?;
        }
        
        txn.commit()?;
        Ok(existed)
    }

    /// Updates an existing record in the database.
    ///
    /// This method first verifies that a record with the given ID exists, then
    /// updates it with the new data. If no record exists, the operation returns `None`.
    ///
    /// # Parameters
    ///
    /// * `model` - The updated model data. The ID field determines which record to update.
    ///
    /// # Returns
    ///
    /// Returns `Some(LocalDbModel)` with the updated data if successful, `None` if no
    /// record with the given ID exists, or an error if the operation fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::{local_db_state::AppDbState, local_db_model::LocalDbModel};
    /// use serde_json::json;
    ///
    /// let db = AppDbState::init("test_db".to_string())?;
    ///
    /// let updated_model = LocalDbModel {
    ///     id: "user_123".to_string(),
    ///     hash: "new_hash".to_string(),
    ///     data: json!({"name": "Jane", "age": 25}),
    /// };
    ///
    /// match db.update(updated_model)? {
    ///     Some(model) => println!("Updated: {:?}", model),
    ///     None => println!("Record not found for update"),
    /// }
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - Transaction creation fails
    /// - JSON serialization fails
    /// - Database operations fail
    /// - Transaction commit fails
    pub fn update(&self, model: LocalDbModel) -> Result<Option<LocalDbModel>, LmdbError> {
        let mut txn = self.env.begin_rw_txn()?;
        
        let exists = match txn.get(self.db, &model.id) {
            Ok(_) => true,
            Err(LmdbError::NotFound) => false,
            Err(e) => return Err(e),
        };
        
        if exists {
            let json = serde_json::to_string(&model)
                .map_err(|_| LmdbError::Other(1))?;
            txn.put(self.db, &model.id, &json, WriteFlags::empty())?;
            txn.commit()?;
            Ok(Some(model))
        } else {
            Ok(None)
        }
    }

    /// Removes all records from the database while preserving the database structure.
    ///
    /// This method iterates through all records and deletes them individually.
    /// The database remains operational after this operation and can continue
    /// to accept new records.
    ///
    /// # Returns
    ///
    /// Returns the number of records that were deleted, or an error if the operation fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// let db = AppDbState::init("test_db".to_string())?;
    ///
    /// let deleted_count = db.clear_all_records()?;
    /// println!("Deleted {} records", deleted_count);
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - Transaction creation fails
    /// - Cursor operations fail
    /// - Delete operations fail
    /// - Transaction commit fails
    pub fn clear_all_records(&self) -> Result<usize, LmdbError> {
        let mut txn = self.env.begin_rw_txn()?;
        let mut count = 0;
        
        let keys: Vec<Vec<u8>> = {
            let mut cursor = txn.open_ro_cursor(self.db)?;
            cursor.iter()
                .map(|(key, _)| key.to_vec())
                .collect()
        };
        
        for key in keys {
            match txn.del(self.db, &key, None) {
                Ok(_) => count += 1,
                Err(e) => warn!("Error deleting key: {e:?}"),
            }
        }
        txn.commit()?;
        Ok(count)
    }

    /// Completely resets the database to a clean state with a new name.
    ///
    /// This operation performs the following steps:
    /// 1. Closes the current database environment
    /// 2. Removes the existing database directory and all its contents
    /// 3. Creates a new database environment with the specified name
    /// 4. Updates the internal state to use the new database
    ///
    /// # Parameters
    ///
    /// * `name` - The new name for the database
    ///
    /// # Returns
    ///
    /// Returns `Ok(true)` on success, or an error if any step fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// let mut db = AppDbState::init("old_db".to_string())?;
    ///
    /// // Reset to a new database
    /// db.reset_database("new_db")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The existing database directory cannot be removed
    /// - The new database directory cannot be created
    /// - LMDB environment initialization fails
    /// - Database creation within the environment fails
    ///
    /// # Safety
    ///
    /// This operation is destructive and will permanently delete all data in the current database.
    /// Ensure that any important data is backed up before calling this method.
    pub fn reset_database(&mut self, name: &str) -> Result<bool, Box<dyn std::error::Error>> {
        if Path::new(&self.path).exists() {
            fs::remove_dir_all(&self.path)?;
        }
        
        let new_db_dir = format!("{name}.lmdb");
        let path = Path::new(&new_db_dir);
        
        if !path.exists() {
            fs::create_dir_all(path)?;
        }
        
        let new_env = Environment::new()
            .set_max_dbs(10)
            .set_map_size(1024 * 1024 * 1024)
            .open(path)?;
            
        let new_db = new_env.create_db(Some(MAIN_DB_NAME), DatabaseFlags::empty())?;
        
        self.env = new_env;
        self.db = new_db;
        self.path = new_db_dir;
        
        Ok(true)
    }
    
    /// Provides explicit database connection management.
    ///
    /// This method serves as an explicit indicator that database resources should be
    /// cleaned up. While LMDB automatically closes connections when the environment
    /// is dropped, this function provides a clear signal for connection lifecycle
    /// management, particularly useful in FFI scenarios like Flutter hot restart.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success. This operation cannot fail as it only provides
    /// a signal for cleanup rather than performing actual resource deallocation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use offline_first_core::local_db_state::AppDbState;
    ///
    /// let mut db = AppDbState::init("test_db".to_string())?;
    ///
    /// // Before hot restart or application shutdown
    /// db.close_database()?;
    /// # Ok::<(), lmdb::Error>(())
    /// ```
    ///
    /// # Notes
    ///
    /// In LMDB, database connections are automatically managed through RAII.
    /// The actual cleanup occurs when the `AppDbState` instance is dropped.
    /// This method primarily serves as documentation and explicit lifecycle management
    /// for integration scenarios.
    pub fn close_database(&mut self) -> Result<(), LmdbError> {
        info!("Database connection will be closed when AppDbState is dropped");
        Ok(())
    }
}