Skip to main content

Keyspace

Struct Keyspace 

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

The core key-value store.

All operations are single-threaded per shard — no internal locking. Memory usage is tracked incrementally on every mutation.

Implementations§

Source§

impl Keyspace

Source

pub fn new() -> Self

Creates a new, empty keyspace with default config (no memory limit).

Source

pub fn with_config(config: ShardConfig) -> Self

Creates a new, empty keyspace with the given config.

Source

pub fn set_drop_handle(&mut self, handle: DropHandle)

Attaches a background drop handle for lazy free. When set, large values removed by del/eviction/expiration are dropped on a background thread instead of blocking the shard.

Source

pub fn get(&mut self, key: &str) -> Result<Option<Value>, WrongType>

Retrieves the string value for key, or None if missing/expired.

Returns Err(WrongType) if the key holds a non-string value. Expired keys are removed lazily on access. Successful reads update the entry’s last access time for LRU tracking.

Source

pub fn value_type(&mut self, key: &str) -> &'static str

Returns the type name of the value at key, or “none” if missing.

Source

pub fn set( &mut self, key: String, value: Bytes, expire: Option<Duration>, ) -> SetResult

Stores a key-value pair. If the key already existed, the old entry (including any TTL) is replaced entirely.

expire sets an optional TTL as a duration from now.

Returns SetResult::OutOfMemory if the memory limit is reached and the eviction policy is NoEviction. With AllKeysLru, this will evict keys to make room before inserting.

Source

pub fn del(&mut self, key: &str) -> bool

Removes a key. Returns true if the key existed (and wasn’t expired).

When a drop handle is set, large values are dropped on the background thread instead of inline.

Removes a key like del, but always defers the value’s destructor to the background drop thread (when available). Semantically identical to DEL — the key is gone immediately, memory is accounted for immediately, but the actual deallocation happens off the hot path.

Source

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

Returns true if the key exists and hasn’t expired.

Source

pub fn expire(&mut self, key: &str, seconds: u64) -> bool

Sets an expiration on an existing key. Returns true if the key exists (and the TTL was set), false if the key doesn’t exist.

Source

pub fn ttl(&mut self, key: &str) -> TtlResult

Returns the TTL status for a key, following Redis semantics:

  • Seconds(n) if the key has a TTL
  • NoExpiry if the key exists without a TTL
  • NotFound if the key doesn’t exist
Source

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

Removes the expiration from a key.

Returns true if the key existed and had a timeout that was removed. Returns false if the key doesn’t exist or has no expiration.

Source

pub fn pttl(&mut self, key: &str) -> TtlResult

Returns the TTL status for a key in milliseconds, following Redis semantics:

  • Milliseconds(n) if the key has a TTL
  • NoExpiry if the key exists without a TTL
  • NotFound if the key doesn’t exist
Source

pub fn pexpire(&mut self, key: &str, millis: u64) -> bool

Sets an expiration on an existing key in milliseconds.

Returns true if the key exists (and the TTL was set), false if the key doesn’t exist.

Source

pub fn incr(&mut self, key: &str) -> Result<i64, IncrError>

Increments the integer value of a key by 1.

If the key doesn’t exist, it’s initialized to 0 before incrementing. Returns the new value after the operation.

Source

pub fn decr(&mut self, key: &str) -> Result<i64, IncrError>

Decrements the integer value of a key by 1.

If the key doesn’t exist, it’s initialized to 0 before decrementing. Returns the new value after the operation.

Source

pub fn incr_by(&mut self, key: &str, delta: i64) -> Result<i64, IncrError>

Adds delta to the current integer value of the key, creating it if necessary. Used by INCR, DECR, INCRBY, and DECRBY.

Preserves the existing TTL when updating an existing key.

Source

pub fn incr_by_float( &mut self, key: &str, delta: f64, ) -> Result<String, IncrFloatError>

Adds a float delta to the current value of the key, creating it if necessary. Used by INCRBYFLOAT.

Preserves the existing TTL when updating an existing key. Returns the new value as a string (matching Redis behavior).

Source

pub fn append(&mut self, key: &str, value: &[u8]) -> Result<usize, WriteError>

Appends a value to an existing string key, or creates a new key if it doesn’t exist. Returns the new string length.

Source

pub fn strlen(&mut self, key: &str) -> Result<usize, WrongType>

Returns the length of the string value stored at key. Returns 0 if the key does not exist.

Source

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

Returns all keys matching a glob pattern.

Warning: O(n) scan of the entire keyspace. Use SCAN for production workloads with large key counts.

Source

pub fn count_keys_in_slot(&self, slot: u16) -> usize

Counts live keys in this keyspace that hash to the given cluster slot.

O(n) scan over all entries — same cost as KEYS.

Source

pub fn get_keys_in_slot(&self, slot: u16, count: usize) -> Vec<String>

Returns up to count live keys that hash to the given cluster slot.

O(n) scan over all entries — same cost as KEYS.

Source

pub fn rename(&mut self, key: &str, newkey: &str) -> Result<(), RenameError>

Renames a key to a new name. Returns an error if the source key doesn’t exist. If the destination key already exists, it is overwritten.

Source

pub fn stats(&self) -> KeyspaceStats

Returns aggregated stats for this keyspace.

All fields are tracked incrementally — this is O(1).

Source

pub fn len(&self) -> usize

Returns the number of live keys.

Source

pub fn clear(&mut self)

Removes all keys from the keyspace.

Source

pub fn is_empty(&self) -> bool

Returns true if the keyspace has no entries.

Source

pub fn scan_keys( &self, cursor: u64, count: usize, pattern: Option<&str>, ) -> (u64, Vec<String>)

Scans keys starting from a cursor position.

Returns the next cursor (0 if scan complete) and a batch of keys. The pattern argument supports glob-style matching (*, ?, [abc]).

Source

pub fn iter_entries(&self) -> impl Iterator<Item = (&str, &Value, i64)>

Iterates over all live (non-expired) entries, yielding the key, a clone of the value, and the remaining TTL in milliseconds (-1 for entries with no expiration). Used by snapshot and AOF rewrite.

Source

pub fn restore(&mut self, key: String, value: Value, ttl: Option<Duration>)

Restores an entry during recovery, bypassing memory limits.

ttl is the remaining time-to-live. If None, the key has no expiry. This is used only during shard startup when loading from snapshot/AOF — normal writes should go through set().

Source

pub fn lpush( &mut self, key: &str, values: &[Bytes], ) -> Result<usize, WriteError>

Pushes one or more values to the head (left) of a list.

Creates the list if the key doesn’t exist. Returns Err(WriteError::WrongType) if the key exists but holds a non-list value, or Err(WriteError::OutOfMemory) if the memory limit is reached. Returns the new length on success.

Source

pub fn rpush( &mut self, key: &str, values: &[Bytes], ) -> Result<usize, WriteError>

Pushes one or more values to the tail (right) of a list.

Creates the list if the key doesn’t exist. Returns Err(WriteError::WrongType) if the key exists but holds a non-list value, or Err(WriteError::OutOfMemory) if the memory limit is reached. Returns the new length on success.

Source

pub fn lpop(&mut self, key: &str) -> Result<Option<Bytes>, WrongType>

Pops a value from the head (left) of a list.

Returns Ok(None) if the key doesn’t exist. Removes the key if the list becomes empty. Returns Err(WrongType) on type mismatch.

Source

pub fn rpop(&mut self, key: &str) -> Result<Option<Bytes>, WrongType>

Pops a value from the tail (right) of a list.

Returns Ok(None) if the key doesn’t exist. Removes the key if the list becomes empty. Returns Err(WrongType) on type mismatch.

Source

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

Returns a range of elements from a list by index.

Supports negative indices (e.g. -1 = last element). Out-of-bounds indices are clamped to the list boundaries. Returns Err(WrongType) on type mismatch. Missing keys return an empty vec.

Source

pub fn llen(&mut self, key: &str) -> Result<usize, WrongType>

Returns the length of a list, or 0 if the key doesn’t exist.

Returns Err(WrongType) on type mismatch.

Source

pub fn zadd( &mut self, key: &str, members: &[(f64, String)], flags: &ZAddFlags, ) -> Result<ZAddResult, WriteError>

Adds members with scores to a sorted set, with optional ZADD flags.

Creates the sorted set if the key doesn’t exist. Returns a ZAddResult containing the count for the client response and the list of members that were actually applied (for AOF correctness). Returns Err(WriteError::WrongType) on type mismatch, or Err(WriteError::OutOfMemory) if the memory limit is reached.

Source

pub fn zrem( &mut self, key: &str, members: &[String], ) -> Result<Vec<String>, WrongType>

Removes members from a sorted set. Returns the names of members that were actually removed (for AOF correctness). Deletes the key if the set becomes empty.

Returns Err(WrongType) if the key holds a non-sorted-set value.

Source

pub fn zscore( &mut self, key: &str, member: &str, ) -> Result<Option<f64>, WrongType>

Returns the score for a member in a sorted set.

Returns Ok(None) if the key or member doesn’t exist. Returns Err(WrongType) on type mismatch.

Source

pub fn zrank( &mut self, key: &str, member: &str, ) -> Result<Option<usize>, WrongType>

Returns the 0-based rank of a member in a sorted set (lowest score = 0).

Returns Ok(None) if the key or member doesn’t exist. Returns Err(WrongType) on type mismatch.

Source

pub fn zrange( &mut self, key: &str, start: i64, stop: i64, ) -> Result<Vec<(String, f64)>, WrongType>

Returns a range of members from a sorted set by rank.

Supports negative indices. If with_scores is true, the result includes (member, score) pairs; otherwise just members. Returns Err(WrongType) on type mismatch.

Source

pub fn zcard(&mut self, key: &str) -> Result<usize, WrongType>

Returns the number of members in a sorted set, or 0 if the key doesn’t exist.

Returns Err(WrongType) on type mismatch.

Source

pub fn hset( &mut self, key: &str, fields: &[(String, Bytes)], ) -> Result<usize, WriteError>

Sets one or more field-value pairs in a hash.

Creates the hash if the key doesn’t exist. Returns the number of new fields added (fields that were updated don’t count).

Source

pub fn hget( &mut self, key: &str, field: &str, ) -> Result<Option<Bytes>, WrongType>

Gets the value of a field in a hash.

Returns None if the key or field doesn’t exist.

Source

pub fn hgetall(&mut self, key: &str) -> Result<Vec<(String, Bytes)>, WrongType>

Gets all field-value pairs from a hash.

Returns an empty vec if the key doesn’t exist.

Source

pub fn hdel( &mut self, key: &str, fields: &[String], ) -> Result<Vec<String>, WrongType>

Deletes one or more fields from a hash.

Returns the fields that were actually removed.

Source

pub fn hexists(&mut self, key: &str, field: &str) -> Result<bool, WrongType>

Checks if a field exists in a hash.

Source

pub fn hlen(&mut self, key: &str) -> Result<usize, WrongType>

Returns the number of fields in a hash.

Source

pub fn hincrby( &mut self, key: &str, field: &str, delta: i64, ) -> Result<i64, IncrError>

Increments a field’s integer value by the given amount.

Creates the hash and field if they don’t exist, starting from 0.

Source

pub fn hkeys(&mut self, key: &str) -> Result<Vec<String>, WrongType>

Returns all field names in a hash.

Source

pub fn hvals(&mut self, key: &str) -> Result<Vec<Bytes>, WrongType>

Returns all values in a hash.

Source

pub fn hmget( &mut self, key: &str, fields: &[String], ) -> Result<Vec<Option<Bytes>>, WrongType>

Gets multiple field values from a hash.

Returns None for fields that don’t exist.

Source

pub fn sadd( &mut self, key: &str, members: &[String], ) -> Result<usize, WriteError>

Adds one or more members to a set.

Creates the set if the key doesn’t exist. Returns the number of new members added (existing members don’t count).

Source

pub fn srem( &mut self, key: &str, members: &[String], ) -> Result<usize, WrongType>

Removes one or more members from a set.

Returns the number of members that were actually removed.

Source

pub fn smembers(&mut self, key: &str) -> Result<Vec<String>, WrongType>

Returns all members of a set.

Source

pub fn sismember(&mut self, key: &str, member: &str) -> Result<bool, WrongType>

Checks if a member exists in a set.

Source

pub fn scard(&mut self, key: &str) -> Result<usize, WrongType>

Returns the cardinality (number of elements) of a set.

Source

pub fn expire_sample(&mut self, count: usize) -> usize

Randomly samples up to count keys and removes any that have expired.

Returns the number of keys actually removed. Used by the active expiration cycle to clean up keys that no one is reading.

Trait Implementations§

Source§

impl Default for Keyspace

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> 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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
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
Source§

impl<T> OptionalSend for T
where T: Send + ?Sized,

Source§

impl<T> OptionalSync for T
where T: Sync + ?Sized,