StorageEngine

Struct StorageEngine 

Source
pub struct StorageEngine { /* private fields */ }
Expand description

The main storage engine for FlashKV.

This is the “brain” of the database - it stores all key-value pairs and handles concurrent access from multiple client connections.

§Thread Safety

This struct is designed to be wrapped in an Arc and shared across all client handler tasks. All operations are thread-safe.

§Example

use flashkv::storage::StorageEngine;
use bytes::Bytes;
use std::time::Duration;

let engine = StorageEngine::new();

// Set a key
engine.set(Bytes::from("name"), Bytes::from("Ariz"));

// Get the value
let value = engine.get(&Bytes::from("name"));
assert_eq!(value, Some(Bytes::from("Ariz")));

// Set with expiry
engine.set_with_ttl(Bytes::from("session"), Bytes::from("abc123"), Duration::from_secs(60));

Implementations§

Source§

impl StorageEngine

Source

pub fn new() -> Self

Creates a new storage engine with default settings.

Source

pub fn set(&self, key: Bytes, value: Bytes) -> bool

Sets a key-value pair without expiry.

If the key already exists, its value is overwritten.

§Returns

Returns true if a new key was created, false if an existing key was updated.

Source

pub fn set_with_ttl(&self, key: Bytes, value: Bytes, ttl: Duration) -> bool

Sets a key-value pair with a TTL (Time-To-Live).

The key will automatically expire after the specified duration.

§Returns

Returns true if a new key was created, false if an existing key was updated.

Source

pub fn get(&self, key: &Bytes) -> Option<Bytes>

Gets the value for a key.

Returns None if the key doesn’t exist or has expired. This implements “lazy expiry” - expired keys are detected and removed on access.

Source

pub fn get_entry(&self, key: &Bytes) -> Option<Entry>

Gets the full entry for a key (including metadata).

This is useful for commands like TTL that need access to expiry information.

Source

pub fn delete(&self, key: &Bytes) -> bool

Deletes a key from the database.

§Returns

Returns true if the key was deleted, false if it didn’t exist.

Source

pub fn delete_many(&self, keys: &[Bytes]) -> u64

Deletes multiple keys from the database.

§Returns

Returns the number of keys that were deleted.

Source

pub fn exists(&self, key: &Bytes) -> bool

Checks if a key exists (and is not expired).

Source

pub fn exists_many(&self, keys: &[Bytes]) -> u64

Counts how many of the given keys exist.

Source

pub fn expire(&self, key: &Bytes, ttl: Duration) -> bool

Sets an expiry time on an existing key.

§Returns

Returns true if the expiry was set, false if the key doesn’t exist.

Source

pub fn persist(&self, key: &Bytes) -> bool

Removes the expiry from a key (makes it persistent).

§Returns

Returns true if the expiry was removed, false if the key doesn’t exist or didn’t have an expiry.

Source

pub fn ttl(&self, key: &Bytes) -> Option<i64>

Gets the remaining TTL for a key in seconds.

§Returns
  • Some(seconds) if the key exists and has an expiry
  • Some(-1) if the key exists but has no expiry
  • None if the key doesn’t exist
Source

pub fn pttl(&self, key: &Bytes) -> Option<i64>

Gets the remaining TTL for a key in milliseconds.

Source

pub fn incr(&self, key: &Bytes) -> Result<i64, &'static str>

Increments an integer value by 1.

If the key doesn’t exist, it’s set to 0 before the operation. Returns an error if the value is not a valid integer.

Source

pub fn incr_by(&self, key: &Bytes, delta: i64) -> Result<i64, &'static str>

Increments an integer value by a specified amount.

Source

pub fn decr(&self, key: &Bytes) -> Result<i64, &'static str>

Decrements an integer value by 1.

Source

pub fn decr_by(&self, key: &Bytes, delta: i64) -> Result<i64, &'static str>

Decrements an integer value by a specified amount.

Source

pub fn append(&self, key: &Bytes, value: &Bytes) -> usize

Appends a value to an existing string.

If the key doesn’t exist, it’s created with the given value.

§Returns

Returns the length of the string after the append.

Source

pub fn strlen(&self, key: &Bytes) -> usize

Gets the length of a string value.

Returns 0 if the key doesn’t exist.

Source

pub fn keys(&self, pattern: &str) -> Vec<Bytes>

Returns all keys matching a pattern (simplified glob matching).

Supported patterns:

  • * matches everything
  • h*llo matches hello, hallo, hxllo
  • h?llo matches hello, hallo, but not hllo
  • h[ae]llo matches hello and hallo, but not hillo

Warning: This operation scans all keys and can be slow on large databases.

Source

pub fn flush(&self)

Clears all data from the database.

This is equivalent to the Redis FLUSHDB command.

Source

pub fn len(&self) -> u64

Returns the approximate number of keys in the database.

This is an approximation because it uses relaxed atomic ordering.

Source

pub fn is_empty(&self) -> bool

Returns true if the database is empty.

Source

pub fn stats(&self) -> StorageStats

Returns database statistics.

Source

pub fn cleanup_expired(&self) -> u64

Cleans up expired keys from all shards.

This is called by the background expiry sweeper.

§Returns

Returns the number of keys that were cleaned up.

Source

pub fn lpush(&self, key: Bytes, values: Vec<Bytes>) -> usize

Pushes one or more values to the left (head) of a list. Creates the list if it doesn’t exist.

§Returns

The length of the list after the push operation.

Source

pub fn rpush(&self, key: Bytes, values: Vec<Bytes>) -> usize

Pushes one or more values to the right (tail) of a list. Creates the list if it doesn’t exist.

§Returns

The length of the list after the push operation.

Source

pub fn lpop(&self, key: &Bytes) -> Option<Bytes>

Removes and returns the first element (head) of a list.

§Returns

The removed element, or None if the list is empty or doesn’t exist.

Source

pub fn rpop(&self, key: &Bytes) -> Option<Bytes>

Removes and returns the last element (tail) of a list.

§Returns

The removed element, or None if the list is empty or doesn’t exist.

Source

pub fn llen(&self, key: &Bytes) -> usize

Returns the length of a list.

§Returns

The length of the list, or 0 if the list doesn’t exist.

Source

pub fn lindex(&self, key: &Bytes, index: i64) -> Option<Bytes>

Returns the element at the specified index in a list. Negative indices count from the end (-1 is the last element).

§Returns

The element at the index, or None if index is out of range.

Source

pub fn lrange(&self, key: &Bytes, start: i64, stop: i64) -> Vec<Bytes>

Returns a range of elements from a list. Both start and stop are inclusive. Negative indices count from the end.

§Returns

A vector of elements in the specified range.

Source

pub fn lset(&self, key: &Bytes, index: i64, value: Bytes) -> Result<(), String>

Sets the element at the specified index in a list. Negative indices count from the end.

§Returns

Ok(()) if successful, Err with message if index is out of range or list doesn’t exist.

Source

pub fn lrem(&self, key: &Bytes, count: i64, value: &Bytes) -> usize

Removes elements equal to the given value from a list.

  • count > 0: Remove count elements equal to value, from head to tail.
  • count < 0: Remove |count| elements equal to value, from tail to head.
  • count = 0: Remove all elements equal to value.
§Returns

The number of removed elements.

Source

pub fn list_exists(&self, key: &Bytes) -> bool

Checks if a key exists as a list.

Source

pub fn key_type(&self, key: &Bytes) -> &'static str

Returns the type of a key (“string”, “list”, or “none”).

Source

pub fn memory_info(&self) -> MemoryInfo

Returns memory usage information (approximate).

Trait Implementations§

Source§

impl Debug for StorageEngine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for StorageEngine

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more