epoch_db/
lib.rs

1//! # EpochDB 🦀
2//!
3//! An intelligent, persistent, and concurrent key-value store for Rust,
4//! designed to manage data with a lifecycle.
5//!
6//! **EpochDB** is an opinionated database engine built on the robust foundation of `sled`.
7//! It's designed specifically for workloads where the relevance of data changes over time,
8//! such as caching, session management, and real-time analytics.
9//!
10//! It provides a high-level, ergonomic API by treating data's **access frequency**
11//! and **age** as first-class citizens.
12
13use db::errors::TransientError;
14use serde::{Deserialize, Serialize};
15use sled::Tree;
16use std::{
17    path::PathBuf,
18    sync::{Arc, atomic::AtomicBool},
19    thread::JoinHandle,
20};
21
22pub mod db;
23pub mod metadata;
24
25/// This is the main struct which represents the database.
26///
27/// This struct holds the connection to the `sled` database and provides
28/// safe, high-level access to the various data trees. It manages a background
29/// thread for handling TTL (Time-To-Live) expirations automatically.
30///
31/// When this struct is dropped, it will signal the background thread to shut down
32/// and wait for it to finish gracefully.
33///
34/// This struct also holds 2 Arc<sled::Tree> directly instead of a single sled::Db,
35/// since almost all of the functions uses the tree directly which requires the sled::Db to
36/// constantly open each trees.
37/// Passing trees from the struct deletes the constant need to open the trees
38#[derive(Debug)]
39pub struct DB {
40    /// Stores the key and value
41    data_tree: Arc<Tree>,
42    /// Stores the key and the metadata
43    meta_tree: Arc<Tree>,
44    /// Stores the ttl timestamp and the key
45    ttl_tree: Arc<Tree>,
46    /// Manage the background thread which checks for expired keys
47    ttl_thread: Option<JoinHandle<Result<(), TransientError>>>,
48    /// Signals the ttl_thread to gracefully shutdown, when the DB is dropped
49    shutdown: Arc<AtomicBool>,
50    /// Path to the database
51    pub path: PathBuf,
52}
53
54/// Contains additional information about a key, such as its access frequency and lifecycle.
55///
56/// NOTE: This struct derives Serialize and Deserialize to be stored as raw bytes (&[u8]) in the underlying sled tree.
57#[derive(Debug, Serialize, Deserialize, PartialEq)]
58pub struct Metadata {
59    /// The number of time the key has been accessed
60    pub freq: u64,
61    /// Timestamp of key creation, in seconds since the UNIX epoch
62    pub created_at: u64,
63    /// The key's time-to-live in seconds. If None, the key is persistent and never expires.
64    pub ttl: Option<u64>,
65}