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
use bytes::Bytes;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::core::ttl_sweep::TtlConfig;
use crate::error::{FeoxError, Result};
use super::FeoxStore;
impl FeoxStore {
/// Insert or update a key-value pair with TTL (Time-To-Live).
///
/// # Arguments
///
/// * `key` - The key to insert
/// * `value` - The value to store
/// * `ttl_seconds` - Time-to-live in seconds
///
/// # Returns
///
/// Returns `Ok(())` if successful.
///
/// # Example
///
/// ```rust
/// # use feoxdb::FeoxStore;
/// # fn main() -> feoxdb::Result<()> {
/// # let store = FeoxStore::builder().enable_ttl(true).build()?;
/// // Key expires after 60 seconds
/// store.insert_with_ttl(b"session:123", b"data", 60)?;
/// # Ok(())
/// # }
/// ```
///
/// # Performance
///
/// * Memory mode: ~800ns
/// * Persistent mode: ~1µs (buffered write)
pub fn insert_with_ttl(&self, key: &[u8], value: &[u8], ttl_seconds: u64) -> Result<bool> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
self.insert_with_ttl_and_timestamp(key, value, ttl_seconds, None)
}
/// Insert or update a key-value pair with TTL and explicit timestamp.
///
/// # Arguments
///
/// * `key` - The key to insert
/// * `value` - The value to store
/// * `ttl_seconds` - Time-to-live in seconds
/// * `timestamp` - Optional timestamp for conflict resolution. If `None`, uses current time.
///
/// # Returns
///
/// Returns `Ok(())` if successful.
pub fn insert_with_ttl_and_timestamp(
&self,
key: &[u8],
value: &[u8],
ttl_seconds: u64,
timestamp: Option<u64>,
) -> Result<bool> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
let timestamp = match timestamp {
Some(0) | None => self.get_timestamp(),
Some(ts) => ts,
};
// Calculate expiry timestamp
let ttl_expiry = if ttl_seconds > 0 {
timestamp + (ttl_seconds * 1_000_000_000) // Convert seconds to nanoseconds
} else {
0
};
self.insert_with_timestamp_and_ttl_internal(key, value, Some(timestamp), ttl_expiry)
}
/// Insert or update a key-value pair with TTL using zero-copy Bytes.
///
/// This method avoids copying the value data by directly using the Bytes type,
/// which provides reference-counted zero-copy semantics.
///
/// # Arguments
///
/// * `key` - The key to insert
/// * `value` - The value to store as Bytes
/// * `ttl_seconds` - Time-to-live in seconds
///
/// # Returns
///
/// Returns `Ok(())` if successful.
///
/// # Example
///
/// ```rust
/// # use feoxdb::FeoxStore;
/// # use bytes::Bytes;
/// # fn main() -> feoxdb::Result<()> {
/// # let store = FeoxStore::builder().enable_ttl(true).build()?;
/// let data = Bytes::from_static(b"session_data");
/// // Key expires after 60 seconds
/// store.insert_bytes_with_ttl(b"session:123", data, 60)?;
/// # Ok(())
/// # }
/// ```
///
/// # Performance
///
/// * Memory mode: ~800ns (avoids value copy)
/// * Persistent mode: ~1µs (buffered write, avoids value copy)
pub fn insert_bytes_with_ttl(
&self,
key: &[u8],
value: Bytes,
ttl_seconds: u64,
) -> Result<bool> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
self.insert_bytes_with_ttl_and_timestamp(key, value, ttl_seconds, None)
}
/// Insert or update a key-value pair with TTL and explicit timestamp using zero-copy Bytes.
///
/// # Arguments
///
/// * `key` - The key to insert
/// * `value` - The value to store as Bytes
/// * `ttl_seconds` - Time-to-live in seconds
/// * `timestamp` - Optional timestamp for conflict resolution. If `None`, uses current time.
///
/// # Returns
///
/// Returns `Ok(())` if successful.
pub fn insert_bytes_with_ttl_and_timestamp(
&self,
key: &[u8],
value: Bytes,
ttl_seconds: u64,
timestamp: Option<u64>,
) -> Result<bool> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
self.insert_bytes_with_timestamp_and_ttl_internal(key, value, timestamp, ttl_seconds)
}
/// Get the remaining TTL (Time-To-Live) for a key in seconds.
///
/// # Arguments
///
/// * `key` - The key to check
///
/// # Returns
///
/// Returns `Some(seconds)` if the key has TTL set, `None` if no TTL or key not found.
///
/// # Example
///
/// ```rust
/// # use feoxdb::FeoxStore;
/// # fn main() -> feoxdb::Result<()> {
/// # let store = FeoxStore::builder().enable_ttl(true).build()?;
/// store.insert_with_ttl(b"session", b"data", 3600)?;
///
/// // Check remaining TTL
/// if let Ok(Some(ttl)) = store.get_ttl(b"session") {
/// println!("Session expires in {} seconds", ttl);
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_ttl(&self, key: &[u8]) -> Result<Option<u64>> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
self.validate_key(key)?;
let record = self
.hash_table
.read(key, |_, v| v.clone())
.ok_or(FeoxError::KeyNotFound)?;
let ttl_expiry = record.ttl_expiry.load(Ordering::Acquire);
if ttl_expiry == 0 {
return Ok(None); // No TTL set
}
let now = self.get_timestamp();
if now >= ttl_expiry {
return Ok(Some(0)); // Already expired
}
// Return remaining seconds
Ok(Some((ttl_expiry - now) / 1_000_000_000))
}
/// Update the TTL for an existing key.
///
/// # Arguments
///
/// * `key` - The key to update
/// * `ttl_seconds` - New TTL in seconds (0 to remove TTL)
///
/// # Returns
///
/// Returns `Ok(())` if successful.
///
/// # Errors
///
/// * `KeyNotFound` - Key does not exist
///
/// # Example
///
/// ```rust
/// # use feoxdb::FeoxStore;
/// # fn main() -> feoxdb::Result<()> {
/// # let store = FeoxStore::builder().enable_ttl(true).build()?;
/// # store.insert(b"key", b"value")?;
/// // Extend TTL to 1 hour
/// store.update_ttl(b"key", 3600)?;
/// # Ok(())
/// # }
/// ```
pub fn update_ttl(&self, key: &[u8], ttl_seconds: u64) -> Result<()> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
self.validate_key(key)?;
let record = self
.hash_table
.read(key, |_, v| v.clone())
.ok_or(FeoxError::KeyNotFound)?;
let new_expiry = if ttl_seconds > 0 {
self.get_timestamp() + (ttl_seconds * 1_000_000_000)
} else {
0
};
record.ttl_expiry.store(new_expiry, Ordering::Release);
Ok(())
}
/// Remove TTL from a key, making it persistent.
///
/// # Arguments
///
/// * `key` - The key to persist
///
/// # Returns
///
/// Returns `Ok(())` if successful.
///
/// # Errors
///
/// * `KeyNotFound` - Key does not exist
///
/// # Example
///
/// ```rust
/// # use feoxdb::FeoxStore;
/// # fn main() -> feoxdb::Result<()> {
/// # let store = FeoxStore::builder().enable_ttl(true).build()?;
/// # store.insert_with_ttl(b"temp", b"data", 60)?;
/// // Remove TTL, make permanent
/// store.persist(b"temp")?;
/// # Ok(())
/// # }
/// ```
pub fn persist(&self, key: &[u8]) -> Result<()> {
if !self.enable_ttl {
return Err(FeoxError::TtlNotEnabled);
}
self.update_ttl(key, 0)
}
/// Start the TTL sweeper if configured
/// This must be called with an `Arc<Self>` after construction
pub fn start_ttl_sweeper(self: &Arc<Self>, config: Option<TtlConfig>) {
// Only start TTL sweeper if TTL is enabled
if !self.enable_ttl {
return;
}
let ttl_config = config.unwrap_or_else(|| {
if self.memory_only {
TtlConfig::default_memory()
} else {
TtlConfig::default_persistent()
}
});
if ttl_config.enabled {
let weak_store = Arc::downgrade(self);
let mut sweeper = crate::core::ttl_sweep::TtlSweeper::new(weak_store, ttl_config);
sweeper.start();
// Store the sweeper
*self.ttl_sweeper.write() = Some(sweeper);
}
}
/// Get current timestamp (public for TTL cleaner)
pub fn get_timestamp_pub(&self) -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos() as u64
}
}