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 sync::{Arc, atomic::AtomicBool},
18 thread::JoinHandle,
19};
20
21pub mod db;
22pub mod metadata;
23
24/// This is the main struct which represents the database.
25///
26/// This struct holds the connection to the `sled` database and provides
27/// safe, high-level access to the various data trees. It manages a background
28/// thread for handling TTL (Time-To-Live) expirations automatically.
29///
30/// When this struct is dropped, it will signal the background thread to shut down
31/// and wait for it to finish gracefully.
32///
33/// This struct also holds 2 Arc<sled::Tree> directly instead of a single sled::Db,
34/// since almost all of the functions uses the tree directly which requires the sled::Db to
35/// constantly open each trees.
36/// Passing trees from the struct deletes the constant need to open the trees
37#[derive(Debug)]
38pub struct DB {
39 /// Stores the key and value
40 data_tree: Arc<Tree>,
41 /// Stores the key and the metadata
42 meta_tree: Arc<Tree>,
43 /// Stores the ttl timestamp and the key
44 ttl_tree: Arc<Tree>,
45 /// Manage the background thread which checks for expired keys
46 ttl_thread: Option<JoinHandle<Result<(), TransientError>>>,
47 /// Signals the ttl_thread to gracefully shutdown, when the DB is dropped
48 shutdown: Arc<AtomicBool>,
49}
50
51/// Contains additional information about a key, such as its access frequency and lifecycle.
52///
53/// NOTE: This struct derives Serialize and Deserialize to be stored as raw bytes (&[u8]) in the underlying sled tree.
54#[derive(Debug, Serialize, Deserialize, PartialEq)]
55pub struct Metadata {
56 /// The number of time the key has been accessed
57 pub freq: u64,
58 /// Timestamp of key creation, in seconds since the UNIX epoch
59 pub created_at: u64,
60 /// The key's time-to-live in seconds. If None, the key is persistent and never expires.
61 pub ttl: Option<u64>,
62}